@fnndsc/argus 0.48.1 → 0.48.2
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.
- package/dist/assets/{Settings-C45vzN59.js → Settings-2RQVwvnQ.js} +1 -1
- package/dist/assets/{Texture-Dxy8yu8l.js → Texture-BTXL_xdB.js} +1 -1
- package/dist/assets/{addVolumesToViewports-9fYLW3SL.js → addVolumesToViewports-DJp6hKow.js} +1 -1
- package/dist/assets/{asciidoc-C42sg1-0.js → asciidoc-BvmVgZkb.js} +1 -1
- package/dist/assets/{cornerstoneEngine-BZwM3FCO.js → cornerstoneEngine-BleRTwP7.js} +2 -2
- package/dist/assets/{documentEngines-6OTLfnSd.js → documentEngines-Dku3XAlE.js} +1 -1
- package/dist/assets/{field-BL_j7bBL.js → field-DBwJhEgd.js} +1 -1
- package/dist/assets/{index-C3g0oOm6.js → index-96g1c4N8.js} +1 -1
- package/dist/assets/{index-vLqSFfC4.js → index-C2PSqMru.js} +1 -1
- package/dist/assets/{index-BeMYT4EK.js → index-C6QjPZQ_.js} +1 -1
- package/dist/assets/{index-DwbwxBew.js → index-C7-uwVws.js} +1 -1
- package/dist/assets/{index-DB3IkzxW.js → index-CNGZbo-S.js} +1 -1
- package/dist/assets/{index-CW82Cpv5.js → index-COu2z5IR.js} +8 -8
- package/dist/assets/{index-DCsD9tff.js → index-CXPkJUt9.js} +1 -1
- package/dist/assets/{index-BOBNWuTk.js → index-Cos2T2Dw.js} +1 -1
- package/dist/assets/{index-CyCZEGve.js → index-D4jKFjXY.js} +1 -1
- package/dist/assets/{index-BiEwWGch.js → index-DniTzx9c.js} +1 -1
- package/dist/assets/{index-DPzdPxX6.js → index-DvRiiN3w.js} +1 -1
- package/dist/assets/{index-BKRnNeIw.js → index-JoTqs14_.js} +1 -1
- package/dist/assets/{index-Ccl1Oi2r.js → index-KIrn2OnR.js} +1 -1
- package/dist/assets/{index-C70jFenc.js → index-SEFX26xD.js} +1 -1
- package/dist/assets/{niivueEngine-CDj3oRPj.js → niivueEngine-Dd9ONOnD.js} +2 -2
- package/dist/assets/{slabScene-BNtmAwKe.js → slabScene-gPj785hr.js} +1 -1
- package/dist/assets/{syntax-BErZglCz.js → syntax-CK34dlF6.js} +3 -3
- package/dist/build.json +1 -1
- package/dist/index.html +1 -1
- package/dist/notes.json +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./cornerstoneEngine-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./cornerstoneEngine-BleRTwP7.js","./refusal-DOpm8I8L.js","./_commonjsHelpers-CE1G-McA.js","./__vite-browser-external-D7Ct-6yo.js","./niivueEngine-Dd9ONOnD.js","./field-DBwJhEgd.js","./syntax-CK34dlF6.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))i(n);new MutationObserver(n=>{for(const r of n)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(n){const r={};return n.integrity&&(r.integrity=n.integrity),n.referrerPolicy&&(r.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?r.credentials="include":n.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(n){if(n.ep)return;n.ep=!0;const r=t(n);fetch(n.href,r)}})();function eE(s,e){document.querySelector(".share-sheet")?.remove();const t=document.createElement("div");t.className="share-sheet cloud-ask cloud-elevate",t.id="cloud-elevate-sheet",t.setAttribute("role","dialog");const i=document.createElement("div");i.className="share-head",i.textContent="MANAGE · YOUR PASSWORD";const n=document.createElement("pre");n.className="share-script",n.textContent=[`${s}`,"","This session was entered as READ: nothing outside this host changes.","That line would act. Your password, checked at the door you logged in by, makes this","session MANAGE until you leave it; it crosses once and is kept nowhere."].join(`
|
|
3
3
|
`);const r=document.createElement("input");r.type="password",r.className="cloud-password",r.autocomplete="current-password",r.setAttribute("aria-label","Password");const o=(h,d)=>{const u=document.createElement("button");return u.type="button",u.className=d,u.textContent=h,u},a=o("MANAGE","share-copy cloud-manage"),l=o("NOT NOW","share-close"),c=document.createElement("div");return c.className="share-pills",c.append(a,l),t.append(i,n,r,c),document.body.appendChild(t),r.focus(),new Promise(h=>{const d=u=>{r.value="",t.remove(),h(u)};a.addEventListener("click",()=>d(r.value===""?null:r.value)),l.addEventListener("click",()=>d(null)),r.addEventListener("keydown",u=>{u.key==="Enter"&&d(r.value===""?null:r.value)}),t.addEventListener("keydown",u=>{u.key==="Escape"&&d(null)})})}const tE=450,vb=12;function Po(s,e,t=Date.now()){const i=Number(s.dataset.edgeAt??0);return s.dataset.edge===e&&t-i<tE?!1:(delete s.dataset.edge,s.offsetWidth,s.dataset.edge=e,s.dataset.edgeAt=String(t),!0)}function sE(s,e){return e?"▲ TOP":`▼ ${s} MORE`}function iE(s,e){const t=s.getBoundingClientRect().bottom;let i=0;for(const n of s.querySelectorAll(e)){const r=n.getBoundingClientRect();r.height>0&&r.top>=t-2&&(i+=1)}return i}function nE(s){const e=parseFloat(getComputedStyle(s).lineHeight)||16;return Math.max(0,Math.ceil((s.scrollHeight-s.scrollTop-s.clientHeight)/e))}function ai(s,e={}){s.dataset.more="wired",s.classList.add("holds-more");const t=document.createElement("button");t.type="button",t.className=`more-chip${e.className!==void 0?` ${e.className}`:""}`,t.hidden=!0;const i=e.label??sE,n=()=>s.scrollTop+s.clientHeight>=s.scrollHeight-2;t.addEventListener("click",l=>{if(l.stopPropagation(),e.press!==void 0){e.press();return}s.scrollBy({top:n()?-s.scrollHeight:Math.max(1,s.clientHeight-t.offsetHeight),behavior:"smooth"})});const r=e.mount??s;r.appendChild(t);let o=!1;const a=()=>{if(!o){o=!0;try{r===s&&s.lastElementChild!==t&&s.appendChild(t);const l=(e.scrolls?.()??!0)&&s.scrollHeight>s.clientHeight+2;if(t.hidden!==!l&&(t.hidden=!l),!l)return;const c=e.rows!==void 0?iE(s,e.rows):nE(s),h=i(c,n());t.textContent!==h&&(t.textContent=h)}finally{o=!1}}};return s.addEventListener("scroll",a,{passive:!0}),rE(s,n),typeof ResizeObserver<"u"&&new ResizeObserver(a).observe(s),new MutationObserver(a).observe(s,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","class","style"]}),a(),t}function rE(s,e){const t=()=>s.scrollHeight>s.clientHeight+2,i=()=>s.scrollTop<=0;let n=s.scrollTop;s.addEventListener("scrollend",()=>{const o=s.scrollTop!==n;n=s.scrollTop,!(!o||!t())&&(i()?Po(s,"top"):e()&&Po(s,"bottom"))}),s.addEventListener("wheel",o=>{!t()||o.deltaY===0||(o.deltaY<0&&i()?Po(s,"top"):o.deltaY>0&&e()&&Po(s,"bottom"))},{passive:!0});let r=null;s.addEventListener("touchstart",o=>{r=o.touches[0]?.clientY??null},{passive:!0}),s.addEventListener("touchmove",o=>{const a=o.touches[0]?.clientY;r===null||a===void 0||!t()||(a-r>vb&&i()?(Po(s,"top"),r=null):r-a>vb&&e()&&(Po(s,"bottom"),r=null))},{passive:!0}),s.addEventListener("animationend",o=>{o.target===s&&o.animationName.startsWith("edge-flare")&&delete s.dataset.edge})}function et(s){const e=document.getElementById(s);if(e===null)throw new Error(`required element #${s} is missing`);return e}function sn(s){const e=et(s);if(!(e instanceof HTMLTemplateElement))throw new Error(`#${s} is not a template`);const t=e.content.firstElementChild;if(!(t instanceof HTMLElement))throw new Error(`template #${s} is empty`);return t.cloneNode(!0)}function Js(s,e){const t=s.querySelector(e);if(t===null)throw new Error(`pane template is missing ${e}`);return t}const Hy=24,up="argus.dormant";class oE{constructor(e=Hy,t){this.cap=e,this.store=t,this.rehydrate()}cap;store;groups=new Map;add(e){for(this.groups.delete(e.id),this.groups.set(e.id,e);this.groups.size>this.cap;){const t=this.oldest_id();if(t===void 0)break;this.groups.delete(t)}this.persist()}list(){return[...this.groups.values()].sort((e,t)=>t.lastTouched-e.lastTouched)}get(e){return this.groups.get(e)}has(e){return this.groups.has(e)}dismiss(e){const t=this.groups.delete(e);return t&&this.persist(),t}oldest_id(){let e;for(const t of this.groups.values())(e===void 0||t.lastTouched<e.lastTouched)&&(e=t);return e?.id}persist(){if(this.store!==void 0)try{this.store.setItem(up,JSON.stringify([...this.groups.values()]))}catch{}}rehydrate(){if(this.store!==void 0)try{const e=this.store.getItem(up);if(e===null)return;const t=JSON.parse(e);if(!Array.isArray(t))return;for(const i of t)i!==null&&typeof i=="object"&&typeof i.id=="string"&&this.groups.set(i.id,i)}catch{}}}function Vy(){try{const s=globalThis.localStorage;return s===void 0?void 0:(s.getItem(up),s)}catch{return}}function aE(s){if(!s.startsWith("#/"))return null;let e;try{e=decodeURI(s.slice(1))}catch{return null}e=e.replace(/\/+$/,"")||"/";const t=e.split("/").filter(o=>o!==""),i=t[t.length-1]??"";return!t.includes("data")&&(/^feed_\d+$/.test(i)||/^[\w.-]+_\d+$/.test(i)&&t.some(o=>/^feed_\d+$/.test(o)))?{kind:"runs",target:i}:{kind:"folder",path:/\.[A-Za-z0-9]{1,8}$/.test(i)&&!/_\d+$/.test(i)?`/${t.slice(0,-1).join("/")}`:e}}function qy(s,e){return`${s.replace(/\/+$/,"")}/#${encodeURI(e)}`}const lE=2500;function Ky(s){const e=document.createElement("div");e.className="link-line";const t=document.createElement("button");t.type="button",t.className="link-pill",t.textContent="LINK";const i=document.createElement("span");i.className="link-address",e.append(t,i),Ng(e,s);const n=r=>{r.stopPropagation(),Yy(e)};return t.addEventListener("click",n),i.addEventListener("click",n),e}function Ng(s,e){const t=qy(window.location.origin,e),i=s.querySelector(".link-address");i!==null&&i.textContent!==t&&(i.textContent=t),s.dataset.link=t,s.title=`a link that opens ARGUS at ${e} — press to copy`}async function Yy(s,e=navigator.clipboard){const t=s.dataset.link??"",i=s.querySelector(".link-pill");let n=!1;try{if(e===void 0)throw new Error("no clipboard");await e.writeText(t),n=!0}catch{const o=s.querySelector(".link-address"),a=window.getSelection();if(o!==null&&a!==null){const l=document.createRange();l.selectNodeContents(o),a.removeAllRanges(),a.addRange(l)}}s.dataset.copied=n?"yes":"no",i!==null&&(i.textContent=n?"COPIED":"SELECT + COPY");const r=Date.now();return s.dataset.shown=String(r),setTimeout(()=>{s.dataset.shown===String(r)&&(delete s.dataset.copied,i!==null&&(i.textContent="LINK"))},lE),n}const cE="desktop clear";function Xy(s){const e=s.split(`
|
|
4
4
|
`).map(t=>t.trim()).filter(t=>t!==""&&!t.startsWith("#"));return["# ARGUS view: run these lines in the ARGUS console to see what I see",cE,...e].join(`
|
|
@@ -88,9 +88,9 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
88
88
|
<span class="argus-progress-label"></span>
|
|
89
89
|
<span class="argus-progress-elapsed"></span>`,this.region.appendChild(n);const r={element:n,labelElement:n.querySelector(".argus-progress-label"),barFill:n.querySelector(".argus-progress-fill"),startedAt:performance.now()};return this.rows.set(e,r),r}row_paint(e,t){const i=t.label??t.operation,n=t.current!==void 0&&t.total!==void 0&&t.total>0?` ${g0(t.current,t.unit)}/${g0(t.total,t.unit)}`:"";if(e.labelElement.innerHTML=`${m0(i)}<span class="argus-progress-counts">${m0(n)}</span>`,e.barFill!==null){const r=t.percent??(t.current!==void 0&&t.total!==void 0&&t.total>0?t.current/t.total*100:0);e.barFill.style.width=`${Math.max(0,Math.min(100,r))}%`}}row_remove(e){const t=this.rows.get(e);t!==void 0&&(t.element.remove(),this.rows.delete(e),this.rows.size===0&&this.elapsedTimer!==null&&(clearInterval(this.elapsedTimer),this.elapsedTimer=null))}elapsed_ensure(){this.elapsedTimer===null&&(this.elapsed_paint(),this.elapsedTimer=window.setInterval(()=>this.elapsed_paint(),R2))}elapsed_paint(){const e=performance.now();for(const t of this.rows.values()){const i=t.element.querySelector(".argus-progress-elapsed");i!==null&&(i.textContent=`${((e-t.startedAt)/1e3).toFixed(1)}s`)}}}function i_(s){return/\dfr\b/.test(s)}function _0(s){const e=s.trim().match(/^minmax\(\s*([^,]+?)\s*,/);return e!==null?(e[1]??"3em").trim():"3em"}const md="argus.columns";function Ru(){try{const s=globalThis.localStorage;return s===void 0?null:(s.getItem(`${md}.probe`),s)}catch{return null}}function N2(s,e,t){const i=new Map;if(s===null)return i;for(const n of t)try{const r=s.getItem(`${md}.${e}.${n}`),o=r===null?Number.NaN:Number(r);Number.isFinite(o)&&o>0&&i.set(n,Math.round(o))}catch{}return i}function B2(s,e,t,i){if(s!==null)try{i===null?s.removeItem(`${md}.${e}.${t}`):s.setItem(`${md}.${e}.${t}`,String(Math.round(i)))}catch{}}function G2(s){const e=getComputedStyle(s);return s.getBoundingClientRect().width+(Number.parseFloat(e.marginLeft)||0)+(Number.parseFloat(e.marginRight)||0)}function P2(s,e,t,i=0,n=!1){if(n&&!s.expanse){const c=t>=0?t:Math.min(0,Math.max(s.floor-s.width,t));return c===0?{left:null,right:null,moved:c}:{left:Math.round(s.width+c),right:null,moved:c}}let r,o;const a=c=>t>=0?Math.max(0,Math.min(o,c)):Math.min(0,Math.max(r,c));if(e===null){r=s.floor-s.width,o=i;const c=a(t);return{left:Math.round(s.width+c),right:null,moved:c}}if(s.expanse){r=s.floor-s.width,o=e.width-e.floor;const c=a(t);return c===0?{left:null,right:null,moved:c}:{left:null,right:Math.round(e.width-c),moved:c}}if(e.expanse){r=s.floor-s.width,o=e.width-e.floor;const c=a(t);return{left:Math.round(s.width+c),right:null,moved:c}}r=s.floor-s.width,o=e.width-e.floor;const l=a(t);return l===0?{left:null,right:null,moved:l}:{left:Math.round(s.width+l),right:Math.round(e.width-l),moved:l}}const L2="roster-grip";function W2(s,e){for(const t of s.querySelectorAll(`.${L2}`)){if(t.dataset.wired==="1")continue;t.dataset.wired="1";const i=t.closest(".roster-cap");if(i===null)continue;t.addEventListener("click",r=>{r.stopPropagation()});const n=()=>{let r=i.nextElementSibling;for(;r!==null&&!r.classList.contains("roster-cap");)r=r.nextElementSibling;if(!(r instanceof HTMLElement))return null;const o=e.key_read(r);return o===null?null:{cap:r,key:o}};t.addEventListener("dblclick",r=>{r.stopPropagation();const o=e.key_read(i),a=n();o!==null&&e.reset(o),a!==null&&e.reset(a.key)}),t.addEventListener("pointerdown",r=>{const o=e.key_read(i);if(o===null||r.button!==0)return;r.preventDefault(),r.stopPropagation();try{t.setPointerCapture(r.pointerId)}catch{}const a=r.clientX,l=(g,m)=>{const w=G2(g),y=e.floor_measure(m);return{width:w,floor:y,expanse:e.expanse_is(m)&&w>y+1}},c=l(i,o),h=n(),d=h===null?null:l(h.cap,h.key);if(c.expanse&&d===null)return;const u=e.expanseSlack(),p=s.scrollWidth>s.clientWidth+1;s.classList.add("roster-sizing");const f=g=>{const m=P2(c,d,g.clientX-a,u,p);m.left!==null&&e.size(o,m.left),m.right!==null&&h!==null&&e.size(h.key,m.right)},_=()=>{s.classList.remove("roster-sizing"),window.removeEventListener("pointermove",f),window.removeEventListener("pointerup",_),window.removeEventListener("pointercancel",_)};window.addEventListener("pointermove",f),window.addEventListener("pointerup",_),window.addEventListener("pointercancel",_)})}}function b0(s,e){const t=s.trim().match(/^([\d.]+)\s*(px|em|rem)$/);if(t===null)return 0;const i=Number(t[1]);if(t[2]==="px")return i;const n=t[2]==="rem"?document.documentElement:e,r=Number.parseFloat(getComputedStyle(n).fontSize)||16;return i*r}class F2{root;capsRows=[];strip;input;columns;value_of;onChange;leadingCells;terms;state={sortKey:null,sortDir:"asc",filter:""};changeQueued=!1;change_emit(){this.changeQueued||(this.changeQueued=!0,window.requestAnimationFrame(()=>{this.changeQueued=!1,this.onChange()}))}host_prepare(e){this.root.parentElement!==e&&e.prepend(this.root);for(const t of[...e.children])t!==this.root&&t.remove()}shown=0;total=0;constructor(e,t,i,n,r=0,o=!0,a=[]){this.terms=a,this.columns=e,this.value_of=t,this.onChange=i,n!==void 0&&(this.state={...this.state,sortKey:n.key,sortDir:n.dir}),this.leadingCells=r,this.root=document.createElement("div"),this.root.className="roster-order",this.strip=document.createElement("div"),this.strip.className="roster-filter",this.strip.hidden=!0;const l=document.createElement("span");l.className="roster-filter-glyph",l.textContent="FILTER :",this.input=document.createElement("input"),this.input.className="roster-filter-input",this.input.placeholder="text, or column:text (e.g. owner:<user> status:error)",this.input.setAttribute("autocomplete","off"),this.input.addEventListener("input",()=>this.filter_set(this.input.value,!1)),this.input.addEventListener("keydown",c=>{c.key==="Escape"&&(c.stopPropagation(),this.strip_toggle(!1))}),this.strip.append(l,this.input),o&&this.root.appendChild(this.caps_mint()),this.root.appendChild(this.strip),this.caps_paint()}caps_mint(){const e=document.createElement("div");e.className="roster-caps";for(let t=0;t<this.leadingCells;t++)e.appendChild(document.createElement("span"));for(const t of this.columns){const i=document.createElement("button");if(i.className="roster-cap",i.dataset.key=t.key,i.title=`sort by ${t.label.toLowerCase()} (again to reverse)`,i.addEventListener("click",()=>this.sort_toggle(t.key)),t!==this.columns[this.columns.length-1]){const n=document.createElement("span");n.className="roster-grip",n.title="drag to size the column; press twice to give it back",i.appendChild(n)}e.appendChild(i)}return this.capsRows.push(e),this.caps_paint(),e}state_get(){return{...this.state}}sort_toggle(e){this.state.sortKey===e?this.sort_set(e,this.state.sortDir==="asc"?"desc":"asc"):this.sort_set(e,"asc")}sort_set(e,t){this.columns.some(i=>i.key===e)&&(this.state={...this.state,sortKey:e,sortDir:t},this.caps_paint(),this.change_emit())}onFilter=null;filterChange_observe(e){this.onFilter=e}filterText_get(){return this.state.filter}filter_set(e,t=!0){this.state={...this.state,filter:e},this.onFilter?.(e),t&&(this.input.value=e),e.length>0&&this.strip.hidden&&(this.strip.hidden=!1,this.onStrip?.()),this.change_emit()}strip_toggle(e){const t=e??this.strip.hidden;this.strip.hidden=!t,t?this.input.focus():this.state.filter.length>0&&this.filter_set(""),this.onStrip?.()}strip_isOpen(){return!this.strip.hidden}onStrip=null;stripChange_observe(e){this.onStrip=e}matches(e){return this.terms_parse().every(t=>{const i=t.key===null?void 0:this.terms.find(r=>r.key===t.key);return(i!==void 0?i.value(e).toLowerCase():t.key!==null?String(this.value_of(e,t.key)).toLowerCase():[...this.columns.map(r=>String(this.value_of(e,r.key))),...this.terms.map(r=>r.value(e))].join(" ").toLowerCase()).includes(t.text)})}sorted(e){const t=[...e],i=this.state.sortKey;if(i===null)return t;const n=this.state.sortDir==="asc"?1:-1;return t.sort((r,o)=>{const a=this.value_of(r,i),l=this.value_of(o,i);return typeof a=="number"&&typeof l=="number"?(a-l)*n:String(a).localeCompare(String(l),void 0,{numeric:!0,sensitivity:"base"})*n}),t}counts_set(e,t){this.shown=e,this.total=t}terms_parse(){return this.state.filter.toLowerCase().split(/\s+/).filter(e=>e.length>0).map(e=>{const t=e.indexOf(":");if(t>0){const i=e.slice(0,t);if(this.columns.some(n=>n.key===i)||this.terms.some(n=>n.key===i))return{key:i,text:e.slice(t+1)}}return{key:null,text:e}})}apply(e){const t=this.sorted(e.filter(i=>this.matches(i)));return this.shown=t.length,this.total=e.length,t}summary(){const e=[];return this.state.filter.length>0&&e.push(`FILTERED ${this.shown}/${this.total}`),e.join(" · ")}caps_paint(){const e=this.capsRows.filter(t=>t.parentElement===null||t.isConnected);this.capsRows.length=0,this.capsRows.push(...e);for(const t of this.capsRows)for(const i of t.querySelectorAll(".roster-cap")){const n=i.dataset.key??"",r=this.columns.find(l=>l.key===n),o=n===this.state.sortKey;i.classList.toggle("roster-active",o);let a=i.querySelector(".roster-cap-words");a===null&&(a=document.createElement("span"),a.className="roster-cap-words",i.prepend(a)),a.textContent=`${r?.label??n}${o?this.state.sortDir==="asc"?" ▲":" ▼":""}`}}}const U2=["state-live","state-settled","state-stale","state-wait","state-note","state-refused"];function Ts(s,e,t){s!==null&&(s.classList.remove(...U2),e!==null&&s.classList.add(`state-${e}`),t!==void 0&&(s.textContent=t))}function fa(s,e){s?.classList.remove(`state-${e}`)}function $2(s,e,t){s?.classList.toggle(`state-${e}`,t)}class j2{container;order;field=null;constructor(e,t){this.container=e,this.order=t}field_open(){this.order.host_prepare(this.container);const e=document.createElement("div");return e.className="listing-field",this.container.appendChild(e),this.field=e,ai(e,{rows:".listing-row"}),e}field_get(){return this.field}}function H2(s){return s.map(e=>({key:e.key,label:e.label}))}function V2(s){const e=new Map(s.map(t=>[t.key,t]));return(t,i)=>{const n=e.get(i);if(n===void 0)return"";if(n.compare!==void 0)return n.compare(t);const r=n.cell(t);return r instanceof Node?r.textContent??"":r==null?"":String(r)}}function q2(s,e,t){const i=document.createElement("div");i.className=t.className(s);for(const n of t.leading?.(s)??[])i.appendChild(n);for(const n of e){const r=n.cell(s);if(r instanceof Node){i.appendChild(r);continue}const o=document.createElement("span");o.className=n.className,o.textContent=r==null?"":String(r),i.appendChild(o)}return t.decorate?.(i,s),i}function zc(s){let e=0,t=0,i=!1;for(const n of s)e+=n.done,t+=n.total,i=i||n.failed===!0;return{done:e,total:t,...i?{failed:!0}:{}}}function gd(s){const e=document.createElement("span");if(e.className="listing-progress",s===null||s.total===0)return e.classList.add("listing-progress-idle"),e.title=s===null?"no work":"nothing scheduled yet",e;const t=s.failed===!0,i=s.done>=s.total,n=t&&s.succeeded!==void 0?s.succeeded:s.done,r=Math.min(1,Math.max(0,n/s.total));e.classList.add(t?"listing-progress-failed":i?"listing-progress-done":"listing-progress-running"),e.title=t&&s.succeeded!==void 0?`${s.succeeded}/${s.total} succeeded — errored`:`${s.done}/${s.total}`;const o=document.createElement("span");return o.className="listing-progress-fill",o.style.width=`${Math.round(r*100)}%`,e.appendChild(o),e}function Dh(s,e){const t=document.createElement("span");t.className="listing-actions";for(const i of e){if(i.offered!==void 0&&!i.offered(s))continue;const n=document.createElement("button");n.className="listing-action",n.textContent=i.label,i.disabled?.(s)===!0&&(n.disabled=!0),i.selected?.(s)===!0&&n.classList.add("listing-action-selected"),n.addEventListener("click",r=>{r.stopPropagation(),i.run(s)}),t.appendChild(n)}return t}function K2(s,e){return s.mode==="fold"&&s.open.has(e)}function Y2(s,e){return s.mode!=="fold"||s.open.delete(e)?!1:(s.open.add(e),!0)}function M0(s){const e=s.trim();if(/^(auto|min-content|max-content)$/.test(e)||/^fit-content\(/.test(e))return!1;const t=/^minmax\(\s*([^,]+?)\s*,\s*([^)]+?)\s*\)$/.exec(e);if(t!==null){const i=t[1]??"";return/^(?:[1-9]\d*|0*\.\d*[1-9]\d*|[1-9]\d*\.\d+)(px|em|rem|ch|vw|vh|%)$/.test(i)}return/^(?:\d+\.?\d*|\.\d+)(px|em|rem|ch|vw|vh|%|fr)$/.test(e)}function X2(s){let e=0;for(const t of s){if(t.capped!==!1)break;e+=1}return e}function ma(s,e){return{level_visit(t){return t(s,e)}}}function xc(s,e,t){const i=[];let n=!1;for(const r of s){if(r.width===void 0||r.width.trim()==="")throw new Error(`listing trait '${r.key}' declares no width`);if(!M0(r.width))throw new Error(`listing trait '${r.key}' declares a content-sized track '${r.width.trim()}': a row is its own grid, so a track sized to its content sizes per row and jogs every column after it`);if(r.capped===!1){if(n)throw new Error(`uncapped listing trait '${r.key}' must lead the traits`)}else n=!0;const o=t?.get(r.key);o===void 0?i.push(r.width.trim()):i.push(i_(r.width)?`minmax(${o}px, 1fr)`:`${o}px`)}if(e!==void 0){if(e.width===void 0||e.width.trim()==="")throw new Error("listing actions on the row declare no track; declare a width, or a row zone for the verbs to ride");if(!M0(e.width))throw new Error(`listing actions declare a content-sized track '${e.width.trim()}'`);i.push(e.width.trim())}return i.join(" ")}let Pl=new Map,Ih=new Map;function Z2(s){if(Pl=new Map,Ih=new Map,s!==null)for(const e of s.handles)Pl.has(e.address)||Pl.set(e.address,e),Ih.set(e.kind,Math.max(Ih.get(e.kind)??0,`${e.ordinal}`.length));wz()}function vz(s){const e=Math.max(3,Ih.get(s.kind)??0);return`${s.kind}${`${s.ordinal}`.padStart(e,"0")}`}function wz(){const s=new Map;for(const e of document.querySelectorAll(".listing-index")){const t=e.closest(".listing-row"),i=t?.parentElement??null;if(t===null||i===null)continue;if(t.classList.contains("listing-lead")){e.textContent="",e.classList.remove("numbered");continue}const r=i.classList.contains("listing-rows")&&i.parentElement?.classList.contains("listing-block")===!0?i.closest(".listing-field")??i:i,o=s.get(r);o===void 0?s.set(r,[t]):o.push(t)}for(const e of s.values()){const t=`${Math.max(e.length,1)}`.length;e.forEach((i,n)=>{const r=i.querySelector(".listing-index");if(r===null)return;const o=r.dataset.address,a=o===void 0?void 0:Pl.get(o);r.textContent=a===void 0?`${n+1}`.padStart(t,"0"):vz(a),r.classList.toggle("numbered",a!==void 0)})}}function J2(s){return{key:"index",label:"",className:"listing-index-cell",width:"5.2rem",capped:!1,cell:e=>{const t=document.createElement("span");t.className="listing-index";const i=s?.(e);i!==void 0&&(t.dataset.address=i);const n=i===void 0?void 0:Pl.get(i);return n!==void 0&&(t.textContent=vz(n),t.classList.add("numbered")),t}}}class n_{declaration;host;select;order;template;child;expansion;rowsByKey=new Map;dataByKey=new Map;cellsByKey=new Map;leadKeys=new Set;indicated=null;depth;constructor(e,t,i,n,r=0){e={...e,traits:[J2(e.address),...e.traits]},this.declaration=e,this.host=t,this.select=n,this.depth=r,this.template=xc(e.traits,this.trackActions_get(),this.sized);const o=e.traits.filter(a=>a.capped!==!1);if(this.order=new F2(H2(o),V2(e.traits),()=>this.host.repaint(),e.defaultSort,X2(e.traits),i,e.terms??[]),this.expansion={mode:e.child===void 0?"replace":"fold",open:new Set},this.child=e.child===void 0?null:this.childSeat_build(e.child),this.child!==null){const a=this.child;this.order.filterChange_observe(l=>a.filter_set(l))}}childSeat_build(e){return e.level_visit((t,i)=>{const n=new n_(i,this.host,!1,null,this.depth+1);return{filter_set:r=>n.filter_set(r),sort_set:(r,o)=>n.sort_set(r,o),survives:r=>n.anyMatch(t(r)),render:(r,o,a)=>{const l=document.createElement("div");l.className="listing-level",l.dataset.depth=String(this.depth+1),l.style.setProperty("--roster-cols",n.template),l.appendChild(n.order.caps_mint()),n.rows_draw(t(r),[],l,a),o.appendChild(l)},forget:()=>n.forget(),open_set:(r,o)=>n.open_set(r,o),open_clear:()=>n.open_clear(),template_select:r=>n.template_select(r)}})}actions_set(e){this.declaration={...this.declaration,...e===null?{actions:void 0}:{actions:e}},this.template=xc(this.traits_shown(),this.trackActions_get(),this.sized)}shed=new Set;traits_shown(){return this.shed.size===0?this.declaration.traits:this.declaration.traits.filter(e=>!this.shed.has(e.key))}shed_set(e){this.shed.clear();for(const t of e)this.shed.add(t);this.template=xc(this.traits_shown(),this.trackActions_get(),this.sized)}shedOrder(){return this.declaration.traits.filter(e=>e.shed!==void 0).sort((e,t)=>e.shed-t.shed).map(e=>e.key)}label_find(e){return this.declaration.traits.find(t=>t.key===e)?.label??e}sized=new Map;column_size(e,t){t===null?this.sized.delete(e):this.sized.set(e,t),this.template=xc(this.traits_shown(),this.trackActions_get(),this.sized)}track_find(e){return this.declaration.traits.find(t=>t.key===e)?.width??null}traitKeys(){return this.declaration.traits.map(e=>e.key)}expanse_find(){const e=this.declaration.traits.find(t=>i_(t.width??""));return e===void 0?null:{key:e.key,width:e.width??""}}trackActions_get(){return this.host.framed()?void 0:this.declaration.actions}filter_set(e){this.order.filter_set(e,!1)}sort_set(e,t){this.order.sort_set(e,t),this.child?.sort_set(e,t)}open_set(e,t){if(e===0){if(this.expansion.open.clear(),this.expansion.mode==="fold")for(const i of t)this.expansion.open.add(i);return}this.child?.open_set(e-1,t)}open_clear(){this.expansion.open.clear(),this.child?.open_clear()}template_select(e){if(e===0)return this.template;if(this.child===null)throw new Error(`no listing level at depth ${this.depth+e}`);return this.child.template_select(e-1)}anyMatch(e){return e.some(t=>this.order.matches(t)||(this.child?.survives(t)??!1))}filter_isEmpty(){return this.order.state_get().filter.length===0}rows_keep(e,t){const i=t?[...e]:e.filter(n=>this.order.matches(n)||(this.child?.survives(n)??!1));return this.order.sorted(i)}forget(){this.rowsByKey.clear(),this.dataByKey.clear(),this.cellsByKey.clear(),this.leadKeys.clear(),this.indicated=null,this.child?.forget()}rows_draw(e,t,i,n){for(const o of t)i.appendChild(this.row_build(o,!0));const r=this.rows_keep(e,n);for(const o of r){const a=this.row_build(o,!1);if(this.child===null){i.appendChild(a);continue}const l=this.declaration.key(o),c=this.order.filterText_get()!==""&&!this.order.matches(o)&&(this.child?.survives(o)??!1),h=K2(this.expansion,l)||c,d=document.createElement("div"),u=this.declaration.row?.groupClassName?.(o);d.className=`listing-group${h?" listing-open":""}${u===void 0||u===""?"":` ${u}`}`,d.appendChild(a),h&&(a.classList.add("listing-open"),this.child.render(o,d,n||this.order.matches(o))),i.appendChild(d)}return r.length}row_build(e,t){const i=this.declaration,n=i.key(e),r=this.host.framed(),o=q2(e,this.traits_shown(),{className:h=>{const d=i.row?.className?.(h);return d===void 0||d===""?"listing-row":`listing-row ${d}`},decorate:(h,d)=>{if(h.dataset.key=n,i.actions!==void 0&&!r){const u=document.createElement("span");u.className="listing-actions",!t&&i.actions.always===!0&&u.replaceChildren(...Dh(d,i.actions.of(d)).childNodes),h.appendChild(u),this.cellsByKey.set(n,u)}i.row?.decorate?.(h,d)}});if(this.rowsByKey.set(n,o),this.dataByKey.set(n,e),t&&(this.leadKeys.add(n),o.classList.add("listing-lead")),i.activatable?.(e)===!1)return o;o.classList.add("listing-activatable");const a=i.actions!==void 0&&i.actions.always!==!0&&i.actions.of(e).length>0,l=!t&&this.child!==null,c=this.controlCell_find(o);return o.addEventListener("click",h=>{if(!(!t&&this.select!==null&&this.select(n,e))){if(c!==null&&h.target instanceof Node&&c.contains(h.target)){l||this.row_indicate(null),this.row_activate(e,n,t);return}if(!a){this.row_activate(e,n,t);return}this.row_indicate(n),l&&c===null&&this.row_activate(e,n,!1)}}),a&&!l&&o.addEventListener("dblclick",()=>{this.row_indicate(null),this.row_activate(e,n,t)}),o}controlCell_find(e){const t=this.declaration.control;if(t===void 0)return null;const i=this.declaration.traits.findIndex(r=>r.key===t);if(i<0)throw new Error(`listing level declares control '${t}', which names no trait`);const n=e.children[i];return n instanceof HTMLElement?(n.classList.add("listing-control"),n):null}row_activate(e,t,i){if(!i&&this.child!==null){Y2(this.expansion,t),this.host.repaint(),this.declaration.activate?.(e);return}this.host.activating_is(t)||(this.host.activation_begin(t,this.rowsByKey.get(t)??null,e7(t)),this.declaration.activate?.(e))}row_indicate(e,t=!1){const i=this.host.framed();if(this.indication_drop(),e===null){this.host.indication_release(this);return}const n=this.dataByKey.get(e),r=this.rowsByKey.get(e);if(n===void 0||r===void 0){this.host.indication_release(this);return}this.indicated=e,r.classList.add("listing-indicated");const o=this.declaration.actions?.of(n)??[];if(this.host.indication_claim({level:this,key:e,drop:()=>this.indication_drop(),restore:()=>this.rowsByKey.has(e)?(this.row_indicate(e,!0),!0):!1}),i)this.host.zoneVerbs_set([...Dh(n,o).childNodes]);else{const a=this.cellsByKey.get(e);a!==void 0&&o.length>0&&a.replaceChildren(...Dh(n,o).childNodes)}t||this.declaration.indicated?.(n)}indication_drop(){this.indicated!==null&&(this.cellsByKey.get(this.indicated)?.replaceChildren(),this.rowsByKey.get(this.indicated)?.classList.remove("listing-indicated"),this.indicated=null)}indicated_get(){return this.indicated}readout_show(e,t){if(this.indicated!==e)return;if(this.host.framed()){this.host.zoneReadout_set(t);return}const i=this.cellsByKey.get(e);if(i===void 0)return;const n=document.createElement("span");n.className="listing-readout",n.append(t),i.querySelector(".listing-readout")?.remove(),i.appendChild(n)}row_element(e){return this.rowsByKey.get(e)??null}keysOnStage_list(){return[...this.rowsByKey.keys()].filter(e=>!this.leadKeys.has(e))}}class sr{declaration;level;host;gridHost;stateSpan;activating=null;filterBlock;selectBlock;zone;wired=!1;zonePane_get(){return this.zone?.closest(".workspace-pane, [data-frame-host]")??null}zoneOpened=!1;claim=null;blocks=[];field=null;painter=null;selecting=!1;selection=new Map;repaintQueued=!1;constructor(e){if(this.declaration=e,this.gridHost=e.gridHost??e.mount,this.zone=e.rowZone??Q2(e.mount,e.chrome?.prefix),e.selection!==void 0&&this.zone===null)throw new Error("a listing that selects declares a row zone: a selection's verbs ride the frame");this.level=new n_(e,{repaint:()=>this.repaint_queue(),framed:()=>this.zone!==null,activating_is:i=>this.activating?.key===i,activation_begin:(i,n,r)=>this.activation_begin(i,n,r),zoneVerbs_set:i=>this.zoneVerbs_set(i),zoneReadout_set:i=>this.zoneReadout_set(i),indication_claim:i=>{this.claim!==null&&this.claim.level!==i.level&&this.claim.drop(),this.claim=i},indication_release:i=>{this.claim===null||this.claim.level!==i||(this.claim=null,this.zoneVerbs_set([]))}},e.caps!=="each",e.selection===void 0?null:(i,n)=>this.selection_gather(i,n)),this.host=new j2(e.mount,this.level.order),this.gridHost.style.setProperty("--roster-cols",this.level.template),this.zone!==null&&(this.zone.classList.add("listing-zone"),this.zone.hidden=!0,e.mount.classList.add("listing-framed"),this.zone_wire());const t=e.chrome;this.stateSpan=t?.root.querySelector(".pane-state")??null,this.filterBlock=t?.root.querySelector(`.${t.prefix}-filter`)??null,this.selectBlock=t?.root.querySelector(`.${t.prefix}-select`)??null,this.filterBlock?.classList.add("rail-off"),this.filterBlock?.addEventListener("click",()=>this.filter_toggle()),t?.root.querySelector(`.${t.prefix}-refresh`)?.addEventListener("click",()=>this.declaration.refresh?.()),this.columns_wire(t),this.level.order.stripChange_observe(()=>this.filterBlock_sync()),this.selectBlock?.addEventListener("click",()=>this.select_toggle()),t?.root.addEventListener("argus:roster",i=>{const n=i.detail;n.op==="sort"?this.level.sort_set(n.key,n.dir??"asc"):n.text===""?this.level.order.strip_toggle(!1):this.level.order.filter_set(n.text)}),this.filterBlock_sync()}rows_set(e,t){this.field!==null&&t.field!==this.field&&(this.selection.clear(),this.claim?.drop(),this.claim=null),this.field=t.field,this.blocks=e,this.activation_settle(),this.render(),this.grips_ensure()}activation_begin(e,t,i){this.activating?.element?.classList.remove("listing-activating"),this.activating={key:e,element:t},t?.classList.add("listing-activating"),Ts(this.stateSpan,"wait",`OPENING ${i}`)}activation_settle(){this.activating!==null&&(this.activating.element?.classList.remove("listing-activating"),this.activating=null,fa(this.stateSpan,"wait"))}activation_refuse(e){this.activating!==null&&(this.activation_settle(),Ts(this.stateSpan,"refused",e.toUpperCase()))}activating_get(){return this.activating?.key??null}repaint_queue(){this.repaintQueued||(this.repaintQueued=!0,window.requestAnimationFrame(()=>{this.repaintQueued=!1,this.render()}))}render(){this.level.forget();const e=this.host.field_open(),t=this.level.filter_isEmpty();let i=0,n=0;const r=this.blocks.reduce((o,a)=>o+a.rows.length,0);this.blocks.length>0&&r===0&&this.declaration.empty!==void 0&&e.appendChild(this.declaration.empty());for(const o of this.blocks){const a=document.createElement("section");if(a.className="listing-block",a.dataset.key=o.key,o.header!==void 0&&a.appendChild(o.header),this.declaration.caps==="each"&&a.appendChild(this.level.order.caps_mint()),n+=o.rows.length,this.painter!==null){const l=this.level.rows_keep(o.rows,t);i+=l.length,this.painter({...o,rows:l},a)}else{const l=document.createElement("div");l.className="listing-rows",i+=this.level.rows_draw(o.rows,o.lead??[],l,t),a.appendChild(l)}e.appendChild(a)}!t&&r>0&&i===0&&this.declaration.filteredEmpty!==void 0&&e.appendChild(this.declaration.filteredEmpty(this.level.order.filterText_get())),this.level.order.counts_set(i,n),wz(),this.claim!==null&&!this.claim.restore()&&(this.claim=null,this.zoneVerbs_set([])),this.selection_render(),this.state_render(),this.shed_fit()}shedObserver=null;shedWidth=-1;shed_fit(e=!1){const t=this.level.shedOrder();if(t.length===0)return;this.shedObserver===null&&typeof ResizeObserver<"u"&&(this.shedObserver=new ResizeObserver(()=>this.shed_fit()),this.shedObserver.observe(this.gridHost));const i=this.declaration.mount.querySelector(".roster-order .roster-caps")??this.declaration.mount.querySelector(".roster-caps");if(i===null||i.clientWidth===0)return;const n=i.clientWidth;if(!e&&n===this.shedWidth){for(const c of i.querySelectorAll(".roster-cap"))c.hidden=this.level.shed.has(c.dataset.key??"");return}this.shedWidth=n;const r=[...this.level.shed].join(","),o=c=>{this.level.shed_set(c),this.gridHost.style.setProperty("--roster-cols",this.level.template);for(const h of i.querySelectorAll(".roster-cap"))h.hidden=this.level.shed.has(h.dataset.key??"");return i.scrollWidth<=i.clientWidth+1};let a=[],l=o(a);for(const c of t){if(l)break;a=[...a,c],l=o(a)}a.join(",")!==r&&(this.columnsBlock_paint(),this.field!==null&&this.render())}row_indicate(e){if(e===null){this.claim?.drop();const t=this.claim;this.claim=null,t!==null&&this.zoneVerbs_set([]);return}this.level.row_indicate(e)}indicated_get(){return this.claim?.key??null}indication_refresh(){this.claim!==null&&(this.claim.restore()||(this.claim=null,this.zoneVerbs_set([])))}readout_show(e,t){this.level.readout_show(e,t)}row_element(e){return this.level.row_element(e)}template_get(e=0){return this.level.template_select(e)}field_get(){return this.host.field_get()}open_set(e,t){this.level.open_set(e,t),this.field!==null&&this.render()}open_clear(){this.level.open_clear()}painter_set(e){this.painter=e}actions_declare(e){this.level.actions_set(e),this.gridHost.style.setProperty("--roster-cols",this.level.template),this.field!==null&&this.render()}columnsBlock=null;columnsPrefix=null;columns_wire(e){if(this.columnsPrefix=e?.prefix??null,this.columnsBlock=e?.root.querySelector(`.${e.prefix}-columns`)??null,this.columnsBlock?.addEventListener("click",()=>this.columns_reset()),this.columnsPrefix!==null){for(const[t,i]of N2(Ru(),this.columnsPrefix,this.level.traitKeys()))this.level.column_size(t,i);this.gridHost.style.setProperty("--roster-cols",this.level.template)}this.columnsBlock_paint(),this.grips_ensure()}grips_ensure(){const e=this.declaration.mount.querySelector(".roster-order .roster-caps");if(e===null)return;const t=Ru();W2(e,{key_read:i=>i.dataset.key??null,expanse_is:i=>i_(this.level.track_find(i)??""),floor_measure:i=>b0(_0(this.level.track_find(i)??"3em"),e),expanseSlack:()=>{const i=this.level.expanse_find(),n=i===null?null:e.querySelector(`.roster-cap[data-key="${i.key}"]`);return n===null||i===null?0:Math.max(0,n.getBoundingClientRect().width-b0(_0(i.width),e))},size:(i,n)=>this.column_size(i,n,t),reset:i=>this.column_size(i,null,t)})}column_size(e,t,i){this.level.column_size(e,t),this.gridHost.style.setProperty("--roster-cols",this.level.template),this.columnsPrefix!==null&&B2(i,this.columnsPrefix,e,t),this.columnsBlock_paint()}columns_reset(){const e=Ru();for(const t of[...this.level.sized.keys()])this.column_size(t,null,e)}columns_sized(){return[...this.level.sized.keys()]}columnsBlock_paint(){if(this.columnsBlock===null)return;const e=this.level.sized.size>0,t=[...this.level.shed].map(i=>this.level.label_find(i));this.columnsBlock.textContent=`COLUMNS${e?" · SIZED":""}${t.length>0?` · ${t.length} HIDDEN`:""}`,this.columnsBlock.classList.toggle("rail-off",!e&&t.length===0),this.columnsBlock.title=`${e?"columns sized by hand; press to give them all back":"drag a cap's edge to size its column; a double-press gives one back"}${t.length>0?`. Hidden for want of room: ${t.join(", ")} (a wider pane brings them back)`:""}`}filter_toggle(e){this.level.order.strip_toggle(e)}filter_set(e){this.level.order.filter_set(e)}filterText_get(){return this.level.order.filterText_get()}filterBlock_sync(){if(this.filterBlock===null)return;const e=this.level.order.strip_isOpen();this.filterBlock.textContent=e?"FILTER ON":"FILTER OFF",this.filterBlock.classList.toggle("rail-off",!e)}select_toggle(e){this.declaration.selection!==void 0&&(this.selecting=e??!this.selecting,this.zoneOpened=!1,this.claim!==null&&this.row_indicate(null),this.declaration.mount.classList.toggle("listing-selecting",this.selecting),this.selectBlock?.classList.toggle("rail-off",!this.selecting),this.selectBlock!==null&&(this.selectBlock.textContent=this.selecting?"SELECT ON":"SELECT OFF"),this.selection_render(),this.state_render())}select_isOn(){return this.selecting}selection_get(){return[...this.selection.keys()]}selection_gather(e,t){return this.selecting?(this.selection.has(e)?this.selection.delete(e):this.selection.set(e,t),this.selection_render(),this.state_render(),!0):!1}selection_render(){for(const i of this.level.keysOnStage_list())this.level.row_element(i)?.classList.toggle("listing-selected",this.selection.has(i));if(this.zone===null)return;if(!this.selecting){this.claim===null&&this.zoneVerbs_set([]);return}const e=[...this.selection.entries()],t=e.length>0?this.declaration.selection?.verbs(e)??[]:[];this.zoneVerbs_set(t.length===0?[]:[...Dh(void 0,t).childNodes])}zone_wire(){const e=this.zone,t=this.zonePane_get();if(e===null||t===null||this.wired)return;this.wired=!0,e.closest(".mode-frame")?.addEventListener("click",n=>{n.target instanceof Node&&e.contains(n.target)||(this.zoneOpened=!1)},!0),new MutationObserver(()=>{t.dataset.modes!=="open"&&(this.zoneOpened=!1,this.claim!==null&&this.row_indicate(null))}).observe(t,{attributes:!0,attributeFilter:["data-modes"]})}zoneVerbs_set(e){const t=this.zone;if(t===null)return;t.replaceChildren(...e),t.hidden=e.length===0,this.wired||this.zone_wire();const i=this.zonePane_get();if(i!==null){if(e.length>0){i.dataset.modes!=="open"&&(i.dataset.modes="open",this.zoneOpened=!0);return}this.zoneOpened&&(this.zoneOpened=!1,delete i.dataset.modes)}}zoneReadout_set(e){const t=this.zone;if(t===null)return;t.querySelector(".listing-readout")?.remove();const i=document.createElement("span");i.className="listing-readout",i.append(e),t.appendChild(i),t.hidden=!1}selectionShown_count(){let e=0;for(const t of this.selection.keys())this.level.row_element(t)!==null&&(e+=1);return e}state_refresh(){this.state_render()}state_render(){if(this.stateSpan===null)return;const e={filter:this.level.order.summary(),selecting:this.selecting,selected:this.selection.size,shown:this.selectionShown_count(),shed:this.level.shed.size},t=this.declaration.state!==void 0?this.declaration.state(e):t7(e);t!==null&&(this.stateSpan.textContent=t)}}function Q2(s,e){const t=s.parentElement?.querySelector(":scope > .mode-frame")??null;if(t===null)return null;const i=document.createElement("span");i.className=e===void 0?"listing-zone":`listing-zone ${e}-row-zone`,i.hidden=!0;const n=t.querySelector(":scope > .mode-fill");return n!==null?t.insertBefore(i,n):t.appendChild(i),i}function e7(s){return s.split("/").filter(e=>e!=="").pop()??s}function t7(s){const e=[];return s.selecting&&e.push("SELECT"),s.filter!==""&&e.push(s.filter),(s.shed??0)>0&&e.push(`${s.shed} COLUMN${s.shed===1?"":"S"} HIDDEN`),s.selected>0&&e.push(s.shown===s.selected?`${s.selected} SELECTED`:`${s.selected} SELECTED · ${s.shown} SHOWN`),e.join(" · ")}const s7="modulepreload",i7=function(s,e){return new URL(s,e).href},v0={},Xl=function(e,t,i){let n=Promise.resolve();if(t&&t.length>0){let c=function(h){return Promise.all(h.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};const o=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");n=c(t.map(h=>{if(h=i7(h,i),h in v0)return;v0[h]=!0;const d=h.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(i)for(let f=o.length-1;f>=0;f--){const _=o[f];if(_.href===h&&(!d||_.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${u}`))return;const p=document.createElement("link");if(p.rel=d?"stylesheet":s7,d||(p.as="script"),p.crossOrigin="",p.href=h,l&&p.setAttribute("nonce",l),document.head.appendChild(p),d)return new Promise((f,_)=>{p.addEventListener("load",f),p.addEventListener("error",()=>_(new Error(`Unable to preload CSS for ${h}`)))})}))}function r(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return n.then(o=>{for(const a of o||[])a.status==="rejected"&&r(a.reason);return e().catch(r)})},n7=["single","mpr","3d","slab"],w0=["wl","zoom","pan","length","angle","probe"],Ch=["gray","hot","jet","cool"],yz=[{name:"brain",lower:0,upper:80,modalities:["CT"]},{name:"bone",lower:-500,upper:1300,modalities:["CT"]},{name:"lung",lower:-1400,upper:200,modalities:["CT"]},{name:"soft",lower:-160,upper:240,modalities:["CT"]},{name:"liver",lower:-10,upper:140,modalities:["CT"]}],Bp=/\.(nii|nii\.gz|mgz|mgh)$/i,_d=/\.dcm$/i;function r7(s,e){const t=s.toLowerCase();return yz.find(i=>i.name===t&&(i.modalities.length===0||i.modalities.includes(e.toUpperCase())))}const jr={charge:!0,link:!0,collide:!0,gravity:!1},Lt=.55;function _o(s,e,t){var i,n=1;s==null&&(s=0),e==null&&(e=0),t==null&&(t=0);function r(){var o,a=i.length,l,c=0,h=0,d=0;for(o=0;o<a;++o)l=i[o],c+=l.x||0,h+=l.y||0,d+=l.z||0;for(c=(c/a-s)*n,h=(h/a-e)*n,d=(d/a-t)*n,o=0;o<a;++o)l=i[o],c&&(l.x-=c),h&&(l.y-=h),d&&(l.z-=d)}return r.initialize=function(o){i=o},r.x=function(o){return arguments.length?(s=+o,r):s},r.y=function(o){return arguments.length?(e=+o,r):e},r.z=function(o){return arguments.length?(t=+o,r):t},r.strength=function(o){return arguments.length?(n=+o,r):n},r}function o7(s){const e=+this._x.call(null,s);return Sz(this.cover(e),e,s)}function Sz(s,e,t){if(isNaN(e))return s;var i,n=s._root,r={data:t},o=s._x0,a=s._x1,l,c,h,d,u;if(!n)return s._root=r,s;for(;n.length;)if((h=e>=(l=(o+a)/2))?o=l:a=l,i=n,!(n=n[d=+h]))return i[d]=r,s;if(c=+s._x.call(null,n.data),e===c)return r.next=n,i?i[d]=r:s._root=r,s;do i=i?i[d]=new Array(2):s._root=new Array(2),(h=e>=(l=(o+a)/2))?o=l:a=l;while((d=+h)==(u=+(c>=l)));return i[u]=n,i[d]=r,s}function a7(s){Array.isArray(s)||(s=Array.from(s));const e=s.length,t=new Float64Array(e);let i=1/0,n=-1/0;for(let r=0,o;r<e;++r)isNaN(o=+this._x.call(null,s[r]))||(t[r]=o,o<i&&(i=o),o>n&&(n=o));if(i>n)return this;this.cover(i).cover(n);for(let r=0;r<e;++r)Sz(this,t[r],s[r]);return this}function l7(s){if(isNaN(s=+s))return this;var e=this._x0,t=this._x1;if(isNaN(e))t=(e=Math.floor(s))+1;else{for(var i=t-e||1,n=this._root,r,o;e>s||s>=t;)switch(o=+(s<e),r=new Array(2),r[o]=n,n=r,i*=2,o){case 0:t=e+i;break;case 1:e=t-i;break}this._root&&this._root.length&&(this._root=n)}return this._x0=e,this._x1=t,this}function c7(){var s=[];return this.visit(function(e){if(!e.length)do s.push(e.data);while(e=e.next)}),s}function h7(s){return arguments.length?this.cover(+s[0][0]).cover(+s[1][0]):isNaN(this._x0)?void 0:[[this._x0],[this._x1]]}function Zn(s,e,t){this.node=s,this.x0=e,this.x1=t}function d7(s,e){var t,i=this._x0,n,r,o=this._x1,a=[],l=this._root,c,h;for(l&&a.push(new Zn(l,i,o)),e==null?e=1/0:(i=s-e,o=s+e);c=a.pop();)if(!(!(l=c.node)||(n=c.x0)>o||(r=c.x1)<i))if(l.length){var d=(n+r)/2;a.push(new Zn(l[1],d,r),new Zn(l[0],n,d)),(h=+(s>=d))&&(c=a[a.length-1],a[a.length-1]=a[a.length-1-h],a[a.length-1-h]=c)}else{var u=Math.abs(s-+this._x.call(null,l.data));u<e&&(e=u,i=s-u,o=s+u,t=l.data)}return t}function u7(s){if(isNaN(l=+this._x.call(null,s)))return this;var e,t=this._root,i,n,r,o=this._x0,a=this._x1,l,c,h,d,u;if(!t)return this;if(t.length)for(;;){if((h=l>=(c=(o+a)/2))?o=c:a=c,e=t,!(t=t[d=+h]))return this;if(!t.length)break;e[d+1&1]&&(i=e,u=d)}for(;t.data!==s;)if(n=t,!(t=t.next))return this;return(r=t.next)&&delete t.next,n?(r?n.next=r:delete n.next,this):e?(r?e[d]=r:delete e[d],(t=e[0]||e[1])&&t===(e[1]||e[0])&&!t.length&&(i?i[u]=t:this._root=t),this):(this._root=r,this)}function f7(s){for(var e=0,t=s.length;e<t;++e)this.remove(s[e]);return this}function p7(){return this._root}function m7(){var s=0;return this.visit(function(e){if(!e.length)do++s;while(e=e.next)}),s}function g7(s){var e=[],t,i=this._root,n,r,o;for(i&&e.push(new Zn(i,this._x0,this._x1));t=e.pop();)if(!s(i=t.node,r=t.x0,o=t.x1)&&i.length){var a=(r+o)/2;(n=i[1])&&e.push(new Zn(n,a,o)),(n=i[0])&&e.push(new Zn(n,r,a))}return this}function _7(s){var e=[],t=[],i;for(this._root&&e.push(new Zn(this._root,this._x0,this._x1));i=e.pop();){var n=i.node;if(n.length){var r,o=i.x0,a=i.x1,l=(o+a)/2;(r=n[0])&&e.push(new Zn(r,o,l)),(r=n[1])&&e.push(new Zn(r,l,a))}t.push(i)}for(;i=t.pop();)s(i.node,i.x0,i.x1);return this}function b7(s){return s[0]}function M7(s){return arguments.length?(this._x=s,this):this._x}function r_(s,e){var t=new o_(e??b7,NaN,NaN);return s==null?t:t.addAll(s)}function o_(s,e,t){this._x=s,this._x0=e,this._x1=t,this._root=void 0}function y0(s){for(var e={data:s.data},t=e;s=s.next;)t=t.next={data:s.data};return e}var di=r_.prototype=o_.prototype;di.copy=function(){var s=new o_(this._x,this._x0,this._x1),e=this._root,t,i;if(!e)return s;if(!e.length)return s._root=y0(e),s;for(t=[{source:e,target:s._root=new Array(2)}];e=t.pop();)for(var n=0;n<2;++n)(i=e.source[n])&&(i.length?t.push({source:i,target:e.target[n]=new Array(2)}):e.target[n]=y0(i));return s};di.add=o7;di.addAll=a7;di.cover=l7;di.data=c7;di.extent=h7;di.find=d7;di.remove=u7;di.removeAll=f7;di.root=p7;di.size=m7;di.visit=g7;di.visitAfter=_7;di.x=M7;function v7(s){const e=+this._x.call(null,s),t=+this._y.call(null,s);return zz(this.cover(e,t),e,t,s)}function zz(s,e,t,i){if(isNaN(e)||isNaN(t))return s;var n,r=s._root,o={data:i},a=s._x0,l=s._y0,c=s._x1,h=s._y1,d,u,p,f,_,g,m,w;if(!r)return s._root=o,s;for(;r.length;)if((_=e>=(d=(a+c)/2))?a=d:c=d,(g=t>=(u=(l+h)/2))?l=u:h=u,n=r,!(r=r[m=g<<1|_]))return n[m]=o,s;if(p=+s._x.call(null,r.data),f=+s._y.call(null,r.data),e===p&&t===f)return o.next=r,n?n[m]=o:s._root=o,s;do n=n?n[m]=new Array(4):s._root=new Array(4),(_=e>=(d=(a+c)/2))?a=d:c=d,(g=t>=(u=(l+h)/2))?l=u:h=u;while((m=g<<1|_)===(w=(f>=u)<<1|p>=d));return n[w]=r,n[m]=o,s}function w7(s){var e,t,i=s.length,n,r,o=new Array(i),a=new Array(i),l=1/0,c=1/0,h=-1/0,d=-1/0;for(t=0;t<i;++t)isNaN(n=+this._x.call(null,e=s[t]))||isNaN(r=+this._y.call(null,e))||(o[t]=n,a[t]=r,n<l&&(l=n),n>h&&(h=n),r<c&&(c=r),r>d&&(d=r));if(l>h||c>d)return this;for(this.cover(l,c).cover(h,d),t=0;t<i;++t)zz(this,o[t],a[t],s[t]);return this}function y7(s,e){if(isNaN(s=+s)||isNaN(e=+e))return this;var t=this._x0,i=this._y0,n=this._x1,r=this._y1;if(isNaN(t))n=(t=Math.floor(s))+1,r=(i=Math.floor(e))+1;else{for(var o=n-t||1,a=this._root,l,c;t>s||s>=n||i>e||e>=r;)switch(c=(e<i)<<1|s<t,l=new Array(4),l[c]=a,a=l,o*=2,c){case 0:n=t+o,r=i+o;break;case 1:t=n-o,r=i+o;break;case 2:n=t+o,i=r-o;break;case 3:t=n-o,i=r-o;break}this._root&&this._root.length&&(this._root=a)}return this._x0=t,this._y0=i,this._x1=n,this._y1=r,this}function S7(){var s=[];return this.visit(function(e){if(!e.length)do s.push(e.data);while(e=e.next)}),s}function z7(s){return arguments.length?this.cover(+s[0][0],+s[0][1]).cover(+s[1][0],+s[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]}function Qs(s,e,t,i,n){this.node=s,this.x0=e,this.y0=t,this.x1=i,this.y1=n}function x7(s,e,t){var i,n=this._x0,r=this._y0,o,a,l,c,h=this._x1,d=this._y1,u=[],p=this._root,f,_;for(p&&u.push(new Qs(p,n,r,h,d)),t==null?t=1/0:(n=s-t,r=e-t,h=s+t,d=e+t,t*=t);f=u.pop();)if(!(!(p=f.node)||(o=f.x0)>h||(a=f.y0)>d||(l=f.x1)<n||(c=f.y1)<r))if(p.length){var g=(o+l)/2,m=(a+c)/2;u.push(new Qs(p[3],g,m,l,c),new Qs(p[2],o,m,g,c),new Qs(p[1],g,a,l,m),new Qs(p[0],o,a,g,m)),(_=(e>=m)<<1|s>=g)&&(f=u[u.length-1],u[u.length-1]=u[u.length-1-_],u[u.length-1-_]=f)}else{var w=s-+this._x.call(null,p.data),y=e-+this._y.call(null,p.data),M=w*w+y*y;if(M<t){var v=Math.sqrt(t=M);n=s-v,r=e-v,h=s+v,d=e+v,i=p.data}}return i}function O7(s){if(isNaN(h=+this._x.call(null,s))||isNaN(d=+this._y.call(null,s)))return this;var e,t=this._root,i,n,r,o=this._x0,a=this._y0,l=this._x1,c=this._y1,h,d,u,p,f,_,g,m;if(!t)return this;if(t.length)for(;;){if((f=h>=(u=(o+l)/2))?o=u:l=u,(_=d>=(p=(a+c)/2))?a=p:c=p,e=t,!(t=t[g=_<<1|f]))return this;if(!t.length)break;(e[g+1&3]||e[g+2&3]||e[g+3&3])&&(i=e,m=g)}for(;t.data!==s;)if(n=t,!(t=t.next))return this;return(r=t.next)&&delete t.next,n?(r?n.next=r:delete n.next,this):e?(r?e[g]=r:delete e[g],(t=e[0]||e[1]||e[2]||e[3])&&t===(e[3]||e[2]||e[1]||e[0])&&!t.length&&(i?i[m]=t:this._root=t),this):(this._root=r,this)}function E7(s){for(var e=0,t=s.length;e<t;++e)this.remove(s[e]);return this}function A7(){return this._root}function T7(){var s=0;return this.visit(function(e){if(!e.length)do++s;while(e=e.next)}),s}function D7(s){var e=[],t,i=this._root,n,r,o,a,l;for(i&&e.push(new Qs(i,this._x0,this._y0,this._x1,this._y1));t=e.pop();)if(!s(i=t.node,r=t.x0,o=t.y0,a=t.x1,l=t.y1)&&i.length){var c=(r+a)/2,h=(o+l)/2;(n=i[3])&&e.push(new Qs(n,c,h,a,l)),(n=i[2])&&e.push(new Qs(n,r,h,c,l)),(n=i[1])&&e.push(new Qs(n,c,o,a,h)),(n=i[0])&&e.push(new Qs(n,r,o,c,h))}return this}function I7(s){var e=[],t=[],i;for(this._root&&e.push(new Qs(this._root,this._x0,this._y0,this._x1,this._y1));i=e.pop();){var n=i.node;if(n.length){var r,o=i.x0,a=i.y0,l=i.x1,c=i.y1,h=(o+l)/2,d=(a+c)/2;(r=n[0])&&e.push(new Qs(r,o,a,h,d)),(r=n[1])&&e.push(new Qs(r,h,a,l,d)),(r=n[2])&&e.push(new Qs(r,o,d,h,c)),(r=n[3])&&e.push(new Qs(r,h,d,l,c))}t.push(i)}for(;i=t.pop();)s(i.node,i.x0,i.y0,i.x1,i.y1);return this}function C7(s){return s[0]}function R7(s){return arguments.length?(this._x=s,this):this._x}function k7(s){return s[1]}function N7(s){return arguments.length?(this._y=s,this):this._y}function a_(s,e,t){var i=new l_(e??C7,t??k7,NaN,NaN,NaN,NaN);return s==null?i:i.addAll(s)}function l_(s,e,t,i,n,r){this._x=s,this._y=e,this._x0=t,this._y0=i,this._x1=n,this._y1=r,this._root=void 0}function S0(s){for(var e={data:s.data},t=e;s=s.next;)t=t.next={data:s.data};return e}var ti=a_.prototype=l_.prototype;ti.copy=function(){var s=new l_(this._x,this._y,this._x0,this._y0,this._x1,this._y1),e=this._root,t,i;if(!e)return s;if(!e.length)return s._root=S0(e),s;for(t=[{source:e,target:s._root=new Array(4)}];e=t.pop();)for(var n=0;n<4;++n)(i=e.source[n])&&(i.length?t.push({source:i,target:e.target[n]=new Array(4)}):e.target[n]=S0(i));return s};ti.add=v7;ti.addAll=w7;ti.cover=y7;ti.data=S7;ti.extent=z7;ti.find=x7;ti.remove=O7;ti.removeAll=E7;ti.root=A7;ti.size=T7;ti.visit=D7;ti.visitAfter=I7;ti.x=R7;ti.y=N7;function B7(s){const e=+this._x.call(null,s),t=+this._y.call(null,s),i=+this._z.call(null,s);return xz(this.cover(e,t,i),e,t,i,s)}function xz(s,e,t,i,n){if(isNaN(e)||isNaN(t)||isNaN(i))return s;var r,o=s._root,a={data:n},l=s._x0,c=s._y0,h=s._z0,d=s._x1,u=s._y1,p=s._z1,f,_,g,m,w,y,M,v,S,x,b;if(!o)return s._root=a,s;for(;o.length;)if((M=e>=(f=(l+d)/2))?l=f:d=f,(v=t>=(_=(c+u)/2))?c=_:u=_,(S=i>=(g=(h+p)/2))?h=g:p=g,r=o,!(o=o[x=S<<2|v<<1|M]))return r[x]=a,s;if(m=+s._x.call(null,o.data),w=+s._y.call(null,o.data),y=+s._z.call(null,o.data),e===m&&t===w&&i===y)return a.next=o,r?r[x]=a:s._root=a,s;do r=r?r[x]=new Array(8):s._root=new Array(8),(M=e>=(f=(l+d)/2))?l=f:d=f,(v=t>=(_=(c+u)/2))?c=_:u=_,(S=i>=(g=(h+p)/2))?h=g:p=g;while((x=S<<2|v<<1|M)===(b=(y>=g)<<2|(w>=_)<<1|m>=f));return r[b]=o,r[x]=a,s}function G7(s){Array.isArray(s)||(s=Array.from(s));const e=s.length,t=new Float64Array(e),i=new Float64Array(e),n=new Float64Array(e);let r=1/0,o=1/0,a=1/0,l=-1/0,c=-1/0,h=-1/0;for(let d=0,u,p,f,_;d<e;++d)isNaN(p=+this._x.call(null,u=s[d]))||isNaN(f=+this._y.call(null,u))||isNaN(_=+this._z.call(null,u))||(t[d]=p,i[d]=f,n[d]=_,p<r&&(r=p),p>l&&(l=p),f<o&&(o=f),f>c&&(c=f),_<a&&(a=_),_>h&&(h=_));if(r>l||o>c||a>h)return this;this.cover(r,o,a).cover(l,c,h);for(let d=0;d<e;++d)xz(this,t[d],i[d],n[d],s[d]);return this}function P7(s,e,t){if(isNaN(s=+s)||isNaN(e=+e)||isNaN(t=+t))return this;var i=this._x0,n=this._y0,r=this._z0,o=this._x1,a=this._y1,l=this._z1;if(isNaN(i))o=(i=Math.floor(s))+1,a=(n=Math.floor(e))+1,l=(r=Math.floor(t))+1;else{for(var c=o-i||1,h=this._root,d,u;i>s||s>=o||n>e||e>=a||r>t||t>=l;)switch(u=(t<r)<<2|(e<n)<<1|s<i,d=new Array(8),d[u]=h,h=d,c*=2,u){case 0:o=i+c,a=n+c,l=r+c;break;case 1:i=o-c,a=n+c,l=r+c;break;case 2:o=i+c,n=a-c,l=r+c;break;case 3:i=o-c,n=a-c,l=r+c;break;case 4:o=i+c,a=n+c,r=l-c;break;case 5:i=o-c,a=n+c,r=l-c;break;case 6:o=i+c,n=a-c,r=l-c;break;case 7:i=o-c,n=a-c,r=l-c;break}this._root&&this._root.length&&(this._root=h)}return this._x0=i,this._y0=n,this._z0=r,this._x1=o,this._y1=a,this._z1=l,this}function L7(){var s=[];return this.visit(function(e){if(!e.length)do s.push(e.data);while(e=e.next)}),s}function W7(s){return arguments.length?this.cover(+s[0][0],+s[0][1],+s[0][2]).cover(+s[1][0],+s[1][1],+s[1][2]):isNaN(this._x0)?void 0:[[this._x0,this._y0,this._z0],[this._x1,this._y1,this._z1]]}function Wt(s,e,t,i,n,r,o){this.node=s,this.x0=e,this.y0=t,this.z0=i,this.x1=n,this.y1=r,this.z1=o}function F7(s,e,t,i){var n,r=this._x0,o=this._y0,a=this._z0,l,c,h,d,u,p,f=this._x1,_=this._y1,g=this._z1,m=[],w=this._root,y,M;for(w&&m.push(new Wt(w,r,o,a,f,_,g)),i==null?i=1/0:(r=s-i,o=e-i,a=t-i,f=s+i,_=e+i,g=t+i,i*=i);y=m.pop();)if(!(!(w=y.node)||(l=y.x0)>f||(c=y.y0)>_||(h=y.z0)>g||(d=y.x1)<r||(u=y.y1)<o||(p=y.z1)<a))if(w.length){var v=(l+d)/2,S=(c+u)/2,x=(h+p)/2;m.push(new Wt(w[7],v,S,x,d,u,p),new Wt(w[6],l,S,x,v,u,p),new Wt(w[5],v,c,x,d,S,p),new Wt(w[4],l,c,x,v,S,p),new Wt(w[3],v,S,h,d,u,x),new Wt(w[2],l,S,h,v,u,x),new Wt(w[1],v,c,h,d,S,x),new Wt(w[0],l,c,h,v,S,x)),(M=(t>=x)<<2|(e>=S)<<1|s>=v)&&(y=m[m.length-1],m[m.length-1]=m[m.length-1-M],m[m.length-1-M]=y)}else{var b=s-+this._x.call(null,w.data),z=e-+this._y.call(null,w.data),T=t-+this._z.call(null,w.data),A=b*b+z*z+T*T;if(A<i){var E=Math.sqrt(i=A);r=s-E,o=e-E,a=t-E,f=s+E,_=e+E,g=t+E,n=w.data}}return n}const U7=(s,e,t,i,n,r)=>Math.sqrt((s-i)**2+(e-n)**2+(t-r)**2);function $7(s,e,t,i){const n=[],r=s-i,o=e-i,a=t-i,l=s+i,c=e+i,h=t+i;return this.visit((d,u,p,f,_,g,m)=>{if(!d.length)do{const w=d.data;U7(s,e,t,this._x(w),this._y(w),this._z(w))<=i&&n.push(w)}while(d=d.next);return u>l||p>c||f>h||_<r||g<o||m<a}),n}function j7(s){if(isNaN(u=+this._x.call(null,s))||isNaN(p=+this._y.call(null,s))||isNaN(f=+this._z.call(null,s)))return this;var e,t=this._root,i,n,r,o=this._x0,a=this._y0,l=this._z0,c=this._x1,h=this._y1,d=this._z1,u,p,f,_,g,m,w,y,M,v,S;if(!t)return this;if(t.length)for(;;){if((w=u>=(_=(o+c)/2))?o=_:c=_,(y=p>=(g=(a+h)/2))?a=g:h=g,(M=f>=(m=(l+d)/2))?l=m:d=m,e=t,!(t=t[v=M<<2|y<<1|w]))return this;if(!t.length)break;(e[v+1&7]||e[v+2&7]||e[v+3&7]||e[v+4&7]||e[v+5&7]||e[v+6&7]||e[v+7&7])&&(i=e,S=v)}for(;t.data!==s;)if(n=t,!(t=t.next))return this;return(r=t.next)&&delete t.next,n?(r?n.next=r:delete n.next,this):e?(r?e[v]=r:delete e[v],(t=e[0]||e[1]||e[2]||e[3]||e[4]||e[5]||e[6]||e[7])&&t===(e[7]||e[6]||e[5]||e[4]||e[3]||e[2]||e[1]||e[0])&&!t.length&&(i?i[S]=t:this._root=t),this):(this._root=r,this)}function H7(s){for(var e=0,t=s.length;e<t;++e)this.remove(s[e]);return this}function V7(){return this._root}function q7(){var s=0;return this.visit(function(e){if(!e.length)do++s;while(e=e.next)}),s}function K7(s){var e=[],t,i=this._root,n,r,o,a,l,c,h;for(i&&e.push(new Wt(i,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1));t=e.pop();)if(!s(i=t.node,r=t.x0,o=t.y0,a=t.z0,l=t.x1,c=t.y1,h=t.z1)&&i.length){var d=(r+l)/2,u=(o+c)/2,p=(a+h)/2;(n=i[7])&&e.push(new Wt(n,d,u,p,l,c,h)),(n=i[6])&&e.push(new Wt(n,r,u,p,d,c,h)),(n=i[5])&&e.push(new Wt(n,d,o,p,l,u,h)),(n=i[4])&&e.push(new Wt(n,r,o,p,d,u,h)),(n=i[3])&&e.push(new Wt(n,d,u,a,l,c,p)),(n=i[2])&&e.push(new Wt(n,r,u,a,d,c,p)),(n=i[1])&&e.push(new Wt(n,d,o,a,l,u,p)),(n=i[0])&&e.push(new Wt(n,r,o,a,d,u,p))}return this}function Y7(s){var e=[],t=[],i;for(this._root&&e.push(new Wt(this._root,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1));i=e.pop();){var n=i.node;if(n.length){var r,o=i.x0,a=i.y0,l=i.z0,c=i.x1,h=i.y1,d=i.z1,u=(o+c)/2,p=(a+h)/2,f=(l+d)/2;(r=n[0])&&e.push(new Wt(r,o,a,l,u,p,f)),(r=n[1])&&e.push(new Wt(r,u,a,l,c,p,f)),(r=n[2])&&e.push(new Wt(r,o,p,l,u,h,f)),(r=n[3])&&e.push(new Wt(r,u,p,l,c,h,f)),(r=n[4])&&e.push(new Wt(r,o,a,f,u,p,d)),(r=n[5])&&e.push(new Wt(r,u,a,f,c,p,d)),(r=n[6])&&e.push(new Wt(r,o,p,f,u,h,d)),(r=n[7])&&e.push(new Wt(r,u,p,f,c,h,d))}t.push(i)}for(;i=t.pop();)s(i.node,i.x0,i.y0,i.z0,i.x1,i.y1,i.z1);return this}function X7(s){return s[0]}function Z7(s){return arguments.length?(this._x=s,this):this._x}function J7(s){return s[1]}function Q7(s){return arguments.length?(this._y=s,this):this._y}function eB(s){return s[2]}function tB(s){return arguments.length?(this._z=s,this):this._z}function c_(s,e,t,i){var n=new h_(e??X7,t??J7,i??eB,NaN,NaN,NaN,NaN,NaN,NaN);return s==null?n:n.addAll(s)}function h_(s,e,t,i,n,r,o,a,l){this._x=s,this._y=e,this._z=t,this._x0=i,this._y0=n,this._z0=r,this._x1=o,this._y1=a,this._z1=l,this._root=void 0}function z0(s){for(var e={data:s.data},t=e;s=s.next;)t=t.next={data:s.data};return e}var Ls=c_.prototype=h_.prototype;Ls.copy=function(){var s=new h_(this._x,this._y,this._z,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1),e=this._root,t,i;if(!e)return s;if(!e.length)return s._root=z0(e),s;for(t=[{source:e,target:s._root=new Array(8)}];e=t.pop();)for(var n=0;n<8;++n)(i=e.source[n])&&(i.length?t.push({source:i,target:e.target[n]=new Array(8)}):e.target[n]=z0(i));return s};Ls.add=B7;Ls.addAll=G7;Ls.cover=P7;Ls.data=L7;Ls.extent=W7;Ls.find=F7;Ls.findAllWithinRadius=$7;Ls.remove=j7;Ls.removeAll=H7;Ls.root=V7;Ls.size=q7;Ls.visit=K7;Ls.visitAfter=Y7;Ls.x=Z7;Ls.y=Q7;Ls.z=tB;function Ms(s){return function(){return s}}function Bi(s){return(s()-.5)*1e-6}function ku(s){return s.x+s.vx}function x0(s){return s.y+s.vy}function sB(s){return s.z+s.vz}function kr(s){var e,t,i,n,r=1,o=1;typeof s!="function"&&(s=Ms(s==null?1:+s));function a(){for(var h,d=e.length,u,p,f,_,g,m,w,y=0;y<o;++y)for(u=(t===1?r_(e,ku):t===2?a_(e,ku,x0):t===3?c_(e,ku,x0,sB):null).visitAfter(l),h=0;h<d;++h)p=e[h],m=i[p.index],w=m*m,f=p.x+p.vx,t>1&&(_=p.y+p.vy),t>2&&(g=p.z+p.vz),u.visit(M);function M(v,S,x,b,z,T,A){var E=[S,x,b,z,T,A],O=E[0],R=E[1],C=E[2],k=E[t],G=E[t+1],L=E[t+2],W=v.data,ee=v.r,X=m+ee;if(W){if(W.index>p.index){var he=f-W.x-W.vx,Ae=t>1?_-W.y-W.vy:0,Pe=t>2?g-W.z-W.vz:0,De=he*he+Ae*Ae+Pe*Pe;De<X*X&&(he===0&&(he=Bi(n),De+=he*he),t>1&&Ae===0&&(Ae=Bi(n),De+=Ae*Ae),t>2&&Pe===0&&(Pe=Bi(n),De+=Pe*Pe),De=(X-(De=Math.sqrt(De)))/De*r,p.vx+=(he*=De)*(X=(ee*=ee)/(w+ee)),t>1&&(p.vy+=(Ae*=De)*X),t>2&&(p.vz+=(Pe*=De)*X),W.vx-=he*(X=1-X),t>1&&(W.vy-=Ae*X),t>2&&(W.vz-=Pe*X))}return}return O>f+X||k<f-X||t>1&&(R>_+X||G<_-X)||t>2&&(C>g+X||L<g-X)}}function l(h){if(h.data)return h.r=i[h.data.index];for(var d=h.r=0;d<Math.pow(2,t);++d)h[d]&&h[d].r>h.r&&(h.r=h[d].r)}function c(){if(e){var h,d=e.length,u;for(i=new Array(d),h=0;h<d;++h)u=e[h],i[u.index]=+s(u,h,e)}}return a.initialize=function(h,...d){e=h,n=d.find(u=>typeof u=="function")||Math.random,t=d.find(u=>[1,2,3].includes(u))||2,c()},a.iterations=function(h){return arguments.length?(o=+h,a):o},a.strength=function(h){return arguments.length?(r=+h,a):r},a.radius=function(h){return arguments.length?(s=typeof h=="function"?h:Ms(+h),c(),a):s},a}function iB(s){return s.index}function O0(s,e){var t=s.get(e);if(!t)throw new Error("node not found: "+e);return t}function xo(s){var e=iB,t=u,i,n=Ms(30),r,o,a,l,c,h,d=1;s==null&&(s=[]);function u(m){return 1/Math.min(l[m.source.index],l[m.target.index])}function p(m){for(var w=0,y=s.length;w<d;++w)for(var M=0,v,S,x,b=0,z=0,T=0,A,E;M<y;++M)v=s[M],S=v.source,x=v.target,b=x.x+x.vx-S.x-S.vx||Bi(h),a>1&&(z=x.y+x.vy-S.y-S.vy||Bi(h)),a>2&&(T=x.z+x.vz-S.z-S.vz||Bi(h)),A=Math.sqrt(b*b+z*z+T*T),A=(A-r[M])/A*m*i[M],b*=A,z*=A,T*=A,x.vx-=b*(E=c[M]),a>1&&(x.vy-=z*E),a>2&&(x.vz-=T*E),S.vx+=b*(E=1-E),a>1&&(S.vy+=z*E),a>2&&(S.vz+=T*E)}function f(){if(o){var m,w=o.length,y=s.length,M=new Map(o.map((S,x)=>[e(S,x,o),S])),v;for(m=0,l=new Array(w);m<y;++m)v=s[m],v.index=m,typeof v.source!="object"&&(v.source=O0(M,v.source)),typeof v.target!="object"&&(v.target=O0(M,v.target)),l[v.source.index]=(l[v.source.index]||0)+1,l[v.target.index]=(l[v.target.index]||0)+1;for(m=0,c=new Array(y);m<y;++m)v=s[m],c[m]=l[v.source.index]/(l[v.source.index]+l[v.target.index]);i=new Array(y),_(),r=new Array(y),g()}}function _(){if(o)for(var m=0,w=s.length;m<w;++m)i[m]=+t(s[m],m,s)}function g(){if(o)for(var m=0,w=s.length;m<w;++m)r[m]=+n(s[m],m,s)}return p.initialize=function(m,...w){o=m,h=w.find(y=>typeof y=="function")||Math.random,a=w.find(y=>[1,2,3].includes(y))||2,f()},p.links=function(m){return arguments.length?(s=m,f(),p):s},p.id=function(m){return arguments.length?(e=m,p):e},p.iterations=function(m){return arguments.length?(d=+m,p):d},p.strength=function(m){return arguments.length?(t=typeof m=="function"?m:Ms(+m),_(),p):t},p.distance=function(m){return arguments.length?(n=typeof m=="function"?m:Ms(+m),g(),p):n},p}var nB={value:()=>{}};function Oz(){for(var s=0,e=arguments.length,t={},i;s<e;++s){if(!(i=arguments[s]+"")||i in t||/[\s.]/.test(i))throw new Error("illegal type: "+i);t[i]=[]}return new Rh(t)}function Rh(s){this._=s}function rB(s,e){return s.trim().split(/^|\s+/).map(function(t){var i="",n=t.indexOf(".");if(n>=0&&(i=t.slice(n+1),t=t.slice(0,n)),t&&!e.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:i}})}Rh.prototype=Oz.prototype={constructor:Rh,on:function(s,e){var t=this._,i=rB(s+"",t),n,r=-1,o=i.length;if(arguments.length<2){for(;++r<o;)if((n=(s=i[r]).type)&&(n=oB(t[n],s.name)))return n;return}if(e!=null&&typeof e!="function")throw new Error("invalid callback: "+e);for(;++r<o;)if(n=(s=i[r]).type)t[n]=E0(t[n],s.name,e);else if(e==null)for(n in t)t[n]=E0(t[n],s.name,null);return this},copy:function(){var s={},e=this._;for(var t in e)s[t]=e[t].slice();return new Rh(s)},call:function(s,e){if((n=arguments.length-2)>0)for(var t=new Array(n),i=0,n,r;i<n;++i)t[i]=arguments[i+2];if(!this._.hasOwnProperty(s))throw new Error("unknown type: "+s);for(r=this._[s],i=0,n=r.length;i<n;++i)r[i].value.apply(e,t)},apply:function(s,e,t){if(!this._.hasOwnProperty(s))throw new Error("unknown type: "+s);for(var i=this._[s],n=0,r=i.length;n<r;++n)i[n].value.apply(e,t)}};function oB(s,e){for(var t=0,i=s.length,n;t<i;++t)if((n=s[t]).name===e)return n.value}function E0(s,e,t){for(var i=0,n=s.length;i<n;++i)if(s[i].name===e){s[i]=nB,s=s.slice(0,i).concat(s.slice(i+1));break}return t!=null&&s.push({name:e,value:t}),s}var Oa=0,zl=0,Za=0,Ez=1e3,bd,xl,Md=0,Oo=0,Qd=0,Zl=typeof performance=="object"&&performance.now?performance:Date,Az=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(s){setTimeout(s,17)};function Tz(){return Oo||(Az(aB),Oo=Zl.now()+Qd)}function aB(){Oo=0}function Gp(){this._call=this._time=this._next=null}Gp.prototype=Dz.prototype={constructor:Gp,restart:function(s,e,t){if(typeof s!="function")throw new TypeError("callback is not a function");t=(t==null?Tz():+t)+(e==null?0:+e),!this._next&&xl!==this&&(xl?xl._next=this:bd=this,xl=this),this._call=s,this._time=t,Pp()},stop:function(){this._call&&(this._call=null,this._time=1/0,Pp())}};function Dz(s,e,t){var i=new Gp;return i.restart(s,e,t),i}function lB(){Tz(),++Oa;for(var s=bd,e;s;)(e=Oo-s._time)>=0&&s._call.call(void 0,e),s=s._next;--Oa}function A0(){Oo=(Md=Zl.now())+Qd,Oa=zl=0;try{lB()}finally{Oa=0,hB(),Oo=0}}function cB(){var s=Zl.now(),e=s-Md;e>Ez&&(Qd-=e,Md=s)}function hB(){for(var s,e=bd,t,i=1/0;e;)e._call?(i>e._time&&(i=e._time),s=e,e=e._next):(t=e._next,e._next=null,e=s?s._next=t:bd=t);xl=s,Pp(i)}function Pp(s){if(!Oa){zl&&(zl=clearTimeout(zl));var e=s-Oo;e>24?(s<1/0&&(zl=setTimeout(A0,s-Zl.now()-Qd)),Za&&(Za=clearInterval(Za))):(Za||(Md=Zl.now(),Za=setInterval(cB,Ez)),Oa=1,Az(A0))}}const dB=1664525,uB=1013904223,T0=4294967296;function fB(){let s=1;return()=>(s=(dB*s+uB)%T0)/T0}var D0=3;function Nu(s){return s.x}function I0(s){return s.y}function pB(s){return s.z}var mB=10,gB=Math.PI*(3-Math.sqrt(5)),_B=Math.PI*20/(9+Math.sqrt(221));function Nr(s,e){e=e||2;var t=Math.min(D0,Math.max(1,Math.round(e))),i,n=1,r=.001,o=1-Math.pow(r,1/300),a=0,l=.6,c=new Map,h=Dz(p),d=Oz("tick","end"),u=fB();s==null&&(s=[]);function p(){f(),d.call("tick",i),n<r&&(h.stop(),d.call("end",i))}function f(m){var w,y=s.length,M;m===void 0&&(m=1);for(var v=0;v<m;++v)for(n+=(a-n)*o,c.forEach(function(S){S(n)}),w=0;w<y;++w)M=s[w],M.fx==null?M.x+=M.vx*=l:(M.x=M.fx,M.vx=0),t>1&&(M.fy==null?M.y+=M.vy*=l:(M.y=M.fy,M.vy=0)),t>2&&(M.fz==null?M.z+=M.vz*=l:(M.z=M.fz,M.vz=0));return i}function _(){for(var m=0,w=s.length,y;m<w;++m){if(y=s[m],y.index=m,y.fx!=null&&(y.x=y.fx),y.fy!=null&&(y.y=y.fy),y.fz!=null&&(y.z=y.fz),isNaN(y.x)||t>1&&isNaN(y.y)||t>2&&isNaN(y.z)){var M=mB*(t>2?Math.cbrt(.5+m):t>1?Math.sqrt(.5+m):m),v=m*gB,S=m*_B;t===1?y.x=M:t===2?(y.x=M*Math.cos(v),y.y=M*Math.sin(v)):(y.x=M*Math.sin(v)*Math.cos(S),y.y=M*Math.cos(v),y.z=M*Math.sin(v)*Math.sin(S))}(isNaN(y.vx)||t>1&&isNaN(y.vy)||t>2&&isNaN(y.vz))&&(y.vx=0,t>1&&(y.vy=0),t>2&&(y.vz=0))}}function g(m){return m.initialize&&m.initialize(s,u,t),m}return _(),i={tick:f,restart:function(){return h.restart(p),i},stop:function(){return h.stop(),i},numDimensions:function(m){return arguments.length?(t=Math.min(D0,Math.max(1,Math.round(m))),c.forEach(g),i):t},nodes:function(m){return arguments.length?(s=m,_(),c.forEach(g),i):s},alpha:function(m){return arguments.length?(n=+m,i):n},alphaMin:function(m){return arguments.length?(r=+m,i):r},alphaDecay:function(m){return arguments.length?(o=+m,i):+o},alphaTarget:function(m){return arguments.length?(a=+m,i):a},velocityDecay:function(m){return arguments.length?(l=1-m,i):1-l},randomSource:function(m){return arguments.length?(u=m,c.forEach(g),i):u},force:function(m,w){return arguments.length>1?(w==null?c.delete(m):c.set(m,g(w)),i):c.get(m)},find:function(){var m=Array.prototype.slice.call(arguments),w=m.shift()||0,y=(t>1?m.shift():null)||0,M=(t>2?m.shift():null)||0,v=m.shift()||1/0,S=0,x=s.length,b,z,T,A,E,O;for(v*=v,S=0;S<x;++S)E=s[S],b=w-E.x,z=y-(E.y||0),T=M-(E.z||0),A=b*b+z*z+T*T,A<v&&(O=E,v=A);return O},on:function(m,w){return arguments.length>1?(d.on(m,w),i):d.on(m)}}}function Br(){var s,e,t,i,n,r=Ms(-30),o,a=1,l=1/0,c=.81;function h(f){var _,g=s.length,m=(e===1?r_(s,Nu):e===2?a_(s,Nu,I0):e===3?c_(s,Nu,I0,pB):null).visitAfter(u);for(n=f,_=0;_<g;++_)t=s[_],m.visit(p)}function d(){if(s){var f,_=s.length,g;for(o=new Array(_),f=0;f<_;++f)g=s[f],o[g.index]=+r(g,f,s)}}function u(f){var _=0,g,m,w=0,y,M,v,S,x=f.length;if(x){for(y=M=v=S=0;S<x;++S)(g=f[S])&&(m=Math.abs(g.value))&&(_+=g.value,w+=m,y+=m*(g.x||0),M+=m*(g.y||0),v+=m*(g.z||0));_*=Math.sqrt(4/x),f.x=y/w,e>1&&(f.y=M/w),e>2&&(f.z=v/w)}else{g=f,g.x=g.data.x,e>1&&(g.y=g.data.y),e>2&&(g.z=g.data.z);do _+=o[g.data.index];while(g=g.next)}f.value=_}function p(f,_,g,m,w){if(!f.value)return!0;var y=[g,m,w][e-1],M=f.x-t.x,v=e>1?f.y-t.y:0,S=e>2?f.z-t.z:0,x=y-_,b=M*M+v*v+S*S;if(x*x/c<b)return b<l&&(M===0&&(M=Bi(i),b+=M*M),e>1&&v===0&&(v=Bi(i),b+=v*v),e>2&&S===0&&(S=Bi(i),b+=S*S),b<a&&(b=Math.sqrt(a*b)),t.vx+=M*f.value*n/b,e>1&&(t.vy+=v*f.value*n/b),e>2&&(t.vz+=S*f.value*n/b)),!0;if(f.length||b>=l)return;(f.data!==t||f.next)&&(M===0&&(M=Bi(i),b+=M*M),e>1&&v===0&&(v=Bi(i),b+=v*v),e>2&&S===0&&(S=Bi(i),b+=S*S),b<a&&(b=Math.sqrt(a*b)));do f.data!==t&&(x=o[f.data.index]*n/b,t.vx+=M*x,e>1&&(t.vy+=v*x),e>2&&(t.vz+=S*x));while(f=f.next)}return h.initialize=function(f,..._){s=f,i=_.find(g=>typeof g=="function")||Math.random,e=_.find(g=>[1,2,3].includes(g))||2,d()},h.strength=function(f){return arguments.length?(r=typeof f=="function"?f:Ms(+f),d(),h):r},h.distanceMin=function(f){return arguments.length?(a=f*f,h):Math.sqrt(a)},h.distanceMax=function(f){return arguments.length?(l=f*f,h):Math.sqrt(l)},h.theta=function(f){return arguments.length?(c=f*f,h):Math.sqrt(c)},h}function d_(s){var e=Ms(.1),t,i,n;typeof s!="function"&&(s=Ms(s==null?0:+s));function r(a){for(var l=0,c=t.length,h;l<c;++l)h=t[l],h.vx+=(n[l]-h.x)*i[l]*a}function o(){if(t){var a,l=t.length;for(i=new Array(l),n=new Array(l),a=0;a<l;++a)i[a]=isNaN(n[a]=+s(t[a],a,t))?0:+e(t[a],a,t)}}return r.initialize=function(a){t=a,o()},r.strength=function(a){return arguments.length?(e=typeof a=="function"?a:Ms(+a),o(),r):e},r.x=function(a){return arguments.length?(s=typeof a=="function"?a:Ms(+a),o(),r):s},r}function u_(s){var e=Ms(.1),t,i,n;typeof s!="function"&&(s=Ms(s==null?0:+s));function r(a){for(var l=0,c=t.length,h;l<c;++l)h=t[l],h.vy+=(n[l]-h.y)*i[l]*a}function o(){if(t){var a,l=t.length;for(i=new Array(l),n=new Array(l),a=0;a<l;++a)i[a]=isNaN(n[a]=+s(t[a],a,t))?0:+e(t[a],a,t)}}return r.initialize=function(a){t=a,o()},r.strength=function(a){return arguments.length?(e=typeof a=="function"?a:Ms(+a),o(),r):e},r.y=function(a){return arguments.length?(s=typeof a=="function"?a:Ms(+a),o(),r):s},r}function f_(s){var e=Ms(.1),t,i,n;typeof s!="function"&&(s=Ms(s==null?0:+s));function r(a){for(var l=0,c=t.length,h;l<c;++l)h=t[l],h.vz+=(n[l]-h.z)*i[l]*a}function o(){if(t){var a,l=t.length;for(i=new Array(l),n=new Array(l),a=0;a<l;++a)i[a]=isNaN(n[a]=+s(t[a],a,t))?0:+e(t[a],a,t)}}return r.initialize=function(a){t=a,o()},r.strength=function(a){return arguments.length?(e=typeof a=="function"?a:Ms(+a),o(),r):e},r.z=function(a){return arguments.length?(s=typeof a=="function"?a:Ms(+a),o(),r):s},r}function bB(s){let e=2166136261;for(let t=0;t<s.length;t++)e^=s.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function MB(s){let e=s>>>0;return()=>(e=Math.imul(e,1664525)+1013904223>>>0,e/4294967296)}function Ea(s){return MB(bB(s))}const Qi=.55,vB=12,wB=60,Bu=60;function yB(s){const e=new Map(s.map((t,i)=>[t.id,i]));return s.map(t=>`${t.parents.map(n=>e.get(n)??-1).join(".")}:${t.radius.toFixed(2)}`).join("|")}function SB(s,e,t){const[i,n,r]=s,o=i*Math.cos(e)+r*Math.sin(e),a=-i*Math.sin(e)+r*Math.cos(e),l=n*Math.cos(t)-a*Math.sin(t),c=n*Math.sin(t)+a*Math.cos(t);return[o,l,c]}function zB(s,e,t){const i=f=>Math.hypot(f[0],f[1],f[2]),n=i(e),r=i(t);if(n<1e-9||r<1e-9)return s;const o=[e[0]/n,e[1]/n,e[2]/n],a=[t[0]/r,t[1]/r,t[2]/r],l=[o[1]*a[2]-o[2]*a[1],o[2]*a[0]-o[0]*a[2],o[0]*a[1]-o[1]*a[0]],c=i(l),h=o[0]*a[0]+o[1]*a[1]+o[2]*a[2];if(c<1e-9)return h>0?s:[-s[0],-s[1],-s[2]];const d=[l[0]/c,l[1]/c,l[2]/c],u=d[0]*s[0]+d[1]*s[1]+d[2]*s[2],p=[d[1]*s[2]-d[2]*s[1],d[2]*s[0]-d[0]*s[2],d[0]*s[1]-d[1]*s[0]];return[s[0]*h+p[0]*c+d[0]*u*(1-h),s[1]*h+p[1]*c+d[1]*u*(1-h),s[2]*h+p[2]*c+d[2]*u*(1-h)]}function C0(s,e,t){if(e.length===0)return s;let i=0;for(const n of e)i+=t.get(n.id.slice(6))??Qi;return i/=e.length,Math.max(s+2,Math.sqrt(e.length)*i*1.6)}function Gu(s,e,t){const i=e<=1?0:1-2*(s+.5)/e,n=Math.sqrt(Math.max(0,1-i*i)),r=s*Math.PI*(3-Math.sqrt(5));return[Math.cos(r)*n*t,i*t,Math.sin(r)*n*t]}function p_(s,e,t=()=>{},i="clumps",n=Ea){const r=new Map(s.map(O=>[O.id,O])),o=new Map,a=[];for(const O of s)O.group===null?a.push(O):o.set(O.group,[...o.get(O.group)??[],O]);const l=new Map,c=new Map,h=new Map,d=new Set;let u=0;const p=Math.max(1,o.size),f=new Map;for(const[O,R]of o){const C=R.filter(X=>X.seed!==void 0),k=[0,0,0];for(const X of C)k[0]+=X.seed[0],k[1]+=X.seed[1],k[2]+=X.seed[2];C.length>0&&(k[0]/=C.length,k[1]/=C.length,k[2]/=C.length,h.set(O,k)),R.every(X=>X.frozen===!0&&X.seed!==void 0)&&d.add(O);const G=new Map,L=C.length===0?yB(R):null,W=L===null?void 0:f.get(L);if(C.length===R.length)for(const X of R)G.set(X.id,[X.seed[0]-k[0],X.seed[1]-k[1],X.seed[2]-k[2]]);else if(W!==void 0){const X=n(O),he=X()*Math.PI*2,Ae=(X()-.5)*Math.PI;R.forEach((Pe,De)=>{G.set(Pe.id,SB(W[De]??[0,0,0],he,Ae))})}else{const X=R.map(oe=>{const pe={id:oe.id,r:oe.radius};return oe.seed!==void 0&&(pe.x=oe.seed[0]-k[0],pe.y=oe.seed[1]-k[1],pe.z=oe.seed[2]-k[2],oe.frozen===!0&&(pe.fx=pe.x,pe.fy=pe.y,pe.fz=pe.z)),pe}),he=new Set(R.map(oe=>oe.id)),Ae=[];for(const oe of R)for(const pe of oe.parents)he.has(pe)&&Ae.push({source:pe,target:oe.id});const Pe=new Map(R.map(oe=>[oe.id,oe.radius])),De=Nr(X,3).force("link",xo(Ae).id(oe=>oe.id).distance(e.link?oe=>(Pe.get(oe.source.id)??Qi)+(Pe.get(oe.target.id)??Qi)+1.4:2.2)).force("charge",Br().strength(oe=>e.charge?-6*(oe.r/Qi)**2:-6).distanceMax(vB)).force("center",_o(0,0,0)).stop();e.collide&&De.force("collide",kr().radius(oe=>oe.r*1.2));for(let oe=0;oe<wB;oe++)De.tick();const ie=[0,0,0];for(const oe of X)ie[0]+=oe.x??0,ie[1]+=oe.y??0,ie[2]+=oe.z??0;ie[0]/=X.length,ie[1]/=X.length,ie[2]/=X.length;for(const oe of X)G.set(oe.id,[(oe.x??0)-ie[0],(oe.y??0)-ie[1],(oe.z??0)-ie[2]]);L!==null&&f.set(L,R.map(oe=>G.get(oe.id)??[0,0,0]))}let ee=Qi;for(const X of R){const he=G.get(X.id)??[0,0,0];l.set(X.id,he),ee=Math.max(ee,Math.hypot(he[0],he[1],he[2])+X.radius)}c.set(O,ee),u+=1,u%50===0&&t(.3*(u/p))}t(.3);const _=O=>{const R=r.get(O);return R!==void 0&&R.group!==null?`group:${R.group}`:O},g=[],m=new Map;let w=!1;for(const[O]of o){const R=`group:${O}`,C=c.get(O)??Qi,k={id:R,r:C},G=h.get(O);G!==void 0&&(k.x=G[0],k.y=G[1],k.z=G[2],d.has(O)&&(k.fx=G[0],k.fy=G[1],k.fz=G[2],w=!0)),m.set(R,C),g.push(k)}for(const O of a){const R={id:O.id,r:O.radius};O.seed!==void 0&&(R.x=O.seed[0],R.y=O.seed[1],R.z=O.seed[2],O.frozen===!0&&(R.fx=O.seed[0],R.fy=O.seed[1],R.fz=O.seed[2],w=!0)),m.set(O.id,O.radius),g.push(R)}const y=new Set,M=[];for(const O of s)for(const R of O.parents){if(!r.has(R))continue;const C=_(R),k=_(O.id);if(C===k)continue;const G=`${C}\0${k}`;y.has(G)||(y.add(G),M.push({source:C,target:k}))}const v=new Map;for(const O of M)if(O.source.startsWith("group:")!==O.target.startsWith("group:")){const R=O.source.startsWith("group:")?O.source:O.target,C=O.source.startsWith("group:")?O.target:O.source;v.has(R)||v.set(R,C)}const S=new Map;for(const O of g){const R=v.get(O.id);R!==void 0&&S.set(R,[...S.get(R)??[],O])}const x=g.reduce((O,R)=>O+R.r*R.r,0),b=g.filter(O=>!O.id.startsWith("group:"));b.forEach((O,R)=>{if(O.x!==void 0)return;const[C,k,G]=Gu(R,b.length,Math.sqrt(x)*1.2+10);O.x=C,O.y=k,O.z=G});for(const[O,R]of S){const C=g.find(G=>G.id===O),k=Math.sqrt(R.reduce((G,L)=>G+L.r*L.r,0))*1.4+2;R.forEach((G,L)=>{if(G.x!==void 0)return;const[W,ee,X]=Gu(L,R.length,k);G.x=(C?.x??0)+W,G.y=(C?.y??0)+ee,G.z=(C?.z??0)+X})}const z=new Set;if(i==="spokes"){const O=C=>{const k=o.get(C)??[],G=new Set(k.map(W=>W.id)),L=k.find(W=>W.parents.some(ee=>!G.has(ee)))??k[0];return L===void 0?[0,0,0]:l.get(L.id)??[0,0,0]},R=[];for(const C of g){if(C.id.startsWith("group:")&&v.has(C.id)){z.add(C.id);continue}if(C.id.startsWith("group:"))R.push(C);else{const k=S.get(C.id)??[];let G=C.r;const L=C0(C.r,k,c);for(const W of k){const ee=W.id.slice(6),X=O(ee);G=Math.max(G,L+Math.hypot(X[0],X[1],X[2])+2*(c.get(ee)??Qi))}R.push({id:C.id,r:G,x:C.x,y:C.y,z:C.z,...C.fx!==void 0?{fx:C.fx,fy:C.fy,fz:C.fz}:{}})}}if(!R.every(C=>C.fx!==void 0)){const C=Nr(R,3).force("charge",Br().strength(k=>-1.5*k.r)).force("collide",kr().radius(k=>k.r*.9)).stop();w||C.force("center",_o(0,0,0));for(let k=0;k<Bu;k++)C.tick(),k%5===0&&t(.3+.7*(k/Bu))}for(const C of R){const k=g.find(G=>G.id===C.id);k!==void 0&&k!==C&&(k.x=C.x,k.y=C.y,k.z=C.z)}for(const C of g){if(C.id.startsWith("group:")||!S.has(C.id))continue;const k=S.get(C.id)??[],G=C0(C.r,k,c);k.forEach((L,W)=>{if(L.fx!==void 0||h.has(L.id.slice(6)))return;const ee=O(L.id.slice(6)),X=Gu(W,k.length,1),he=.35+.65*(W*.6180339887%1),Ae=C.r+1.4+G*he+Math.hypot(ee[0],ee[1],ee[2]);L.x=(C.x??0)+X[0]*Ae,L.y=(C.y??0)+X[1]*Ae,L.z=(C.z??0)+X[2]*Ae})}}if(!g.every(O=>O.fx!==void 0)&&i!=="spokes"){const O=Nr(g,3).force("link",xo(M).id(k=>k.id).distance(e.link?k=>(m.get(k.source.id)??Qi)+(m.get(k.target.id)??Qi)+1.4:2.2)).stop(),R=Br().strength(k=>e.charge?-6*(k.r/Qi)**2:-6);if(e.reach!==void 0&&R.distanceMax(e.reach),O.force("charge",R),w||O.force("center",_o(0,0,0)),e.collide&&O.force("collide",kr().radius(k=>k.r*1.05)),e.gravity){const k=G=>Math.min(1,(G.r/Qi)**2*.08);O.force("gx",d_(0).strength(k)).force("gy",u_(0).strength(k)).force("gz",f_(0).strength(k))}const C=Bu;for(let k=0;k<C;k++)O.tick(),k%5===0&&t(.3+.7*(k/C))}const A=new Map(g.map(O=>[O.id,O]));if(i==="spokes")for(const[O,R]of o){if(R.some(Pe=>Pe.seed!==void 0))continue;const C=`group:${O}`,k=A.get(C),G=v.get(C),L=G===void 0?void 0:A.get(G);if(k===void 0||L===void 0)continue;const W=[(k.x??0)-(L.x??0),(k.y??0)-(L.y??0),(k.z??0)-(L.z??0)],ee=new Set(R.map(Pe=>Pe.id)),X=R.find(Pe=>Pe.parents.some(De=>!ee.has(De)))??R[0],he=l.get(X.id)??[0,0,0],Ae=[-he[0],-he[1],-he[2]];for(const Pe of R){const De=l.get(Pe.id)??[0,0,0];l.set(Pe.id,zB(De,Ae,W))}}const E={};for(const O of s){const R=A.get(_(O.id)),C=[R?.x??0,R?.y??0,R?.z??0],k=O.group===null?[0,0,0]:l.get(O.id)??[0,0,0];E[O.id]=[C[0]+k[0],C[1]+k[1],C[2]+k[2]]}return t(1),E}const R0=80;function Iz(s,e,t=()=>{},i=Ea){const n=s.some(u=>u.seed===void 0),r=n?p_(s,e,u=>t(.05*u),"spokes",i):{};t(.05);const o=s.map(u=>{const p=u.seed??r[u.id],f={id:u.id,r:u.radius};return p!==void 0&&(f.x=p[0],f.y=p[1],f.z=p[2],u.frozen===!0&&u.seed!==void 0&&(f.fx=p[0],f.fy=p[1],f.fz=p[2])),f}),a=new Set(s.map(u=>u.id)),l=[];for(const u of s)for(const p of u.parents)a.has(p)&&l.push({source:p,target:u.id});const c=new Map(s.map(u=>[u.id,u.radius])),h=o.some(u=>u.fx!==void 0);if(!o.every(u=>u.fx!==void 0)){const u=Nr(o,3).force("link",xo(l).id(f=>f.id).distance(e.link?f=>(c.get(f.source.id)??Lt)+(c.get(f.target.id)??Lt)+1.4:2.2)).stop(),p=Br().strength(f=>e.charge?-6*(f.r/Lt)**2:-6);if(e.reach!==void 0&&p.distanceMax(e.reach),u.force("charge",p),h||u.force("center",_o(0,0,0)),e.collide&&u.force("collide",kr().radius(f=>f.r*1.2)),e.gravity){const f=_=>(_.r/Lt)**2*.08;u.force("gx",d_(0).strength(f)).force("gy",u_(0).strength(f)).force("gz",f_(0).strength(f))}n&&u.alpha(.6);for(let f=0;f<R0;f++)u.tick(),f%2===0&&t(.05+.95*(f/R0))}const d={};for(const u of o)d[u.id]=[u.x??0,u.y??0,u.z??0];return t(1),d}function Cz(s){const e=new Map;for(const t of s)for(const i of t.parents)e.set(i,(e.get(i)??0)+1),e.set(t.id,(e.get(t.id)??0)+1);return s.map(t=>t.metric??e.get(t.id)??1)}function Rz(s){const e=Cz(s),t=Math.max(...e,1);return new Map(s.map((i,n)=>[i.id,Lt*(.5+(e[n]??1)/t*1.2)]))}function kz(s,e=3,t=new Map,i=jr,n=new Set){const r=[];for(const w of s)for(const y of w.parents)r.push({source:y,target:w.id});const o=Cz(s),a=Math.max(...o,1),l=o.map(w=>Lt*(.5+w/a*1.2)),c=new Map(s.map((w,y)=>[w.id,l[y]??Lt])),h=s.map(w=>{const y=t.get(w.id);return y===void 0?{id:w.id}:n.has(w.id)?{id:w.id,x:y[0],y:y[1],z:y[2],fx:y[0],fy:y[1],fz:y[2]}:{id:w.id,x:y[0],y:y[1],z:y[2]}}),d=w=>n.has(w.id)&&w.fx!==void 0;let u=h,p=r;if(n.size>0){const w=new Set(h.filter(v=>!d(v)).map(v=>v.id));p=r.filter(v=>w.has(v.source)||w.has(v.target));const y=new Set(w);for(const v of p)y.add(v.source),y.add(v.target);u=h.filter(v=>y.has(v.id));const M=new Set(u.map(v=>v.id));p=p.filter(v=>M.has(v.source)&&M.has(v.target))}const f=Br().strength(i.charge?w=>n.has(w.id)?0:-6*((c.get(w.id)??Lt)/Lt)**2:w=>n.has(w.id)?0:-6);i.reach!==void 0&&f.distanceMax(i.reach);const _=Nr(u,e).force("link",xo(p).id(w=>w.id).distance(i.link?w=>(c.get(w.source.id)??Lt)+(c.get(w.target.id)??Lt)+1.4:2.2)).force("charge",f).stop();if(n.size===0&&_.force("center",e===2?_o(0,0):_o(0,0,0)),i.collide&&_.force("collide",kr().radius(w=>(c.get(w.id)??Lt)*1.2)),i.gravity){const w=y=>((c.get(y.id)??Lt)/Lt)**2*.08;_.force("gx",d_(0).strength(w)).force("gy",u_(0).strength(w)),e===3&&_.force("gz",f_(0).strength(w))}const g=u.length===0?0:t.size>0?90:150;let m=0;return{total:g,moving:u.length,step:w=>{for(let y=0;y<w&&m<g;y++,m++)_.tick()},place:()=>s.map((w,y)=>{const M=h[y];return{id:w.id,position:[M?.x??0,M?.y??0,M?.z??0],radius:l[y]??Lt}})}}function xB(s,e=3,t=new Map,i=jr,n=new Set){const r=kz(s,e,t,i,n);return r.step(r.total),r.place()}function OB(s,e,t=new Map,i=new Set){const n=Rz(s.map(r=>{const o={id:r.id,parents:[...r.parentIds,...r.joinParentIds]};return r.metric!==void 0&&(o.metric=r.metric),o}));return s.map(r=>{const o=t.get(r.id);return{id:r.id,parents:[...r.parentIds,...r.joinParentIds],radius:n.get(r.id)??Lt,group:r.ghost===!0?null:e(r),...r.attrs===void 0?{}:{attrs:r.attrs},...o===void 0?{}:{seed:o},...i.has(r.id)?{frozen:!0}:{}}})}const k0=160,N0=120,B0=5,EB=.9,G0=.3,AB=.9;function Nz(s,e){const t=new Map;for(const[i,n]of s)t.set(i,e===0||n/e>AB?0:Math.log(e/Math.max(1,n)));return t}function TB(s,e,t=()=>{}){const i=b=>typeof b.attrs?.plugin=="string"?b.attrs.plugin:null,n=b=>b.attrs?.kind==="star"&&i(b)!==null,r=s.filter(n),o=new Map(r.map(b=>[i(b),b])),a=s.filter(b=>!n(b)),l=new Map;for(const b of a){const z=i(b);b.group===null||z===null||!o.has(z)||l.set(b.group,(l.get(b.group)??new Set).add(z))}const c=new Map;for(const b of l.values())for(const z of b)c.set(z,(c.get(z)??0)+1);const h=Nz(c,l.size),d=Math.max(1e-9,...h.values()),u=new Map;for(const b of l.values()){const z=[...b].sort();for(let T=0;T<z.length;T++)for(let A=T+1;A<z.length;A++){const E=`${z[T]}\0${z[A]}`;u.set(E,(u.get(E)??0)+1)}}const p=Math.max(6,Math.sqrt(r.length)*4,Math.sqrt(a.length)*1.6),f=r.map(b=>P0(b,p,Ea(`star:${b.id}`))),_=[];for(const[b,z]of u){const[T,A]=b.split("\0"),E=Math.min(c.get(T)??1,c.get(A)??1);_.push({source:o.get(T).id,target:o.get(A).id,share:z/Math.max(1,E)})}if(f.length>0&&f.some(b=>b.fx===void 0)){const b=Nr(f,3).force("link",xo(_).id(z=>z.id).distance(z=>p*(1.1-Number(z.share))).strength(z=>.05+.6*Number(z.share))).force("charge",Br().strength(-30).distanceMax(p*3)).force("collide",kr().radius(z=>z.r*3)).force("center",_o(0,0,0)).stop();for(let z=0;z<k0;z++)b.tick(),z%4===0&&t(.4*(z/k0))}const g=new Map(f.map(b=>[b.id,[b.x??0,b.y??0,b.z??0]]));t(.4);const m=[...f.map(b=>({...b,fx:b.x??0,fy:b.y??0,fz:b.z??0})),...a.map(b=>{const z=i(b),T=z===null?void 0:o.get(z),A=T===void 0?void 0:g.get(T.id);return P0(b,2,Ea(`stage:${b.id}`),A)})],w=new Set(s.map(b=>b.id)),y=new Map(s.map(b=>[b.id,b.radius])),M=[];for(const b of a){for(const O of b.parents)w.has(O)&&M.push({source:O,target:b.id,strength:1,length:(y.get(O)??Lt)+b.radius+1.4});const z=i(b),T=z===null?void 0:o.get(z),A=z===null?0:h.get(z)??0,E=b.group===null?1:Math.max(1,l.get(b.group)?.size??1);if(T!==void 0&&A>0){const O=A/d,R=(G0+(EB-G0)*O)/Math.sqrt(E);M.push({source:T.id,target:b.id,strength:R,length:T.radius+b.radius+1})}}const v=Nr(m,3).force("link",xo(M).id(b=>b.id).distance(b=>Number(b.length)).strength(b=>Number(b.strength))).stop();if(e.charge){const b=Br().strength(z=>-6*(z.r/Lt)**2);b.distanceMax(Math.min(e.reach??B0,B0)),v.force("charge",b)}e.collide&&v.force("collide",kr().radius(b=>b.r*1.2));const S=m.some(b=>b.fx===void 0);for(let b=0;S&&b<N0;b++)v.tick(),b%4===0&&t(.4+.6*(b/N0));const x={};for(const b of m)x[b.id]=[b.x??0,b.y??0,b.z??0];return t(1),x}function P0(s,e,t,i=[0,0,0]){const n={id:s.id,r:s.radius},r=s.seed??[i[0]+(t()-.5)*2*e,i[1]+(t()-.5)*2*e,i[2]+(t()-.5)*2*e];return n.x=r[0],n.y=r[1],n.z=r[2],s.frozen===!0&&s.seed!==void 0&&(n.fx=r[0],n.fy=r[1],n.fz=r[2]),n}const Aa=.4,DB=400,Lo=.35,IB=.01,CB=3;function L0(s,e,t){let i=0,n=0;for(const r of new Set([...s,...e])){const o=t.get(r)??0;n+=o,s.has(r)&&e.has(r)&&(i+=o)}return n===0?0:i/n}const W0=1.4,RB=Math.PI/3;function kB(s,e){const t=new Map,i=new Map(s.map(h=>[h.id,h])),n=new Map,r=[];for(const h of s){const d=h.parents.find(u=>i.has(u));d===void 0?r.push(h):n.set(d,[...n.get(d)??[],h])}const o=new Map,a=[];r.forEach((h,d)=>{const u=bo(e),p=d===0?0:h.radius*2+W0;t.set(h.id,[u[0]*p,u[1]*p,u[2]*p]),o.set(h.id,u),a.push(h)});for(let h=a.shift();h!==void 0;h=a.shift()){const d=t.get(h.id),u=o.get(h.id);for(const p of n.get(h.id)??[]){if(t.has(p.id))continue;const f=e()*RB,_=NB(u,e),g=Bz([u[0]*Math.cos(f)+_[0]*Math.sin(f),u[1]*Math.cos(f)+_[1]*Math.sin(f),u[2]*Math.cos(f)+_[2]*Math.sin(f)]),m=h.radius+p.radius+W0;t.set(p.id,[d[0]+g[0]*m,d[1]+g[1]*m,d[2]+g[2]*m]),o.set(p.id,g),a.push(p)}}for(const h of s)t.has(h.id)||t.set(h.id,[0,0,0]);const l=[0,0,0];for(const h of t.values())l[0]+=h[0]/t.size,l[1]+=h[1]/t.size,l[2]+=h[2]/t.size;let c=Lt;for(const h of s){const d=t.get(h.id),u=[d[0]-l[0],d[1]-l[1],d[2]-l[2]];t.set(h.id,u),c=Math.max(c,Math.hypot(u[0],u[1],u[2])+h.radius)}return{local:t,radius:c}}function Bz(s){const e=Math.max(1e-9,Math.hypot(s[0],s[1],s[2]));return[s[0]/e,s[1]/e,s[2]/e]}function NB(s,e){const t=Math.abs(s[0])<.9?[1,0,0]:[0,1,0],i=Bz([s[1]*t[2]-s[2]*t[1],s[2]*t[0]-s[0]*t[2],s[0]*t[1]-s[1]*t[0]]),n=[s[1]*i[2]-s[2]*i[1],s[2]*i[0]-s[0]*i[2],s[0]*i[1]-s[1]*i[0]],r=e()*Math.PI*2;return[i[0]*Math.cos(r)+n[0]*Math.sin(r),i[1]*Math.cos(r)+n[1]*Math.sin(r),i[2]*Math.cos(r)+n[2]*Math.sin(r)]}function bo(s){const e=s()*2-1,t=s()*Math.PI*2,i=Math.sqrt(1-e*e);return[i*Math.cos(t),i*Math.sin(t),e]}class BB{size;cells=new Map;constructor(e){this.size=e}key(e){return`${Math.floor(e[0]/this.size)},${Math.floor(e[1]/this.size)},${Math.floor(e[2]/this.size)}`}add(e){const t=this.key(e.centre);this.cells.set(t,[...this.cells.get(t)??[],e])}touching(e,t){const i=[],[n,r,o]=[Math.floor(e[0]/this.size),Math.floor(e[1]/this.size),Math.floor(e[2]/this.size)];for(let a=-1;a<=1;a++)for(let l=-1;l<=1;l++)for(let c=-1;c<=1;c++)for(const h of this.cells.get(`${n+a},${r+l},${o+c}`)??[]){const d=t+h.particle.radius+Aa;Math.hypot(e[0]-h.centre[0],e[1]-h.centre[1],e[2]-h.centre[2])<d&&i.push(h)}return i}}function F0(s,e,t,i){let n=[e[0]-s.centre[0],e[1]-s.centre[1],e[2]-s.centre[2]];const r=Math.hypot(n[0],n[1],n[2]);n=r<1e-9?bo(i):[n[0]/r,n[1]/r,n[2]/r];const o=t+s.particle.radius+Aa;return[s.centre[0]+n[0]*o,s.centre[1]+n[1]*o,s.centre[2]+n[2]*o]}function GB(s,e,t=()=>{}){const i={},n={};if(s.length>0&&s.every(f=>f.frozen===!0&&f.seed!==void 0)){for(const f of s)i[f.id]=f.seed;return t(1),{positions:i,arrival:n}}const r=new Map;for(const f of s){if(f.group===null){i[f.id]=[0,0,0];continue}r.set(f.group,[...r.get(f.group)??[],f])}const o=[...r].map(([f,_])=>{const g=new Set;let m=Number.POSITIVE_INFINITY;for(const M of _){const v=M.attrs?.plugin;typeof v=="string"&&g.add(v);const S=M.attrs?.createdAt;typeof S=="number"&&S<m&&(m=S)}if(_.every(M=>M.frozen===!0&&M.seed!==void 0)){const M=_.map(b=>b.seed),v=[0,1,2].map(b=>M.reduce((z,T)=>z+T[b],0)/M.length),S=new Map;let x=Lt;for(const b of _){const z=b.seed,T=[z[0]-v[0],z[1]-v[1],z[2]-v[2]];S.set(b.id,T),x=Math.max(x,Math.hypot(T[0],T[1],T[2])+b.radius)}return{key:f,nodes:_,plugins:g,created:m,local:S,radius:x,held:!0,centre:v}}const{local:w,radius:y}=kB(_,Ea(`turn:${f}`));return{key:f,nodes:_,plugins:g,created:m,local:w,radius:y,held:!1}});o.sort((f,_)=>f.created-_.created||(f.key<_.key?-1:f.key>_.key?1:0));const a=new Map;for(const f of o)for(const _ of f.plugins)a.set(_,(a.get(_)??0)+1);const l=Nz(a,o.length),c=Math.max(Lt,...o.map(f=>f.radius)),h=new BB(2*c+Aa),d=[];let u=0;const p=(f,_,g)=>{const m={particle:f,centre:g};d.push(m),h.add(m),u=Math.max(u,Math.hypot(g[0],g[1],g[2])+f.radius);for(const w of f.nodes){const y=f.local.get(w.id)??[0,0,0];i[w.id]=f.held&&w.seed!==void 0?w.seed:[g[0]+y[0],g[1]+y[1],g[2]+y[2]],n[w.id]=_}};return o.forEach((f,_)=>{f.held&&f.centre!==void 0&&p(f,_,f.centre)}),o.forEach((f,_)=>{if(f.held)return;const g=Ea(`accrete:${f.key}`);let m;if(d.length===0)m=[0,0,0];else{let w=d[d.length-1],y=-1;for(const z of d){const T=L0(f.plugins,z.particle.plugins,l);T>=y&&(w=z,y=T)}const M=u+CB*f.radius+c,v=Math.max(.5,f.radius*.5),S=bo(g);let x=[S[0]*M,S[1]*M,S[2]*M],b=null;for(let z=0;z<DB&&b===null;z++){const T=bo(g),A=[w.centre[0]-x[0],w.centre[1]-x[1],w.centre[2]-x[2]],E=Math.max(1e-9,Math.hypot(A[0],A[1],A[2])),O=[T[0]*(1-Lo)+A[0]/E*Lo,T[1]*(1-Lo)+A[1]/E*Lo,T[2]*(1-Lo)+A[2]/E*Lo],R=[x[0]+O[0]*v,x[1]+O[1]*v,x[2]+O[2]*v],C=h.touching(R,f.radius);if(C.length===0){if(Math.hypot(R[0],R[1],R[2])>M*2){const L=bo(g);x=[L[0]*M,L[1]*M,L[2]*M]}else x=R;continue}let k=C[0],G=-1;for(const L of C){const W=L0(f.plugins,L.particle.plugins,l);W>G&&(k=L,G=W)}if(g()<Math.max(IB,G)&&(b=F0(k,x,f.radius,g),h.touching(b,f.radius-1e-6).some(L=>L!==k&&Gz(b,f.radius,L))&&(b=null)),b===null){const L=F0(k,x,f.radius,g),W=[L[0]-k.centre[0],L[1]-k.centre[1],L[2]-k.centre[2]],ee=Math.max(1e-9,Math.hypot(W[0],W[1],W[2]));x=[L[0]+W[0]/ee*v,L[1]+W[1]/ee*v,L[2]+W[2]/ee*v]}}m=b??PB(w,f.radius,h,g)}p(f,_,m),_%8===0&&t(_/Math.max(1,o.length))}),t(1),{positions:i,arrival:n}}function Gz(s,e,t){return Math.hypot(s[0]-t.centre[0],s[1]-t.centre[1],s[2]-t.centre[2])<e+t.particle.radius+Aa*.5}function PB(s,e,t,i){for(let o=0;o<8;o++)for(let a=0;a<24;a++){const l=bo(i),c=e+s.particle.radius+Aa+o*e,h=[s.centre[0]+l[0]*c,s.centre[1]+l[1]*c,s.centre[2]+l[2]*c];if(!t.touching(h,e).some(d=>Gz(h,e,d)))return h}const n=bo(i),r=e+s.particle.radius+Aa+8*e;return[s.centre[0]+n[0]*r,s.centre[1]+n[1]*r,s.centre[2]+n[2]*r]}function Pz(s){const e=new Map(s.map(f=>[f.id,f])),t=new Map,i=(f,_)=>{const g=t.get(f.id);if(g!==void 0)return g;if(_.has(f.id)||f.parentIds.length===0)return t.set(f.id,0),0;_.add(f.id);let m=0;for(const w of f.parentIds){const y=e.get(w);y&&(m=Math.max(m,i(y,_)+1))}return t.set(f.id,m),m};for(const f of s)i(f,new Set);const n=new Map,r=[],o=(f,_)=>f.id.localeCompare(_.id,void 0,{numeric:!0});for(const f of s){const _=f.parentIds.find(m=>e.has(m));if(_===void 0){r.push(f);continue}const g=n.get(_)??[];g.push(f),n.set(_,g)}r.sort(o);for(const f of n.values())f.sort(o);const a=new Map;let l=0;const c=new Set,h=f=>{c.add(f.id);const _=(n.get(f.id)??[]).filter(y=>!c.has(y.id));if(_.length===0){const y=l++;return a.set(f.id,y),[y,y]}let g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY;for(const y of _){const[M,v]=h(y);g=Math.min(g,M),m=Math.max(m,v)}const w=(g+m)/2;return a.set(f.id,w),[g,m]};for(const f of r)h(f);for(const f of s)a.has(f.id)||h(f);const d=Math.max(...Array.from(t.values()),0)+1,u=Math.max(l-1,0);return{placements:s.map(f=>({id:f.id,x:a.get(f.id)??0,tier:t.get(f.id)??0})),width:u,tierCount:d}}const LB=2.6,WB=2;function m_(s){const e=s.map(r=>r.metric??0),t=Math.max(...e,0),i=Pz(s),n=new Map(i.placements.map(r=>[r.id,r]));return s.map(r=>{const o=n.get(r.id),a=((o?.x??0)-i.width/2)*WB,l=((i.tierCount-1)/2-(o?.tier??0))*LB,c=r.metric??0,h=t>0?.55+c/t*1:1,d=[a,l,0];return{id:r.id,position:d,radius:Lt*h}})}const FB=.02;function UB(s){const e=new Map(s.nodes.map(a=>[a.id,a])),t=[],i=new Map;for(const a of s.edges){const l=e.get(a.from),c=e.get(a.to);l===void 0||c===void 0||l.halo||c.halo||(t.push({source:a.from,target:a.to}),i.set(a.from,[...i.get(a.from)??[],a.to]),i.set(a.to,[...i.get(a.to)??[],a.from]))}const n=new Set([s.grabbed]),r=[s.grabbed];for(;r.length>0;){const a=r.pop();for(const l of i.get(a)??[])n.has(l)||e.get(l)?.dim===!0||(n.add(l),r.push(l))}const o=t.filter(a=>n.has(a.source)&&n.has(a.target));return{ids:n,links:o}}class $B{nodes;grabbed;sim;constructor(e){const{ids:t,links:i}=UB(e),n=new Map(e.nodes.map(a=>[a.id,a.radius])),r=a=>n.get(a)??e.baseRadius,o=new Map(e.nodes.map(a=>[a.id,a.position]));this.nodes=[...t].filter(a=>o.has(a)).map(a=>{const[l,c,h]=o.get(a);return{id:a,x:l,y:c,z:h}}),this.sim=Nr(this.nodes,e.dimensions).force("link",xo(i).id(a=>a.id).distance(a=>r(a.source.id)+r(a.target.id)+1.4)).force("charge",Br().strength(a=>-6*(r(a.id)/e.baseRadius)**2).distanceMax(12)).force("collide",kr().radius(a=>r(a.id)*1.2)).alpha(.25).alphaTarget(.08).stop(),this.grabbed=this.nodes.find(a=>a.id===e.grabbed),this.grabbed!==void 0&&(this.grabbed.fx=this.grabbed.x,this.grabbed.fy=this.grabbed.y,this.grabbed.fz=this.grabbed.z)}pin(e){this.grabbed!==void 0&&([this.grabbed.fx,this.grabbed.fy,this.grabbed.fz]=e)}release(){this.grabbed!==void 0&&(this.grabbed.fx=null,this.grabbed.fy=null,this.grabbed.fz=null),this.sim.alphaTarget(0)}step(e){return!e&&this.sim.alpha()<=FB?!1:(this.sim.tick(),!0)}positions(){return this.nodes.map(e=>({id:e.id,position:[e.x,e.y,e.z]}))}}function eu(s){const e={id:s.id,parents:s.parents,radius:s.radius,group:s.group};return s.seed!==void 0&&(e.seed=s.seed),s.frozen!==void 0&&(e.frozen=s.frozen),e}function Lz(s){const e=s.attrs?.metric;return typeof e=="number"?e:void 0}function Wz(s){const e={};for(const t of s)e[t.id]=t.position;return e}const jB={id:"galaxy",label:"GALAXY",needs:[],run:(s,e)=>({positions:Iz(s.nodes.map(eu),s.physics,e)})},HB={id:"spokes",label:"SPOKES",needs:[],run:(s,e)=>({positions:p_(s.nodes.map(eu),s.physics,e,"spokes")})},VB={id:"clumps",label:"CLUMPS",needs:[],run:(s,e)=>({positions:p_(s.nodes.map(eu),s.physics,e,"clumps")})},qB={id:"ranked",label:"RANKED",needs:[],run:(s,e)=>{const t=s.nodes.map(n=>{const r={id:n.id,parentIds:n.parents},o=Lz(n);return o!==void 0&&(r.metric=o),r}),i=Wz(m_(t));return e(1),{positions:i}}},KB={id:"molecule",label:"MOLECULE",needs:[],run:(s,e)=>{const t=s.nodes.map(o=>{const a={id:o.id,parents:o.parents},l=Lz(o);return l!==void 0&&(a.metric=l),a}),i=new Map,n=new Set;for(const o of s.nodes)o.seed!==void 0&&i.set(o.id,o.seed),o.frozen===!0&&n.add(o.id);const r=Wz(xB(t,3,i,s.physics,n));return e(1),{positions:r}}},YB={id:"constellations",label:"CONSTELLATIONS",needs:["plugin"],run:(s,e)=>({positions:TB(s.nodes,s.physics,e)})},XB={id:"hubs",label:"HUBS",needs:[],run:(s,e)=>({positions:Iz(s.nodes.map(eu),s.physics,e)})},ZB={id:"accretion",label:"ACCRETION",needs:["plugin"],run:(s,e)=>GB(s.nodes,s.physics,e)},JB=[jB,HB,VB,YB,XB,ZB,qB,KB];function QB(s){return JB.find(e=>e.id===s)}function eG(s,e){const t=[];let i="",n=[],r=!1,o=0,a=!1;const l=()=>{n.push(i),i="",a=!0},c=()=>{t.push(n),n=[],a=!1};for(;o<s.length;){const h=s[o];if(r){if(h==='"'){if(s[o+1]==='"'){i+='"',o+=2;continue}r=!1,o+=1;continue}i+=h,o+=1;continue}if(h==='"'&&i===""){r=!0,o+=1;continue}if(h===e){l(),o+=1;continue}if(h==="\r"&&s[o+1]===`
|
|
90
90
|
`){l(),c(),o+=2;continue}if(h===`
|
|
91
|
-
`||h==="\r"){l(),c(),o+=1;continue}i+=h,o+=1}return(i!==""||a||n.length>0)&&(l(),c()),t}function tG(s){if(s.length===0)return!1;const e=new Set;for(const t of s){const i=t.trim();if(i===""||e.has(i.toLowerCase())||i!==""&&Number.isFinite(Number(i)))return!1;e.add(i.toLowerCase())}return!0}function sG(s,e){const t=/\.tsv$/i.test(e)?" ":",",i=eG(s,t);if(i.length===0)return{caps:[],rows:[],headed:!1};const n=i[0],r=tG(n),o=r?i.slice(1):i,a=i.reduce((h,d)=>Math.max(h,d.length),0),l=r?Array.from({length:a},(h,d)=>(n[d]??`COLUMN ${d+1}`).trim()):Array.from({length:a},(h,d)=>`COLUMN ${d+1}`),c=o.map(h=>Array.from({length:a},(d,u)=>h[u]??""));return{caps:l,rows:c,headed:r}}const U0=/\.json$/i,iG=4*1024*1024,Pu=/("(?:\\.|[^"\\])*")(\s*:)?|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|\b(true|false|null)\b/g;function $0(s){if(s.length>iG)return null;let e;try{e=JSON.parse(s)}catch{return null}const t=JSON.stringify(e,null,2),i=document.createDocumentFragment();let n=0;Pu.lastIndex=0;for(let r=Pu.exec(t);r!==null;r=Pu.exec(t)){r.index>n&&i.append(t.slice(n,r.index));const o=document.createElement("span"),[a,l,c,h,d]=r;l!==void 0?(o.className=c!==void 0?"json-key":"json-string",o.textContent=l,i.append(o),c!==void 0&&i.append(c)):h!==void 0?(o.className="json-number",o.textContent=h,i.append(o)):(o.className="json-literal",o.textContent=d??a,i.append(o)),n=r.index+a.length}return n<t.length&&i.append(t.slice(n)),i}const nG=/\.(?:md|markdown|adoc|asciidoc|asc)$/i,rG=2*1024*1024,j0="doc-";function Fz(s){return nG.test(s)}function oG(s){const e=new Map;for(const t of Array.from(s.querySelectorAll("h1, h2, h3, h4, h5, h6"))){if(t.id!=="")continue;const i=(t.textContent??"").trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu,"").replace(/\s/g,"-"),n=e.get(i)??0;e.set(i,n+1),t.id=n===0?i:`${i}-${n}`}}function aG(s){for(const e of Array.from(s.querySelectorAll("[id]")))e.id=`${j0}${e.id}`;for(const e of Array.from(s.querySelectorAll("a[href]"))){const t=e.getAttribute("href")??"";t.startsWith("#")?e.setAttribute("href",`#${j0}${t.slice(1)}`):/^(?:https?:|mailto:)/i.test(t)?(e.target="_blank",e.rel="noopener noreferrer"):(e.removeAttribute("href"),e.classList.add("doc-link-local"),e.title=t)}for(const e of Array.from(s.querySelectorAll("img"))){const t=document.createElement("span");t.className="doc-image",t.textContent=`[image: ${e.alt!==""?e.alt:e.getAttribute("src")??""}]`,e.replaceWith(t)}s.addEventListener("click",e=>{const t=e.target?.closest('a[href^="#"]')??null;if(t===null)return;e.preventDefault(),s.querySelector(`[id="${CSS.escape((t.getAttribute("href")??"").slice(1))}"]`)?.scrollIntoView({block:"start",behavior:"smooth"})})}async function Uz(s,e){if(e.length>rG)return null;const{documentHtml_build:t}=await Xl(async()=>{const{documentHtml_build:r}=await import("./documentEngines-
|
|
91
|
+
`||h==="\r"){l(),c(),o+=1;continue}i+=h,o+=1}return(i!==""||a||n.length>0)&&(l(),c()),t}function tG(s){if(s.length===0)return!1;const e=new Set;for(const t of s){const i=t.trim();if(i===""||e.has(i.toLowerCase())||i!==""&&Number.isFinite(Number(i)))return!1;e.add(i.toLowerCase())}return!0}function sG(s,e){const t=/\.tsv$/i.test(e)?" ":",",i=eG(s,t);if(i.length===0)return{caps:[],rows:[],headed:!1};const n=i[0],r=tG(n),o=r?i.slice(1):i,a=i.reduce((h,d)=>Math.max(h,d.length),0),l=r?Array.from({length:a},(h,d)=>(n[d]??`COLUMN ${d+1}`).trim()):Array.from({length:a},(h,d)=>`COLUMN ${d+1}`),c=o.map(h=>Array.from({length:a},(d,u)=>h[u]??""));return{caps:l,rows:c,headed:r}}const U0=/\.json$/i,iG=4*1024*1024,Pu=/("(?:\\.|[^"\\])*")(\s*:)?|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|\b(true|false|null)\b/g;function $0(s){if(s.length>iG)return null;let e;try{e=JSON.parse(s)}catch{return null}const t=JSON.stringify(e,null,2),i=document.createDocumentFragment();let n=0;Pu.lastIndex=0;for(let r=Pu.exec(t);r!==null;r=Pu.exec(t)){r.index>n&&i.append(t.slice(n,r.index));const o=document.createElement("span"),[a,l,c,h,d]=r;l!==void 0?(o.className=c!==void 0?"json-key":"json-string",o.textContent=l,i.append(o),c!==void 0&&i.append(c)):h!==void 0?(o.className="json-number",o.textContent=h,i.append(o)):(o.className="json-literal",o.textContent=d??a,i.append(o)),n=r.index+a.length}return n<t.length&&i.append(t.slice(n)),i}const nG=/\.(?:md|markdown|adoc|asciidoc|asc)$/i,rG=2*1024*1024,j0="doc-";function Fz(s){return nG.test(s)}function oG(s){const e=new Map;for(const t of Array.from(s.querySelectorAll("h1, h2, h3, h4, h5, h6"))){if(t.id!=="")continue;const i=(t.textContent??"").trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu,"").replace(/\s/g,"-"),n=e.get(i)??0;e.set(i,n+1),t.id=n===0?i:`${i}-${n}`}}function aG(s){for(const e of Array.from(s.querySelectorAll("[id]")))e.id=`${j0}${e.id}`;for(const e of Array.from(s.querySelectorAll("a[href]"))){const t=e.getAttribute("href")??"";t.startsWith("#")?e.setAttribute("href",`#${j0}${t.slice(1)}`):/^(?:https?:|mailto:)/i.test(t)?(e.target="_blank",e.rel="noopener noreferrer"):(e.removeAttribute("href"),e.classList.add("doc-link-local"),e.title=t)}for(const e of Array.from(s.querySelectorAll("img"))){const t=document.createElement("span");t.className="doc-image",t.textContent=`[image: ${e.alt!==""?e.alt:e.getAttribute("src")??""}]`,e.replaceWith(t)}s.addEventListener("click",e=>{const t=e.target?.closest('a[href^="#"]')??null;if(t===null)return;e.preventDefault(),s.querySelector(`[id="${CSS.escape((t.getAttribute("href")??"").slice(1))}"]`)?.scrollIntoView({block:"start",behavior:"smooth"})})}async function Uz(s,e){if(e.length>rG)return null;const{documentHtml_build:t}=await Xl(async()=>{const{documentHtml_build:r}=await import("./documentEngines-Dku3XAlE.js");return{documentHtml_build:r}},[],import.meta.url),i=/\.(?:md|markdown)$/i.test(s)?"markdown":"asciidoc",n=document.createElement("article");return n.className=`doc-rendered doc-${i}`,n.innerHTML=await t(e,i),i==="markdown"&&oG(n),aG(n),n}function lG(s){return s.model?.kind==="fs.listing"&&Array.isArray(s.model.data)&&s.model.data.length>0}function $z(s){const e=(s.renderedErr??s.rendered??"").replace(/\x1b\[[0-9;]*m/g,"").split(`
|
|
92
92
|
`).map(i=>i.trim()).filter(i=>i.length>0).join(" · "),t=[...s.errors??[]].reverse().find(i=>i.type==="error")?.message?.replace(/^\[[^\]]*\]\s*\|\s*/,"")??"";return e||t||"refused"}function H0(s){return/-v(\d+(?:\.\d+)*)$/.exec(s)?.[1]??""}const V0="",cG="/bin",q0="/bin/recent",Oc={dir:"",file:"",link:"",plugin:"",pipeline:"",vfs:"",job:""},Lu=["list","cards","preview"],hG=5e3,dG=new Set(["png","jpg","jpeg","gif","svg","webp","bmp"]),uG=new Set(["txt","md","adoc","rst","json","csv","tsv","log","yaml","yml","toml","ini","cfg","xml","html","py","sh","ts","js","mjs","r","c","h","cpp","java","go","rs","sql","tex","bib"]),K0=160,Y0=100,Ec=10,fG=30,pG=256*1024,mG=4e3,gG=12*1024*1024,_G=400;function tu(s){return dG.has(jz(s))}function jz(s){const e=s.split("/").pop()??"",t=e.lastIndexOf(".");return t>0?e.slice(t+1).toLowerCase():""}function bG(s){if(s.includes("\0"))return!0;const e=(s.match(/\uFFFD/g)??[]).length;return e>0&&e/s.length>.02}const MG=80;function X0(s,e){if(s===null)return[];const t=document.createElement("button");return t.className="files-close-pill files-download-pill",t.textContent="DOWNLOAD",t.title="save this file to your disk",t.addEventListener("click",()=>s.download(e)),[t]}function Z0(s){const e="http://www.w3.org/2000/svg",t=document.createElementNS(e,"svg");t.setAttribute("viewBox",`0 0 ${K0} ${Y0}`),t.setAttribute("preserveAspectRatio","xMidYMid meet");const i=Pz(s),n=Math.max(i.width,1),r=Math.max(i.tierCount-1,1),o=new Map;for(const a of i.placements)o.set(a.id,{x:Ec+a.x/n*(K0-2*Ec),y:Ec+a.tier/r*(Y0-2*Ec)});for(const a of s){const l=o.get(a.id);if(l)for(const c of a.parentIds){const h=o.get(c);if(!h)continue;const d=document.createElementNS(e,"line");d.setAttribute("x1",String(h.x)),d.setAttribute("y1",String(h.y)),d.setAttribute("x2",String(l.x)),d.setAttribute("y2",String(l.y)),d.setAttribute("stroke","currentColor"),d.setAttribute("stroke-width","1"),d.setAttribute("opacity","0.6"),t.appendChild(d)}}for(const[,a]of o){const l=document.createElementNS(e,"circle");l.setAttribute("cx",String(a.x)),l.setAttribute("cy",String(a.y)),l.setAttribute("r",s.length>fG?"2.2":"4"),l.setAttribute("fill","currentColor"),t.appendChild(l)}return t}function Ac(s){return s.type==="dir"||s.type==="vfs"||s.type==="link"||s.type==="job"?"dir":s.type==="file"?"file":s.type==="plugin"||s.type==="pipeline"?s.type:null}class Hz{container;recent=null;activate;listing;lastListings=[];contentShown=!1;denied=new Set;following=!1;viewMode="list";viewPill;modeSpan;preview;catalogue;runStrip=null;feedOpen=null;headCache=new Map;thumbObserver=null;frameTopObserver=null;stale=!1;home=null;ceiling=null;stateSpan;indicate=null;selectionVerbs=null;constructor(e,t,i=null,n={}){this.container=e,this.activate=t,this.preview=i,this.catalogue=n.catalogue===!0,this.catalogue&&e.parentElement?.classList.add("files-catalogue");const r=e.closest(".pane-files")??e.parentElement;this.viewPill=e.parentElement?.querySelector(".files-view")??null,this.modeSpan=e.closest(".pane-files")?.querySelector(".pane-mode")??null,this.stateSpan=r?.querySelector(".pane-state")??null,this.viewPill?.addEventListener("click",()=>{this.view_set(Lu[(Lu.indexOf(this.viewMode)+1)%Lu.length]??"list")});const o=e.parentElement?.querySelector(":scope > .mode-frame")!==null;this.listing=new sr({mount:e,traits:this.traits_declare(),key:a=>a.home===!0?"~":a.path,address:a=>a.path,chrome:r===null?void 0:{root:r,prefix:"files"},control:"control",activate:a=>this.row_activate(a),activatable:a=>a.updir||Ac(a.entry)!==null,indicated:a=>this.indicate?.(a.entry,a.path),row:{className:a=>`files-row files-type-${a.entry.type}${a.home===!0?" files-lead-home":a.updir?" files-lead-up":""}${!a.updir&&this.denied.has(a.path)?" files-denied":""}`,decorate:(a,l)=>{a.dataset.path=l.path,!l.updir&&this.denied.has(l.path)&&(a.title="listed but not readable — CUBE refused this identity access to the contents")}},...o?{selection:{verbs:a=>this.selectionVerbs?.(a.map(([l,c])=>[l,c.entry]))??[]}}:{},state:a=>this.stateLine_compose(a),defaultSort:{key:"name",dir:"asc"}}),this.empty_render()}traits_declare(){return this.catalogue?this.catalogueTraits_declare():this.browserTraits_declare()}browserTraits_declare(){return[{key:"control",label:"",className:"files-control",capped:!1,width:"2.4em",cell:e=>{const t=document.createElement("span"),i=e.updir?"dir":e.entry.type,n=e.updir||Ac(e.entry)!==null;return t.className=`files-control files-glyph files-glyph-${i}${n?" files-capsule":""}`,t.textContent=e.home===!0?V0:!e.updir&&this.denied.has(e.path)?"⃠":Oc[i],t}},{key:"name",label:"NAME",className:"files-name",width:"minmax(12em, 1fr)",cell:e=>{const t=document.createElement("span");if(t.className="files-name",t.textContent=e.home===!0?"~":e.entry.name,e.home===!0){const i=document.createElement("span");i.className="files-target",i.textContent=e.path,t.appendChild(i),t.title=`home: ${e.path}`}if(!e.updir&&e.entry.type==="link"&&e.entry.target!==void 0){const i=document.createElement("span");i.className="files-target",i.textContent=`→ ${e.entry.target}`,t.appendChild(i),t.title=e.entry.target}return t},compare:e=>e.entry.name},{key:"type",shed:2,label:"TYPE",className:"files-type",width:"6em",cell:e=>e.updir?"":e.entry.type},{key:"size",label:"SIZE",className:"files-size",width:"6em",cell:e=>e.updir||e.entry.type==="dir"?"":eM(e.entry.size),compare:e=>e.entry.size},{key:"date",shed:3,label:"DATE",className:"files-date",width:"7em",cell:e=>e.updir?"":e.entry.date.slice(0,10),compare:e=>e.entry.date},{key:"owner",shed:1,label:"OWNER",className:"files-owner",width:"10em",cell:e=>e.updir?"":e.entry.owner}]}row_activate(e){if(e.updir){this.activate({kind:"dir",path:e.path});return}const t=Ac(e.entry);t!==null&&this.activate({kind:t,path:e.path})}listing_fail(e){const t=e.trim().split(`
|
|
93
|
-
`)[0]?.slice(0,120)??"";Ts(this.stateSpan,"refused",`COULD NOT LIST${t===""?"":` · ${t.toUpperCase()}`}`);const i=this.lastListings.length===0?this.container.querySelector(".files-empty"):null;i!==null&&(i.textContent=`COULD NOT LIST — ${t}`)}envelope_observe(e){if(e.status==="error"&&!lG(e)){this.listing.activation_refuse($z(e));return}if(e.model?.kind!=="fs.listing")return;const t=J0(e.model.data);if(t===null||t.length===0)return;this.lastListings=t;const i=t[0]?.path??"";this.container.closest(".workspace-pane")?.classList.toggle("files-projection",/^\/(proc|net|etc|usr)(\/|$)/.test(i)),!this.contentShown&&this.listings_render(t)}ambient_observe(e){if(e.model?.kind!=="fs.listing")return;const t=J0(e.model.data);if(t===null||this.lastListings.length===0)return;let i=!1;const n=this.lastListings.map(r=>{const o=t.find(a=>a.path===r.path);return o===void 0?r:(i=!0,o)});if(i){if(this.contentShown){this.lastListings=n;return}this.listings_render(n)}}contentTable_show(e,t){const i=sG(t,e);if(i.caps.length===0){this.content_show(e,t);return}const n=i.rows.slice(0,hG),r=i.rows.length>n.length;this.contentRelease?.(),this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren(),this.diagram_declare(!1);const o=document.createElement("section");o.className="files-content-view files-table-view";const a=document.createElement("header");a.className="files-path files-content-header";const l=document.createElement("span");l.textContent=e;const c=document.createElement("span");c.className="pane-state",a.append(l,c);const h=document.createElement("div");h.className="files-table-field";const d=document.createElement("span");d.className="field-rule";const u=document.createElement("button");u.className="mode-strip",u.title="display modes";const p=document.createElement("span");p.className="mode-elbow";const f=document.createElement("aside");f.className="mode-frame";const _=document.createElement("button");_.className="strategy-pill csv-filter rail-off",_.textContent="FILTER OFF",_.title="filter the table";const g=document.createElement("button");g.className="strategy-pill csv-raw",g.textContent="RAW",g.title="the bytes as written",g.addEventListener("click",()=>this.content_show(e,t));const m=document.createElement("button");m.className="strategy-pill csv-close",m.textContent="CLOSE",m.title="leave the table; the listing beneath returns",m.addEventListener("click",()=>this.listing_restore());const w=document.createElement("span");w.className="mode-fill",f.append(_,g,w);const y=this.preview;if(y!==null){const x=document.createElement("button");x.className="strategy-pill csv-download",x.textContent="DOWNLOAD",x.title="save this file to your disk",x.addEventListener("click",()=>y.download(e)),f.append(x)}f.append(m);const M=document.createElement("div");M.className="files-table-rows",h.append(d,u,p,f,M),o.append(a,h),this.container.appendChild(o);const v=i.caps.map((x,b)=>({key:`c${b}`,label:x.toUpperCase(),className:"files-table-cell",cell:z=>z.cells[b]??"",width:"minmax(6em, 1fr)"}));new sr({mount:M,traits:v,key:x=>String(x.index),chrome:{root:o,prefix:"csv"},state:x=>{const b=[];return x.filter!==""?b.push(`${x.filter} ROWS`):b.push(r?`SHOWING ${n.length} OF ${i.rows.length} ROWS`:`${i.rows.length} ROWS`),i.headed||b.push("NO HEADER: COLUMNS NUMBERED"),b.join(" · ")},empty:()=>{const x=document.createElement("div");return x.className="files-note",x.textContent="NO ROWS",x}}).rows_set([{key:e,rows:n.map((x,b)=>({index:b,cells:x}))}],{field:e}),this.contentRelease=()=>{M.replaceChildren()}}content_show(e,t,i=!1,n=!1){this.diagram_declare(!1),this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren();const r=document.createElement("header");r.className="files-path files-content-header";const o=document.createElement("span");o.textContent=e;const a=document.createElement("button");a.className="files-close-pill",a.textContent="CLOSE",a.addEventListener("click",()=>this.listing_restore());const l=document.createElement("pre");l.className="files-content";const c=i||!U0.test(e)?null:$0(t),h=[];if(c!==null||i&&U0.test(e)&&$0(t)!==null){const u=document.createElement("button");u.className="files-close-pill",u.textContent=c!==null?"RAW":"PRETTY",u.addEventListener("click",()=>this.content_show(e,t,c!==null)),h.push(u)}const d=Fz(e);if(d){const u=document.createElement("button");u.className="files-close-pill files-render-pill",u.textContent=n?"SOURCE":"RENDERED",u.title=n?"the document as written":"the document as its page",u.addEventListener("click",()=>this.content_show(e,t,!1,!n)),h.push(u)}if(r.append(o,...X0(this.preview,e),...h,a),c!==null?(l.classList.add("files-json"),l.append(c)):l.textContent=t,this.container.append(r,l),ai(l),c===null){if(d&&n){Uz(e,t).then(u=>{u===null||!l.isConnected||(u.classList.add("files-content"),l.replaceWith(u),ai(u))}).catch(()=>{});return}Xl(async()=>{const{sourceSpans_build:u}=await import("./syntax-BErZglCz.js").then(p=>p.ao);return{sourceSpans_build:u}},[],import.meta.url).then(({sourceSpans_build:u})=>u(t,Zg(e))).then(u=>{if(u===null||!l.isConnected)return;const p=l.querySelector(":scope > .more-chip");l.replaceChildren(u),p!==null&&l.append(p),l.classList.add("files-source")}).catch(()=>{})}}contentRefused_show(e,t){this.diagram_declare(!1),this.denied.add(e),this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren();const i=document.createElement("header");i.className="files-path files-content-header files-content-refused";const n=document.createElement("span");n.textContent=e;const r=document.createElement("button");r.className="files-close-pill",r.textContent="CLOSE",r.addEventListener("click",()=>this.listing_restore()),i.append(n,r);const o=document.createElement("div");o.className="files-refused";const a=document.createElement("p");a.className="files-refused-lede",a.textContent="READ REFUSED";const l=document.createElement("pre");l.className="files-refused-said",l.textContent=t,o.append(a,l),this.container.append(i,o)}contentImage_show(e,t){this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren();const i=document.createElement("header");i.className="files-path files-content-header";const n=document.createElement("span");n.textContent=e;const r=document.createElement("button");r.className="files-close-pill",r.textContent="CLOSE",r.addEventListener("click",()=>this.listing_restore()),i.append(n,...X0(this.preview,e),r);const o=document.createElement("img");o.className="files-image",o.src=t,o.alt=e,this.container.append(i,o)}rowVerbs_declare(e,t){this.indicate=t??null,this.listing.actions_declare({of:i=>i.updir?[]:e(i.entry,i.path).map(n=>({label:n.label,run:()=>n.run(i.entry),...n.offered!==void 0?{offered:()=>n.offered(i.entry)}:{},...n.disabled!==void 0?{disabled:()=>n.disabled(i.entry)}:{}}))})}catalogueTraits_declare(){return[...this.browserTraits_declare().filter(i=>i.key==="control"||i.key==="name"),{key:"type",label:"TYPE",className:"files-type",width:"6em",cell:i=>i.updir?"":i.entry.type},{key:"version",label:"VERSION",className:"files-version",width:"7em",cell:i=>i.updir?"":H0(i.entry.name),compare:i=>H0(i.entry.name)}]}catalogue_is(){return this.catalogue}binding_set(e){if(this.runStrip===null){const i=document.createElement("div");i.className="files-run-strip";const n=document.createElement("span");n.className="files-binding";const r=document.createElement("input");r.className="files-command",r.spellcheck=!1,r.autocomplete="off",r.placeholder="the line RUN will run",i.append(n,r),this.container.parentElement?.insertBefore(i,this.container),this.runStrip=i;const o=this.container.closest(".pane-files")?.querySelector(".pane-title");o!=null&&(o.textContent="CATALOGUE")}const t=this.runStrip.querySelector(".files-binding");t!==null&&(t.textContent=`INPUT ${e.input} → ${e.place}`),this.frameTop_track()}commandLine_get(){return this.runStrip?.querySelector(".files-command")?.value.trim()??""}commandLine_set(e){const t=this.runStrip?.querySelector(".files-command")??null;t!==null&&(t.value=e)}indicated_get(){return this.listing.indicated_get()}feedOpen_declare(e){this.feedOpen=e}run_show(e){if(this.runStrip===null)return;this.runStrip.querySelector(".files-feed")?.remove();const t=document.createElement("button");t.className="files-feed listing-capsule listing-action-selected",t.textContent=`FEED ${e}`,t.title="open this run's graph beside the catalogue",t.addEventListener("click",()=>this.feedOpen?.(e)),this.runStrip.appendChild(t)}row_indicate(e){this.listing.row_indicate(e)}rowReadout_show(e,t){this.listing.readout_show(e,t)}selectionVerbs_declare(e){this.selectionVerbs=e}select_toggle(e){this.listing.select_toggle(e)}select_isOn(){return this.listing.select_isOn()}selection_get(){return this.listing.selection_get()}path_current(){return this.lastListings[0]?.path??null}content_isShown(){return this.contentShown}contentRelease=null;contentHtml_show(e,t,i={}){this.contentRelease?.(),this.contentRelease=i.release??null,this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren();const n=document.createElement("section");n.className="files-content-view";const r=document.createElement("header");r.className="files-path files-content-header";const o=document.createElement("span");o.textContent=e;const a=document.createElement("button");if(a.className="files-close-pill",a.textContent="CLOSE",a.addEventListener("click",()=>this.listing_restore()),r.append(o,a),n.appendChild(r),t!==""){const c=document.createElement("pre");c.className="files-content",c.innerHTML=t,n.appendChild(c)}let l=null;return i.diagram===!0&&(l=document.createElement("div"),l.className="files-diagram",n.appendChild(l)),this.diagram_declare(i.diagram===!0),this.container.appendChild(n),l}contentText_set(e){const t=this.container.querySelector(".files-content-view");if(t===null)return;const i=t.querySelector(".files-content"),n=i??document.createElement("pre");n.className="files-content",n.innerHTML=e,i===null&&t.querySelector(".files-content-header")?.after(n)}recent_set(e){this.recent=e===null?null:[...e],this.lastListings.length>0&&!this.contentShown&&this.listings_render(this.lastListings)}listing_restore(){this.contentRelease?.(),this.contentRelease=null,this.lastListings.length>0?this.listings_render(this.lastListings):this.empty_render()}empty_render(){this.diagram_declare(!1),this.container.replaceChildren();const e=document.createElement("p");e.className="files-empty",e.textContent="AWAITING LISTING — TYPE ls IN THE CONSOLE",this.container.appendChild(e)}listings_render(e){this.diagram_declare(!1),this.contentShown=!1,this.container.parentElement?.classList.remove("content-view"),this.lastListings=e,this.thumbObserver?.disconnect(),this.thumbObserver=null,this.stale=e.some(n=>n.fresh===!1),$2(this.stateSpan,"stale",this.stale),this.listing.painter_set(this.viewMode==="list"?null:(n,r)=>this.cards_paint(n,r));const t=e.map(n=>this.block_build(n)),i=e.find(n=>n.path===cG);if(this.recent!==null&&this.recent.length>0&&i!==void 0){const n=this.recentBlock_build(i);n!==null&&t.unshift(n)}this.listing.rows_set(t,{field:e[0]?.path??""}),this.frameTop_track()}crumbs_build(e){const t=document.createElement("header");t.className="files-path files-crumbs";const i=[],n=this.home;let r;n!==null&&(e===n||e.startsWith(`${n}/`))?(i.push({label:"~",path:n}),r=e.slice(n.length)):(i.push({label:"/",path:"/"}),r=e);let o=i[0]?.path??"/";for(const a of r.split("/").filter(l=>l.length>0))o=o==="/"?`/${a}`:`${o}/${a}`,i.push({label:a,path:o});return i.forEach((a,l)=>{l>0&&i[l-1]?.label!=="/"&&t.append("/");const c=l===i.length-1,h=document.createElement(c?"span":"button");h.className=c?"files-crumb files-crumb-here":"files-crumb",h.textContent=a.label,h.dataset.path=a.path,c||(h.title=`go to ${a.path}`,h.addEventListener("click",d=>{d.stopPropagation(),this.activate({kind:"dir",path:a.path})})),t.appendChild(h)}),this.catalogue||t.appendChild(Ky(e)),t}link_copy(e){const t=Q0(e),n=[...this.container.querySelectorAll(".files-crumbs")].filter(r=>r.querySelector(".files-crumb-here")?.dataset.path===t||r.querySelector(".files-crumb-here")?.dataset.path===e).map(r=>r.querySelector(".link-line")).filter(r=>r!==null)[0];return n===void 0?null:(Ng(n,e),Yy(n))}ceiling_set(e,t=".."){this.ceiling=e===null?null:{path:e.replace(/\/+$/,"")||"/",word:t}}home_set(e){e!==this.home&&(this.home=e,!this.contentShown&&this.lastListings.length>0&&this.listings_render(this.lastListings))}block_build(e){const t=this.crumbs_build(e.path),i=e.items.map(r=>({entry:r,path:Tc(e.path,r.name),updir:!1})),n=[];if(!this.catalogue&&this.home!==null&&e.path!==this.home&&n.push({entry:{name:"~",type:"dir",size:0,owner:"",date:""},path:this.home,updir:!0,home:!0}),e.path!=="/"){const r=this.ceiling!==null&&this.ceiling.path===e.path?this.ceiling.word:"..";n.push({entry:{name:r,type:"dir",size:0,owner:"",date:""},path:Q0(e.path),updir:!0})}return{key:e.path,header:t,lead:n,rows:i}}recentBlock_build(e){const t=new Map(e.items.map(r=>[r.name,r])),i=[];for(const r of this.recent??[]){const o=t.get(r);o!==void 0&&i.push({entry:o,path:Tc(q0,r),updir:!1})}if(i.length===0)return null;const n=document.createElement("header");return n.className="files-path files-recent",n.textContent="RECENT",{key:q0,header:n,lead:[],rows:i}}cards_paint(e,t){const i=this.viewMode==="preview",n=document.createElement("div");n.className=i?"files-cards files-previews":"files-cards";for(const o of e.lead??[]){const a=document.createElement("article");a.className=o.home===!0?"files-card files-card-up files-card-home files-activatable":"files-card files-card-up files-activatable",a.textContent=o.home===!0?`${V0} ~`:"▴ ..",a.addEventListener("click",()=>this.activate({kind:"dir",path:o.path})),n.appendChild(a)}const r=e.key;for(const o of e.rows)n.appendChild(this.card_build(r,o.entry,i));t.appendChild(n)}frameTop_track(){const e=this.container.parentElement,t=this.container.querySelector(".roster-order"),i=this.container.querySelector(".files-path");if(this.frameTopObserver?.disconnect(),this.frameTopObserver=null,e===null)return;if(t===null||i===null){e.style.removeProperty("--mode-frame-top"),e.style.removeProperty("--roster-frame-h");return}const n=()=>{const r=e.getBoundingClientRect().top,o=Math.ceil(t.getBoundingClientRect().bottom-r);e.style.setProperty("--roster-frame-h",`${o}px`),e.style.setProperty("--mode-frame-top",`${Math.ceil(i.getBoundingClientRect().bottom-r)}px`)};n(),this.frameTopObserver=new ResizeObserver(n),this.frameTopObserver.observe(t),this.frameTopObserver.observe(i)}follow_set(e){this.following=e,this.listing.state_refresh()}follow_get(){return this.following}view_set(e){this.viewMode=e,this.viewPill!==null&&(this.viewPill.textContent=e.toUpperCase()),this.modeSpan!==null&&(this.modeSpan.textContent=e==="list"?"":e.toUpperCase()),this.lastListings.length>0&&!this.contentShown&&this.listings_render(this.lastListings)}view_get(){return this.viewMode}body_get(){return this.container.closest(".files-body")}diagram_declare(e){this.body_get()?.classList.toggle("diagram-shown",e),e||this.mode_annunciate(this.viewMode==="list"?"":this.viewMode.toUpperCase())}mode_annunciate(e){this.modeSpan!==null&&(this.modeSpan.textContent=e)}stateLine_compose(e){const t=[];return this.following&&t.push("CWD"),e.selecting&&t.push("SELECT"),t.push(this.stale?"STALE":e.filter),e.selected>0&&t.push(e.shown===e.selected?`${e.selected} SELECTED`:`${e.selected} SELECTED · ${e.shown} SHOWN`),t.filter(i=>i!=="").join(" · ")}card_build(e,t,i=!1){const n=document.createElement("article");n.className=`files-card files-type-${t.type}`,i&&n.appendChild(this.thumb_build(Tc(e,t.name),t));const r=document.createElement("div");r.className="files-card-head";const o=document.createElement("span");o.className="files-card-badge",o.textContent=t.type.toUpperCase();const a=document.createElement("span");a.className="files-card-size",a.textContent=t.type==="dir"||t.size===0?"":eM(t.size),r.append(o,a);const l=document.createElement("div");l.className="files-card-title",l.textContent=t.name;const c=document.createElement("div");c.className="files-card-meta";const h=document.createElement("span");h.textContent=t.owner;const d=document.createElement("span");if(d.textContent=t.date.slice(0,10),c.append(h,d),n.append(r,l,c),t.type==="link"&&t.target!==void 0){const f=document.createElement("div");f.className="files-card-target",f.textContent=`→ ${t.target}`,f.title=t.target,n.appendChild(f)}const u=Tc(e,t.name),p=Ac(t);return p!==null&&(n.classList.add("files-activatable"),n.addEventListener("click",()=>this.activate({kind:p,path:u}))),n}thumb_build(e,t){const i=document.createElement("div");i.className="files-card-thumb";const n=()=>{i.textContent=Oc[t.type]};if(bz.test(t.name)||_d.test(t.name)){i.classList.add("thumb-series");const d=document.createElement("span");d.className="thumb-series-mark",d.textContent="DCM";const u=/^\d+-(.*)-[0-9a-f]{7}$/.exec(t.name)?.[1];if(i.replaceChildren(d),u!==void 0){const p=document.createElement("span");p.className="thumb-series-text",p.textContent=u.replace(/_/g," "),i.appendChild(p)}return i}if(this.preview===null||!(t.type==="file"||t.type==="plugin"||t.type==="pipeline"))return n(),i;if(t.type==="plugin")return i.replaceChildren(Z0([{id:e,parentIds:[]}])),i;if(t.type==="pipeline"){const d=this.preview;i.classList.add("thumb-wait"),i.textContent=Oc[t.type];const u=()=>{d.pipelineGlimpse(e).then(p=>{if(i.classList.remove("thumb-wait"),p===null||p.length===0){n();return}if(p.length>MG){i.textContent=`${p.length} NODES`,i.classList.add("thumb-count");return}i.replaceChildren(Z0(p))}).catch(()=>{i.classList.remove("thumb-wait"),n()})};return this.thumbObserver_get().observe(i),i.addEventListener("files:thumb-seen",u,{once:!0}),i}const r=this.headCache.get(e);if(r!==void 0){const d=document.createElement("pre");return d.textContent=r,i.appendChild(d),i}const o=tu(e)&&t.size<=gG,a=jz(e),l=(a===""||uG.has(a))&&t.size<=pG;if(!o&&!l)return n(),i;i.classList.add("thumb-wait"),i.textContent=Oc.file;const c=this.preview,h=()=>{if(o){const d=document.createElement("img");d.alt=t.name,d.addEventListener("load",()=>{i.classList.remove("thumb-wait")}),d.addEventListener("error",()=>{i.classList.remove("thumb-wait"),n()}),d.src=c.imageUrl(e),i.replaceChildren(d);return}c.textHead(e,mG).then(d=>{if(this.headCache.size>=_G&&this.headCache.clear(),this.headCache.set(e,d),i.classList.remove("thumb-wait"),d.trim()===""||bG(d)){n();return}const u=document.createElement("pre");u.textContent=d,i.replaceChildren(u)}).catch(()=>{i.classList.remove("thumb-wait"),n()})};return this.thumbObserver_get().observe(i),i.addEventListener("files:thumb-seen",h,{once:!0}),i}thumbObserver_get(){return this.thumbObserver===null&&(this.thumbObserver=new IntersectionObserver(e=>{for(const t of e)t.isIntersecting&&(this.thumbObserver?.unobserve(t.target),t.target.dispatchEvent(new CustomEvent("files:thumb-seen")))},{root:this.container,rootMargin:"25%"})),this.thumbObserver}filter_toggle(e){this.listing.filter_toggle(e)}}function J0(s){if(!Array.isArray(s))return null;for(const e of s){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.path!="string"||!Array.isArray(t.items))return null}return s}function Tc(s,e){return s.endsWith("/")?`${s}${e}`:`${s}/${e}`}function Q0(s){const e=s.endsWith("/")?s.slice(0,-1):s,t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function eM(s){if(s<1024)return String(s);const e=["K","M","G","T"];let t=s,i=-1;for(;t>=1024&&i<e.length-1;)t=t/1024,i=i+1;return`${t<10?t.toFixed(1):Math.round(t)}${e[i]}`}class vG{grid;startHere;host;paintId=0;constructor(e,t){this.host=t,this.grid=e.querySelector(".launcher-grid"),ai(this.grid,{rows:".launcher-tile",mount:this.grid.parentElement??this.grid});const i=e.querySelector(".launcher-body");i!==null&&ai(i,{rows:".launcher-tile",scrolls:()=>/auto|scroll/.test(getComputedStyle(i).overflowY)}),this.startHere=e.querySelector(".launcher-start"),this.startHere.addEventListener("click",()=>{this.host.startHere_set(!this.host.startHere_get()),this.startHere_render()}),this.startHere_render()}render(){const e=++this.paintId;this.host.tiles().then(t=>{e!==this.paintId||!this.grid.isConnected||(this.grid.replaceChildren(...t.map((i,n)=>this.tile_build(i,n===0||i.wide===!0))),this.startHere_render())}).catch(()=>{e!==this.paintId||!this.grid.isConnected||this.grid.replaceChildren()})}numeral_press(e){const t=this.grid.querySelector(`[data-numeral="${e}"]`);return t===null?!1:(t.click(),!0)}startHere_render(){const e=this.host.startHere_get();this.startHere.textContent=e?"START HERE · ON":"START HERE · OFF",this.startHere.classList.toggle("pacs-capsule-off",!e)}tile_build(e,t){const i=document.createElement("button");i.className=`launcher-tile${t?" launcher-tile-wide":""}`,i.style.setProperty("--tile-hue",`var(${e.hue})`),i.dataset.numeral=e.numeral,i.title=e.verb,i.addEventListener("click",h=>{h.target instanceof Element&&h.target.closest(".launcher-row, .launcher-figure")!==null||(this.host.leave?.(),e.enter())});const n=document.createElement("span");n.className="launcher-head";const r=document.createElement("span");r.className="launcher-name",r.textContent=e.name;const o=document.createElement("span");o.className="launcher-numeral",o.textContent=e.numeral,n.append(r);for(const h of e.figures){const d=document.createElement(h.open===void 0?"span":"button");if(d.className=`launcher-figure${h.errored===!0?" launcher-figure-errored":""}`,d.textContent=h.text,h.open!==void 0){const u=h.open;d.addEventListener("click",p=>{p.stopPropagation(),this.host.leave?.(),u()})}n.appendChild(d)}n.appendChild(o);const a=document.createElement("span");a.className="launcher-rule";const l=document.createElement("span");l.className="launcher-rows";for(const h of e.rows){const d=document.createElement(h.open===void 0?"span":"button");d.className=`launcher-row${h.arrived===!0?" launcher-row-arrived":""}`;const u=document.createElement("span");u.className=`launcher-dot${h.errored===!0?" launcher-dot-errored":""}`;const p=document.createElement("span");if(p.className="launcher-row-text",p.textContent=h.text,d.append(u,p),h.open!==void 0){const f=h.open,_=document.createElement("span");_.className="launcher-go",_.textContent="›",d.appendChild(_),d.addEventListener("click",g=>{g.stopPropagation(),this.host.leave?.(),f()})}l.appendChild(d)}const c=document.createElement("span");return c.className="launcher-verb",c.textContent=e.verb,i.append(n,a),e.about!==void 0&&i.appendChild(wG(e.about)),i.append(l,c),i}}function wG(s){const e=document.createElement("span");e.className="launcher-about";const t=document.createElement("span");if(t.className="launcher-about-text",t.textContent=s.text,e.appendChild(t),s.list!==void 0&&s.list.length>0){const i=document.createElement("span");i.className="launcher-about-list";for(const n of s.list){const r=document.createElement("span");r.className="launcher-about-item",r.textContent=n,i.appendChild(r)}e.appendChild(i)}if(s.tail!==void 0){const i=document.createElement("span");i.className="launcher-about-text",i.textContent=s.tail,e.appendChild(i)}return e}const Fi={left:{axis:"col",place:"before",focusWord:"left",arrow:"ArrowLeft",edge:"leftmost"},right:{axis:"col",place:"after",focusWord:"right",arrow:"ArrowRight",edge:"rightmost"},above:{axis:"row",place:"before",focusWord:"up",arrow:"ArrowUp",edge:"topmost"},below:{axis:"row",place:"after",focusWord:"down",arrow:"ArrowDown",edge:"bottommost"}},Vz=["left","right","above","below"];function tM(s){return s==="left"||s==="right"||s==="above"||s==="below"}function yG(s,e){return s==="row"?e?"above":"below":e?"left":"right"}function SG(s,e){return s!=="row"&&s!=="col"||e!=="before"&&e!=="after"?null:yG(s,e==="before")}function zG(s){return Vz.find(e=>Fi[e].focusWord===s)??null}function xG(s){return Vz.find(e=>Fi[e].arrow===s)??null}function OG(s){return s?"before":"after"}function Ri(s){return`[data-split="${Fi[s].axis}"][data-place="${Fi[s].place}"]`}const su=new Set(["pane","view","file","header","console","back","desktop","dashboard","help","notes","launcher","attach","argus","trek","stratus","chris","capacity"]),EG=new Set(su),g_={help:new Set(["pane","keys","verbs"]),notes:new Set(["pane"]),capacity:new Set(["pane"]),file:new Set(["home","back","download","delete","follow","root","open","list","cards","preview","sort","filter"]),trek:new Set(["","--seed"])};let Vn=null,Mn=null;const Wo="argus.desktop.",sM="~/.config/argus/desktops";function iM(){return[...su].sort().map(s=>{const e=g_[s];return e===void 0?{subject:s}:{subject:s,verbs:[...e].sort()}})}function AG(s){const e=s.trim().split(/\s+/),t=(e[0]??"").toLowerCase();if(!su.has(t))return null;const i=g_[t];if(i!==void 0&&!i.has((e[1]??"").toLowerCase()))return null;let n=null,r=e.slice(1);return(r[0]?.startsWith("@")||r[0]?.startsWith("%"))&&(n=r[0],r=r.slice(1)),{subject:t,target:n,words:r}}function Wu(s,e){if(e===null)return s.focused_get();if(e.startsWith("@"))return e.slice(1);const t=parseInt(e.slice(1),10);return Mn===null?null:Mn[t-1]??null}function TG(s,e,t){return e!==null&&t.includes(s.paneKind_get(e)??"")?e:s.panes_shown().find(i=>t.includes(s.paneKind_get(i)??""))??null}function jn(s,e,t){const n=s.paneMount_get(e)?.querySelector(t)??null;return n===null?!1:(n.click(),!0)}function kh(s,e,t){const i=s.paneMount_get(e);if(i===null)return!1;for(const n of i.querySelectorAll(".drawer-child"))if(n.textContent?.trim().toUpperCase()===t)return n.click(),!0;return!1}function DG(s,e,t){return jn(s,e,`.drawer-cwdbind[data-follow="${t?"on":"off"}"]`)}function no(s,e,t,i){const r=s.paneMount_get(e)?.querySelector(t)??null;if(r===null)return!1;for(let o=0;o<4;o++){if(r.textContent?.trim().toUpperCase()===i)return!0;r.click()}return r.textContent?.trim().toUpperCase()===i}function qz(s,e){const t=s.focused_get(),i=t!==null?s.paneRect_get(t):null;if(i===null)return null;const n=i.x+i.width/2,r=i.y+i.height/2;let o=null;for(const a of s.panes_shown()){if(a===t)continue;const l=s.paneRect_get(a);if(l===null)continue;const c=l.x+l.width/2-n,h=l.y+l.height/2-r,d=e==="left"?-c:e==="right"?c:e==="up"?-h:h;if(d<=1)continue;const u=Math.abs(e==="left"||e==="right"?h:c),p=d+u*2;(o===null||p<o.score)&&(o={id:a,score:p})}return o===null?null:(s.focus_set(o.id),o.id)}const zn=[{key:"%",topic:"pane",selector:Ri("right"),does:"split right (tmux)"},{key:'"',topic:"pane",selector:Ri("below"),does:"split below (tmux)"},{key:"h",topic:"pane",selector:Ri("left"),does:"split left"},{key:"j",topic:"pane",selector:Ri("below"),does:"split below"},{key:"k",topic:"pane",selector:Ri("above"),does:"split above"},{key:"l",topic:"pane",selector:Ri("right"),does:"split right"},{key:"H",topic:"pane",selector:Ri("left"),does:"move this pane left",move:!0},{key:"J",topic:"pane",selector:Ri("below"),does:"move this pane below",move:!0},{key:"K",topic:"pane",selector:Ri("above"),does:"move this pane above",move:!0},{key:"L",topic:"pane",selector:Ri("right"),does:"move this pane right",move:!0},{key:"m",topic:"pane",selector:'.drawer-mode[data-mode="move"]',does:"arm MOVE (then a direction)"},{key:"z",topic:"pane",selector:".drawer-zoom",does:"zoom (tmux), or double-click the pane's header"},{key:"x",topic:"pane",selector:".drawer-close",does:"close (tmux)"},{key:"u",topic:"binding",selector:'.drawer-bind[data-bind="unlinked"]',does:"the next split is unlinked"},{key:"f",topic:"binding",selector:'.drawer-bind[data-bind="fs"]',does:"the next split is a linked filesystem"},{key:"v",topic:"binding",selector:'.drawer-bind[data-bind="viewer"]',does:"the next split is a linked viewer"},{key:"1",topic:"claim",selector:".empty-go-files",does:"claim an empty pane as FILES"},{key:"o",topic:"focus",selector:null,does:"focus the next pane (tmux)"},{key:";",topic:"focus",selector:null,does:"focus the last pane (tmux)"},{key:"q",topic:"focus",selector:null,does:"show every pane's @id on its bar (tmux)"},{key:"Space",topic:"pane",selector:null,does:"flip this pane's split: beside becomes above (tmux next layout)"},{key:"!",topic:"pane",selector:null,does:"break this pane out: alone on stage, the rest a PANES card (tmux)"},{key:"Ctrl-←↑↓→",topic:"pane",selector:null,does:"move the boundary beside this pane a step (tmux)"},{key:"w",topic:"stage",selector:null,does:"PANES, the desktops (tmux window chooser)"},{key:"r",topic:"focus",selector:null,does:"the keys into this pane's frame: Tab or ↑↓ walk its verbs, Enter presses, ← or Esc leaves"},{key:"&",topic:"pane",selector:null,does:"close every pane on the stage (tmux kill-window)"},{key:"[",topic:"console",selector:null,does:"the console's scrollback takes the keys (tmux)"},{key:"O",topic:"focus",selector:null,does:"focus the previous pane"},{key:"←↑↓→",topic:"focus",selector:null,does:"focus the pane in that direction (tmux)"},{key:":",topic:"console",selector:null,does:"the command line (tmux)"},{key:"?",topic:"console",selector:null,does:"this table"}];function Kz(s){let e=0;for(const t of s.panes_shown())jn(s,t,".drawer-close")&&(e+=1);return`closed ${e} pane${e===1?"":"s"}`}function Yz(){return["prefix chords — Ctrl-B opens the focused pane's drawer; one key then presses one capsule",...zn.map(s=>` ${s.key.padEnd(6)} ${s.does}`)," Tab walks the verbs; Enter fires; Esc closes the drawer","in a pane holding a listing, no prefix needed:"," ↑↓ move the row cursor (Home/End: first/last)"," Enter indicates the row (its verbs ride the frame); Enter again goes (opens, enters, folds open)"," → the keys into the frame, as Ctrl-B r"].join(`
|
|
93
|
+
`)[0]?.slice(0,120)??"";Ts(this.stateSpan,"refused",`COULD NOT LIST${t===""?"":` · ${t.toUpperCase()}`}`);const i=this.lastListings.length===0?this.container.querySelector(".files-empty"):null;i!==null&&(i.textContent=`COULD NOT LIST — ${t}`)}envelope_observe(e){if(e.status==="error"&&!lG(e)){this.listing.activation_refuse($z(e));return}if(e.model?.kind!=="fs.listing")return;const t=J0(e.model.data);if(t===null||t.length===0)return;this.lastListings=t;const i=t[0]?.path??"";this.container.closest(".workspace-pane")?.classList.toggle("files-projection",/^\/(proc|net|etc|usr)(\/|$)/.test(i)),!this.contentShown&&this.listings_render(t)}ambient_observe(e){if(e.model?.kind!=="fs.listing")return;const t=J0(e.model.data);if(t===null||this.lastListings.length===0)return;let i=!1;const n=this.lastListings.map(r=>{const o=t.find(a=>a.path===r.path);return o===void 0?r:(i=!0,o)});if(i){if(this.contentShown){this.lastListings=n;return}this.listings_render(n)}}contentTable_show(e,t){const i=sG(t,e);if(i.caps.length===0){this.content_show(e,t);return}const n=i.rows.slice(0,hG),r=i.rows.length>n.length;this.contentRelease?.(),this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren(),this.diagram_declare(!1);const o=document.createElement("section");o.className="files-content-view files-table-view";const a=document.createElement("header");a.className="files-path files-content-header";const l=document.createElement("span");l.textContent=e;const c=document.createElement("span");c.className="pane-state",a.append(l,c);const h=document.createElement("div");h.className="files-table-field";const d=document.createElement("span");d.className="field-rule";const u=document.createElement("button");u.className="mode-strip",u.title="display modes";const p=document.createElement("span");p.className="mode-elbow";const f=document.createElement("aside");f.className="mode-frame";const _=document.createElement("button");_.className="strategy-pill csv-filter rail-off",_.textContent="FILTER OFF",_.title="filter the table";const g=document.createElement("button");g.className="strategy-pill csv-raw",g.textContent="RAW",g.title="the bytes as written",g.addEventListener("click",()=>this.content_show(e,t));const m=document.createElement("button");m.className="strategy-pill csv-close",m.textContent="CLOSE",m.title="leave the table; the listing beneath returns",m.addEventListener("click",()=>this.listing_restore());const w=document.createElement("span");w.className="mode-fill",f.append(_,g,w);const y=this.preview;if(y!==null){const x=document.createElement("button");x.className="strategy-pill csv-download",x.textContent="DOWNLOAD",x.title="save this file to your disk",x.addEventListener("click",()=>y.download(e)),f.append(x)}f.append(m);const M=document.createElement("div");M.className="files-table-rows",h.append(d,u,p,f,M),o.append(a,h),this.container.appendChild(o);const v=i.caps.map((x,b)=>({key:`c${b}`,label:x.toUpperCase(),className:"files-table-cell",cell:z=>z.cells[b]??"",width:"minmax(6em, 1fr)"}));new sr({mount:M,traits:v,key:x=>String(x.index),chrome:{root:o,prefix:"csv"},state:x=>{const b=[];return x.filter!==""?b.push(`${x.filter} ROWS`):b.push(r?`SHOWING ${n.length} OF ${i.rows.length} ROWS`:`${i.rows.length} ROWS`),i.headed||b.push("NO HEADER: COLUMNS NUMBERED"),b.join(" · ")},empty:()=>{const x=document.createElement("div");return x.className="files-note",x.textContent="NO ROWS",x}}).rows_set([{key:e,rows:n.map((x,b)=>({index:b,cells:x}))}],{field:e}),this.contentRelease=()=>{M.replaceChildren()}}content_show(e,t,i=!1,n=!1){this.diagram_declare(!1),this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren();const r=document.createElement("header");r.className="files-path files-content-header";const o=document.createElement("span");o.textContent=e;const a=document.createElement("button");a.className="files-close-pill",a.textContent="CLOSE",a.addEventListener("click",()=>this.listing_restore());const l=document.createElement("pre");l.className="files-content";const c=i||!U0.test(e)?null:$0(t),h=[];if(c!==null||i&&U0.test(e)&&$0(t)!==null){const u=document.createElement("button");u.className="files-close-pill",u.textContent=c!==null?"RAW":"PRETTY",u.addEventListener("click",()=>this.content_show(e,t,c!==null)),h.push(u)}const d=Fz(e);if(d){const u=document.createElement("button");u.className="files-close-pill files-render-pill",u.textContent=n?"SOURCE":"RENDERED",u.title=n?"the document as written":"the document as its page",u.addEventListener("click",()=>this.content_show(e,t,!1,!n)),h.push(u)}if(r.append(o,...X0(this.preview,e),...h,a),c!==null?(l.classList.add("files-json"),l.append(c)):l.textContent=t,this.container.append(r,l),ai(l),c===null){if(d&&n){Uz(e,t).then(u=>{u===null||!l.isConnected||(u.classList.add("files-content"),l.replaceWith(u),ai(u))}).catch(()=>{});return}Xl(async()=>{const{sourceSpans_build:u}=await import("./syntax-CK34dlF6.js").then(p=>p.ao);return{sourceSpans_build:u}},[],import.meta.url).then(({sourceSpans_build:u})=>u(t,Zg(e))).then(u=>{if(u===null||!l.isConnected)return;const p=l.querySelector(":scope > .more-chip");l.replaceChildren(u),p!==null&&l.append(p),l.classList.add("files-source")}).catch(()=>{})}}contentRefused_show(e,t){this.diagram_declare(!1),this.denied.add(e),this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren();const i=document.createElement("header");i.className="files-path files-content-header files-content-refused";const n=document.createElement("span");n.textContent=e;const r=document.createElement("button");r.className="files-close-pill",r.textContent="CLOSE",r.addEventListener("click",()=>this.listing_restore()),i.append(n,r);const o=document.createElement("div");o.className="files-refused";const a=document.createElement("p");a.className="files-refused-lede",a.textContent="READ REFUSED";const l=document.createElement("pre");l.className="files-refused-said",l.textContent=t,o.append(a,l),this.container.append(i,o)}contentImage_show(e,t){this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren();const i=document.createElement("header");i.className="files-path files-content-header";const n=document.createElement("span");n.textContent=e;const r=document.createElement("button");r.className="files-close-pill",r.textContent="CLOSE",r.addEventListener("click",()=>this.listing_restore()),i.append(n,...X0(this.preview,e),r);const o=document.createElement("img");o.className="files-image",o.src=t,o.alt=e,this.container.append(i,o)}rowVerbs_declare(e,t){this.indicate=t??null,this.listing.actions_declare({of:i=>i.updir?[]:e(i.entry,i.path).map(n=>({label:n.label,run:()=>n.run(i.entry),...n.offered!==void 0?{offered:()=>n.offered(i.entry)}:{},...n.disabled!==void 0?{disabled:()=>n.disabled(i.entry)}:{}}))})}catalogueTraits_declare(){return[...this.browserTraits_declare().filter(i=>i.key==="control"||i.key==="name"),{key:"type",label:"TYPE",className:"files-type",width:"6em",cell:i=>i.updir?"":i.entry.type},{key:"version",label:"VERSION",className:"files-version",width:"7em",cell:i=>i.updir?"":H0(i.entry.name),compare:i=>H0(i.entry.name)}]}catalogue_is(){return this.catalogue}binding_set(e){if(this.runStrip===null){const i=document.createElement("div");i.className="files-run-strip";const n=document.createElement("span");n.className="files-binding";const r=document.createElement("input");r.className="files-command",r.spellcheck=!1,r.autocomplete="off",r.placeholder="the line RUN will run",i.append(n,r),this.container.parentElement?.insertBefore(i,this.container),this.runStrip=i;const o=this.container.closest(".pane-files")?.querySelector(".pane-title");o!=null&&(o.textContent="CATALOGUE")}const t=this.runStrip.querySelector(".files-binding");t!==null&&(t.textContent=`INPUT ${e.input} → ${e.place}`),this.frameTop_track()}commandLine_get(){return this.runStrip?.querySelector(".files-command")?.value.trim()??""}commandLine_set(e){const t=this.runStrip?.querySelector(".files-command")??null;t!==null&&(t.value=e)}indicated_get(){return this.listing.indicated_get()}feedOpen_declare(e){this.feedOpen=e}run_show(e){if(this.runStrip===null)return;this.runStrip.querySelector(".files-feed")?.remove();const t=document.createElement("button");t.className="files-feed listing-capsule listing-action-selected",t.textContent=`FEED ${e}`,t.title="open this run's graph beside the catalogue",t.addEventListener("click",()=>this.feedOpen?.(e)),this.runStrip.appendChild(t)}row_indicate(e){this.listing.row_indicate(e)}rowReadout_show(e,t){this.listing.readout_show(e,t)}selectionVerbs_declare(e){this.selectionVerbs=e}select_toggle(e){this.listing.select_toggle(e)}select_isOn(){return this.listing.select_isOn()}selection_get(){return this.listing.selection_get()}path_current(){return this.lastListings[0]?.path??null}content_isShown(){return this.contentShown}contentRelease=null;contentHtml_show(e,t,i={}){this.contentRelease?.(),this.contentRelease=i.release??null,this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren();const n=document.createElement("section");n.className="files-content-view";const r=document.createElement("header");r.className="files-path files-content-header";const o=document.createElement("span");o.textContent=e;const a=document.createElement("button");if(a.className="files-close-pill",a.textContent="CLOSE",a.addEventListener("click",()=>this.listing_restore()),r.append(o,a),n.appendChild(r),t!==""){const c=document.createElement("pre");c.className="files-content",c.innerHTML=t,n.appendChild(c)}let l=null;return i.diagram===!0&&(l=document.createElement("div"),l.className="files-diagram",n.appendChild(l)),this.diagram_declare(i.diagram===!0),this.container.appendChild(n),l}contentText_set(e){const t=this.container.querySelector(".files-content-view");if(t===null)return;const i=t.querySelector(".files-content"),n=i??document.createElement("pre");n.className="files-content",n.innerHTML=e,i===null&&t.querySelector(".files-content-header")?.after(n)}recent_set(e){this.recent=e===null?null:[...e],this.lastListings.length>0&&!this.contentShown&&this.listings_render(this.lastListings)}listing_restore(){this.contentRelease?.(),this.contentRelease=null,this.lastListings.length>0?this.listings_render(this.lastListings):this.empty_render()}empty_render(){this.diagram_declare(!1),this.container.replaceChildren();const e=document.createElement("p");e.className="files-empty",e.textContent="AWAITING LISTING — TYPE ls IN THE CONSOLE",this.container.appendChild(e)}listings_render(e){this.diagram_declare(!1),this.contentShown=!1,this.container.parentElement?.classList.remove("content-view"),this.lastListings=e,this.thumbObserver?.disconnect(),this.thumbObserver=null,this.stale=e.some(n=>n.fresh===!1),$2(this.stateSpan,"stale",this.stale),this.listing.painter_set(this.viewMode==="list"?null:(n,r)=>this.cards_paint(n,r));const t=e.map(n=>this.block_build(n)),i=e.find(n=>n.path===cG);if(this.recent!==null&&this.recent.length>0&&i!==void 0){const n=this.recentBlock_build(i);n!==null&&t.unshift(n)}this.listing.rows_set(t,{field:e[0]?.path??""}),this.frameTop_track()}crumbs_build(e){const t=document.createElement("header");t.className="files-path files-crumbs";const i=[],n=this.home;let r;n!==null&&(e===n||e.startsWith(`${n}/`))?(i.push({label:"~",path:n}),r=e.slice(n.length)):(i.push({label:"/",path:"/"}),r=e);let o=i[0]?.path??"/";for(const a of r.split("/").filter(l=>l.length>0))o=o==="/"?`/${a}`:`${o}/${a}`,i.push({label:a,path:o});return i.forEach((a,l)=>{l>0&&i[l-1]?.label!=="/"&&t.append("/");const c=l===i.length-1,h=document.createElement(c?"span":"button");h.className=c?"files-crumb files-crumb-here":"files-crumb",h.textContent=a.label,h.dataset.path=a.path,c||(h.title=`go to ${a.path}`,h.addEventListener("click",d=>{d.stopPropagation(),this.activate({kind:"dir",path:a.path})})),t.appendChild(h)}),this.catalogue||t.appendChild(Ky(e)),t}link_copy(e){const t=Q0(e),n=[...this.container.querySelectorAll(".files-crumbs")].filter(r=>r.querySelector(".files-crumb-here")?.dataset.path===t||r.querySelector(".files-crumb-here")?.dataset.path===e).map(r=>r.querySelector(".link-line")).filter(r=>r!==null)[0];return n===void 0?null:(Ng(n,e),Yy(n))}ceiling_set(e,t=".."){this.ceiling=e===null?null:{path:e.replace(/\/+$/,"")||"/",word:t}}home_set(e){e!==this.home&&(this.home=e,!this.contentShown&&this.lastListings.length>0&&this.listings_render(this.lastListings))}block_build(e){const t=this.crumbs_build(e.path),i=e.items.map(r=>({entry:r,path:Tc(e.path,r.name),updir:!1})),n=[];if(!this.catalogue&&this.home!==null&&e.path!==this.home&&n.push({entry:{name:"~",type:"dir",size:0,owner:"",date:""},path:this.home,updir:!0,home:!0}),e.path!=="/"){const r=this.ceiling!==null&&this.ceiling.path===e.path?this.ceiling.word:"..";n.push({entry:{name:r,type:"dir",size:0,owner:"",date:""},path:Q0(e.path),updir:!0})}return{key:e.path,header:t,lead:n,rows:i}}recentBlock_build(e){const t=new Map(e.items.map(r=>[r.name,r])),i=[];for(const r of this.recent??[]){const o=t.get(r);o!==void 0&&i.push({entry:o,path:Tc(q0,r),updir:!1})}if(i.length===0)return null;const n=document.createElement("header");return n.className="files-path files-recent",n.textContent="RECENT",{key:q0,header:n,lead:[],rows:i}}cards_paint(e,t){const i=this.viewMode==="preview",n=document.createElement("div");n.className=i?"files-cards files-previews":"files-cards";for(const o of e.lead??[]){const a=document.createElement("article");a.className=o.home===!0?"files-card files-card-up files-card-home files-activatable":"files-card files-card-up files-activatable",a.textContent=o.home===!0?`${V0} ~`:"▴ ..",a.addEventListener("click",()=>this.activate({kind:"dir",path:o.path})),n.appendChild(a)}const r=e.key;for(const o of e.rows)n.appendChild(this.card_build(r,o.entry,i));t.appendChild(n)}frameTop_track(){const e=this.container.parentElement,t=this.container.querySelector(".roster-order"),i=this.container.querySelector(".files-path");if(this.frameTopObserver?.disconnect(),this.frameTopObserver=null,e===null)return;if(t===null||i===null){e.style.removeProperty("--mode-frame-top"),e.style.removeProperty("--roster-frame-h");return}const n=()=>{const r=e.getBoundingClientRect().top,o=Math.ceil(t.getBoundingClientRect().bottom-r);e.style.setProperty("--roster-frame-h",`${o}px`),e.style.setProperty("--mode-frame-top",`${Math.ceil(i.getBoundingClientRect().bottom-r)}px`)};n(),this.frameTopObserver=new ResizeObserver(n),this.frameTopObserver.observe(t),this.frameTopObserver.observe(i)}follow_set(e){this.following=e,this.listing.state_refresh()}follow_get(){return this.following}view_set(e){this.viewMode=e,this.viewPill!==null&&(this.viewPill.textContent=e.toUpperCase()),this.modeSpan!==null&&(this.modeSpan.textContent=e==="list"?"":e.toUpperCase()),this.lastListings.length>0&&!this.contentShown&&this.listings_render(this.lastListings)}view_get(){return this.viewMode}body_get(){return this.container.closest(".files-body")}diagram_declare(e){this.body_get()?.classList.toggle("diagram-shown",e),e||this.mode_annunciate(this.viewMode==="list"?"":this.viewMode.toUpperCase())}mode_annunciate(e){this.modeSpan!==null&&(this.modeSpan.textContent=e)}stateLine_compose(e){const t=[];return this.following&&t.push("CWD"),e.selecting&&t.push("SELECT"),t.push(this.stale?"STALE":e.filter),e.selected>0&&t.push(e.shown===e.selected?`${e.selected} SELECTED`:`${e.selected} SELECTED · ${e.shown} SHOWN`),t.filter(i=>i!=="").join(" · ")}card_build(e,t,i=!1){const n=document.createElement("article");n.className=`files-card files-type-${t.type}`,i&&n.appendChild(this.thumb_build(Tc(e,t.name),t));const r=document.createElement("div");r.className="files-card-head";const o=document.createElement("span");o.className="files-card-badge",o.textContent=t.type.toUpperCase();const a=document.createElement("span");a.className="files-card-size",a.textContent=t.type==="dir"||t.size===0?"":eM(t.size),r.append(o,a);const l=document.createElement("div");l.className="files-card-title",l.textContent=t.name;const c=document.createElement("div");c.className="files-card-meta";const h=document.createElement("span");h.textContent=t.owner;const d=document.createElement("span");if(d.textContent=t.date.slice(0,10),c.append(h,d),n.append(r,l,c),t.type==="link"&&t.target!==void 0){const f=document.createElement("div");f.className="files-card-target",f.textContent=`→ ${t.target}`,f.title=t.target,n.appendChild(f)}const u=Tc(e,t.name),p=Ac(t);return p!==null&&(n.classList.add("files-activatable"),n.addEventListener("click",()=>this.activate({kind:p,path:u}))),n}thumb_build(e,t){const i=document.createElement("div");i.className="files-card-thumb";const n=()=>{i.textContent=Oc[t.type]};if(bz.test(t.name)||_d.test(t.name)){i.classList.add("thumb-series");const d=document.createElement("span");d.className="thumb-series-mark",d.textContent="DCM";const u=/^\d+-(.*)-[0-9a-f]{7}$/.exec(t.name)?.[1];if(i.replaceChildren(d),u!==void 0){const p=document.createElement("span");p.className="thumb-series-text",p.textContent=u.replace(/_/g," "),i.appendChild(p)}return i}if(this.preview===null||!(t.type==="file"||t.type==="plugin"||t.type==="pipeline"))return n(),i;if(t.type==="plugin")return i.replaceChildren(Z0([{id:e,parentIds:[]}])),i;if(t.type==="pipeline"){const d=this.preview;i.classList.add("thumb-wait"),i.textContent=Oc[t.type];const u=()=>{d.pipelineGlimpse(e).then(p=>{if(i.classList.remove("thumb-wait"),p===null||p.length===0){n();return}if(p.length>MG){i.textContent=`${p.length} NODES`,i.classList.add("thumb-count");return}i.replaceChildren(Z0(p))}).catch(()=>{i.classList.remove("thumb-wait"),n()})};return this.thumbObserver_get().observe(i),i.addEventListener("files:thumb-seen",u,{once:!0}),i}const r=this.headCache.get(e);if(r!==void 0){const d=document.createElement("pre");return d.textContent=r,i.appendChild(d),i}const o=tu(e)&&t.size<=gG,a=jz(e),l=(a===""||uG.has(a))&&t.size<=pG;if(!o&&!l)return n(),i;i.classList.add("thumb-wait"),i.textContent=Oc.file;const c=this.preview,h=()=>{if(o){const d=document.createElement("img");d.alt=t.name,d.addEventListener("load",()=>{i.classList.remove("thumb-wait")}),d.addEventListener("error",()=>{i.classList.remove("thumb-wait"),n()}),d.src=c.imageUrl(e),i.replaceChildren(d);return}c.textHead(e,mG).then(d=>{if(this.headCache.size>=_G&&this.headCache.clear(),this.headCache.set(e,d),i.classList.remove("thumb-wait"),d.trim()===""||bG(d)){n();return}const u=document.createElement("pre");u.textContent=d,i.replaceChildren(u)}).catch(()=>{i.classList.remove("thumb-wait"),n()})};return this.thumbObserver_get().observe(i),i.addEventListener("files:thumb-seen",h,{once:!0}),i}thumbObserver_get(){return this.thumbObserver===null&&(this.thumbObserver=new IntersectionObserver(e=>{for(const t of e)t.isIntersecting&&(this.thumbObserver?.unobserve(t.target),t.target.dispatchEvent(new CustomEvent("files:thumb-seen")))},{root:this.container,rootMargin:"25%"})),this.thumbObserver}filter_toggle(e){this.listing.filter_toggle(e)}}function J0(s){if(!Array.isArray(s))return null;for(const e of s){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.path!="string"||!Array.isArray(t.items))return null}return s}function Tc(s,e){return s.endsWith("/")?`${s}${e}`:`${s}/${e}`}function Q0(s){const e=s.endsWith("/")?s.slice(0,-1):s,t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function eM(s){if(s<1024)return String(s);const e=["K","M","G","T"];let t=s,i=-1;for(;t>=1024&&i<e.length-1;)t=t/1024,i=i+1;return`${t<10?t.toFixed(1):Math.round(t)}${e[i]}`}class vG{grid;startHere;host;paintId=0;constructor(e,t){this.host=t,this.grid=e.querySelector(".launcher-grid"),ai(this.grid,{rows:".launcher-tile",mount:this.grid.parentElement??this.grid});const i=e.querySelector(".launcher-body");i!==null&&ai(i,{rows:".launcher-tile",scrolls:()=>/auto|scroll/.test(getComputedStyle(i).overflowY)}),this.startHere=e.querySelector(".launcher-start"),this.startHere.addEventListener("click",()=>{this.host.startHere_set(!this.host.startHere_get()),this.startHere_render()}),this.startHere_render()}render(){const e=++this.paintId;this.host.tiles().then(t=>{e!==this.paintId||!this.grid.isConnected||(this.grid.replaceChildren(...t.map((i,n)=>this.tile_build(i,n===0||i.wide===!0))),this.startHere_render())}).catch(()=>{e!==this.paintId||!this.grid.isConnected||this.grid.replaceChildren()})}numeral_press(e){const t=this.grid.querySelector(`[data-numeral="${e}"]`);return t===null?!1:(t.click(),!0)}startHere_render(){const e=this.host.startHere_get();this.startHere.textContent=e?"START HERE · ON":"START HERE · OFF",this.startHere.classList.toggle("pacs-capsule-off",!e)}tile_build(e,t){const i=document.createElement("button");i.className=`launcher-tile${t?" launcher-tile-wide":""}`,i.style.setProperty("--tile-hue",`var(${e.hue})`),i.dataset.numeral=e.numeral,i.title=e.verb,i.addEventListener("click",h=>{h.target instanceof Element&&h.target.closest(".launcher-row, .launcher-figure")!==null||(this.host.leave?.(),e.enter())});const n=document.createElement("span");n.className="launcher-head";const r=document.createElement("span");r.className="launcher-name",r.textContent=e.name;const o=document.createElement("span");o.className="launcher-numeral",o.textContent=e.numeral,n.append(r);for(const h of e.figures){const d=document.createElement(h.open===void 0?"span":"button");if(d.className=`launcher-figure${h.errored===!0?" launcher-figure-errored":""}`,d.textContent=h.text,h.open!==void 0){const u=h.open;d.addEventListener("click",p=>{p.stopPropagation(),this.host.leave?.(),u()})}n.appendChild(d)}n.appendChild(o);const a=document.createElement("span");a.className="launcher-rule";const l=document.createElement("span");l.className="launcher-rows";for(const h of e.rows){const d=document.createElement(h.open===void 0?"span":"button");d.className=`launcher-row${h.arrived===!0?" launcher-row-arrived":""}`;const u=document.createElement("span");u.className=`launcher-dot${h.errored===!0?" launcher-dot-errored":""}`;const p=document.createElement("span");if(p.className="launcher-row-text",p.textContent=h.text,d.append(u,p),h.open!==void 0){const f=h.open,_=document.createElement("span");_.className="launcher-go",_.textContent="›",d.appendChild(_),d.addEventListener("click",g=>{g.stopPropagation(),this.host.leave?.(),f()})}l.appendChild(d)}const c=document.createElement("span");return c.className="launcher-verb",c.textContent=e.verb,i.append(n,a),e.about!==void 0&&i.appendChild(wG(e.about)),i.append(l,c),i}}function wG(s){const e=document.createElement("span");e.className="launcher-about";const t=document.createElement("span");if(t.className="launcher-about-text",t.textContent=s.text,e.appendChild(t),s.list!==void 0&&s.list.length>0){const i=document.createElement("span");i.className="launcher-about-list";for(const n of s.list){const r=document.createElement("span");r.className="launcher-about-item",r.textContent=n,i.appendChild(r)}e.appendChild(i)}if(s.tail!==void 0){const i=document.createElement("span");i.className="launcher-about-text",i.textContent=s.tail,e.appendChild(i)}return e}const Fi={left:{axis:"col",place:"before",focusWord:"left",arrow:"ArrowLeft",edge:"leftmost"},right:{axis:"col",place:"after",focusWord:"right",arrow:"ArrowRight",edge:"rightmost"},above:{axis:"row",place:"before",focusWord:"up",arrow:"ArrowUp",edge:"topmost"},below:{axis:"row",place:"after",focusWord:"down",arrow:"ArrowDown",edge:"bottommost"}},Vz=["left","right","above","below"];function tM(s){return s==="left"||s==="right"||s==="above"||s==="below"}function yG(s,e){return s==="row"?e?"above":"below":e?"left":"right"}function SG(s,e){return s!=="row"&&s!=="col"||e!=="before"&&e!=="after"?null:yG(s,e==="before")}function zG(s){return Vz.find(e=>Fi[e].focusWord===s)??null}function xG(s){return Vz.find(e=>Fi[e].arrow===s)??null}function OG(s){return s?"before":"after"}function Ri(s){return`[data-split="${Fi[s].axis}"][data-place="${Fi[s].place}"]`}const su=new Set(["pane","view","file","header","console","back","desktop","dashboard","help","notes","launcher","attach","argus","trek","stratus","chris","capacity"]),EG=new Set(su),g_={help:new Set(["pane","keys","verbs"]),notes:new Set(["pane"]),capacity:new Set(["pane"]),file:new Set(["home","back","download","delete","follow","root","open","list","cards","preview","sort","filter"]),trek:new Set(["","--seed"])};let Vn=null,Mn=null;const Wo="argus.desktop.",sM="~/.config/argus/desktops";function iM(){return[...su].sort().map(s=>{const e=g_[s];return e===void 0?{subject:s}:{subject:s,verbs:[...e].sort()}})}function AG(s){const e=s.trim().split(/\s+/),t=(e[0]??"").toLowerCase();if(!su.has(t))return null;const i=g_[t];if(i!==void 0&&!i.has((e[1]??"").toLowerCase()))return null;let n=null,r=e.slice(1);return(r[0]?.startsWith("@")||r[0]?.startsWith("%"))&&(n=r[0],r=r.slice(1)),{subject:t,target:n,words:r}}function Wu(s,e){if(e===null)return s.focused_get();if(e.startsWith("@"))return e.slice(1);const t=parseInt(e.slice(1),10);return Mn===null?null:Mn[t-1]??null}function TG(s,e,t){return e!==null&&t.includes(s.paneKind_get(e)??"")?e:s.panes_shown().find(i=>t.includes(s.paneKind_get(i)??""))??null}function jn(s,e,t){const n=s.paneMount_get(e)?.querySelector(t)??null;return n===null?!1:(n.click(),!0)}function kh(s,e,t){const i=s.paneMount_get(e);if(i===null)return!1;for(const n of i.querySelectorAll(".drawer-child"))if(n.textContent?.trim().toUpperCase()===t)return n.click(),!0;return!1}function DG(s,e,t){return jn(s,e,`.drawer-cwdbind[data-follow="${t?"on":"off"}"]`)}function no(s,e,t,i){const r=s.paneMount_get(e)?.querySelector(t)??null;if(r===null)return!1;for(let o=0;o<4;o++){if(r.textContent?.trim().toUpperCase()===i)return!0;r.click()}return r.textContent?.trim().toUpperCase()===i}function qz(s,e){const t=s.focused_get(),i=t!==null?s.paneRect_get(t):null;if(i===null)return null;const n=i.x+i.width/2,r=i.y+i.height/2;let o=null;for(const a of s.panes_shown()){if(a===t)continue;const l=s.paneRect_get(a);if(l===null)continue;const c=l.x+l.width/2-n,h=l.y+l.height/2-r,d=e==="left"?-c:e==="right"?c:e==="up"?-h:h;if(d<=1)continue;const u=Math.abs(e==="left"||e==="right"?h:c),p=d+u*2;(o===null||p<o.score)&&(o={id:a,score:p})}return o===null?null:(s.focus_set(o.id),o.id)}const zn=[{key:"%",topic:"pane",selector:Ri("right"),does:"split right (tmux)"},{key:'"',topic:"pane",selector:Ri("below"),does:"split below (tmux)"},{key:"h",topic:"pane",selector:Ri("left"),does:"split left"},{key:"j",topic:"pane",selector:Ri("below"),does:"split below"},{key:"k",topic:"pane",selector:Ri("above"),does:"split above"},{key:"l",topic:"pane",selector:Ri("right"),does:"split right"},{key:"H",topic:"pane",selector:Ri("left"),does:"move this pane left",move:!0},{key:"J",topic:"pane",selector:Ri("below"),does:"move this pane below",move:!0},{key:"K",topic:"pane",selector:Ri("above"),does:"move this pane above",move:!0},{key:"L",topic:"pane",selector:Ri("right"),does:"move this pane right",move:!0},{key:"m",topic:"pane",selector:'.drawer-mode[data-mode="move"]',does:"arm MOVE (then a direction)"},{key:"z",topic:"pane",selector:".drawer-zoom",does:"zoom (tmux), or double-click the pane's header"},{key:"x",topic:"pane",selector:".drawer-close",does:"close (tmux)"},{key:"u",topic:"binding",selector:'.drawer-bind[data-bind="unlinked"]',does:"the next split is unlinked"},{key:"f",topic:"binding",selector:'.drawer-bind[data-bind="fs"]',does:"the next split is a linked filesystem"},{key:"v",topic:"binding",selector:'.drawer-bind[data-bind="viewer"]',does:"the next split is a linked viewer"},{key:"1",topic:"claim",selector:".empty-go-files",does:"claim an empty pane as FILES"},{key:"o",topic:"focus",selector:null,does:"focus the next pane (tmux)"},{key:";",topic:"focus",selector:null,does:"focus the last pane (tmux)"},{key:"q",topic:"focus",selector:null,does:"show every pane's @id on its bar (tmux)"},{key:"Space",topic:"pane",selector:null,does:"flip this pane's split: beside becomes above (tmux next layout)"},{key:"!",topic:"pane",selector:null,does:"break this pane out: alone on stage, the rest a PANES card (tmux)"},{key:"Ctrl-←↑↓→",topic:"pane",selector:null,does:"move the boundary beside this pane a step (tmux)"},{key:"w",topic:"stage",selector:null,does:"PANES, the desktops (tmux window chooser)"},{key:"r",topic:"focus",selector:null,does:"the keys into this pane's frame: Tab or ↑↓ walk its verbs, Enter presses, ← or Esc leaves"},{key:"&",topic:"pane",selector:null,does:"close every pane on the stage (tmux kill-window)"},{key:"[",topic:"console",selector:null,does:"the console's scrollback takes the keys (tmux)"},{key:"O",topic:"focus",selector:null,does:"focus the previous pane"},{key:"←↑↓→",topic:"focus",selector:null,does:"focus the pane in that direction (tmux)"},{key:":",topic:"console",selector:null,does:"the command line (tmux)"},{key:"?",topic:"console",selector:null,does:"this table"}];function Kz(s){let e=0;for(const t of s.panes_shown())jn(s,t,".drawer-close")&&(e+=1);return`closed ${e} pane${e===1?"":"s"}`}function Yz(){return["prefix chords — Ctrl-B opens the focused pane's drawer; one key then presses one capsule",...zn.map(s=>` ${s.key.padEnd(6)} ${s.does}`)," Tab walks the verbs; Enter fires; Esc closes the drawer","in a pane holding a listing, no prefix needed:"," ↑↓ move the row cursor (Home/End: first/last)"," Enter indicates the row (its verbs ride the frame); Enter again goes (opens, enters, folds open)"," → the keys into the frame, as Ctrl-B r"].join(`
|
|
94
94
|
`)}const Ta=[],IG=[{subject:"pane",line:()=>"pane [@id|%n] split left|right|above|below · zoom · close · close all · bind unlinked|fs|viewer"},{subject:"pane claim",line:()=>`pane [@id|%n] claim ${["files",...Object.keys(Vn?.claims??{})].join("|")} · focus left|right|up|down|@id|last · flip · resize left|right|up|down [percent]`},{subject:"view",line:()=>`${`view ${["files",...Object.keys(Vn?.views??{})].join("|")}`.padEnd(28)}(the gutter givens, workspace scope)`},{subject:"file",line:()=>"file [@id] home|back|download|delete · follow · root · list|cards|preview · sort <col> [asc|desc] · filter <text>|off"},{subject:"header",line:()=>"header stats|dag|away|restore"}],CG=["console open|close|toggle|zoom|height <px>","back (contextual back — exactly Esc)","desktop save|load|show|list|delete [name] · load <ChRIS file> · clear · share","attach [--reveal] (how to reach THIS session from a terminal or another browser)","stratus oci [manage] (through a porter: your cloud session, entered as READ; manage asks your password once, there or here)","chris (through a porter: back to your ChRIS session)","argus verbs (this table; the long form is docs/argus-lang.adoc)","argus keys (the prefix chords: one key, one drawer verb)","help pane|keys|verbs (the KEYS pane on the stage; keys and verbs print the tables here; bare help is the session's)","notes pane (what the installed releases changed, as a pane; bare notes prints it here)","capacity pane [<family>] (what the region has free for a family, as a pane; bare capacity prints it here)","trek [--seed <n>] (the bridge takes the screen: BSD trek played from its controls; --credits, --help and --version are the session's)"],RG=new Set(["--credits","--help","-h","--version","-V"]);function Xz(s){const e=s.trim().split(/\s+/);return e[0]!=="trek"?!1:!e.slice(1).some(t=>RG.has(t))}function Zz(){const s=[];for(const e of IG){s.push(e.line());for(const t of Vn?.lines??[])t.after===e.subject&&s.push(t.line)}s.push(...CG),Ta.splice(0,Ta.length,...s)}function nM(s){Vn=s;for(const[e,t]of Object.entries(s.subjects))su.add(e),t!==null&&(g_[e]=t);for(const e of s.chords){const t=zn.findIndex(r=>r.key===e.after),{after:i,...n}=e;zn.splice(t===-1?zn.length:t+1+s.chords.filter(r=>r.after===e.after&&s.chords.indexOf(r)<s.chords.indexOf(e)).length,0,n)}Zz()}Zz();function kG(s,e){const t=new URL(window.location.href),i=t.searchParams.get("token")??"",n=i===""?"":e?i:"•".repeat(8),r=i===""?t.origin+t.pathname:`${t.origin}${t.pathname}?token=${n}`,o=s.identity_get(),a=/^(127\.|\[?::1\]?$|localhost$)/.test(t.hostname),l=["attach — this session, from anywhere that can reach it"];return o!==null&&o!==""&&l.push(` identity ${o}`),l.push(""),l.push(" this machine chell --remote"),l.push(` another machine chell --remote --attach "${r}"`),l.push(` another browser ${r}`),l.push(""),a&&(l.push(" bound to loopback — another machine cannot reach this session;"),l.push(" relaunch the daemon with CALYPSO_BIND=0.0.0.0 to change that")),i===""?(l.push(" this page carries no token: it was opened without one, and a"),l.push(" second surface cannot attach with what is on screen")):e?l.push(" revealed — anyone who reads this line holds the session"):(l.push(" the token is masked — `attach --reveal` prints it. It is a bearer"),l.push(" credential with no expiry: treat the line like a password")),l.join(`
|
|
95
95
|
`)}async function Nh(s,e){const t=AG(e);if(t===null)return null;const{subject:i,words:n}=t,r=(n[0]??"").toLowerCase(),o=(n[1]??"").toLowerCase();if(i==="argus")return r==="keys"?Yz():Ta.join(`
|
|
96
96
|
`);if(i==="back")return window.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})),"back";if(i==="trek")return Xz(["trek",...n].join(" "))?s.trek_open(["trek",...n].join(" ")):null;if(i==="stratus"||i==="chris"){if(i==="chris")return n.length===0?await s.session_switch("chris",!1):"chris: takes no words (it returns to your ChRIS session)";const c=(n[0]??"oci").toLowerCase();if(c!=="oci")return`stratus: ${c}: the only cloud is oci`;const h=n.slice(1).map(f=>f.toLowerCase());if(h.length>1)return"stratus oci: takes one word, read or manage";const d=h[0];if(d!==void 0&&d!=="read"&&d!=="manage")return`stratus oci: ${d}: unknown word (read looks only; manage may build, tear down and spend, after your password)`;const u=s.manage_is();if(u!==null)return d==="manage"?u?"stratus oci: MODE MANAGE already":await s.elevate_ask("stratus oci manage")?"stratus oci: MODE MANAGE":"stratus oci manage: not raised; MODE READ":`stratus oci: this is your cloud session, MODE ${u?"MANAGE":"READ"}${u?"":" (stratus oci manage asks your password once)"}`;const p=d==="manage"?"manage":"read";return await s.session_switch("stratus",p==="manage")}if(i==="attach")return kG(s,r==="--reveal"||o==="--reveal");if(i==="dashboard"||i==="launcher")return s.launcher_enter(),"dashboard";if(i==="view"){const c={files:{button:"gutter-files",primary:"files"},...Vn?.views??{}},h=c[r];return h===void 0?`view: unknown given '${r}' (${Object.keys(c).join("|")})`:(document.getElementById(h.button)?.click(),Mn!==null&&(Mn.length=0,Mn.push(h.primary)),`view ${r}`)}if(i==="header"){if(r==="restore")return document.getElementById("header-restore")?.click(),"header restored";if(r==="stats")return document.querySelector(".panel-1")?.click(),"header stats";if(r==="dag")return document.querySelector(".panel-2")?.click(),"header dag";if(r==="away"){const c=document.body.dataset.header,h=c==="stats"?".panel-1":".panel-2";return c!=="away"&&(c===void 0&&document.querySelector(".panel-2")?.click(),document.querySelector(h)?.click()),"header away"}return`header: unknown face '${r}' (stats|dag|away|restore)`}if(i==="console"){const c=document.getElementById("drawer");if(c===null)return"console: no drawer";const h=c.classList.contains("drawer-closed");if(r==="toggle"||r==="open"&&h||r==="close"&&!h)return document.getElementById("drawer-toggle")?.click(),`console ${r}`;if(r==="zoom")return s.consoleZoom_toggle(),"console zoom";if(r==="height"){const d=parseInt(o,10);return Number.isNaN(d)?"console height <px>":(c.style.height=`${d}px`,`console height ${d}`)}return r==="open"||r==="close"?`console already ${r==="open"?"open":"closed"}`:`console: unknown verb '${r}' (open|close|toggle|zoom|height)`}const a={file:{selector:".pane-files",named:"files"},...Vn?.listings??{}};if(a[i]!==void 0&&(r==="sort"||r==="filter")){const c=a[i].selector,h=Wu(s,t.target),u=(h===null?null:s.paneMount_get(h))?.querySelector(c)??document.querySelector(c);if(u===null){const f=a[i].named;return`${i} ${r}: no ${f} pane`}if(r==="sort"){if(o==="")return`${i} sort <column> [asc|desc]`;const f=(n[2]??"asc").toLowerCase()==="desc"?"desc":"asc";return u.dispatchEvent(new CustomEvent("argus:roster",{detail:{op:"sort",key:o,dir:f}})),`${i} sorted by ${o} ${f}`}const p=o==="off"?"":n.slice(1).join(" ");return u.dispatchEvent(new CustomEvent("argus:roster",{detail:{op:"filter",text:p}})),p===""?`${i} filter off`:`${i} filtered: ${p}`}if(Vn!==null&&!EG.has(i)){const c=Vn.run(s,t,()=>Wu(s,t.target));if(c!==void 0)return c}if(i==="help"||i==="notes")return NG(s,i,r);if(i==="capacity")return r==="pane"?s.capacity_open(n[1]??""):"capacity pane [<family>]";if(i==="desktop")return PG(s,r,n[1]);const l=Wu(s,t.target);if(l===null)return`${i}: no target pane (nothing focused?)`;if(i==="pane"){if(r==="split"){if(!tM(o))return"pane split left|right|above|below";const c=new Set(s.panes_shown());if(!jn(s,l,Ri(o)))return`pane split: '${l}' has no drawer`;const h=s.panes_shown().find(d=>!c.has(d));return h!==void 0&&Mn!==null&&Mn.push(h),`split ${o}: ${h??"(no pane created)"}`}if(r==="move")return tM(o)?s.pane_move(l,o):"pane move left|right|above|below";if(r==="zoom")return jn(s,l,".drawer-zoom")?`zoomed ${l}`:"pane zoom: no drawer";if(r==="close"&&o==="all")return Kz(s);if(r==="close")return jn(s,l,".drawer-close")?`closed ${l}`:"pane close: no drawer";if(r==="bind")return["unlinked","fs","viewer"].includes(o)?jn(s,l,`.drawer-bind[data-bind="${o}"]`)?`bind ${o}`:"pane bind: no drawer":"pane bind unlinked|fs|viewer";if(r==="claim"){const c={files:".empty-go-files",...Vn?.claims??{}},h=c[o];return h===void 0?`pane claim ${Object.keys(c).join("|")}`:jn(s,l,h)?`claiming ${l} as ${o}`:`pane claim: '${l}' is not an unlinked pane`}if(r==="flip")return s.pane_flip(l);if(r==="resize"){const c=zG(o);if(c===null)return"pane resize left|right|up|down [percent]";const h=n[2]!==void 0?Number(n[2]):5;return!Number.isFinite(h)||h<=0||h>70?"pane resize: the step is a percent, 1 to 70":s.pane_resize(l,c,h/100)}if(r==="focus"){if(o==="last")return s.focus_last()??"pane focus last: no pane was focused before this one";if(o.startsWith("@"))return s.focus_set(o.slice(1))?`focused ${o.slice(1)}`:`no pane '${o.slice(1)}'`;const c=qz(s,o);return c!==null?`focused ${c}`:`pane focus: nothing ${o} of here`}return`pane: unknown verb '${r}'`}if(i==="file"){const c=TG(s,l,["files","catalogue"]);if(c===null)return`file ${r}: no files pane on stage`;if(r==="list"||r==="cards"||r==="preview")return no(s,c,".files-view",r.toUpperCase())?`file ${r}`:`file ${r}: no files mode frame`;if(r==="open"){const h=n.slice(1).join(" ").trim();return h===""?"file open <folder>":s.files_open(c,h)?`file open ${h}`:`file open: '${c}' is not a files pane`}return r==="follow"||r==="root"?DG(s,c,r==="follow")?`file ${r}`:`file ${r}: not offered by '${c}'`:r==="home"||r==="back"?jn(s,c,r==="home"?".files-home":".files-back")?`file ${r}`:`file ${r}: not offered by '${c}'`:r==="download"?s.file_download(c)?"file download":"file download: nothing indicated":r==="delete"?s.file_delete(c)?"file delete":"file delete: nothing indicated":"file home|back|download|delete|sort|filter|follow|root|list|cards|preview"}return null}function NG(s,e,t){return e==="notes"?t==="pane"?s.notes_open():"notes pane":t==="keys"?Yz():t==="verbs"?Ta.join(`
|
|
@@ -102,7 +102,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
102
102
|
`)[0]})`}if(e==="delete")return window.localStorage.removeItem(Wo+t),`deleted '${t}' (local; a CFS copy, if any, is yours to rm)`;if(e==="load"){if(t.includes("/")){const n=await s.session_run(`cat ${t}`);if(n.trim()===""||/No such|cannot|error/i.test(n.split(`
|
|
103
103
|
`)[0]??""))return`desktop load: cannot read ${t}`;const r=(s.identity_get()??"").split("@")[0]??"",o=r!==""&&(t==="~"||t.startsWith("~/")||t.startsWith(`/home/${r}/`));return`loaded ${t}
|
|
104
104
|
${await Lp(s,n,o?null:t)}`}let i=window.localStorage.getItem(Wo+t);if(i===null){const n=await s.session_run(`cat ${sM}/${t}.desk`);n.trim().length>0&&!n.includes("No such")&&!n.toLowerCase().includes("error")&&(i=n)}return i===null?`(no desktop '${t}')`:`loaded '${t}'
|
|
105
|
-
${await Lp(s,i,null)}`}return"desktop save|load|show|list|delete [name] · load <ChRIS file> · clear · share"}const Si={universe:{text:"Every analysis, drawn as a galaxy. Alike analyses cluster; failures glow red. Rearrange it:",list:["GALAXY: grouped by pipeline (the default)","SPOKES · CLUMPS: the same groups, tidier","CONSTELLATIONS: grouped by the tools they used","DATA: hung from the data they began with (format, modality, series)","ACCRETION: grown oldest-first, like next to like"],tail:"Replay its history, or fly in to any one analysis to see its steps."},clusters:{text:"The OpenShift clusters in this tenancy, found by their tag: each one's condition or last finished build step, its address and what it costs per hour. One with a step gone wrong shows in red; one torn down reads GONE until what is left of it is removed. Opening the tile, or a cluster on it, opens the controller: its condition, spec, steps and cost, and the lines that build, verify and tear it down."},vms:{text:"The virtual machines this host keeps, as vm status reads them from its records: each one's state (declared, data only, built, gone), the ChRIS on it or its address, and what it bills an hour at list price. A row opens the script that declares the VM on the script screen, its VM BUILD seat the way in; the tile opens the library."},scripts:{text:"The library of scripts: each .mise file in a git source mounted at /scripts/, with where its lines stand (done, ready, changed, not yet) as play --status reads them from this host's records. Opening the tile opens the library on the script screen; a row opens that script, its lines as the rail, each a form over its line with RUN."},capacity:{text:"What this region has free for the machine families your clusters use, zone by zone: the cores and memory a new cluster or a bigger one could take."},analyses:{text:"Your analyses, newest first. Open one to follow it, read its logs and browse its results."},files:{text:"Your home: the files this session holds."},pacs:{text:"Find studies in the hospital PACS and pull the series you need into ChRIS."},cloud:{text:"Your cloud session: the tenancy and what is built in it. Entering asks which way in:",list:["READ: look only; nothing outside this host changes","MANAGE: build, tear down and spend, each after its own lock and the name typed back"],tail:"Which it is stays fixed for that session; enter again to change it."},panes:{text:"Saved workspaces: return to a piece of work as you left it."},keys:{text:"Keyboard shortcuts and the commands ARGUS understands."},notes:{text:"A list of updates since the previous release."},console:{text:"A command line into the same session; what you do here shows in the panes, and the other way round."}};function LG(s){return async()=>{const[e,t,i]=await Promise.all([s.ask("ls ~"),s.notes_latest(),s.contribution?.()??Promise.resolve({afterFiles:[],afterPanes:[]})]);let n=[],r="~";for(const m of e.envelopes){if(m.model?.kind!=="fs.listing")continue;const y=m.model.data[0];y!==void 0&&Array.isArray(y.items)&&(n=y.items,typeof y.path=="string"&&(r=y.path))}const o=n.filter(m=>m.type==="dir"),a=s.desktops(),l={key:"files",name:"FILES",hue:"--harvestgold",numeral:"2",figures:[{text:`${n.length} ENTRIES`}],rows:o.slice(0,5).map(m=>({text:m.name,open:()=>s.home_cd(r.endsWith("/")?`${r}${m.name}`:`${r}/${m.name}`)})),verb:"OPEN HOME",about:i.about?.files??Si.files,enter:()=>s.home_open()},c={key:"panes",name:"PANES",hue:"--butter",numeral:"6",figures:[{text:a.length===0?"EMPTY":`${a.length} DESKTOPS`}],rows:a.slice(0,5).map(m=>({text:m.label,open:()=>s.desktop_restore(m.id)})),verb:"SEE DESKTOPS",about:Si.panes,enter:()=>s.panes_open()},h={key:"help",name:"KEYS",hue:"--butter",numeral:"",figures:[{text:`${zn.length} KEYS`},{text:`${Ta.length} VERBS`}],rows:zn.slice(0,5).map(m=>({text:`${m.key.padEnd(6)} ${m.does}`,open:()=>s.keys_open()})),verb:"OPEN THE KEYS",about:Si.keys,enter:()=>s.keys_open()},d=t?.releases[0],u=d?.entries.flatMap(m=>m.changes.filter(w=>!w.internal))??[],p={key:"notes",name:"WHAT'S NEW",hue:"--butter",numeral:"",figures:d===void 0?[{text:"NO NOTES"}]:[{text:s.daemon_stale()?"AFTER RESTART":d.date??"UNDATED"},{text:`${u.length} CHANGE${u.length===1?"":"S"}`}],rows:u.slice(0,3).map(m=>({text:`${m.package.padEnd(7)} ${m.headline}`,open:()=>s.notes_open()})),verb:"OPEN THE NOTES",about:Si.notes,enter:()=>s.notes_open()},f={key:"console",name:"CONSOLE",hue:"--daybreak",numeral:"5",figures:[],rows:[],verb:"OPEN THE CONSOLE",about:Si.console,enter:()=>s.console_open()},_=i.lead===void 0?[]:[i.lead.tile],g=[...i.afterFiles,c,...i.afterPanes,h,p,f];return i.lead!==void 0&&i.lead.weight>=n.length?[..._,l,...g]:[l,..._,...g]}}const WG=/\s--(?:\s|$)/;function iu(s){const e=WG.exec(s),t=e===null?s:s.slice(0,e.index),i=e===null?"":s.slice(e.index),n=t.lastIndexOf(";"),r=n===-1?0:n+1,o=t.slice(r),a=/^\s*\S+/.exec(o),l=r+(a===null?o.length:a[0].length);return{head:t.slice(0,l),args:t.slice(l),tail:i}}function Jz(s,e){return`cd "${s}"; ${e}`}function FG(s){return/^[A-Za-z0-9_./:@+=,-]+$/.test(s)?s:`"${s.replace(/(["\\])/g,"\\$1")}"`}function Qz(s){const e=[],t=/"(?:[^"\\]|\\.)*"|\S+/g;let i=t.exec(s);for(;i!==null;)e.push(i[0]),i=t.exec(s);return e}function oM(s){return s.length>=2&&s.startsWith('"')&&s.endsWith('"')?s.slice(1,-1).replace(/\\(["\\])/g,"$1"):s}function e1(s){return s.startsWith("-")&&s!=="-"&&!/^-\d/.test(s)}function UG(s,e){const t=Qz(iu(s).args);for(let i=0;i<t.length;i++){const n=t[i]??"";if(n===e){const r=t[i+1];return r===void 0||e1(r)?!0:oM(r)}if(n.startsWith(`${e}=`))return oM(n.slice(e.length+1))}return null}function aM(s,e,t){const i=iu(s),n=Qz(i.args),r=[];let o=!1;const a=t===null||t===""?[]:t===!0?[e]:[e,FG(t)];for(let c=0;c<n.length;c++){const h=n[c]??"";if(h===e||h.startsWith(`${e}=`)){if(h===e){const d=n[c+1];d!==void 0&&!e1(d)&&c++}o||(r.push(...a),o=!0);continue}r.push(h)}o||r.push(...a);const l=r.length===0?"":` ${r.join(" ")}`;return`${i.head}${l}${i.tail}`}function $G(s){return/\bfeed_title=/.test(iu(s).tail)}function jG(s,e){return`${s} -- feed_title="${e.replace(/(["\\])/g,"\\$1")}"`}function t1(s){return iu(s).head.replace(/^.*;\s*/,"").trim()}function HG(s,e,t){return/^[A-Za-z0-9_-]+$/.test(s)&&t.filter(n=>n===s).length===1?s:`@${e}`}const s1={listing:"files.row",rules:[{name:"image",label:()=>"IMAGE",offered:s=>s.kind==="seriesFolder"},{name:"gather",label:()=>"GATHER",offered:s=>s.kind!=="catalogue"&&s.projection!==!0},{name:"process",label:()=>"PROCESS",offered:s=>(s.kind==="directory"||s.kind==="seriesFolder")&&(s.feed===null||(s.node??null)!==null)},{name:"run",label:()=>"RUN",offered:s=>s.kind==="catalogue"&&s.bound===!0},{name:"edit",label:()=>"EDIT",offered:s=>s.kind==="file"&&s.editable===!0},{name:"download",label:()=>"DOWNLOAD",offered:s=>s.kind==="file"},{name:"link",label:()=>"LINK",offered:s=>s.kind!=="catalogue"},{name:"move",label:()=>"MOVE",offered:s=>s.kind!=="catalogue"&&s.projection!==!0},{name:"copy",label:()=>"COPY",offered:s=>s.kind!=="catalogue"&&s.projection!==!0},{name:"delete",label:()=>"DELETE",offered:s=>s.kind!=="catalogue"&&s.projection!==!0},{name:"share",label:s=>`SHARE FEED ${s.feed??""}`,offered:s=>s.kind!=="catalogue"&&s.feed!==null&&s.projection!==!0}],states:[{name:"a plain file outside a feed",facts:{kind:"file",feed:null}},{name:"a file inside a feed",facts:{kind:"file",feed:12}},{name:"a directory",facts:{kind:"directory",feed:null}},{name:"a directory inside a feed that is not a node",facts:{kind:"directory",feed:12,node:null}},{name:"a node's data inside a feed",facts:{kind:"directory",feed:12,node:456}},{name:"a DICOM series folder",facts:{kind:"seriesFolder",feed:null}},{name:"a catalogue entry",facts:{kind:"catalogue",feed:null}},{name:"a catalogue entry in a bound catalogue",facts:{kind:"catalogue",feed:null,bound:!0}},{name:"a node's data seen through /proc",facts:{kind:"directory",feed:12,node:456,projection:!0}},{name:"a file seen through /proc",facts:{kind:"file",feed:12,projection:!0}},{name:"a text file",facts:{kind:"file",feed:null,editable:!0}},{name:"a feed's note seen through /proc",facts:{kind:"file",feed:12,projection:!0,editable:!0}}]},i1={listing:"files.selection",rules:[{name:"delete",label:s=>`DELETE ${s.count}`,offered:()=>!0},{name:"move",label:s=>`MOVE ${s.count}`,offered:()=>!0},{name:"copy",label:s=>`COPY ${s.count}`,offered:()=>!0},{name:"share",label:s=>s.feeds.length===1?`SHARE FEED ${s.feeds[0]}`:`SHARE ${s.feeds.length} FEEDS`,offered:s=>s.feeds.length>0}],states:[{name:"a selection outside any feed",facts:{count:3,feeds:[]}},{name:"a selection in one feed",facts:{count:2,feeds:[12]}},{name:"a selection spanning feeds",facts:{count:5,feeds:[12,13]}}]},n1={listing:"runs.row",rules:[{name:"note",label:()=>"NOTE",offered:()=>!0},{name:"tag",label:()=>"TAG",offered:()=>!0},{name:"rename",label:()=>"RENAME",offered:()=>!0},{name:"share",label:()=>"SHARE",offered:()=>!0},{name:"delete",label:()=>"DELETE",offered:()=>!0}],states:[{name:"any feed",facts:{feedId:12}}]},Ol={listing:"pacs.study",rules:[{name:"pullStudy",label:()=>"PULL STUDY",offered:s=>s.addressable},{name:"gather",label:()=>"GATHER",offered:s=>s.addressable},{name:"process",label:()=>"PROCESS",offered:s=>s.allInCube}],states:[{name:"a study with a path",facts:{addressable:!0,allInCube:!1}},{name:"a study with none",facts:{addressable:!1,allInCube:!1}},{name:"a study wholly home",facts:{addressable:!0,allInCube:!0,anyInCube:!0}},{name:"a study partly home",facts:{addressable:!0,allInCube:!1,anyInCube:!0}}]},lo={listing:"pacs.series",rules:[{name:"gather",label:()=>"GATHER",offered:s=>s.addressable||s.inCube},{name:"image",label:()=>"IMAGE",offered:s=>s.inCube&&s.folderKnown},{name:"dir",label:()=>"DIR",offered:s=>s.inCube&&s.folderKnown},{name:"process",label:()=>"PROCESS",offered:s=>s.inCube&&s.folderKnown},{name:"pull",label:()=>"PULL",offered:s=>!s.inCube}],states:[{name:"not yet retrieved",facts:{inCube:!1,folderKnown:!1,addressable:!0}},{name:"not retrieved and unaddressable",facts:{inCube:!1,folderKnown:!1,addressable:!1}},{name:"home, folder not yet named",facts:{inCube:!0,folderKnown:!1,addressable:!0}},{name:"home, folder named",facts:{inCube:!0,folderKnown:!0,addressable:!0}}]},r1={listing:"gather.series",rules:[{name:"remove",label:()=>"REMOVE",offered:()=>!0},{name:"pull",label:()=>"PULL",offered:s=>s.pullable===!0},{name:"image",label:()=>"IMAGE",offered:s=>s.folderKnown&&s.imagery!==!1},{name:"process",label:()=>"PROCESS",offered:()=>!0}],states:[{name:"folder named",facts:{folderKnown:!0}},{name:"a place that is not imagery",facts:{folderKnown:!0,imagery:!1}},{name:"folder not yet named",facts:{folderKnown:!1}},{name:"not retrieved yet",facts:{folderKnown:!1,pullable:!0}}]},o1={listing:"gather.cohort",rules:[{name:"save",label:()=>"SAVE",offered:s=>s.count>0},{name:"export",label:()=>"EXPORT CSV",offered:s=>s.count>0},{name:"feed",label:()=>"CREATE FEED",offered:s=>s.count>0&&s.feed===null},{name:"process",label:()=>"PROCESS",offered:s=>s.count>0},{name:"dismiss",label:()=>"DISMISS",offered:()=>!0}],states:[{name:"holding series",facts:{count:2,feed:null}},{name:"holding series, rooted in a feed",facts:{count:2,feed:4501}},{name:"emptied",facts:{count:0,feed:null}}]};function Jr(s){return{listing:s.listing,visit(e){return e(s)}}}Jr(s1),Jr(i1),Jr(n1),Jr(Ol),Jr(lo),Jr(o1),Jr(r1);function gn(s,e){const t=s.rules.find(i=>i.name===e);if(t===void 0)throw new Error(`${s.listing} declares no verb '${e}'`);return t}const Fo={fold:"5.2em",patient:"13em",mrn:"7.5em"};function VG(s){return{inCube:s.pulled===!0,folderKnown:s.folderPath!==void 0,addressable:s.vfsPath!==void 0}}function lM(s){if(s.series.length===0)return null;const e=[];for(const i of s.series){if(i.pulled!==!0||i.folderPath===void 0)return null;e.push(i.folderPath.replace(/\/[^/]+\/?$/,""))}const t=e[0]??"";return e.every(i=>i===t)&&t!==""?t:null}function Cn(s){const e=VG(s),t=i=>gn(lo,i).offered(e);return{gather:t("gather"),image:t("image"),dir:t("dir"),pull:t("pull")}}function qG(s,e,t,i){let n=!1;for(const r of s.studies)for(const o of r.series)o.seriesUID===e&&(i!==void 0&&o.folderPath!==i&&(o.folderPath=i,n=!0),o.pulled!==!0&&(o.pulled=!0,t!==void 0&&t>0&&(o.pulledFiles=t),n=!0));return n}const cM=[{id:"pacs-f-name",term:"PatientName"},{id:"pacs-f-mrn",term:"PatientID"},{id:"pacs-f-date",term:"StudyDate"},{id:"pacs-f-accession",term:"AccessionNumber"},{id:"pacs-f-modality",term:"Modality"}],Dc={running:"RETRIEVING",done:"✓ PULLED",error:"✗ ERROR",unconfirmed:"? UNCONFIRMED",stalled:"STALLED",queued:"QUEUED",idle:"NOT RETRIEVED"},KG="--fresh",hM="--anon",YG=/\s*--anon\b/,XG=["pacs-f-name","pacs-f-mrn","pacs-f-accession","pacs-f-date"],dM=/\s*--fresh\b/;function uM(s){const e=Date.parse(s);if(Number.isNaN(e))return null;const t=Math.max(0,Math.round((Date.now()-e)/1e3)),i=[{limit:60,size:1,name:"SECOND"},{limit:3600,size:60,name:"MINUTE"},{limit:86400,size:3600,name:"HOUR"},{limit:2592e3,size:86400,name:"DAY"},{limit:31536e3,size:2592e3,name:"MONTH"},{limit:1/0,size:31536e3,name:"YEAR"}];for(const n of i){if(t>=n.limit)continue;const r=Math.max(1,Math.floor(t/n.size));return`${r} ${n.name}${r===1?"":"S"} AGO`}return null}const vd=new Map;function a1(s,e){const t=vd.get(s)??new Set;t.add(e),vd.set(s,t)}const l1=new Map;function c1(s,e){s.replaceChildren(),s.dataset.state=e.status,e.reason!==void 0?s.title=e.reason:s.removeAttribute("title");const t=document.createElement("span");if(t.className="pacs-badge-note",e.status==="idle"){t.textContent=Dc.idle,s.append(gd({done:0,total:0}),t);return}if(e.status==="done"){const a=document.createElement("span");a.className="pacs-bar-full",t.textContent=e.total!==void 0&&e.total>0?`✓ ${e.total} IN CUBE`:"✓ IN CUBE",s.append(a,t);return}if(e.status!=="running"&&e.status!=="queued"){s.textContent=Dc[e.status]??e.status.toUpperCase();return}const i=e.total!==void 0?` ${e.current??0}/${e.total}`:"",n=ZG(e),r=document.createElement("span");r.className=n===null?"pacs-bar pacs-bar-pacing":"pacs-bar";const o=document.createElement("span");o.className="pacs-bar-fill",n!==null&&(o.style.width=`${Math.round(n*100)}%`),r.appendChild(o),t.textContent=e.status==="queued"?Dc.queued:`${Dc.running}${i}`,s.append(r,t)}function ZG(s){return s.status==="queued"||s.total===void 0||s.total===0||(s.current??0)===0?null:Math.min(1,(s.current??0)/s.total)}function JG(s,e){return s.pulled===!0&&e.status!=="done"&&e.status!=="running"&&e.status!=="queued"}function QG(s,e){const t=vd.get(s);if(t!==void 0){for(const i of[...t]){if(!i.isConnected){t.delete(i);continue}e(i)}t.size===0&&vd.delete(s)}}function eP(s){const e=document.createElement("span");if(e.className="pacs-badge",s.pulled===!0){const r=document.createElement("span");r.className="pacs-bar-full";const o=document.createElement("span");return o.className="pacs-badge-note",o.textContent=s.pulledFiles!==void 0?`✓ ${s.pulledFiles} IN CUBE`:"✓ IN CUBE",e.append(r,o),e.dataset.state="done",e}const t=document.createElement("span");t.className="pacs-bar";const i=document.createElement("span");i.className="pacs-badge-note",i.textContent="NOT RETRIEVED",e.append(t,i),e.dataset.state="idle",a1(s.seriesUID,e);const n=l1.get(s.seriesUID);return n!==void 0&&c1(e,n),e}function h1(s,e){return[{key:"series",label:"SERIES",className:"pacs-series-desc",width:"35.5em",cell:t=>s(t).description??""},{key:"state",label:"STATE",className:"pacs-badge",width:"1fr",cell:t=>e(s(t)),compare:t=>s(t).pulled===!0?"done":"idle"},{key:"modality",label:"MODALITY",className:"pacs-series-modality",width:"4em",cell:t=>s(t).modality},{key:"files",label:"FILES",className:"pacs-series-files",width:"6em",cell:t=>{const i=s(t).fileCount;return i!==void 0?`${i} FILES`:""},compare:t=>s(t).fileCount??-1}]}class tP{root;command;results;handlers;litFolders=new Map;badgeStates=new Map;seriesProgress=new Map;studyTracks=new Map;traits;actions;studyTraits;studyActions;patientTraits;listing;patientTracks=new Map;provenance;run;model=null;anon=!1;revealed=!1;anonPill;revealPill;replayed=!1;serverCell;serverStrip;servers=[];chosen=new Set;constructor(e,t){this.root=e,this.handlers=t,this.command=Ic(e,"#pacs-command"),this.results=en(e,"#pacs-results"),this.traits=this.traits_declare(),this.actions=this.actions_declare(),this.studyTraits=this.studyTraits_declare(),this.studyActions=this.studyActions_declare(),this.patientTraits=this.patientTraits_declare(),this.listing=new sr({mount:this.results,traits:this.patientTraits,key:i=>i.key,chrome:{root:e,prefix:"pacs"},activatable:i=>i.studies.length>0,address:i=>i.studies.length>0?bN(i.patient):void 0,control:"fold",row:{className:()=>"pacs-patient-row",groupClassName:i=>i.patient.status==="unasked"?"pacs-patient pacs-patient-unasked":"pacs-patient",decorate:(i,n)=>{n.studies.length>0&&(i.title="unfold this patient's studies (the patient keeps its place)")}},child:ma(i=>i.studies.map((n,r)=>({study:n,key:fM(n,r)})),{traits:this.studyTraits,key:i=>i.key,address:i=>i.study.vfsPath,control:"fold",actions:{of:()=>this.studyActions},row:{className:()=>"pacs-study-row",groupClassName:()=>"pacs-study",decorate:i=>{i.title="unfold this study's series (the study keeps its place)"}},child:ma(i=>i.study.series.map(n=>({study:i.study,studyKey:i.key,series:n})),{traits:this.traits,key:i=>i.series.seriesUID,address:i=>i.series.vfsPath,actions:{of:()=>this.actions},row:{className:()=>"pacs-series",decorate:(i,n)=>{i.dataset.seriesuid=n.series.seriesUID}}})}),state:i=>this.stateLine_compose(i),empty:()=>mM("NO STUDIES FOUND")}),e.style.setProperty("--roster-cols",this.listing.template_get(1)),this.listing.rows_set([],{field:"pacs"});for(const{id:i}of cM){const n=Ic(e,`#${i}`);n.addEventListener("input",()=>this.command_regenerate()),n.addEventListener("keydown",r=>{r.key==="Enter"&&(r.preventDefault(),this.query_run())})}this.serverCell=en(e,"#pacs-f-server"),this.serverStrip=en(e,"#pacs-server-strip"),this.serverCell.addEventListener("click",()=>this.serverStrip_toggle()),this.serverCell_sync(),this.provenance=en(e,"#pacs-provenance"),this.anonPill=en(e,"#pacs-anon"),this.revealPill=en(e,"#pacs-reveal"),this.anonPill.addEventListener("click",()=>this.anon_set(!this.anon)),this.revealPill.addEventListener("click",()=>this.reveal_set(!this.revealed)),this.run=en(e,"#pacs-run"),this.run.addEventListener("click",()=>this.query_run(this.replayed)),this.command.addEventListener("keydown",i=>{i.key==="Enter"&&this.query_run()}),en(e,"#pacs-export").addEventListener("click",()=>this.answer_export()),en(e,"#pacs-gather-shown").addEventListener("click",()=>this.shown_gather()),en(e,"#pacs-pull-shown").addEventListener("click",()=>this.shown_pull())}patientTraits_declare(){return[{key:"fold",label:"",className:"pacs-fold",capped:!1,width:Fo.fold,cell:e=>{const t=document.createElement("span");return t.className=e.studies.length===0?"pacs-fold pacs-fold-none":"pacs-fold",t}},{key:"patient",label:"PATIENT",className:"pacs-patient-name",width:Fo.patient,cell:e=>e.patient.patientName||"(unknown)"},{key:"mrn",label:"MRN",className:"pacs-patient-mrn",width:Fo.mrn,cell:e=>e.patient.patientId||"—"},{key:"answered",label:"ANSWERED",className:"pacs-patient-answered",width:"12em",cell:e=>{const t=document.createElement("span");if(t.className=e.patient.status==="unasked"?"pacs-patient-answered pacs-unasked":"pacs-patient-answered",e.patient.status==="unasked")return t.textContent="UNASKED",e.patient.error!==void 0&&(t.title=e.patient.error),t;const i=e.patient.provenance?.answeredAt;return t.textContent=i===void 0?"—":uM(i)??"—",i!==void 0&&(t.title=i),t},compare:e=>{const t=e.patient.provenance?.answeredAt;if(t===void 0)return Number.MAX_SAFE_INTEGER;const i=Date.parse(t);return Number.isNaN(i)?Number.MAX_SAFE_INTEGER:i}},{key:"progress",label:"PROGRESS",className:"pacs-patient-progress",width:"1fr",cell:e=>{const t=document.createElement("span");return t.className="pacs-patient-progress",this.patientTracks.set(e.key,{mount:t,uids:e.studies.flatMap(i=>i.series.map(n=>n.seriesUID))}),this.patientTrack_paint(e.key),t},compare:e=>{const t=this.patientProgress_compute(e);return t.total===0?-1:t.done/t.total}},{key:"studies",shed:3,label:"STUDIES",className:"pacs-patient-count",width:"6em",cell:e=>e.patient.status==="unasked"?"—":String(e.patient.studyCount),compare:e=>e.patient.status==="unasked"?-1:e.patient.studyCount},{key:"series",shed:2,label:"SERIES",className:"pacs-patient-count",width:"5em",cell:e=>e.patient.status==="unasked"?"—":String(e.patient.seriesCount),compare:e=>e.patient.status==="unasked"?-1:e.patient.seriesCount},{key:"server",shed:1,label:"SERVER",className:"pacs-patient-server",width:"9em",cell:e=>e.patient.server??this.model?.pacsName??"—"}]}patientProgress_compute(e){return zc(e.studies.flatMap(t=>t.series.map(i=>this.seriesProgress.get(i.seriesUID)??{done:0,total:0})))}patientTrack_paint(e){const t=this.patientTracks.get(e);if(t===void 0)return;const i=t.uids.map(n=>this.seriesProgress.get(n)??{done:0,total:0});t.mount.replaceChildren(gd(zc(i)))}patientRows_build(e){const t=(r,o)=>e.studies.filter(a=>a.patientId===r&&(o===void 0||a.server===void 0||a.server===o));if(e.patients!==void 0&&e.patients.length>0)return e.patients.map((r,o)=>({patient:r,key:`${r.patientId}::${r.server??""}::${o}`,studies:t(r.patientId,r.server)}));const i=[],n=new Map;for(const r of e.studies){const o=r.patientId;n.has(o)||(n.set(o,[]),i.push(o)),n.get(o).push(r)}return i.map((r,o)=>{const a=n.get(r)??[];return{key:`${r}::${o}`,studies:a,patient:{patientId:r,...a[0]?.patientName?{patientName:a[0].patientName}:{},status:"found",studyCount:a.length,seriesCount:a.reduce((l,c)=>l+c.series.length,0),...e.provenance===void 0?{}:{provenance:e.provenance}}}})}studyTraits_declare(){return[{key:"fold",label:"",className:"pacs-fold",capped:!1,width:Fo.fold,cell:()=>{const e=document.createElement("span");return e.className="pacs-fold",e}},{key:"patient",label:"PATIENT",className:"pacs-study-patient",width:Fo.patient,cell:e=>e.study.patientName||"(unknown)"},{key:"mrn",label:"MRN",className:"pacs-study-mrn",width:Fo.mrn,cell:e=>e.study.patientId||"—"},{key:"study",label:"STUDY",className:"pacs-study-desc",width:"12em",cell:e=>e.study.description||"(no description)"},{key:"progress",label:"PROGRESS",className:"pacs-study-progress",width:"1fr",cell:e=>{const t=document.createElement("span");return t.className="pacs-study-progress",this.studyTracks.set(e.key,{mount:t,uids:e.study.series.map(i=>i.seriesUID)}),this.studyTrack_paint(e.key),t},compare:e=>{const t=this.studyProgress_compute(e);return t.total===0?-1:t.done/t.total}},{key:"date",label:"DATE",className:"pacs-study-date",width:"7.5em",cell:e=>e.study.date},{key:"accession",label:"ACCESSION",className:"pacs-study-accession",width:"9em",cell:e=>e.study.accession||"—"},{key:"modality",label:"MODALITY",className:"pacs-study-modalities",width:"6.5em",cell:e=>e.study.modalities},{key:"server",label:"SERVER",className:"pacs-study-server",width:"9em",cell:e=>e.study.server??this.model?.pacsName??"—"},{key:"series",label:"SERIES",className:"pacs-study-count",width:"6.5em",cell:e=>String(e.study.series.length),compare:e=>e.study.series.length}]}studyActions_declare(){return[{label:gn(Ol,"pullStudy").label({addressable:!0,allInCube:!1}),offered:e=>gn(Ol,"pullStudy").offered({addressable:e.study.vfsPath!==void 0,allInCube:!1}),run:e=>{const t=e.study.vfsPath;if(t!==void 0){this.handlers.command_run(`pull ${t} &`);for(const i of e.study.series)i.vfsPath!==void 0&&i.pulled!==!0&&this.badgeState_set(i.seriesUID,{status:"queued"})}}},{label:gn(Ol,"gather").label({addressable:!0,allInCube:!1,anyInCube:!0}),offered:e=>e.study.series.some(t=>Cn(t).gather),run:e=>{const t=e.study.series.filter(n=>Cn(n).gather);for(const n of t)this.gather_note(e.study,n);const i=e.study.series.length-t.length;this.handlers.note(`gather: ${t.length} series gathered${i>0?`, ${i} not in CUBE (pull them first)`:""}`)}},{label:gn(Ol,"process").label({addressable:!0,allInCube:!0}),offered:e=>lM(e.study)!==null,run:e=>{const t=lM(e.study);t!==null&&this.handlers.process_open(t)}}]}studyProgress_compute(e){return zc(e.study.series.map(t=>this.seriesProgress.get(t.seriesUID)??{done:0,total:0}))}traits_declare(){return h1(e=>e.series,e=>this.badge_build(e))}actions_declare(){return[{label:gn(lo,"gather").label({inCube:!0,folderKnown:!0,addressable:!0}),offered:e=>Cn(e.series).gather,selected:e=>this.handlers.gathered_is(e.series.seriesUID),run:e=>this.gather_note(e.study,e.series)},{label:gn(lo,"image").label({inCube:!0,folderKnown:!0,addressable:!0}),offered:e=>Cn(e.series).image,selected:e=>e.series.folderPath!==void 0&&(this.litFolders.get(pM(e.series.folderPath))?.viewer??!1),run:e=>{e.series.folderPath!==void 0&&this.handlers.image_open(e.series.folderPath)}},{label:gn(lo,"dir").label({inCube:!0,folderKnown:!0,addressable:!0}),offered:e=>Cn(e.series).dir,selected:e=>e.series.folderPath!==void 0&&(this.litFolders.get(pM(e.series.folderPath))?.browser??!1),run:e=>{e.series.folderPath!==void 0&&this.handlers.dir_open(e.series.folderPath)}},{label:gn(lo,"process").label({inCube:!0,folderKnown:!0,addressable:!0}),offered:e=>Cn(e.series).image,run:e=>{e.series.folderPath!==void 0&&this.handlers.process_open(e.series.folderPath)}},{label:gn(lo,"pull").label({inCube:!1,folderKnown:!1,addressable:!0}),offered:e=>Cn(e.series).pull,disabled:e=>e.series.vfsPath===void 0,run:e=>{const t=e.series.vfsPath;t!==void 0&&(this.handlers.command_run(`pull ${t} &`),this.badgeState_set(e.series.seriesUID,{status:"queued"}))}}]}state_name(e){return e.pulled===!0?"pulled":this.badgeStates.get(e.seriesUID)?.status??"idle"}command_regenerate(){const e=[];for(const{id:n,term:r}of cM){const o=Ic(this.root,`#${n}`).value.trim();o.length>0&&e.push(`${r}:${o}`)}const t=this.chosen.size>1?` --pacsserver ${[...this.chosen].join(",")}`:"",i=this.anon?` ${hM}`:"";this.command.value=e.length>0||t!==""?`pacs query ${e.join(",")}${t}${i}`:""}anon_set(e){e!==this.anon&&(this.anon=e,this.revealed=!1,this.anonPill.textContent=e?"ANON ON":"ANON OFF",this.anonPill.classList.toggle("pacs-capsule-off",!e),this.revealPill.hidden=!e,this.model=null,this.listing.rows_set([],{field:"pending"}),this.provenance_show(void 0),this.command.value=e?`${this.command.value.trim()} ${hM}`.trim():this.command.value.replace(YG,"").trimEnd(),this.masking_apply())}reveal_set(e){this.revealed=e,this.revealPill.textContent=e?"HIDE":"REVEAL",this.revealPill.classList.toggle("pacs-capsule-off",!e),this.masking_apply()}masking_apply(){const e=this.anon&&!this.revealed;for(const t of XG)Ic(this.root,`#${t}`).type=e?"password":"text";this.command.type=e?"password":"text"}serverStrip_toggle(e){const t=e??this.serverStrip.hidden;this.serverStrip.hidden=!t,this.serverCell.classList.toggle("pacs-server-open",t),t&&this.servers.length===0&&this.servers_ask(),t&&this.serverStrip_paint()}query_get(){return this.model===null?null:`pacs query ${this.model.expression}`}serverStrip_isOpen(){return!this.serverStrip.hidden}serverStrip_close(){this.serverStrip_toggle(!1)}servers_ask(){this.handlers.command_run("pacs list")}servers_take(e){this.servers=e,this.serverStrip_paint(),this.serverCell_sync()}serverStrip_paint(){if(this.serverStrip.replaceChildren(),this.servers.length===0){this.serverStrip.appendChild(mM("ASKING THE SESSION FOR REGISTERED SERVERS"));return}for(const e of this.servers){const t=document.createElement("button");t.className=this.chosen.has(e.identifier)?"pacs-server-segment pacs-server-chosen":"pacs-server-segment",t.dataset.server=e.identifier,t.textContent=e.identifier,e.active&&(t.title="the session is connected to this server"),t.addEventListener("click",()=>this.server_choose(e.identifier)),this.serverStrip.appendChild(t)}}server_choose(e){if(this.chosen.has(e)?this.chosen.delete(e):this.chosen.add(e),this.chosen.size===1){const t=[...this.chosen][0];this.handlers.command_show(`pacs connect ${t}`)}this.serverStrip_paint(),this.serverCell_sync(),this.command_regenerate()}serverCell_sync(){const e=[...this.chosen];if(e.length===0){const t=this.servers.find(i=>i.active);this.serverCell.textContent=t?.identifier??"—",this.serverCell.classList.remove("pacs-server-many");return}this.serverCell.textContent=e.length===1?e[0]:`${e[0]} +${e.length-1}`,this.serverCell.classList.toggle("pacs-server-many",e.length>1)}wrote_show(e){const t=this.root.querySelector("#pacs-wrote");t!==null&&(t.textContent=`WROTE ${e}`,t.title="open the folder this landed in",t.classList.add("pacs-wrote-opens"),t.onclick=()=>{const i=e.lastIndexOf("/");this.handlers.dir_open(i<=0?e:e.slice(0,i))},t.hidden=!1)}answer_export(){if(this.model===null)return;const e=this.command.value.trim(),t=e===""?`pacs query ${this.model.expression}`:e;this.handlers.command_show(`${t} --csv-to`)}query_run(e=!1){e&&!dM.test(this.command.value)&&(this.command.value=`${this.command.value.trim()} ${KG}`);const t=this.command.value.trim();t.length!==0&&(this.model=null,this.listing.rows_set([],{field:"pending"}),this.listing.field_get()?.appendChild(this.waiting_build()),this.handlers.command_run(t))}provenance_show(e){if(this.replayed=e?.replayed===!0,this.run.textContent=this.replayed?"RE-QUERY":"QUERY",this.run.classList.toggle("pacs-capsule-requery",this.replayed),this.provenance.hidden=!this.replayed,!this.replayed){this.provenance.textContent="",this.command.value=this.command.value.replace(dM,"").trimEnd();return}const t=e?.answeredAt??"",i=uM(t),n=t.slice(0,10);this.provenance.textContent=i===null?`RESULTS ${n}`:`RESULTS ${n} · ${i}`,this.provenance.title=t}waiting_build(){const e=document.createElement("div");e.className="pacs-waiting";const t=document.createElement("span");t.className="pacs-bar pacs-bar-pacing";const i=document.createElement("span");i.className="pacs-bar-fill",t.appendChild(i);const n=document.createElement("span");return n.className="pacs-waiting-note",n.textContent="QUERYING THE PACS…",e.append(t,n),e}envelope_observe(e){const t=/✓ wrote (\S+)/.exec((e.rendered??"").replace(/\x1b\[[0-9;]*m/g,""));if(t!==null&&this.wrote_show(t[1]),e.model?.kind===gN){const n=mN.safeParse(e.model.data);n.success&&this.servers_take(n.data.servers);return}if(e.model?.kind!==_N)return;const i=fN.safeParse(e.model.data);i.success&&this.results_render(i.data)}progress_observe(e){if(e.operation!=="pull"||e.itemId===void 0)return;const t=e.status??"running",i={status:t};e.current!==void 0&&(i.current=e.current),e.total!==void 0&&(i.total=e.total),e.reason!==void 0&&(i.reason=e.reason),this.badgeState_set(e.itemId,i),t==="done"&&this.model!==null&&qG(this.model,e.itemId,e.current??e.total,e.path)&&this.results_repaint()}badgeState_set(e,t){this.badgeStates.set(e,t),l1.set(e,t),this.seriesProgress.set(e,iP(t,this.seriesProgress.get(e))),QG(e,i=>this.badge_paint(i,t));for(const[i,n]of this.studyTracks)n.uids.includes(e)&&this.studyTrack_paint(i);for(const[i,n]of this.patientTracks)n.uids.includes(e)&&this.patientTrack_paint(i)}badge_build(e){const t=document.createElement("span");if(t.className="pacs-badge",e.pulled===!0){const i=document.createElement("span");i.className="pacs-bar-full";const n=document.createElement("span");return n.className="pacs-badge-note",n.textContent=e.pulledFiles!==void 0?`✓ ${e.pulledFiles} IN CUBE`:"✓ IN CUBE",t.append(i,n),t.dataset.state="done",t}return a1(e.seriesUID,t),this.badge_paint(t,this.badgeStates.get(e.seriesUID)??{status:"idle"}),t}badge_paint(e,t){c1(e,t)}results_render(e){const t=this.model!==null&&this.model.queryId===e.queryId;if(this.model=e,this.provenance_show(e.provenance),!t){this.listing.open_clear(),this.badgeStates.clear();const i=this.patientRows_build(e),n=i.length===1?i[0]:void 0;n!==void 0&&n.studies.length>0&&this.listing.open_set(0,[n.key]),e.studies.length===1&&this.listing.open_set(1,[fM(e.studies[0],0)])}for(const i of e.studies)for(const n of i.series){const r=this.badgeStates.get(n.seriesUID);if(r!==void 0&&JG(n,r)){this.badgeState_set(n.seriesUID,{status:"done",...n.pulledFiles!==void 0?{total:n.pulledFiles}:{}});continue}t&&r!==void 0||this.seriesProgress.set(n.seriesUID,sP(n))}this.results_repaint()}results_repaint(){const e=this.model;if(this.studyTracks.clear(),this.patientTracks.clear(),e===null){this.listing.rows_set([],{field:"pacs"});return}this.listing.rows_set([{key:String(e.queryId),rows:this.patientRows_build(e)}],{field:String(e.queryId)})}studyTrack_paint(e){const t=this.studyTracks.get(e);if(t===void 0)return;const i=t.uids.map(n=>this.seriesProgress.get(n)??{done:0,total:0});t.mount.replaceChildren(gd(zc(i)))}stateLine_compose(e){queueMicrotask(()=>{this.shownGather_render(),this.shownPull_render()});const t=[],i=this.model?.patients??[];if(i.length>0){const n=r=>i.filter(o=>o.status===r).length;t.push(`FOUND ${n("found")} · NONE ${n("none")} · UNASKED ${n("unasked")}`)}return e.filter!==""&&t.push(e.filter),t.join(" · ")}filter_toggle(e){this.listing.filter_toggle(e)}shown_candidates(){const e=[];if(!this.filtering()){for(const t of this.model?.studies??[])for(const i of t.series)e.push({study:t,series:i});return e}for(const t of this.root.querySelectorAll("#pacs-results .pacs-series")){const i=t.dataset.seriesuid;if(i!==void 0)for(const n of this.model?.studies??[]){const r=n.series.find(o=>o.seriesUID===i);r!==void 0&&e.push({study:n,series:r})}}return e}filtering(){return this.listing.filterText_get()!==""}shown_gatherable(){return this.shown_candidates().filter(({series:e})=>Cn(e).gather&&!this.handlers.gathered_is(e.seriesUID))}shownGather_render(){const e=this.root.querySelector("#pacs-gather-shown");if(e===null)return;const t=this.shown_gatherable().length;e.hidden=t===0,e.textContent=this.filtering()?`GATHER ${t} SHOWN`:`GATHER ${t}`}shown_pullable(){return this.shown_candidates().map(({series:e})=>e).filter(e=>Cn(e).pull&&e.vfsPath!==void 0)}shownPull_render(){const e=this.root.querySelector("#pacs-pull-shown");if(e===null)return;const t=this.shown_pullable().length;e.hidden=t===0,e.textContent=this.filtering()?`PULL ${t} SHOWN`:`PULL ${t}`}shown_pull(){const e=this.shown_pullable();if(e.length===0)return;const t=e.map(i=>`"${i.vfsPath}"`).join(" ");this.handlers.command_show(`pull ${t} &`);for(const i of e)this.badgeState_set(i.seriesUID,{status:"queued"});this.handlers.note(`pull: ${e.length} series asked for`),this.shownPull_render()}shown_gather(){const e=this.shown_gatherable();if(e.length!==0){for(const{study:t,series:i}of e)this.gather_note(t,i);this.handlers.note(this.filtering()?`gather: ${e.length} series gathered from what the filter left showing`:`gather: ${e.length} series gathered from the whole answer`),this.shownGather_render()}}gather_note(e,t){t.vfsPath!==void 0&&(this.handlers.gather_add({seriesUID:t.seriesUID,description:t.description,modality:t.modality,series:t,patient:e.patientId||e.patientName,...e.description===void 0||e.description===""?{}:{study:e.description},vfsPath:t.vfsPath,...t.folderPath!==void 0?{folderPath:t.folderPath}:{},...t.fileCount!==void 0?{files:t.fileCount}:{}}),this.selected_refresh())}stage_lit(e){this.litFolders=e,this.selected_refresh()}selected_refresh(){this.listing.indication_refresh()}}function fM(s,e){return s.studyUID??`study-${e}`}function pM(s){return s.replace(/\/$/,"")}function sP(s){const e=s.pulledFiles??0,t=Math.max(s.fileCount??0,e);return s.pulled===!0?{done:t,total:t}:{done:e,total:t}}function iP(s,e){const t=s.total??e?.total??0;return s.status==="error"?{done:s.current??e?.done??0,total:t,failed:!0}:s.status==="done"?{done:t,total:t}:{done:s.current??e?.done??0,total:t}}function en(s,e){const t=s.querySelector(e);if(t===null)throw new Error(`PACS workspace is missing '${e}'`);return t}function Ic(s,e){const t=en(s,e);if(!(t instanceof HTMLInputElement))throw new Error(`'${e}' is not an input`);return t}function mM(s){const e=document.createElement("p");return e.className="files-empty",e.textContent=s,e}class nP{result;handlers;constructor(e,t){this.handlers=t,this.result=Ja(e,".empty-result"),ai(this.result);const i=Ja(e,".empty-prompt");i.addEventListener("keydown",n=>{n.key==="Enter"&&i.value.trim().length>0&&(this.line_run(i.value.trim()),i.value="")}),Ja(e,".empty-go-files").addEventListener("click",()=>{this.line_run("ls .")}),Ja(e,".empty-go-dag").addEventListener("click",()=>{this.line_run("proc feeds")}),Ja(e,".empty-go-pacs").addEventListener("click",()=>{this.handlers.claim("pacs",[])}),window.setTimeout(()=>i.focus(),0)}async line_run(e){this.result.textContent="…";let t;try{t=await this.handlers.execute(e)}catch(n){this.result.textContent=n instanceof Error?n.message:String(n);return}for(const n of t.envelopes){const r=n.model?.kind!==void 0?this.handlers.claimKind_find(n.model.kind):void 0;if(r!==void 0){this.handlers.claim(r,t.envelopes);return}}const i=t.envelopes.map(n=>n.rendered).join(`
|
|
105
|
+
${await Lp(s,i,null)}`}return"desktop save|load|show|list|delete [name] · load <ChRIS file> · clear · share"}const Si={universe:{text:"Every analysis, drawn as a galaxy. Alike analyses cluster; failures glow red. Rearrange it:",list:["GALAXY: grouped by pipeline (the default)","SPOKES · CLUMPS: the same groups, tidier","CONSTELLATIONS: grouped by the tools they used","DATA: hung from the data they began with (format, modality, series)","ACCRETION: grown oldest-first, like next to like"],tail:"Replay its history, or fly in to any one analysis to see its steps."},clusters:{text:"The OpenShift clusters in this tenancy, found by their tag: each one's condition or last finished build step, its address and what it costs per hour. One with a step gone wrong shows in red; one torn down reads GONE until what is left of it is removed. Opening the tile, or a cluster on it, opens the controller: its condition, spec, steps and cost, and the lines that build, verify and tear it down."},vms:{text:"The virtual machines this host keeps, as vm status reads them from its records: each one's state (declared, data only, built, gone), the ChRIS on it or its address, and what it bills an hour at list price. A row opens the script that declares the VM on the script screen, its VM BUILD seat the way in; the tile opens the library."},scripts:{text:"The library of scripts: each .mise file in a git source mounted at /scripts/, with where its lines stand (done, ready, changed, not yet) as play --status reads them from this host's records. Opening the tile opens the library on the script screen; a row opens that script, its lines as the rail, each a form over its line with RUN."},capacity:{text:"What this region has free for the machine families your clusters use, zone by zone: the cores and memory a new cluster or a bigger one could take."},analyses:{text:"Your analyses, newest first. Open one to follow it, read its logs and browse its results."},files:{text:"Your home: the files this session holds."},pacs:{text:"Find studies in the hospital PACS and pull the series you need into ChRIS."},cloud:{text:"Your cloud session: the tenancy and what is built in it. You enter as READ, looking only; nothing outside this host changes until a line would act:",list:["a build, a teardown, a deploy or a user added asks your password once, checked at the door you logged in by","the session is then MANAGE until you leave it, each act still after its own lock and the name typed back"],tail:"MODE READ or MANAGE shows on the strip and beside CONDITION on every cloud screen."},panes:{text:"Saved workspaces: return to a piece of work as you left it."},keys:{text:"Keyboard shortcuts and the commands ARGUS understands."},notes:{text:"A list of updates since the previous release."},console:{text:"A command line into the same session; what you do here shows in the panes, and the other way round."}};function LG(s){return async()=>{const[e,t,i]=await Promise.all([s.ask("ls ~"),s.notes_latest(),s.contribution?.()??Promise.resolve({afterFiles:[],afterPanes:[]})]);let n=[],r="~";for(const m of e.envelopes){if(m.model?.kind!=="fs.listing")continue;const y=m.model.data[0];y!==void 0&&Array.isArray(y.items)&&(n=y.items,typeof y.path=="string"&&(r=y.path))}const o=n.filter(m=>m.type==="dir"),a=s.desktops(),l={key:"files",name:"FILES",hue:"--harvestgold",numeral:"2",figures:[{text:`${n.length} ENTRIES`}],rows:o.slice(0,5).map(m=>({text:m.name,open:()=>s.home_cd(r.endsWith("/")?`${r}${m.name}`:`${r}/${m.name}`)})),verb:"OPEN HOME",about:i.about?.files??Si.files,enter:()=>s.home_open()},c={key:"panes",name:"PANES",hue:"--butter",numeral:"6",figures:[{text:a.length===0?"EMPTY":`${a.length} DESKTOPS`}],rows:a.slice(0,5).map(m=>({text:m.label,open:()=>s.desktop_restore(m.id)})),verb:"SEE DESKTOPS",about:Si.panes,enter:()=>s.panes_open()},h={key:"help",name:"KEYS",hue:"--butter",numeral:"",figures:[{text:`${zn.length} KEYS`},{text:`${Ta.length} VERBS`}],rows:zn.slice(0,5).map(m=>({text:`${m.key.padEnd(6)} ${m.does}`,open:()=>s.keys_open()})),verb:"OPEN THE KEYS",about:Si.keys,enter:()=>s.keys_open()},d=t?.releases[0],u=d?.entries.flatMap(m=>m.changes.filter(w=>!w.internal))??[],p={key:"notes",name:"WHAT'S NEW",hue:"--butter",numeral:"",figures:d===void 0?[{text:"NO NOTES"}]:[{text:s.daemon_stale()?"AFTER RESTART":d.date??"UNDATED"},{text:`${u.length} CHANGE${u.length===1?"":"S"}`}],rows:u.slice(0,3).map(m=>({text:`${m.package.padEnd(7)} ${m.headline}`,open:()=>s.notes_open()})),verb:"OPEN THE NOTES",about:Si.notes,enter:()=>s.notes_open()},f={key:"console",name:"CONSOLE",hue:"--daybreak",numeral:"5",figures:[],rows:[],verb:"OPEN THE CONSOLE",about:Si.console,enter:()=>s.console_open()},_=i.lead===void 0?[]:[i.lead.tile],g=[...i.afterFiles,c,...i.afterPanes,h,p,f];return i.lead!==void 0&&i.lead.weight>=n.length?[..._,l,...g]:[l,..._,...g]}}const WG=/\s--(?:\s|$)/;function iu(s){const e=WG.exec(s),t=e===null?s:s.slice(0,e.index),i=e===null?"":s.slice(e.index),n=t.lastIndexOf(";"),r=n===-1?0:n+1,o=t.slice(r),a=/^\s*\S+/.exec(o),l=r+(a===null?o.length:a[0].length);return{head:t.slice(0,l),args:t.slice(l),tail:i}}function Jz(s,e){return`cd "${s}"; ${e}`}function FG(s){return/^[A-Za-z0-9_./:@+=,-]+$/.test(s)?s:`"${s.replace(/(["\\])/g,"\\$1")}"`}function Qz(s){const e=[],t=/"(?:[^"\\]|\\.)*"|\S+/g;let i=t.exec(s);for(;i!==null;)e.push(i[0]),i=t.exec(s);return e}function oM(s){return s.length>=2&&s.startsWith('"')&&s.endsWith('"')?s.slice(1,-1).replace(/\\(["\\])/g,"$1"):s}function e1(s){return s.startsWith("-")&&s!=="-"&&!/^-\d/.test(s)}function UG(s,e){const t=Qz(iu(s).args);for(let i=0;i<t.length;i++){const n=t[i]??"";if(n===e){const r=t[i+1];return r===void 0||e1(r)?!0:oM(r)}if(n.startsWith(`${e}=`))return oM(n.slice(e.length+1))}return null}function aM(s,e,t){const i=iu(s),n=Qz(i.args),r=[];let o=!1;const a=t===null||t===""?[]:t===!0?[e]:[e,FG(t)];for(let c=0;c<n.length;c++){const h=n[c]??"";if(h===e||h.startsWith(`${e}=`)){if(h===e){const d=n[c+1];d!==void 0&&!e1(d)&&c++}o||(r.push(...a),o=!0);continue}r.push(h)}o||r.push(...a);const l=r.length===0?"":` ${r.join(" ")}`;return`${i.head}${l}${i.tail}`}function $G(s){return/\bfeed_title=/.test(iu(s).tail)}function jG(s,e){return`${s} -- feed_title="${e.replace(/(["\\])/g,"\\$1")}"`}function t1(s){return iu(s).head.replace(/^.*;\s*/,"").trim()}function HG(s,e,t){return/^[A-Za-z0-9_-]+$/.test(s)&&t.filter(n=>n===s).length===1?s:`@${e}`}const s1={listing:"files.row",rules:[{name:"image",label:()=>"IMAGE",offered:s=>s.kind==="seriesFolder"},{name:"gather",label:()=>"GATHER",offered:s=>s.kind!=="catalogue"&&s.projection!==!0},{name:"process",label:()=>"PROCESS",offered:s=>(s.kind==="directory"||s.kind==="seriesFolder")&&(s.feed===null||(s.node??null)!==null)},{name:"run",label:()=>"RUN",offered:s=>s.kind==="catalogue"&&s.bound===!0},{name:"edit",label:()=>"EDIT",offered:s=>s.kind==="file"&&s.editable===!0},{name:"download",label:()=>"DOWNLOAD",offered:s=>s.kind==="file"},{name:"link",label:()=>"LINK",offered:s=>s.kind!=="catalogue"},{name:"move",label:()=>"MOVE",offered:s=>s.kind!=="catalogue"&&s.projection!==!0},{name:"copy",label:()=>"COPY",offered:s=>s.kind!=="catalogue"&&s.projection!==!0},{name:"delete",label:()=>"DELETE",offered:s=>s.kind!=="catalogue"&&s.projection!==!0},{name:"share",label:s=>`SHARE FEED ${s.feed??""}`,offered:s=>s.kind!=="catalogue"&&s.feed!==null&&s.projection!==!0}],states:[{name:"a plain file outside a feed",facts:{kind:"file",feed:null}},{name:"a file inside a feed",facts:{kind:"file",feed:12}},{name:"a directory",facts:{kind:"directory",feed:null}},{name:"a directory inside a feed that is not a node",facts:{kind:"directory",feed:12,node:null}},{name:"a node's data inside a feed",facts:{kind:"directory",feed:12,node:456}},{name:"a DICOM series folder",facts:{kind:"seriesFolder",feed:null}},{name:"a catalogue entry",facts:{kind:"catalogue",feed:null}},{name:"a catalogue entry in a bound catalogue",facts:{kind:"catalogue",feed:null,bound:!0}},{name:"a node's data seen through /proc",facts:{kind:"directory",feed:12,node:456,projection:!0}},{name:"a file seen through /proc",facts:{kind:"file",feed:12,projection:!0}},{name:"a text file",facts:{kind:"file",feed:null,editable:!0}},{name:"a feed's note seen through /proc",facts:{kind:"file",feed:12,projection:!0,editable:!0}}]},i1={listing:"files.selection",rules:[{name:"delete",label:s=>`DELETE ${s.count}`,offered:()=>!0},{name:"move",label:s=>`MOVE ${s.count}`,offered:()=>!0},{name:"copy",label:s=>`COPY ${s.count}`,offered:()=>!0},{name:"share",label:s=>s.feeds.length===1?`SHARE FEED ${s.feeds[0]}`:`SHARE ${s.feeds.length} FEEDS`,offered:s=>s.feeds.length>0}],states:[{name:"a selection outside any feed",facts:{count:3,feeds:[]}},{name:"a selection in one feed",facts:{count:2,feeds:[12]}},{name:"a selection spanning feeds",facts:{count:5,feeds:[12,13]}}]},n1={listing:"runs.row",rules:[{name:"note",label:()=>"NOTE",offered:()=>!0},{name:"tag",label:()=>"TAG",offered:()=>!0},{name:"rename",label:()=>"RENAME",offered:()=>!0},{name:"share",label:()=>"SHARE",offered:()=>!0},{name:"delete",label:()=>"DELETE",offered:()=>!0}],states:[{name:"any feed",facts:{feedId:12}}]},Ol={listing:"pacs.study",rules:[{name:"pullStudy",label:()=>"PULL STUDY",offered:s=>s.addressable},{name:"gather",label:()=>"GATHER",offered:s=>s.addressable},{name:"process",label:()=>"PROCESS",offered:s=>s.allInCube}],states:[{name:"a study with a path",facts:{addressable:!0,allInCube:!1}},{name:"a study with none",facts:{addressable:!1,allInCube:!1}},{name:"a study wholly home",facts:{addressable:!0,allInCube:!0,anyInCube:!0}},{name:"a study partly home",facts:{addressable:!0,allInCube:!1,anyInCube:!0}}]},lo={listing:"pacs.series",rules:[{name:"gather",label:()=>"GATHER",offered:s=>s.addressable||s.inCube},{name:"image",label:()=>"IMAGE",offered:s=>s.inCube&&s.folderKnown},{name:"dir",label:()=>"DIR",offered:s=>s.inCube&&s.folderKnown},{name:"process",label:()=>"PROCESS",offered:s=>s.inCube&&s.folderKnown},{name:"pull",label:()=>"PULL",offered:s=>!s.inCube}],states:[{name:"not yet retrieved",facts:{inCube:!1,folderKnown:!1,addressable:!0}},{name:"not retrieved and unaddressable",facts:{inCube:!1,folderKnown:!1,addressable:!1}},{name:"home, folder not yet named",facts:{inCube:!0,folderKnown:!1,addressable:!0}},{name:"home, folder named",facts:{inCube:!0,folderKnown:!0,addressable:!0}}]},r1={listing:"gather.series",rules:[{name:"remove",label:()=>"REMOVE",offered:()=>!0},{name:"pull",label:()=>"PULL",offered:s=>s.pullable===!0},{name:"image",label:()=>"IMAGE",offered:s=>s.folderKnown&&s.imagery!==!1},{name:"process",label:()=>"PROCESS",offered:()=>!0}],states:[{name:"folder named",facts:{folderKnown:!0}},{name:"a place that is not imagery",facts:{folderKnown:!0,imagery:!1}},{name:"folder not yet named",facts:{folderKnown:!1}},{name:"not retrieved yet",facts:{folderKnown:!1,pullable:!0}}]},o1={listing:"gather.cohort",rules:[{name:"save",label:()=>"SAVE",offered:s=>s.count>0},{name:"export",label:()=>"EXPORT CSV",offered:s=>s.count>0},{name:"feed",label:()=>"CREATE FEED",offered:s=>s.count>0&&s.feed===null},{name:"process",label:()=>"PROCESS",offered:s=>s.count>0},{name:"dismiss",label:()=>"DISMISS",offered:()=>!0}],states:[{name:"holding series",facts:{count:2,feed:null}},{name:"holding series, rooted in a feed",facts:{count:2,feed:4501}},{name:"emptied",facts:{count:0,feed:null}}]};function Jr(s){return{listing:s.listing,visit(e){return e(s)}}}Jr(s1),Jr(i1),Jr(n1),Jr(Ol),Jr(lo),Jr(o1),Jr(r1);function gn(s,e){const t=s.rules.find(i=>i.name===e);if(t===void 0)throw new Error(`${s.listing} declares no verb '${e}'`);return t}const Fo={fold:"5.2em",patient:"13em",mrn:"7.5em"};function VG(s){return{inCube:s.pulled===!0,folderKnown:s.folderPath!==void 0,addressable:s.vfsPath!==void 0}}function lM(s){if(s.series.length===0)return null;const e=[];for(const i of s.series){if(i.pulled!==!0||i.folderPath===void 0)return null;e.push(i.folderPath.replace(/\/[^/]+\/?$/,""))}const t=e[0]??"";return e.every(i=>i===t)&&t!==""?t:null}function Cn(s){const e=VG(s),t=i=>gn(lo,i).offered(e);return{gather:t("gather"),image:t("image"),dir:t("dir"),pull:t("pull")}}function qG(s,e,t,i){let n=!1;for(const r of s.studies)for(const o of r.series)o.seriesUID===e&&(i!==void 0&&o.folderPath!==i&&(o.folderPath=i,n=!0),o.pulled!==!0&&(o.pulled=!0,t!==void 0&&t>0&&(o.pulledFiles=t),n=!0));return n}const cM=[{id:"pacs-f-name",term:"PatientName"},{id:"pacs-f-mrn",term:"PatientID"},{id:"pacs-f-date",term:"StudyDate"},{id:"pacs-f-accession",term:"AccessionNumber"},{id:"pacs-f-modality",term:"Modality"}],Dc={running:"RETRIEVING",done:"✓ PULLED",error:"✗ ERROR",unconfirmed:"? UNCONFIRMED",stalled:"STALLED",queued:"QUEUED",idle:"NOT RETRIEVED"},KG="--fresh",hM="--anon",YG=/\s*--anon\b/,XG=["pacs-f-name","pacs-f-mrn","pacs-f-accession","pacs-f-date"],dM=/\s*--fresh\b/;function uM(s){const e=Date.parse(s);if(Number.isNaN(e))return null;const t=Math.max(0,Math.round((Date.now()-e)/1e3)),i=[{limit:60,size:1,name:"SECOND"},{limit:3600,size:60,name:"MINUTE"},{limit:86400,size:3600,name:"HOUR"},{limit:2592e3,size:86400,name:"DAY"},{limit:31536e3,size:2592e3,name:"MONTH"},{limit:1/0,size:31536e3,name:"YEAR"}];for(const n of i){if(t>=n.limit)continue;const r=Math.max(1,Math.floor(t/n.size));return`${r} ${n.name}${r===1?"":"S"} AGO`}return null}const vd=new Map;function a1(s,e){const t=vd.get(s)??new Set;t.add(e),vd.set(s,t)}const l1=new Map;function c1(s,e){s.replaceChildren(),s.dataset.state=e.status,e.reason!==void 0?s.title=e.reason:s.removeAttribute("title");const t=document.createElement("span");if(t.className="pacs-badge-note",e.status==="idle"){t.textContent=Dc.idle,s.append(gd({done:0,total:0}),t);return}if(e.status==="done"){const a=document.createElement("span");a.className="pacs-bar-full",t.textContent=e.total!==void 0&&e.total>0?`✓ ${e.total} IN CUBE`:"✓ IN CUBE",s.append(a,t);return}if(e.status!=="running"&&e.status!=="queued"){s.textContent=Dc[e.status]??e.status.toUpperCase();return}const i=e.total!==void 0?` ${e.current??0}/${e.total}`:"",n=ZG(e),r=document.createElement("span");r.className=n===null?"pacs-bar pacs-bar-pacing":"pacs-bar";const o=document.createElement("span");o.className="pacs-bar-fill",n!==null&&(o.style.width=`${Math.round(n*100)}%`),r.appendChild(o),t.textContent=e.status==="queued"?Dc.queued:`${Dc.running}${i}`,s.append(r,t)}function ZG(s){return s.status==="queued"||s.total===void 0||s.total===0||(s.current??0)===0?null:Math.min(1,(s.current??0)/s.total)}function JG(s,e){return s.pulled===!0&&e.status!=="done"&&e.status!=="running"&&e.status!=="queued"}function QG(s,e){const t=vd.get(s);if(t!==void 0){for(const i of[...t]){if(!i.isConnected){t.delete(i);continue}e(i)}t.size===0&&vd.delete(s)}}function eP(s){const e=document.createElement("span");if(e.className="pacs-badge",s.pulled===!0){const r=document.createElement("span");r.className="pacs-bar-full";const o=document.createElement("span");return o.className="pacs-badge-note",o.textContent=s.pulledFiles!==void 0?`✓ ${s.pulledFiles} IN CUBE`:"✓ IN CUBE",e.append(r,o),e.dataset.state="done",e}const t=document.createElement("span");t.className="pacs-bar";const i=document.createElement("span");i.className="pacs-badge-note",i.textContent="NOT RETRIEVED",e.append(t,i),e.dataset.state="idle",a1(s.seriesUID,e);const n=l1.get(s.seriesUID);return n!==void 0&&c1(e,n),e}function h1(s,e){return[{key:"series",label:"SERIES",className:"pacs-series-desc",width:"35.5em",cell:t=>s(t).description??""},{key:"state",label:"STATE",className:"pacs-badge",width:"1fr",cell:t=>e(s(t)),compare:t=>s(t).pulled===!0?"done":"idle"},{key:"modality",label:"MODALITY",className:"pacs-series-modality",width:"4em",cell:t=>s(t).modality},{key:"files",label:"FILES",className:"pacs-series-files",width:"6em",cell:t=>{const i=s(t).fileCount;return i!==void 0?`${i} FILES`:""},compare:t=>s(t).fileCount??-1}]}class tP{root;command;results;handlers;litFolders=new Map;badgeStates=new Map;seriesProgress=new Map;studyTracks=new Map;traits;actions;studyTraits;studyActions;patientTraits;listing;patientTracks=new Map;provenance;run;model=null;anon=!1;revealed=!1;anonPill;revealPill;replayed=!1;serverCell;serverStrip;servers=[];chosen=new Set;constructor(e,t){this.root=e,this.handlers=t,this.command=Ic(e,"#pacs-command"),this.results=en(e,"#pacs-results"),this.traits=this.traits_declare(),this.actions=this.actions_declare(),this.studyTraits=this.studyTraits_declare(),this.studyActions=this.studyActions_declare(),this.patientTraits=this.patientTraits_declare(),this.listing=new sr({mount:this.results,traits:this.patientTraits,key:i=>i.key,chrome:{root:e,prefix:"pacs"},activatable:i=>i.studies.length>0,address:i=>i.studies.length>0?bN(i.patient):void 0,control:"fold",row:{className:()=>"pacs-patient-row",groupClassName:i=>i.patient.status==="unasked"?"pacs-patient pacs-patient-unasked":"pacs-patient",decorate:(i,n)=>{n.studies.length>0&&(i.title="unfold this patient's studies (the patient keeps its place)")}},child:ma(i=>i.studies.map((n,r)=>({study:n,key:fM(n,r)})),{traits:this.studyTraits,key:i=>i.key,address:i=>i.study.vfsPath,control:"fold",actions:{of:()=>this.studyActions},row:{className:()=>"pacs-study-row",groupClassName:()=>"pacs-study",decorate:i=>{i.title="unfold this study's series (the study keeps its place)"}},child:ma(i=>i.study.series.map(n=>({study:i.study,studyKey:i.key,series:n})),{traits:this.traits,key:i=>i.series.seriesUID,address:i=>i.series.vfsPath,actions:{of:()=>this.actions},row:{className:()=>"pacs-series",decorate:(i,n)=>{i.dataset.seriesuid=n.series.seriesUID}}})}),state:i=>this.stateLine_compose(i),empty:()=>mM("NO STUDIES FOUND")}),e.style.setProperty("--roster-cols",this.listing.template_get(1)),this.listing.rows_set([],{field:"pacs"});for(const{id:i}of cM){const n=Ic(e,`#${i}`);n.addEventListener("input",()=>this.command_regenerate()),n.addEventListener("keydown",r=>{r.key==="Enter"&&(r.preventDefault(),this.query_run())})}this.serverCell=en(e,"#pacs-f-server"),this.serverStrip=en(e,"#pacs-server-strip"),this.serverCell.addEventListener("click",()=>this.serverStrip_toggle()),this.serverCell_sync(),this.provenance=en(e,"#pacs-provenance"),this.anonPill=en(e,"#pacs-anon"),this.revealPill=en(e,"#pacs-reveal"),this.anonPill.addEventListener("click",()=>this.anon_set(!this.anon)),this.revealPill.addEventListener("click",()=>this.reveal_set(!this.revealed)),this.run=en(e,"#pacs-run"),this.run.addEventListener("click",()=>this.query_run(this.replayed)),this.command.addEventListener("keydown",i=>{i.key==="Enter"&&this.query_run()}),en(e,"#pacs-export").addEventListener("click",()=>this.answer_export()),en(e,"#pacs-gather-shown").addEventListener("click",()=>this.shown_gather()),en(e,"#pacs-pull-shown").addEventListener("click",()=>this.shown_pull())}patientTraits_declare(){return[{key:"fold",label:"",className:"pacs-fold",capped:!1,width:Fo.fold,cell:e=>{const t=document.createElement("span");return t.className=e.studies.length===0?"pacs-fold pacs-fold-none":"pacs-fold",t}},{key:"patient",label:"PATIENT",className:"pacs-patient-name",width:Fo.patient,cell:e=>e.patient.patientName||"(unknown)"},{key:"mrn",label:"MRN",className:"pacs-patient-mrn",width:Fo.mrn,cell:e=>e.patient.patientId||"—"},{key:"answered",label:"ANSWERED",className:"pacs-patient-answered",width:"12em",cell:e=>{const t=document.createElement("span");if(t.className=e.patient.status==="unasked"?"pacs-patient-answered pacs-unasked":"pacs-patient-answered",e.patient.status==="unasked")return t.textContent="UNASKED",e.patient.error!==void 0&&(t.title=e.patient.error),t;const i=e.patient.provenance?.answeredAt;return t.textContent=i===void 0?"—":uM(i)??"—",i!==void 0&&(t.title=i),t},compare:e=>{const t=e.patient.provenance?.answeredAt;if(t===void 0)return Number.MAX_SAFE_INTEGER;const i=Date.parse(t);return Number.isNaN(i)?Number.MAX_SAFE_INTEGER:i}},{key:"progress",label:"PROGRESS",className:"pacs-patient-progress",width:"1fr",cell:e=>{const t=document.createElement("span");return t.className="pacs-patient-progress",this.patientTracks.set(e.key,{mount:t,uids:e.studies.flatMap(i=>i.series.map(n=>n.seriesUID))}),this.patientTrack_paint(e.key),t},compare:e=>{const t=this.patientProgress_compute(e);return t.total===0?-1:t.done/t.total}},{key:"studies",shed:3,label:"STUDIES",className:"pacs-patient-count",width:"6em",cell:e=>e.patient.status==="unasked"?"—":String(e.patient.studyCount),compare:e=>e.patient.status==="unasked"?-1:e.patient.studyCount},{key:"series",shed:2,label:"SERIES",className:"pacs-patient-count",width:"5em",cell:e=>e.patient.status==="unasked"?"—":String(e.patient.seriesCount),compare:e=>e.patient.status==="unasked"?-1:e.patient.seriesCount},{key:"server",shed:1,label:"SERVER",className:"pacs-patient-server",width:"9em",cell:e=>e.patient.server??this.model?.pacsName??"—"}]}patientProgress_compute(e){return zc(e.studies.flatMap(t=>t.series.map(i=>this.seriesProgress.get(i.seriesUID)??{done:0,total:0})))}patientTrack_paint(e){const t=this.patientTracks.get(e);if(t===void 0)return;const i=t.uids.map(n=>this.seriesProgress.get(n)??{done:0,total:0});t.mount.replaceChildren(gd(zc(i)))}patientRows_build(e){const t=(r,o)=>e.studies.filter(a=>a.patientId===r&&(o===void 0||a.server===void 0||a.server===o));if(e.patients!==void 0&&e.patients.length>0)return e.patients.map((r,o)=>({patient:r,key:`${r.patientId}::${r.server??""}::${o}`,studies:t(r.patientId,r.server)}));const i=[],n=new Map;for(const r of e.studies){const o=r.patientId;n.has(o)||(n.set(o,[]),i.push(o)),n.get(o).push(r)}return i.map((r,o)=>{const a=n.get(r)??[];return{key:`${r}::${o}`,studies:a,patient:{patientId:r,...a[0]?.patientName?{patientName:a[0].patientName}:{},status:"found",studyCount:a.length,seriesCount:a.reduce((l,c)=>l+c.series.length,0),...e.provenance===void 0?{}:{provenance:e.provenance}}}})}studyTraits_declare(){return[{key:"fold",label:"",className:"pacs-fold",capped:!1,width:Fo.fold,cell:()=>{const e=document.createElement("span");return e.className="pacs-fold",e}},{key:"patient",label:"PATIENT",className:"pacs-study-patient",width:Fo.patient,cell:e=>e.study.patientName||"(unknown)"},{key:"mrn",label:"MRN",className:"pacs-study-mrn",width:Fo.mrn,cell:e=>e.study.patientId||"—"},{key:"study",label:"STUDY",className:"pacs-study-desc",width:"12em",cell:e=>e.study.description||"(no description)"},{key:"progress",label:"PROGRESS",className:"pacs-study-progress",width:"1fr",cell:e=>{const t=document.createElement("span");return t.className="pacs-study-progress",this.studyTracks.set(e.key,{mount:t,uids:e.study.series.map(i=>i.seriesUID)}),this.studyTrack_paint(e.key),t},compare:e=>{const t=this.studyProgress_compute(e);return t.total===0?-1:t.done/t.total}},{key:"date",label:"DATE",className:"pacs-study-date",width:"7.5em",cell:e=>e.study.date},{key:"accession",label:"ACCESSION",className:"pacs-study-accession",width:"9em",cell:e=>e.study.accession||"—"},{key:"modality",label:"MODALITY",className:"pacs-study-modalities",width:"6.5em",cell:e=>e.study.modalities},{key:"server",label:"SERVER",className:"pacs-study-server",width:"9em",cell:e=>e.study.server??this.model?.pacsName??"—"},{key:"series",label:"SERIES",className:"pacs-study-count",width:"6.5em",cell:e=>String(e.study.series.length),compare:e=>e.study.series.length}]}studyActions_declare(){return[{label:gn(Ol,"pullStudy").label({addressable:!0,allInCube:!1}),offered:e=>gn(Ol,"pullStudy").offered({addressable:e.study.vfsPath!==void 0,allInCube:!1}),run:e=>{const t=e.study.vfsPath;if(t!==void 0){this.handlers.command_run(`pull ${t} &`);for(const i of e.study.series)i.vfsPath!==void 0&&i.pulled!==!0&&this.badgeState_set(i.seriesUID,{status:"queued"})}}},{label:gn(Ol,"gather").label({addressable:!0,allInCube:!1,anyInCube:!0}),offered:e=>e.study.series.some(t=>Cn(t).gather),run:e=>{const t=e.study.series.filter(n=>Cn(n).gather);for(const n of t)this.gather_note(e.study,n);const i=e.study.series.length-t.length;this.handlers.note(`gather: ${t.length} series gathered${i>0?`, ${i} not in CUBE (pull them first)`:""}`)}},{label:gn(Ol,"process").label({addressable:!0,allInCube:!0}),offered:e=>lM(e.study)!==null,run:e=>{const t=lM(e.study);t!==null&&this.handlers.process_open(t)}}]}studyProgress_compute(e){return zc(e.study.series.map(t=>this.seriesProgress.get(t.seriesUID)??{done:0,total:0}))}traits_declare(){return h1(e=>e.series,e=>this.badge_build(e))}actions_declare(){return[{label:gn(lo,"gather").label({inCube:!0,folderKnown:!0,addressable:!0}),offered:e=>Cn(e.series).gather,selected:e=>this.handlers.gathered_is(e.series.seriesUID),run:e=>this.gather_note(e.study,e.series)},{label:gn(lo,"image").label({inCube:!0,folderKnown:!0,addressable:!0}),offered:e=>Cn(e.series).image,selected:e=>e.series.folderPath!==void 0&&(this.litFolders.get(pM(e.series.folderPath))?.viewer??!1),run:e=>{e.series.folderPath!==void 0&&this.handlers.image_open(e.series.folderPath)}},{label:gn(lo,"dir").label({inCube:!0,folderKnown:!0,addressable:!0}),offered:e=>Cn(e.series).dir,selected:e=>e.series.folderPath!==void 0&&(this.litFolders.get(pM(e.series.folderPath))?.browser??!1),run:e=>{e.series.folderPath!==void 0&&this.handlers.dir_open(e.series.folderPath)}},{label:gn(lo,"process").label({inCube:!0,folderKnown:!0,addressable:!0}),offered:e=>Cn(e.series).image,run:e=>{e.series.folderPath!==void 0&&this.handlers.process_open(e.series.folderPath)}},{label:gn(lo,"pull").label({inCube:!1,folderKnown:!1,addressable:!0}),offered:e=>Cn(e.series).pull,disabled:e=>e.series.vfsPath===void 0,run:e=>{const t=e.series.vfsPath;t!==void 0&&(this.handlers.command_run(`pull ${t} &`),this.badgeState_set(e.series.seriesUID,{status:"queued"}))}}]}state_name(e){return e.pulled===!0?"pulled":this.badgeStates.get(e.seriesUID)?.status??"idle"}command_regenerate(){const e=[];for(const{id:n,term:r}of cM){const o=Ic(this.root,`#${n}`).value.trim();o.length>0&&e.push(`${r}:${o}`)}const t=this.chosen.size>1?` --pacsserver ${[...this.chosen].join(",")}`:"",i=this.anon?` ${hM}`:"";this.command.value=e.length>0||t!==""?`pacs query ${e.join(",")}${t}${i}`:""}anon_set(e){e!==this.anon&&(this.anon=e,this.revealed=!1,this.anonPill.textContent=e?"ANON ON":"ANON OFF",this.anonPill.classList.toggle("pacs-capsule-off",!e),this.revealPill.hidden=!e,this.model=null,this.listing.rows_set([],{field:"pending"}),this.provenance_show(void 0),this.command.value=e?`${this.command.value.trim()} ${hM}`.trim():this.command.value.replace(YG,"").trimEnd(),this.masking_apply())}reveal_set(e){this.revealed=e,this.revealPill.textContent=e?"HIDE":"REVEAL",this.revealPill.classList.toggle("pacs-capsule-off",!e),this.masking_apply()}masking_apply(){const e=this.anon&&!this.revealed;for(const t of XG)Ic(this.root,`#${t}`).type=e?"password":"text";this.command.type=e?"password":"text"}serverStrip_toggle(e){const t=e??this.serverStrip.hidden;this.serverStrip.hidden=!t,this.serverCell.classList.toggle("pacs-server-open",t),t&&this.servers.length===0&&this.servers_ask(),t&&this.serverStrip_paint()}query_get(){return this.model===null?null:`pacs query ${this.model.expression}`}serverStrip_isOpen(){return!this.serverStrip.hidden}serverStrip_close(){this.serverStrip_toggle(!1)}servers_ask(){this.handlers.command_run("pacs list")}servers_take(e){this.servers=e,this.serverStrip_paint(),this.serverCell_sync()}serverStrip_paint(){if(this.serverStrip.replaceChildren(),this.servers.length===0){this.serverStrip.appendChild(mM("ASKING THE SESSION FOR REGISTERED SERVERS"));return}for(const e of this.servers){const t=document.createElement("button");t.className=this.chosen.has(e.identifier)?"pacs-server-segment pacs-server-chosen":"pacs-server-segment",t.dataset.server=e.identifier,t.textContent=e.identifier,e.active&&(t.title="the session is connected to this server"),t.addEventListener("click",()=>this.server_choose(e.identifier)),this.serverStrip.appendChild(t)}}server_choose(e){if(this.chosen.has(e)?this.chosen.delete(e):this.chosen.add(e),this.chosen.size===1){const t=[...this.chosen][0];this.handlers.command_show(`pacs connect ${t}`)}this.serverStrip_paint(),this.serverCell_sync(),this.command_regenerate()}serverCell_sync(){const e=[...this.chosen];if(e.length===0){const t=this.servers.find(i=>i.active);this.serverCell.textContent=t?.identifier??"—",this.serverCell.classList.remove("pacs-server-many");return}this.serverCell.textContent=e.length===1?e[0]:`${e[0]} +${e.length-1}`,this.serverCell.classList.toggle("pacs-server-many",e.length>1)}wrote_show(e){const t=this.root.querySelector("#pacs-wrote");t!==null&&(t.textContent=`WROTE ${e}`,t.title="open the folder this landed in",t.classList.add("pacs-wrote-opens"),t.onclick=()=>{const i=e.lastIndexOf("/");this.handlers.dir_open(i<=0?e:e.slice(0,i))},t.hidden=!1)}answer_export(){if(this.model===null)return;const e=this.command.value.trim(),t=e===""?`pacs query ${this.model.expression}`:e;this.handlers.command_show(`${t} --csv-to`)}query_run(e=!1){e&&!dM.test(this.command.value)&&(this.command.value=`${this.command.value.trim()} ${KG}`);const t=this.command.value.trim();t.length!==0&&(this.model=null,this.listing.rows_set([],{field:"pending"}),this.listing.field_get()?.appendChild(this.waiting_build()),this.handlers.command_run(t))}provenance_show(e){if(this.replayed=e?.replayed===!0,this.run.textContent=this.replayed?"RE-QUERY":"QUERY",this.run.classList.toggle("pacs-capsule-requery",this.replayed),this.provenance.hidden=!this.replayed,!this.replayed){this.provenance.textContent="",this.command.value=this.command.value.replace(dM,"").trimEnd();return}const t=e?.answeredAt??"",i=uM(t),n=t.slice(0,10);this.provenance.textContent=i===null?`RESULTS ${n}`:`RESULTS ${n} · ${i}`,this.provenance.title=t}waiting_build(){const e=document.createElement("div");e.className="pacs-waiting";const t=document.createElement("span");t.className="pacs-bar pacs-bar-pacing";const i=document.createElement("span");i.className="pacs-bar-fill",t.appendChild(i);const n=document.createElement("span");return n.className="pacs-waiting-note",n.textContent="QUERYING THE PACS…",e.append(t,n),e}envelope_observe(e){const t=/✓ wrote (\S+)/.exec((e.rendered??"").replace(/\x1b\[[0-9;]*m/g,""));if(t!==null&&this.wrote_show(t[1]),e.model?.kind===gN){const n=mN.safeParse(e.model.data);n.success&&this.servers_take(n.data.servers);return}if(e.model?.kind!==_N)return;const i=fN.safeParse(e.model.data);i.success&&this.results_render(i.data)}progress_observe(e){if(e.operation!=="pull"||e.itemId===void 0)return;const t=e.status??"running",i={status:t};e.current!==void 0&&(i.current=e.current),e.total!==void 0&&(i.total=e.total),e.reason!==void 0&&(i.reason=e.reason),this.badgeState_set(e.itemId,i),t==="done"&&this.model!==null&&qG(this.model,e.itemId,e.current??e.total,e.path)&&this.results_repaint()}badgeState_set(e,t){this.badgeStates.set(e,t),l1.set(e,t),this.seriesProgress.set(e,iP(t,this.seriesProgress.get(e))),QG(e,i=>this.badge_paint(i,t));for(const[i,n]of this.studyTracks)n.uids.includes(e)&&this.studyTrack_paint(i);for(const[i,n]of this.patientTracks)n.uids.includes(e)&&this.patientTrack_paint(i)}badge_build(e){const t=document.createElement("span");if(t.className="pacs-badge",e.pulled===!0){const i=document.createElement("span");i.className="pacs-bar-full";const n=document.createElement("span");return n.className="pacs-badge-note",n.textContent=e.pulledFiles!==void 0?`✓ ${e.pulledFiles} IN CUBE`:"✓ IN CUBE",t.append(i,n),t.dataset.state="done",t}return a1(e.seriesUID,t),this.badge_paint(t,this.badgeStates.get(e.seriesUID)??{status:"idle"}),t}badge_paint(e,t){c1(e,t)}results_render(e){const t=this.model!==null&&this.model.queryId===e.queryId;if(this.model=e,this.provenance_show(e.provenance),!t){this.listing.open_clear(),this.badgeStates.clear();const i=this.patientRows_build(e),n=i.length===1?i[0]:void 0;n!==void 0&&n.studies.length>0&&this.listing.open_set(0,[n.key]),e.studies.length===1&&this.listing.open_set(1,[fM(e.studies[0],0)])}for(const i of e.studies)for(const n of i.series){const r=this.badgeStates.get(n.seriesUID);if(r!==void 0&&JG(n,r)){this.badgeState_set(n.seriesUID,{status:"done",...n.pulledFiles!==void 0?{total:n.pulledFiles}:{}});continue}t&&r!==void 0||this.seriesProgress.set(n.seriesUID,sP(n))}this.results_repaint()}results_repaint(){const e=this.model;if(this.studyTracks.clear(),this.patientTracks.clear(),e===null){this.listing.rows_set([],{field:"pacs"});return}this.listing.rows_set([{key:String(e.queryId),rows:this.patientRows_build(e)}],{field:String(e.queryId)})}studyTrack_paint(e){const t=this.studyTracks.get(e);if(t===void 0)return;const i=t.uids.map(n=>this.seriesProgress.get(n)??{done:0,total:0});t.mount.replaceChildren(gd(zc(i)))}stateLine_compose(e){queueMicrotask(()=>{this.shownGather_render(),this.shownPull_render()});const t=[],i=this.model?.patients??[];if(i.length>0){const n=r=>i.filter(o=>o.status===r).length;t.push(`FOUND ${n("found")} · NONE ${n("none")} · UNASKED ${n("unasked")}`)}return e.filter!==""&&t.push(e.filter),t.join(" · ")}filter_toggle(e){this.listing.filter_toggle(e)}shown_candidates(){const e=[];if(!this.filtering()){for(const t of this.model?.studies??[])for(const i of t.series)e.push({study:t,series:i});return e}for(const t of this.root.querySelectorAll("#pacs-results .pacs-series")){const i=t.dataset.seriesuid;if(i!==void 0)for(const n of this.model?.studies??[]){const r=n.series.find(o=>o.seriesUID===i);r!==void 0&&e.push({study:n,series:r})}}return e}filtering(){return this.listing.filterText_get()!==""}shown_gatherable(){return this.shown_candidates().filter(({series:e})=>Cn(e).gather&&!this.handlers.gathered_is(e.seriesUID))}shownGather_render(){const e=this.root.querySelector("#pacs-gather-shown");if(e===null)return;const t=this.shown_gatherable().length;e.hidden=t===0,e.textContent=this.filtering()?`GATHER ${t} SHOWN`:`GATHER ${t}`}shown_pullable(){return this.shown_candidates().map(({series:e})=>e).filter(e=>Cn(e).pull&&e.vfsPath!==void 0)}shownPull_render(){const e=this.root.querySelector("#pacs-pull-shown");if(e===null)return;const t=this.shown_pullable().length;e.hidden=t===0,e.textContent=this.filtering()?`PULL ${t} SHOWN`:`PULL ${t}`}shown_pull(){const e=this.shown_pullable();if(e.length===0)return;const t=e.map(i=>`"${i.vfsPath}"`).join(" ");this.handlers.command_show(`pull ${t} &`);for(const i of e)this.badgeState_set(i.seriesUID,{status:"queued"});this.handlers.note(`pull: ${e.length} series asked for`),this.shownPull_render()}shown_gather(){const e=this.shown_gatherable();if(e.length!==0){for(const{study:t,series:i}of e)this.gather_note(t,i);this.handlers.note(this.filtering()?`gather: ${e.length} series gathered from what the filter left showing`:`gather: ${e.length} series gathered from the whole answer`),this.shownGather_render()}}gather_note(e,t){t.vfsPath!==void 0&&(this.handlers.gather_add({seriesUID:t.seriesUID,description:t.description,modality:t.modality,series:t,patient:e.patientId||e.patientName,...e.description===void 0||e.description===""?{}:{study:e.description},vfsPath:t.vfsPath,...t.folderPath!==void 0?{folderPath:t.folderPath}:{},...t.fileCount!==void 0?{files:t.fileCount}:{}}),this.selected_refresh())}stage_lit(e){this.litFolders=e,this.selected_refresh()}selected_refresh(){this.listing.indication_refresh()}}function fM(s,e){return s.studyUID??`study-${e}`}function pM(s){return s.replace(/\/$/,"")}function sP(s){const e=s.pulledFiles??0,t=Math.max(s.fileCount??0,e);return s.pulled===!0?{done:t,total:t}:{done:e,total:t}}function iP(s,e){const t=s.total??e?.total??0;return s.status==="error"?{done:s.current??e?.done??0,total:t,failed:!0}:s.status==="done"?{done:t,total:t}:{done:s.current??e?.done??0,total:t}}function en(s,e){const t=s.querySelector(e);if(t===null)throw new Error(`PACS workspace is missing '${e}'`);return t}function Ic(s,e){const t=en(s,e);if(!(t instanceof HTMLInputElement))throw new Error(`'${e}' is not an input`);return t}function mM(s){const e=document.createElement("p");return e.className="files-empty",e.textContent=s,e}class nP{result;handlers;constructor(e,t){this.handlers=t,this.result=Ja(e,".empty-result"),ai(this.result);const i=Ja(e,".empty-prompt");i.addEventListener("keydown",n=>{n.key==="Enter"&&i.value.trim().length>0&&(this.line_run(i.value.trim()),i.value="")}),Ja(e,".empty-go-files").addEventListener("click",()=>{this.line_run("ls .")}),Ja(e,".empty-go-dag").addEventListener("click",()=>{this.line_run("proc feeds")}),Ja(e,".empty-go-pacs").addEventListener("click",()=>{this.handlers.claim("pacs",[])}),window.setTimeout(()=>i.focus(),0)}async line_run(e){this.result.textContent="…";let t;try{t=await this.handlers.execute(e)}catch(n){this.result.textContent=n instanceof Error?n.message:String(n);return}for(const n of t.envelopes){const r=n.model?.kind!==void 0?this.handlers.claimKind_find(n.model.kind):void 0;if(r!==void 0){this.handlers.claim(r,t.envelopes);return}}const i=t.envelopes.map(n=>n.rendered).join(`
|
|
106
106
|
`);this.result.textContent=rP(i)||"(no output)"}}function Ja(s,e){const t=s.querySelector(e);if(t===null)throw new Error(`empty pane template is missing ${e}`);return t}function rP(s){return s.replace(/\x1b\[[0-9;:]*[A-Za-z]/g,"")}class oP{routes=new Map([["console",new Map],["ambient",new Map]]);observers=new Map([["console",[]],["ambient",[]]]);claims=new Map;claimers=new Map;watchers=[];route_add(e,t,i){const n=this.routes.get(e);for(const r of t)n.set(r,[...n.get(r)??[],i])}observer_add(e,t){this.observers.get(e).push(i=>(t(i),!1))}route(e,t){const i=t.model?.kind;if(i===void 0)return!1;let n=!1;for(const r of this.routes.get(e).get(i)??[])n=r(t)||n;return n}observe(e,t){for(const i of this.observers.get(e))i(t)}claim_add(e,t,i){this.claims.set(e,t),i!==void 0&&this.claimers.set(t,i)}claimKind_find(e){return this.claims.get(e)}claimer_get(e){return this.claimers.get(e)}watcher_add(e){this.watchers.push(e)}watched(e,t){for(const i of this.watchers)i(e,t)}}function aP(s,e){s.route_add("console",[SN.view],i=>{const n=yN.safeParse(i.model?.data);return n.success&&e.image_open(n.data.path,n.data.force===!0),!0}),s.route_add("console",["feed.dag","feed.list",Cr.feedIndexing],i=>(e.dag_target().envelope_observe(i),!0)),s.observer_add("console",i=>e.pacs().envelope_observe(i)),s.route_add("ambient",["feed.dag"],i=>{const n=Qg.safeParse(i.model?.data);if(!n.success)return!0;for(const r of e.dags())r.model_refresh(n.data);for(const r of e.universes())r.model_refresh(n.data);return!0}),s.route_add("ambient",["gather.cohort"],i=>(e.cohort_adopt(i),!0)),s.watcher_add((i,n)=>{for(const r of e.dags())r.watched_observe(i,n);for(const r of e.universes())r.watched_observe(i,n)});const t=(i,n)=>{const r=e.dag_get(e.pane_replace(i,"dag"));for(const o of n)r?.envelope_observe(o)};s.claim_add("feed.dag","dag",t),s.claim_add("feed.list","dag",t),s.claim_add("pacs.query","pacs",(i,n)=>{e.pacs_present();for(const r of n)e.pacs().envelope_observe(r)}),s.claim_add(ua.series,"image",(i,n)=>{const r=e.image_get(e.pane_replace(i,"image"));for(const o of n){if(o.model?.kind!==ua.series)continue;const a=nz.safeParse(o.model.data);a.success&&r?.series_show(a.data)}}),s.claim_add(ua.tags,"tags",(i,n)=>{const r=e.tags_get(e.pane_replace(i,"tags"));for(const o of n){if(o.model?.kind!==ua.tags)continue;const a=iz.safeParse(o.model.data);a.success&&r?.model_show(a.data)}})}const __="185",lP=0,gM=1,cP=2,Bh=1,hP=2,El=3,Hr=0,li=1,qn=2,Jn=0,Mo=1,Vr=2,_M=3,bM=4,dP=5,co=100,uP=101,fP=102,pP=103,mP=104,gP=200,_P=201,bP=202,MP=203,Wp=204,Fp=205,vP=206,wP=207,yP=208,SP=209,zP=210,xP=211,OP=212,EP=213,AP=214,Up=0,$p=1,jp=2,Da=3,Hp=4,Vp=5,qp=6,Kp=7,d1=0,TP=1,DP=2,xn=0,u1=1,f1=2,p1=3,m1=4,g1=5,_1=6,b1=7,M1=300,Eo=301,Ia=302,Fu=303,Uu=304,nu=306,Yp=1e3,Kn=1001,Xp=1002,Ps=1003,IP=1004,Cc=1005,js=1006,$u=1007,uo=1008,zi=1009,v1=1010,w1=1011,Jl=1012,b_=1013,Tn=1014,on=1015,ir=1016,M_=1017,v_=1018,Ql=1020,y1=35902,S1=35899,z1=1021,x1=1022,an=1023,nr=1026,fo=1027,w_=1028,y_=1029,Ao=1030,S_=1031,z_=1033,Gh=33776,Ph=33777,Lh=33778,Wh=33779,Zp=35840,Jp=35841,Qp=35842,em=35843,tm=36196,sm=37492,im=37496,nm=37488,rm=37489,wd=37490,om=37491,am=37808,lm=37809,cm=37810,hm=37811,dm=37812,um=37813,fm=37814,pm=37815,mm=37816,gm=37817,_m=37818,bm=37819,Mm=37820,vm=37821,wm=36492,ym=36494,Sm=36495,zm=36283,xm=36284,yd=36285,Om=36286,CP=3200,Em=0,RP=1,Or="",ki="srgb",Sd="srgb-linear",zd="linear",kt="srgb",Uo=7680,MM=519,kP=512,NP=513,BP=514,x_=515,GP=516,PP=517,O_=518,LP=519,Am=35044,vM="300 es",yn=2e3,ec=2001;function WP(s){for(let e=s.length-1;e>=0;--e)if(s[e]>=65535)return!0;return!1}function xd(s){return document.createElementNS("http://www.w3.org/1999/xhtml",s)}function FP(){const s=xd("canvas");return s.style.display="block",s}const wM={};function Od(...s){const e="THREE."+s.shift();console.log(e,...s)}function O1(s){const e=s[0];if(typeof e=="string"&&e.startsWith("TSL:")){const t=s[1];t&&t.isStackTrace?s[0]+=" "+t.getLocation():s[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return s}function tt(...s){s=O1(s);const e="THREE."+s.shift();{const t=s[0];t&&t.isStackTrace?console.warn(t.getError(e)):console.warn(e,...s)}}function bt(...s){s=O1(s);const e="THREE."+s.shift();{const t=s[0];t&&t.isStackTrace?console.error(t.getError(e)):console.error(e,...s)}}function ga(...s){const e=s.join(" ");e in wM||(wM[e]=!0,tt(...s))}function UP(s,e,t){return new Promise(function(i,n){function r(){switch(s.clientWaitSync(e,s.SYNC_FLUSH_COMMANDS_BIT,0)){case s.WAIT_FAILED:n();break;case s.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:i()}}setTimeout(r,t)})}const $P={[Up]:$p,[jp]:qp,[Hp]:Kp,[Da]:Vp,[$p]:Up,[qp]:jp,[Kp]:Hp,[Vp]:Da};class Io{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return i===void 0?!1:i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){const i=this._listeners;if(i===void 0)return;const n=i[e];if(n!==void 0){const r=n.indexOf(t);r!==-1&&n.splice(r,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const i=t[e.type];if(i!==void 0){e.target=this;const n=i.slice(0);for(let r=0,o=n.length;r<o;r++)n[r].call(this,e);e.target=null}}}const Ws=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],ju=Math.PI/180,Tm=180/Math.PI;function Gr(){const s=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(Ws[s&255]+Ws[s>>8&255]+Ws[s>>16&255]+Ws[s>>24&255]+"-"+Ws[e&255]+Ws[e>>8&255]+"-"+Ws[e>>16&15|64]+Ws[e>>24&255]+"-"+Ws[t&63|128]+Ws[t>>8&255]+"-"+Ws[t>>16&255]+Ws[t>>24&255]+Ws[i&255]+Ws[i>>8&255]+Ws[i>>16&255]+Ws[i>>24&255]).toLowerCase()}function vt(s,e,t){return Math.max(e,Math.min(t,s))}function jP(s,e){return(s%e+e)%e}function Hu(s,e,t){return(1-t)*s+t*e}function vn(s,e){switch(e.constructor){case Float32Array:return s;case Uint32Array:return s/4294967295;case Uint16Array:return s/65535;case Uint8Array:return s/255;case Int32Array:return Math.max(s/2147483647,-1);case Int16Array:return Math.max(s/32767,-1);case Int8Array:return Math.max(s/127,-1);default:throw new Error("THREE.MathUtils: Invalid component type.")}}function Pt(s,e){switch(e.constructor){case Float32Array:return s;case Uint32Array:return Math.round(s*4294967295);case Uint16Array:return Math.round(s*65535);case Uint8Array:return Math.round(s*255);case Int32Array:return Math.round(s*2147483647);case Int16Array:return Math.round(s*32767);case Int8Array:return Math.round(s*127);default:throw new Error("THREE.MathUtils: Invalid component type.")}}const ub=class ub{constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("THREE.Vector2: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,n=e.elements;return this.x=n[0]*t+n[3]*i+n[6],this.y=n[1]*t+n[4]*i+n[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=vt(this.x,e.x,t.x),this.y=vt(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=vt(this.x,e,t),this.y=vt(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(vt(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(vt(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),n=Math.sin(t),r=this.x-e.x,o=this.y-e.y;return this.x=r*i-o*n+e.x,this.y=r*n+o*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};ub.prototype.isVector2=!0;let nt=ub;class Co{constructor(e=0,t=0,i=0,n=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=n}static slerpFlat(e,t,i,n,r,o,a){let l=i[n+0],c=i[n+1],h=i[n+2],d=i[n+3],u=r[o+0],p=r[o+1],f=r[o+2],_=r[o+3];if(d!==_||l!==u||c!==p||h!==f){let g=l*u+c*p+h*f+d*_;g<0&&(u=-u,p=-p,f=-f,_=-_,g=-g);let m=1-a;if(g<.9995){const w=Math.acos(g),y=Math.sin(w);m=Math.sin(m*w)/y,a=Math.sin(a*w)/y,l=l*m+u*a,c=c*m+p*a,h=h*m+f*a,d=d*m+_*a}else{l=l*m+u*a,c=c*m+p*a,h=h*m+f*a,d=d*m+_*a;const w=1/Math.sqrt(l*l+c*c+h*h+d*d);l*=w,c*=w,h*=w,d*=w}}e[t]=l,e[t+1]=c,e[t+2]=h,e[t+3]=d}static multiplyQuaternionsFlat(e,t,i,n,r,o){const a=i[n],l=i[n+1],c=i[n+2],h=i[n+3],d=r[o],u=r[o+1],p=r[o+2],f=r[o+3];return e[t]=a*f+h*d+l*p-c*u,e[t+1]=l*f+h*u+c*d-a*p,e[t+2]=c*f+h*p+a*u-l*d,e[t+3]=h*f-a*d-l*u-c*p,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,n){return this._x=e,this._y=t,this._z=i,this._w=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,n=e._y,r=e._z,o=e._order,a=Math.cos,l=Math.sin,c=a(i/2),h=a(n/2),d=a(r/2),u=l(i/2),p=l(n/2),f=l(r/2);switch(o){case"XYZ":this._x=u*h*d+c*p*f,this._y=c*p*d-u*h*f,this._z=c*h*f+u*p*d,this._w=c*h*d-u*p*f;break;case"YXZ":this._x=u*h*d+c*p*f,this._y=c*p*d-u*h*f,this._z=c*h*f-u*p*d,this._w=c*h*d+u*p*f;break;case"ZXY":this._x=u*h*d-c*p*f,this._y=c*p*d+u*h*f,this._z=c*h*f+u*p*d,this._w=c*h*d-u*p*f;break;case"ZYX":this._x=u*h*d-c*p*f,this._y=c*p*d+u*h*f,this._z=c*h*f-u*p*d,this._w=c*h*d+u*p*f;break;case"YZX":this._x=u*h*d+c*p*f,this._y=c*p*d+u*h*f,this._z=c*h*f-u*p*d,this._w=c*h*d-u*p*f;break;case"XZY":this._x=u*h*d-c*p*f,this._y=c*p*d-u*h*f,this._z=c*h*f+u*p*d,this._w=c*h*d+u*p*f;break;default:tt("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,n=Math.sin(i);return this._x=e.x*n,this._y=e.y*n,this._z=e.z*n,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],n=t[4],r=t[8],o=t[1],a=t[5],l=t[9],c=t[2],h=t[6],d=t[10],u=i+a+d;if(u>0){const p=.5/Math.sqrt(u+1);this._w=.25/p,this._x=(h-l)*p,this._y=(r-c)*p,this._z=(o-n)*p}else if(i>a&&i>d){const p=2*Math.sqrt(1+i-a-d);this._w=(h-l)/p,this._x=.25*p,this._y=(n+o)/p,this._z=(r+c)/p}else if(a>d){const p=2*Math.sqrt(1+a-i-d);this._w=(r-c)/p,this._x=(n+o)/p,this._y=.25*p,this._z=(l+h)/p}else{const p=2*Math.sqrt(1+d-i-a);this._w=(o-n)/p,this._x=(r+c)/p,this._y=(l+h)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(vt(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const n=Math.min(1,t/i);return this.slerp(e,n),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,n=e._y,r=e._z,o=e._w,a=t._x,l=t._y,c=t._z,h=t._w;return this._x=i*h+o*a+n*c-r*l,this._y=n*h+o*l+r*a-i*c,this._z=r*h+o*c+i*l-n*a,this._w=o*h-i*a-n*l-r*c,this._onChangeCallback(),this}slerp(e,t){let i=e._x,n=e._y,r=e._z,o=e._w,a=this.dot(e);a<0&&(i=-i,n=-n,r=-r,o=-o,a=-a);let l=1-t;if(a<.9995){const c=Math.acos(a),h=Math.sin(c);l=Math.sin(l*c)/h,t=Math.sin(t*c)/h,this._x=this._x*l+i*t,this._y=this._y*l+n*t,this._z=this._z*l+r*t,this._w=this._w*l+o*t,this._onChangeCallback()}else this._x=this._x*l+i*t,this._y=this._y*l+n*t,this._z=this._z*l+r*t,this._w=this._w*l+o*t,this.normalize();return this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),n=Math.sqrt(1-i),r=Math.sqrt(i);return this.set(n*Math.sin(e),n*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}const fb=class fb{constructor(e=0,t=0,i=0){this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("THREE.Vector3: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(yM.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(yM.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,n=this.z,r=e.elements;return this.x=r[0]*t+r[3]*i+r[6]*n,this.y=r[1]*t+r[4]*i+r[7]*n,this.z=r[2]*t+r[5]*i+r[8]*n,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,r=e.elements,o=1/(r[3]*t+r[7]*i+r[11]*n+r[15]);return this.x=(r[0]*t+r[4]*i+r[8]*n+r[12])*o,this.y=(r[1]*t+r[5]*i+r[9]*n+r[13])*o,this.z=(r[2]*t+r[6]*i+r[10]*n+r[14])*o,this}applyQuaternion(e){const t=this.x,i=this.y,n=this.z,r=e.x,o=e.y,a=e.z,l=e.w,c=2*(o*n-a*i),h=2*(a*t-r*n),d=2*(r*i-o*t);return this.x=t+l*c+o*d-a*h,this.y=i+l*h+a*c-r*d,this.z=n+l*d+r*h-o*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,n=this.z,r=e.elements;return this.x=r[0]*t+r[4]*i+r[8]*n,this.y=r[1]*t+r[5]*i+r[9]*n,this.z=r[2]*t+r[6]*i+r[10]*n,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=vt(this.x,e.x,t.x),this.y=vt(this.y,e.y,t.y),this.z=vt(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=vt(this.x,e,t),this.y=vt(this.y,e,t),this.z=vt(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(vt(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,n=e.y,r=e.z,o=t.x,a=t.y,l=t.z;return this.x=n*l-r*a,this.y=r*o-i*l,this.z=i*a-n*o,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return Vu.copy(this).projectOnVector(e),this.sub(Vu)}reflect(e){return this.sub(Vu.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(vt(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,n=this.z-e.z;return t*t+i*i+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const n=Math.sin(t)*e;return this.x=n*Math.sin(i),this.y=Math.cos(t)*e,this.z=n*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),n=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=n,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};fb.prototype.isVector3=!0;let F=fb;const Vu=new F,yM=new Co,pb=class pb{constructor(e,t,i,n,r,o,a,l,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,n,r,o,a,l,c)}set(e,t,i,n,r,o,a,l,c){const h=this.elements;return h[0]=e,h[1]=n,h[2]=a,h[3]=t,h[4]=r,h[5]=l,h[6]=i,h[7]=o,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,r=this.elements,o=i[0],a=i[3],l=i[6],c=i[1],h=i[4],d=i[7],u=i[2],p=i[5],f=i[8],_=n[0],g=n[3],m=n[6],w=n[1],y=n[4],M=n[7],v=n[2],S=n[5],x=n[8];return r[0]=o*_+a*w+l*v,r[3]=o*g+a*y+l*S,r[6]=o*m+a*M+l*x,r[1]=c*_+h*w+d*v,r[4]=c*g+h*y+d*S,r[7]=c*m+h*M+d*x,r[2]=u*_+p*w+f*v,r[5]=u*g+p*y+f*S,r[8]=u*m+p*M+f*x,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],o=e[4],a=e[5],l=e[6],c=e[7],h=e[8];return t*o*h-t*a*c-i*r*h+i*a*l+n*r*c-n*o*l}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],o=e[4],a=e[5],l=e[6],c=e[7],h=e[8],d=h*o-a*c,u=a*l-h*r,p=c*r-o*l,f=t*d+i*u+n*p;if(f===0)return this.set(0,0,0,0,0,0,0,0,0);const _=1/f;return e[0]=d*_,e[1]=(n*c-h*i)*_,e[2]=(a*i-n*o)*_,e[3]=u*_,e[4]=(h*t-n*l)*_,e[5]=(n*r-a*t)*_,e[6]=p*_,e[7]=(i*l-c*t)*_,e[8]=(o*t-i*r)*_,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,n,r,o,a){const l=Math.cos(r),c=Math.sin(r);return this.set(i*l,i*c,-i*(l*o+c*a)+o+e,-n*c,n*l,-n*(-c*o+l*a)+a+t,0,0,1),this}scale(e,t){return ga("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(qu.makeScale(e,t)),this}rotate(e){return ga("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(qu.makeRotation(-e)),this}translate(e,t){return ga("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(qu.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let n=0;n<9;n++)if(t[n]!==i[n])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}};pb.prototype.isMatrix3=!0;let at=pb;const qu=new at,SM=new at().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),zM=new at().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function HP(){const s={enabled:!0,workingColorSpace:Sd,spaces:{},convert:function(n,r,o){return this.enabled===!1||r===o||!r||!o||(this.spaces[r].transfer===kt&&(n.r=Qn(n.r),n.g=Qn(n.g),n.b=Qn(n.b)),this.spaces[r].primaries!==this.spaces[o].primaries&&(n.applyMatrix3(this.spaces[r].toXYZ),n.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===kt&&(n.r=_a(n.r),n.g=_a(n.g),n.b=_a(n.b))),n},workingToColorSpace:function(n,r){return this.convert(n,this.workingColorSpace,r)},colorSpaceToWorking:function(n,r){return this.convert(n,r,this.workingColorSpace)},getPrimaries:function(n){return this.spaces[n].primaries},getTransfer:function(n){return n===Or?zd:this.spaces[n].transfer},getToneMappingMode:function(n){return this.spaces[n].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(n,r=this.workingColorSpace){return n.fromArray(this.spaces[r].luminanceCoefficients)},define:function(n){Object.assign(this.spaces,n)},_getMatrix:function(n,r,o){return n.copy(this.spaces[r].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(n){return this.spaces[n].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(n=this.workingColorSpace){return this.spaces[n].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(n,r){return ga("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),s.workingToColorSpace(n,r)},toWorkingColorSpace:function(n,r){return ga("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),s.colorSpaceToWorking(n,r)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return s.define({[Sd]:{primaries:e,whitePoint:i,transfer:zd,toXYZ:SM,fromXYZ:zM,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:ki},outputColorSpaceConfig:{drawingBufferColorSpace:ki}},[ki]:{primaries:e,whitePoint:i,transfer:kt,toXYZ:SM,fromXYZ:zM,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:ki}}}),s}const Mt=HP();function Qn(s){return s<.04045?s*.0773993808:Math.pow(s*.9478672986+.0521327014,2.4)}function _a(s){return s<.0031308?s*12.92:1.055*Math.pow(s,.41666)-.055}let $o;class VP{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{$o===void 0&&($o=xd("canvas")),$o.width=e.width,$o.height=e.height;const n=$o.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),i=$o}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=xd("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const n=i.getImageData(0,0,e.width,e.height),r=n.data;for(let o=0;o<r.length;o++)r[o]=Qn(r[o]/255)*255;return i.putImageData(n,0,0),t}else if(e.data){const t=e.data.slice(0);for(let i=0;i<t.length;i++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[i]=Math.floor(Qn(t[i]/255)*255):t[i]=Qn(t[i]);return{data:t,width:e.width,height:e.height}}else return tt("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let qP=0;class E_{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:qP++}),this.uuid=Gr(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<"u"&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const i={uuid:this.uuid,url:""},n=this.data;if(n!==null){let r;if(Array.isArray(n)){r=[];for(let o=0,a=n.length;o<a;o++)n[o].isDataTexture?r.push(Ku(n[o].image)):r.push(Ku(n[o]))}else r=Ku(n);i.url=r}return t||(e.images[this.uuid]=i),i}}function Ku(s){return typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&s instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&s instanceof ImageBitmap?VP.getDataURL(s):s.data?{data:Array.from(s.data),width:s.width,height:s.height,type:s.data.constructor.name}:(tt("Texture: Unable to serialize Texture."),{})}let KP=0;const Yu=new F;class Hs extends Io{constructor(e=Hs.DEFAULT_IMAGE,t=Hs.DEFAULT_MAPPING,i=Kn,n=Kn,r=js,o=uo,a=an,l=zi,c=Hs.DEFAULT_ANISOTROPY,h=Or){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:KP++}),this.uuid=Gr(),this.name="",this.source=new E_(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=i,this.wrapT=n,this.magFilter=r,this.minFilter=o,this.anisotropy=c,this.format=a,this.internalFormat=null,this.type=l,this.offset=new nt(0,0),this.repeat=new nt(1,1),this.center=new nt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new at,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Yu).x}get height(){return this.source.getSize(Yu).y}get depth(){return this.source.getSize(Yu).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const i=e[t];if(i===void 0){tt(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const n=this[t];if(n===void 0){tt(`Texture.setValues(): property '${t}' does not exist.`);continue}n&&i&&n.isVector2&&i.isVector2||n&&i&&n.isVector3&&i.isVector3||n&&i&&n.isMatrix3&&i.isMatrix3?n.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==M1)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Yp:e.x=e.x-Math.floor(e.x);break;case Kn:e.x=e.x<0?0:1;break;case Xp:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Yp:e.y=e.y-Math.floor(e.y);break;case Kn:e.y=e.y<0?0:1;break;case Xp:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}Hs.DEFAULT_IMAGE=null;Hs.DEFAULT_MAPPING=M1;Hs.DEFAULT_ANISOTROPY=1;const mb=class mb{constructor(e=0,t=0,i=0,n=1){this.x=e,this.y=t,this.z=i,this.w=n}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("THREE.Vector4: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,r=this.w,o=e.elements;return this.x=o[0]*t+o[4]*i+o[8]*n+o[12]*r,this.y=o[1]*t+o[5]*i+o[9]*n+o[13]*r,this.z=o[2]*t+o[6]*i+o[10]*n+o[14]*r,this.w=o[3]*t+o[7]*i+o[11]*n+o[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,n,r;const l=e.elements,c=l[0],h=l[4],d=l[8],u=l[1],p=l[5],f=l[9],_=l[2],g=l[6],m=l[10];if(Math.abs(h-u)<.01&&Math.abs(d-_)<.01&&Math.abs(f-g)<.01){if(Math.abs(h+u)<.1&&Math.abs(d+_)<.1&&Math.abs(f+g)<.1&&Math.abs(c+p+m-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const y=(c+1)/2,M=(p+1)/2,v=(m+1)/2,S=(h+u)/4,x=(d+_)/4,b=(f+g)/4;return y>M&&y>v?y<.01?(i=0,n=.707106781,r=.707106781):(i=Math.sqrt(y),n=S/i,r=x/i):M>v?M<.01?(i=.707106781,n=0,r=.707106781):(n=Math.sqrt(M),i=S/n,r=b/n):v<.01?(i=.707106781,n=.707106781,r=0):(r=Math.sqrt(v),i=x/r,n=b/r),this.set(i,n,r,t),this}let w=Math.sqrt((g-f)*(g-f)+(d-_)*(d-_)+(u-h)*(u-h));return Math.abs(w)<.001&&(w=1),this.x=(g-f)/w,this.y=(d-_)/w,this.z=(u-h)/w,this.w=Math.acos((c+p+m-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=vt(this.x,e.x,t.x),this.y=vt(this.y,e.y,t.y),this.z=vt(this.z,e.z,t.z),this.w=vt(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=vt(this.x,e,t),this.y=vt(this.y,e,t),this.z=vt(this.z,e,t),this.w=vt(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(vt(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}};mb.prototype.isVector4=!0;let es=mb;class YP extends Io{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:js,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new es(0,0,e,t),this.scissorTest=!1,this.viewport=new es(0,0,e,t),this.textures=[];const n={width:e,height:t,depth:i.depth},r=new Hs(n),o=i.count;for(let a=0;a<o;a++)this.textures[a]=r.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(i),this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.resolveDepthBuffer=i.resolveDepthBuffer,this.resolveStencilBuffer=i.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=i.depthTexture,this.samples=i.samples,this.multiview=i.multiview,this.useArrayDepthTexture=i.useArrayDepthTexture}_setTextureOptions(e={}){const t={minFilter:js,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let i=0;i<this.textures.length;i++)this.textures[i].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,i=1){if(this.width!==e||this.height!==t||this.depth!==i){this.width=e,this.height=t,this.depth=i;for(let n=0,r=this.textures.length;n<r;n++)this.textures[n].image.width=e,this.textures[n].image.height=t,this.textures[n].image.depth=i,this.textures[n].isData3DTexture!==!0&&(this.textures[n].isArrayTexture=this.textures[n].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,i=e.textures.length;t<i;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const n=Object.assign({},e.textures[t].image);this.textures[t].source=new E_(n)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class On extends YP{constructor(e=1,t=1,i={}){super(e,t,i),this.isWebGLRenderTarget=!0}}class E1 extends Hs{constructor(e=null,t=1,i=1,n=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:i,depth:n},this.magFilter=Ps,this.minFilter=Ps,this.wrapR=Kn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class XP extends Hs{constructor(e=null,t=1,i=1,n=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:i,depth:n},this.magFilter=Ps,this.minFilter=Ps,this.wrapR=Kn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const Vd=class Vd{constructor(e,t,i,n,r,o,a,l,c,h,d,u,p,f,_,g){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,n,r,o,a,l,c,h,d,u,p,f,_,g)}set(e,t,i,n,r,o,a,l,c,h,d,u,p,f,_,g){const m=this.elements;return m[0]=e,m[4]=t,m[8]=i,m[12]=n,m[1]=r,m[5]=o,m[9]=a,m[13]=l,m[2]=c,m[6]=h,m[10]=d,m[14]=u,m[3]=p,m[7]=f,m[11]=_,m[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Vd().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return this.determinantAffine()===0?(e.set(1,0,0),t.set(0,1,0),i.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this)}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){if(e.determinantAffine()===0)return this.identity();const t=this.elements,i=e.elements,n=1/jo.setFromMatrixColumn(e,0).length(),r=1/jo.setFromMatrixColumn(e,1).length(),o=1/jo.setFromMatrixColumn(e,2).length();return t[0]=i[0]*n,t[1]=i[1]*n,t[2]=i[2]*n,t[3]=0,t[4]=i[4]*r,t[5]=i[5]*r,t[6]=i[6]*r,t[7]=0,t[8]=i[8]*o,t[9]=i[9]*o,t[10]=i[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,n=e.y,r=e.z,o=Math.cos(i),a=Math.sin(i),l=Math.cos(n),c=Math.sin(n),h=Math.cos(r),d=Math.sin(r);if(e.order==="XYZ"){const u=o*h,p=o*d,f=a*h,_=a*d;t[0]=l*h,t[4]=-l*d,t[8]=c,t[1]=p+f*c,t[5]=u-_*c,t[9]=-a*l,t[2]=_-u*c,t[6]=f+p*c,t[10]=o*l}else if(e.order==="YXZ"){const u=l*h,p=l*d,f=c*h,_=c*d;t[0]=u+_*a,t[4]=f*a-p,t[8]=o*c,t[1]=o*d,t[5]=o*h,t[9]=-a,t[2]=p*a-f,t[6]=_+u*a,t[10]=o*l}else if(e.order==="ZXY"){const u=l*h,p=l*d,f=c*h,_=c*d;t[0]=u-_*a,t[4]=-o*d,t[8]=f+p*a,t[1]=p+f*a,t[5]=o*h,t[9]=_-u*a,t[2]=-o*c,t[6]=a,t[10]=o*l}else if(e.order==="ZYX"){const u=o*h,p=o*d,f=a*h,_=a*d;t[0]=l*h,t[4]=f*c-p,t[8]=u*c+_,t[1]=l*d,t[5]=_*c+u,t[9]=p*c-f,t[2]=-c,t[6]=a*l,t[10]=o*l}else if(e.order==="YZX"){const u=o*l,p=o*c,f=a*l,_=a*c;t[0]=l*h,t[4]=_-u*d,t[8]=f*d+p,t[1]=d,t[5]=o*h,t[9]=-a*h,t[2]=-c*h,t[6]=p*d+f,t[10]=u-_*d}else if(e.order==="XZY"){const u=o*l,p=o*c,f=a*l,_=a*c;t[0]=l*h,t[4]=-d,t[8]=c*h,t[1]=u*d+_,t[5]=o*h,t[9]=p*d-f,t[2]=f*d-p,t[6]=a*h,t[10]=_*d+u}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(ZP,e,JP)}lookAt(e,t,i){const n=this.elements;return fi.subVectors(e,t),fi.lengthSq()===0&&(fi.z=1),fi.normalize(),hr.crossVectors(i,fi),hr.lengthSq()===0&&(Math.abs(i.z)===1?fi.x+=1e-4:fi.z+=1e-4,fi.normalize(),hr.crossVectors(i,fi)),hr.normalize(),Rc.crossVectors(fi,hr),n[0]=hr.x,n[4]=Rc.x,n[8]=fi.x,n[1]=hr.y,n[5]=Rc.y,n[9]=fi.y,n[2]=hr.z,n[6]=Rc.z,n[10]=fi.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,r=this.elements,o=i[0],a=i[4],l=i[8],c=i[12],h=i[1],d=i[5],u=i[9],p=i[13],f=i[2],_=i[6],g=i[10],m=i[14],w=i[3],y=i[7],M=i[11],v=i[15],S=n[0],x=n[4],b=n[8],z=n[12],T=n[1],A=n[5],E=n[9],O=n[13],R=n[2],C=n[6],k=n[10],G=n[14],L=n[3],W=n[7],ee=n[11],X=n[15];return r[0]=o*S+a*T+l*R+c*L,r[4]=o*x+a*A+l*C+c*W,r[8]=o*b+a*E+l*k+c*ee,r[12]=o*z+a*O+l*G+c*X,r[1]=h*S+d*T+u*R+p*L,r[5]=h*x+d*A+u*C+p*W,r[9]=h*b+d*E+u*k+p*ee,r[13]=h*z+d*O+u*G+p*X,r[2]=f*S+_*T+g*R+m*L,r[6]=f*x+_*A+g*C+m*W,r[10]=f*b+_*E+g*k+m*ee,r[14]=f*z+_*O+g*G+m*X,r[3]=w*S+y*T+M*R+v*L,r[7]=w*x+y*A+M*C+v*W,r[11]=w*b+y*E+M*k+v*ee,r[15]=w*z+y*O+M*G+v*X,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],n=e[8],r=e[12],o=e[1],a=e[5],l=e[9],c=e[13],h=e[2],d=e[6],u=e[10],p=e[14],f=e[3],_=e[7],g=e[11],m=e[15],w=l*p-c*u,y=a*p-c*d,M=a*u-l*d,v=o*p-c*h,S=o*u-l*h,x=o*d-a*h;return t*(_*w-g*y+m*M)-i*(f*w-g*v+m*S)+n*(f*y-_*v+m*x)-r*(f*M-_*S+g*x)}determinantAffine(){const e=this.elements,t=e[0],i=e[4],n=e[8],r=e[1],o=e[5],a=e[9],l=e[2],c=e[6],h=e[10];return t*(o*h-a*c)-i*(r*h-a*l)+n*(r*c-o*l)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const n=this.elements;return e.isVector3?(n[12]=e.x,n[13]=e.y,n[14]=e.z):(n[12]=e,n[13]=t,n[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],o=e[4],a=e[5],l=e[6],c=e[7],h=e[8],d=e[9],u=e[10],p=e[11],f=e[12],_=e[13],g=e[14],m=e[15],w=t*a-i*o,y=t*l-n*o,M=t*c-r*o,v=i*l-n*a,S=i*c-r*a,x=n*c-r*l,b=h*_-d*f,z=h*g-u*f,T=h*m-p*f,A=d*g-u*_,E=d*m-p*_,O=u*m-p*g,R=w*O-y*E+M*A+v*T-S*z+x*b;if(R===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const C=1/R;return e[0]=(a*O-l*E+c*A)*C,e[1]=(n*E-i*O-r*A)*C,e[2]=(_*x-g*S+m*v)*C,e[3]=(u*S-d*x-p*v)*C,e[4]=(l*T-o*O-c*z)*C,e[5]=(t*O-n*T+r*z)*C,e[6]=(g*M-f*x-m*y)*C,e[7]=(h*x-u*M+p*y)*C,e[8]=(o*E-a*T+c*b)*C,e[9]=(i*T-t*E-r*b)*C,e[10]=(f*S-_*M+m*w)*C,e[11]=(d*M-h*S-p*w)*C,e[12]=(a*z-o*A-l*b)*C,e[13]=(t*A-i*z+n*b)*C,e[14]=(_*y-f*v-g*w)*C,e[15]=(h*v-d*y+u*w)*C,this}scale(e){const t=this.elements,i=e.x,n=e.y,r=e.z;return t[0]*=i,t[4]*=n,t[8]*=r,t[1]*=i,t[5]*=n,t[9]*=r,t[2]*=i,t[6]*=n,t[10]*=r,t[3]*=i,t[7]*=n,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],n=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,n))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),n=Math.sin(t),r=1-i,o=e.x,a=e.y,l=e.z,c=r*o,h=r*a;return this.set(c*o+i,c*a-n*l,c*l+n*a,0,c*a+n*l,h*a+i,h*l-n*o,0,c*l-n*a,h*l+n*o,r*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,n,r,o){return this.set(1,i,r,0,e,1,o,0,t,n,1,0,0,0,0,1),this}compose(e,t,i){const n=this.elements,r=t._x,o=t._y,a=t._z,l=t._w,c=r+r,h=o+o,d=a+a,u=r*c,p=r*h,f=r*d,_=o*h,g=o*d,m=a*d,w=l*c,y=l*h,M=l*d,v=i.x,S=i.y,x=i.z;return n[0]=(1-(_+m))*v,n[1]=(p+M)*v,n[2]=(f-y)*v,n[3]=0,n[4]=(p-M)*S,n[5]=(1-(u+m))*S,n[6]=(g+w)*S,n[7]=0,n[8]=(f+y)*x,n[9]=(g-w)*x,n[10]=(1-(u+_))*x,n[11]=0,n[12]=e.x,n[13]=e.y,n[14]=e.z,n[15]=1,this}decompose(e,t,i){const n=this.elements;e.x=n[12],e.y=n[13],e.z=n[14];const r=this.determinantAffine();if(r===0)return i.set(1,1,1),t.identity(),this;let o=jo.set(n[0],n[1],n[2]).length();const a=jo.set(n[4],n[5],n[6]).length(),l=jo.set(n[8],n[9],n[10]).length();r<0&&(o=-o),Yi.copy(this);const c=1/o,h=1/a,d=1/l;return Yi.elements[0]*=c,Yi.elements[1]*=c,Yi.elements[2]*=c,Yi.elements[4]*=h,Yi.elements[5]*=h,Yi.elements[6]*=h,Yi.elements[8]*=d,Yi.elements[9]*=d,Yi.elements[10]*=d,t.setFromRotationMatrix(Yi),i.x=o,i.y=a,i.z=l,this}makePerspective(e,t,i,n,r,o,a=yn,l=!1){const c=this.elements,h=2*r/(t-e),d=2*r/(i-n),u=(t+e)/(t-e),p=(i+n)/(i-n);let f,_;if(l)f=r/(o-r),_=o*r/(o-r);else if(a===yn)f=-(o+r)/(o-r),_=-2*o*r/(o-r);else if(a===ec)f=-o/(o-r),_=-o*r/(o-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return c[0]=h,c[4]=0,c[8]=u,c[12]=0,c[1]=0,c[5]=d,c[9]=p,c[13]=0,c[2]=0,c[6]=0,c[10]=f,c[14]=_,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,i,n,r,o,a=yn,l=!1){const c=this.elements,h=2/(t-e),d=2/(i-n),u=-(t+e)/(t-e),p=-(i+n)/(i-n);let f,_;if(l)f=1/(o-r),_=o/(o-r);else if(a===yn)f=-2/(o-r),_=-(o+r)/(o-r);else if(a===ec)f=-1/(o-r),_=-r/(o-r);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return c[0]=h,c[4]=0,c[8]=0,c[12]=u,c[1]=0,c[5]=d,c[9]=0,c[13]=p,c[2]=0,c[6]=0,c[10]=f,c[14]=_,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let n=0;n<16;n++)if(t[n]!==i[n])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}};Vd.prototype.isMatrix4=!0;let At=Vd;const jo=new F,Yi=new At,ZP=new F(0,0,0),JP=new F(1,1,1),hr=new F,Rc=new F,fi=new F,xM=new At,OM=new Co;class qr{constructor(e=0,t=0,i=0,n=qr.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=n}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,n=this._order){return this._x=e,this._y=t,this._z=i,this._order=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const n=e.elements,r=n[0],o=n[4],a=n[8],l=n[1],c=n[5],h=n[9],d=n[2],u=n[6],p=n[10];switch(t){case"XYZ":this._y=Math.asin(vt(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,p),this._z=Math.atan2(-o,r)):(this._x=Math.atan2(u,c),this._z=0);break;case"YXZ":this._x=Math.asin(-vt(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,p),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-d,r),this._z=0);break;case"ZXY":this._x=Math.asin(vt(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-d,p),this._z=Math.atan2(-o,c)):(this._y=0,this._z=Math.atan2(l,r));break;case"ZYX":this._y=Math.asin(-vt(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(u,p),this._z=Math.atan2(l,r)):(this._x=0,this._z=Math.atan2(-o,c));break;case"YZX":this._z=Math.asin(vt(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-d,r)):(this._x=0,this._y=Math.atan2(a,p));break;case"XZY":this._z=Math.asin(-vt(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(u,c),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-h,p),this._y=0);break;default:tt("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return xM.makeRotationFromQuaternion(e),this.setFromRotationMatrix(xM,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return OM.setFromEuler(this),this.setFromQuaternion(OM,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}qr.DEFAULT_ORDER="XYZ";class A_{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let QP=0;const EM=new F,Ho=new Co,Rn=new At,kc=new F,Qa=new F,eL=new F,tL=new Co,AM=new F(1,0,0),TM=new F(0,1,0),DM=new F(0,0,1),IM={type:"added"},sL={type:"removed"},Vo={type:"childadded",child:null},Xu={type:"childremoved",child:null};class ss extends Io{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:QP++}),this.uuid=Gr(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=ss.DEFAULT_UP.clone();const e=new F,t=new qr,i=new Co,n=new F(1,1,1);function r(){i.setFromEuler(t,!1)}function o(){t.setFromQuaternion(i,void 0,!1)}t._onChange(r),i._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:n},modelViewMatrix:{value:new At},normalMatrix:{value:new at}}),this.matrix=new At,this.matrixWorld=new At,this.matrixAutoUpdate=ss.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=ss.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new A_,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Ho.setFromAxisAngle(e,t),this.quaternion.multiply(Ho),this}rotateOnWorldAxis(e,t){return Ho.setFromAxisAngle(e,t),this.quaternion.premultiply(Ho),this}rotateX(e){return this.rotateOnAxis(AM,e)}rotateY(e){return this.rotateOnAxis(TM,e)}rotateZ(e){return this.rotateOnAxis(DM,e)}translateOnAxis(e,t){return EM.copy(e).applyQuaternion(this.quaternion),this.position.add(EM.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(AM,e)}translateY(e){return this.translateOnAxis(TM,e)}translateZ(e){return this.translateOnAxis(DM,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Rn.copy(this.matrixWorld).invert())}lookAt(e,t,i){e.isVector3?kc.copy(e):kc.set(e,t,i);const n=this.parent;this.updateWorldMatrix(!0,!1),Qa.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Rn.lookAt(Qa,kc,this.up):Rn.lookAt(kc,Qa,this.up),this.quaternion.setFromRotationMatrix(Rn),n&&(Rn.extractRotation(n.matrixWorld),Ho.setFromRotationMatrix(Rn),this.quaternion.premultiply(Ho.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(bt("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(IM),Vo.child=e,this.dispatchEvent(Vo),Vo.child=null):bt("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(sL),Xu.child=e,this.dispatchEvent(Xu),Xu.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Rn.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Rn.multiply(e.parent.matrixWorld)),e.applyMatrix4(Rn),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(IM),Vo.child=e,this.dispatchEvent(Vo),Vo.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let i=0,n=this.children.length;i<n;i++){const o=this.children[i].getObjectByProperty(e,t);if(o!==void 0)return o}}getObjectsByProperty(e,t,i=[]){this[e]===t&&i.push(this);const n=this.children;for(let r=0,o=n.length;r<o;r++)n[r].getObjectsByProperty(e,t,i);return i}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Qa,e,eL),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Qa,tL,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const e=this.pivot;if(e!==null){const t=e.x,i=e.y,n=e.z,r=this.matrix.elements;r[12]+=t-r[0]*t-r[4]*i-r[8]*n,r[13]+=i-r[1]*t-r[5]*i-r[9]*n,r[14]+=n-r[2]*t-r[6]*i-r[10]*n}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].updateMatrixWorld(e)}updateWorldMatrix(e,t,i=!1){const n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||i)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,i=!0),t===!0){const r=this.children;for(let o=0,a=r.length;o<a;o++)r[o].updateWorldMatrix(!1,!0,i)}}toJSON(e){const t=e===void 0||typeof e=="string",i={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const n={};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.castShadow===!0&&(n.castShadow=!0),this.receiveShadow===!0&&(n.receiveShadow=!0),this.visible===!1&&(n.visible=!1),this.frustumCulled===!1&&(n.frustumCulled=!1),this.renderOrder!==0&&(n.renderOrder=this.renderOrder),this.static!==!1&&(n.static=this.static),Object.keys(this.userData).length>0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),n.up=this.up.toArray(),this.pivot!==null&&(n.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(n.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(n.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(n.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(n.type="BatchedMesh",n.perObjectFrustumCulled=this.perObjectFrustumCulled,n.sortObjects=this.sortObjects,n.drawRanges=this._drawRanges,n.reservedRanges=this._reservedRanges,n.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),n.instanceInfo=this._instanceInfo.map(a=>({...a})),n.availableInstanceIds=this._availableInstanceIds.slice(),n.availableGeometryIds=this._availableGeometryIds.slice(),n.nextIndexStart=this._nextIndexStart,n.nextVertexStart=this._nextVertexStart,n.geometryCount=this._geometryCount,n.maxInstanceCount=this._maxInstanceCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.matricesTexture=this._matricesTexture.toJSON(e),n.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(n.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(n.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(n.boundingBox=this.boundingBox.toJSON()));function r(a,l){return a[l.uuid]===void 0&&(a[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(n.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=r(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const l=a.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c<h;c++){const d=l[c];r(e.shapes,d)}else r(e.shapes,l)}}if(this.isSkinnedMesh&&(n.bindMode=this.bindMode,n.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(e.skeletons,this.skeleton),n.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const a=[];for(let l=0,c=this.material.length;l<c;l++)a.push(r(e.materials,this.material[l]));n.material=a}else n.material=r(e.materials,this.material);if(this.children.length>0){n.children=[];for(let a=0;a<this.children.length;a++)n.children.push(this.children[a].toJSON(e).object)}if(this.animations.length>0){n.animations=[];for(let a=0;a<this.animations.length;a++){const l=this.animations[a];n.animations.push(r(e.animations,l))}}if(t){const a=o(e.geometries),l=o(e.materials),c=o(e.textures),h=o(e.images),d=o(e.shapes),u=o(e.skeletons),p=o(e.animations),f=o(e.nodes);a.length>0&&(i.geometries=a),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),h.length>0&&(i.images=h),d.length>0&&(i.shapes=d),u.length>0&&(i.skeletons=u),p.length>0&&(i.animations=p),f.length>0&&(i.nodes=f)}return i.object=n,i;function o(a){const l=[];for(const c in a){const h=a[c];delete h.metadata,l.push(h)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot!==null?e.pivot.clone():null,this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i<e.children.length;i++){const n=e.children[i];this.add(n.clone())}return this}}ss.DEFAULT_UP=new F(0,1,0);ss.DEFAULT_MATRIX_AUTO_UPDATE=!0;ss.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class Al extends ss{constructor(){super(),this.isGroup=!0,this.type="Group"}}const iL={type:"move"};class Zu{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Al,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Al,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new F,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new F),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Al,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new F,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new F,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,i){let n=null,r=null,o=null;const a=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){o=!0;for(const _ of e.hand.values()){const g=t.getJointPose(_,i),m=this._getHandJoint(c,_);g!==null&&(m.matrix.fromArray(g.transform.matrix),m.matrix.decompose(m.position,m.rotation,m.scale),m.matrixWorldNeedsUpdate=!0,m.jointRadius=g.radius),m.visible=g!==null}const h=c.joints["index-finger-tip"],d=c.joints["thumb-tip"],u=h.position.distanceTo(d.position),p=.02,f=.005;c.inputState.pinching&&u>p+f?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&u<=p-f&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,i),r!==null&&(l.matrix.fromArray(r.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,r.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(r.linearVelocity)):l.hasLinearVelocity=!1,r.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(r.angularVelocity)):l.hasAngularVelocity=!1,l.eventsEnabled&&l.dispatchEvent({type:"gripUpdated",data:e,target:this})));a!==null&&(n=t.getPose(e.targetRaySpace,i),n===null&&r!==null&&(n=r),n!==null&&(a.matrix.fromArray(n.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,n.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(n.linearVelocity)):a.hasLinearVelocity=!1,n.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(n.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(iL)))}return a!==null&&(a.visible=n!==null),l!==null&&(l.visible=r!==null),c!==null&&(c.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new Al;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}const A1={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},dr={h:0,s:0,l:0},Nc={h:0,s:0,l:0};function Ju(s,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?s+(e-s)*6*t:t<1/2?e:t<2/3?s+(e-s)*6*(2/3-t):s}class Ye{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const n=e;n&&n.isColor?this.copy(n):typeof n=="number"?this.setHex(n):typeof n=="string"&&this.setStyle(n)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=ki){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Mt.colorSpaceToWorking(this,t),this}setRGB(e,t,i,n=Mt.workingColorSpace){return this.r=e,this.g=t,this.b=i,Mt.colorSpaceToWorking(this,n),this}setHSL(e,t,i,n=Mt.workingColorSpace){if(e=jP(e,1),t=vt(t,0,1),i=vt(i,0,1),t===0)this.r=this.g=this.b=i;else{const r=i<=.5?i*(1+t):i+t-i*t,o=2*i-r;this.r=Ju(o,r,e+1/3),this.g=Ju(o,r,e),this.b=Ju(o,r,e-1/3)}return Mt.colorSpaceToWorking(this,n),this}setStyle(e,t=ki){function i(r){r!==void 0&&parseFloat(r)<1&&tt("Color: Alpha component of "+e+" will be ignored.")}let n;if(n=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const o=n[1],a=n[2];switch(o){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:tt("Color: Unknown color model "+e)}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=n[1],o=r.length;if(o===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(r,16),t);tt("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=ki){const i=A1[e.toLowerCase()];return i!==void 0?this.setHex(i,t):tt("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Qn(e.r),this.g=Qn(e.g),this.b=Qn(e.b),this}copyLinearToSRGB(e){return this.r=_a(e.r),this.g=_a(e.g),this.b=_a(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=ki){return Mt.workingToColorSpace(Fs.copy(this),e),Math.round(vt(Fs.r*255,0,255))*65536+Math.round(vt(Fs.g*255,0,255))*256+Math.round(vt(Fs.b*255,0,255))}getHexString(e=ki){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Mt.workingColorSpace){Mt.workingToColorSpace(Fs.copy(this),t);const i=Fs.r,n=Fs.g,r=Fs.b,o=Math.max(i,n,r),a=Math.min(i,n,r);let l,c;const h=(a+o)/2;if(a===o)l=0,c=0;else{const d=o-a;switch(c=h<=.5?d/(o+a):d/(2-o-a),o){case i:l=(n-r)/d+(n<r?6:0);break;case n:l=(r-i)/d+2;break;case r:l=(i-n)/d+4;break}l/=6}return e.h=l,e.s=c,e.l=h,e}getRGB(e,t=Mt.workingColorSpace){return Mt.workingToColorSpace(Fs.copy(this),t),e.r=Fs.r,e.g=Fs.g,e.b=Fs.b,e}getStyle(e=ki){Mt.workingToColorSpace(Fs.copy(this),e);const t=Fs.r,i=Fs.g,n=Fs.b;return e!==ki?`color(${e} ${t.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(i*255)},${Math.round(n*255)})`}offsetHSL(e,t,i){return this.getHSL(dr),this.setHSL(dr.h+e,dr.s+t,dr.l+i)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,i){return this.r=e.r+(t.r-e.r)*i,this.g=e.g+(t.g-e.g)*i,this.b=e.b+(t.b-e.b)*i,this}lerpHSL(e,t){this.getHSL(dr),e.getHSL(Nc);const i=Hu(dr.h,Nc.h,t),n=Hu(dr.s,Nc.s,t),r=Hu(dr.l,Nc.l,t);return this.setHSL(i,n,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,i=this.g,n=this.b,r=e.elements;return this.r=r[0]*t+r[3]*i+r[6]*n,this.g=r[1]*t+r[4]*i+r[7]*n,this.b=r[2]*t+r[5]*i+r[8]*n,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const Fs=new Ye;Ye.NAMES=A1;class nL extends ss{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new qr,this.environmentIntensity=1,this.environmentRotation=new qr,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}const Xi=new F,kn=new F,Qu=new F,Nn=new F,qo=new F,Ko=new F,CM=new F,ef=new F,tf=new F,sf=new F,nf=new es,rf=new es,of=new es;class Li{constructor(e=new F,t=new F,i=new F){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,n){n.subVectors(i,t),Xi.subVectors(e,t),n.cross(Xi);const r=n.lengthSq();return r>0?n.multiplyScalar(1/Math.sqrt(r)):n.set(0,0,0)}static getBarycoord(e,t,i,n,r){Xi.subVectors(n,t),kn.subVectors(i,t),Qu.subVectors(e,t);const o=Xi.dot(Xi),a=Xi.dot(kn),l=Xi.dot(Qu),c=kn.dot(kn),h=kn.dot(Qu),d=o*c-a*a;if(d===0)return r.set(0,0,0),null;const u=1/d,p=(c*l-a*h)*u,f=(o*h-a*l)*u;return r.set(1-p-f,f,p)}static containsPoint(e,t,i,n){return this.getBarycoord(e,t,i,n,Nn)===null?!1:Nn.x>=0&&Nn.y>=0&&Nn.x+Nn.y<=1}static getInterpolation(e,t,i,n,r,o,a,l){return this.getBarycoord(e,t,i,n,Nn)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(r,Nn.x),l.addScaledVector(o,Nn.y),l.addScaledVector(a,Nn.z),l)}static getInterpolatedAttribute(e,t,i,n,r,o){return nf.setScalar(0),rf.setScalar(0),of.setScalar(0),nf.fromBufferAttribute(e,t),rf.fromBufferAttribute(e,i),of.fromBufferAttribute(e,n),o.setScalar(0),o.addScaledVector(nf,r.x),o.addScaledVector(rf,r.y),o.addScaledVector(of,r.z),o}static isFrontFacing(e,t,i,n){return Xi.subVectors(i,t),kn.subVectors(e,t),Xi.cross(kn).dot(n)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,n){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[n]),this}setFromAttributeAndIndices(e,t,i,n){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,n),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Xi.subVectors(this.c,this.b),kn.subVectors(this.a,this.b),Xi.cross(kn).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Li.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Li.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,n,r){return Li.getInterpolation(e,this.a,this.b,this.c,t,i,n,r)}containsPoint(e){return Li.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Li.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,n=this.b,r=this.c;let o,a;qo.subVectors(n,i),Ko.subVectors(r,i),ef.subVectors(e,i);const l=qo.dot(ef),c=Ko.dot(ef);if(l<=0&&c<=0)return t.copy(i);tf.subVectors(e,n);const h=qo.dot(tf),d=Ko.dot(tf);if(h>=0&&d<=h)return t.copy(n);const u=l*d-h*c;if(u<=0&&l>=0&&h<=0)return o=l/(l-h),t.copy(i).addScaledVector(qo,o);sf.subVectors(e,r);const p=qo.dot(sf),f=Ko.dot(sf);if(f>=0&&p<=f)return t.copy(r);const _=p*c-l*f;if(_<=0&&c>=0&&f<=0)return a=c/(c-f),t.copy(i).addScaledVector(Ko,a);const g=h*f-p*d;if(g<=0&&d-h>=0&&p-f>=0)return CM.subVectors(r,n),a=(d-h)/(d-h+(p-f)),t.copy(n).addScaledVector(CM,a);const m=1/(g+_+u);return o=_*m,a=u*m,t.copy(i).addScaledVector(qo,o).addScaledVector(Ko,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class Ro{constructor(e=new F(1/0,1/0,1/0),t=new F(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t+=3)this.expandByPoint(Zi.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,i=e.count;t<i;t++)this.expandByPoint(Zi.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const i=Zi.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(i),this.max.copy(e).add(i),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const i=e.geometry;if(i!==void 0){const r=i.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let o=0,a=r.count;o<a;o++)e.isMesh===!0?e.getVertexPosition(o,Zi):Zi.fromBufferAttribute(r,o),Zi.applyMatrix4(e.matrixWorld),this.expandByPoint(Zi);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Bc.copy(e.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),Bc.copy(i.boundingBox)),Bc.applyMatrix4(e.matrixWorld),this.union(Bc)}const n=e.children;for(let r=0,o=n.length;r<o;r++)this.expandByObject(n[r],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Zi),Zi.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(el),Gc.subVectors(this.max,el),Yo.subVectors(e.a,el),Xo.subVectors(e.b,el),Zo.subVectors(e.c,el),ur.subVectors(Xo,Yo),fr.subVectors(Zo,Xo),Qr.subVectors(Yo,Zo);let t=[0,-ur.z,ur.y,0,-fr.z,fr.y,0,-Qr.z,Qr.y,ur.z,0,-ur.x,fr.z,0,-fr.x,Qr.z,0,-Qr.x,-ur.y,ur.x,0,-fr.y,fr.x,0,-Qr.y,Qr.x,0];return!af(t,Yo,Xo,Zo,Gc)||(t=[1,0,0,0,1,0,0,0,1],!af(t,Yo,Xo,Zo,Gc))?!1:(Pc.crossVectors(ur,fr),t=[Pc.x,Pc.y,Pc.z],af(t,Yo,Xo,Zo,Gc))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Zi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Zi).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Bn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Bn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Bn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Bn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Bn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Bn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Bn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Bn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Bn),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const Bn=[new F,new F,new F,new F,new F,new F,new F,new F],Zi=new F,Bc=new Ro,Yo=new F,Xo=new F,Zo=new F,ur=new F,fr=new F,Qr=new F,el=new F,Gc=new F,Pc=new F,eo=new F;function af(s,e,t,i,n){for(let r=0,o=s.length-3;r<=o;r+=3){eo.fromArray(s,r);const a=n.x*Math.abs(eo.x)+n.y*Math.abs(eo.y)+n.z*Math.abs(eo.z),l=e.dot(eo),c=t.dot(eo),h=i.dot(eo);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>a)return!1}return!0}const hs=new F,Lc=new nt;let rL=0;class Ns extends Io{constructor(e,t,i=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:rL++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=Am,this.updateRanges=[],this.gpuType=on,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let n=0,r=this.itemSize;n<r;n++)this.array[e+n]=t.array[i+n];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,i=this.count;t<i;t++)Lc.fromBufferAttribute(this,t),Lc.applyMatrix3(e),this.setXY(t,Lc.x,Lc.y);else if(this.itemSize===3)for(let t=0,i=this.count;t<i;t++)hs.fromBufferAttribute(this,t),hs.applyMatrix3(e),this.setXYZ(t,hs.x,hs.y,hs.z);return this}applyMatrix4(e){for(let t=0,i=this.count;t<i;t++)hs.fromBufferAttribute(this,t),hs.applyMatrix4(e),this.setXYZ(t,hs.x,hs.y,hs.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)hs.fromBufferAttribute(this,t),hs.applyNormalMatrix(e),this.setXYZ(t,hs.x,hs.y,hs.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)hs.fromBufferAttribute(this,t),hs.transformDirection(e),this.setXYZ(t,hs.x,hs.y,hs.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let i=this.array[e*this.itemSize+t];return this.normalized&&(i=vn(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=Pt(i,this.array)),this.array[e*this.itemSize+t]=i,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=vn(t,this.array)),t}setX(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=vn(t,this.array)),t}setY(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=vn(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=vn(t,this.array)),t}setW(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),i=Pt(i,this.array)),this.array[e+0]=t,this.array[e+1]=i,this}setXYZ(e,t,i,n){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),i=Pt(i,this.array),n=Pt(n,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=n,this}setXYZW(e,t,i,n,r){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),i=Pt(i,this.array),n=Pt(n,this.array),r=Pt(r,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=n,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Am&&(e.usage=this.usage),e}dispose(){this.dispatchEvent({type:"dispose"})}}class T1 extends Ns{constructor(e,t,i){super(new Uint16Array(e),t,i)}}class D1 extends Ns{constructor(e,t,i){super(new Uint32Array(e),t,i)}}class Rt extends Ns{constructor(e,t,i){super(new Float32Array(e),t,i)}}const oL=new Ro,tl=new F,lf=new F;class ko{constructor(e=new F,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):oL.setFromPoints(e).getCenter(i);let n=0;for(let r=0,o=e.length;r<o;r++)n=Math.max(n,i.distanceToSquared(e[r]));return this.radius=Math.sqrt(n),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const i=this.center.distanceToSquared(e);return t.copy(e),i>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;tl.subVectors(e,this.center);const t=tl.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),n=(i-this.radius)*.5;this.center.addScaledVector(tl,n/i),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(lf.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(tl.copy(e.center).add(lf)),this.expandByPoint(tl.copy(e.center).sub(lf))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}let aL=0;const Ti=new At,cf=new ss,Jo=new F,pi=new Ro,sl=new Ro,zs=new F;class ps extends Io{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:aL++}),this.uuid=Gr(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(WP(e)?D1:T1)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,i=0){this.groups.push({start:e,count:t,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const i=this.attributes.normal;if(i!==void 0){const r=new at().getNormalMatrix(e);i.applyNormalMatrix(r),i.needsUpdate=!0}const n=this.attributes.tangent;return n!==void 0&&(n.transformDirection(e),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return Ti.makeRotationFromQuaternion(e),this.applyMatrix4(Ti),this}rotateX(e){return Ti.makeRotationX(e),this.applyMatrix4(Ti),this}rotateY(e){return Ti.makeRotationY(e),this.applyMatrix4(Ti),this}rotateZ(e){return Ti.makeRotationZ(e),this.applyMatrix4(Ti),this}translate(e,t,i){return Ti.makeTranslation(e,t,i),this.applyMatrix4(Ti),this}scale(e,t,i){return Ti.makeScale(e,t,i),this.applyMatrix4(Ti),this}lookAt(e){return cf.lookAt(e),cf.updateMatrix(),this.applyMatrix4(cf.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Jo).negate(),this.translate(Jo.x,Jo.y,Jo.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const i=[];for(let n=0,r=e.length;n<r;n++){const o=e[n];i.push(o.x,o.y,o.z||0)}this.setAttribute("position",new Rt(i,3))}else{const i=Math.min(e.length,t.count);for(let n=0;n<i;n++){const r=e[n];t.setXYZ(n,r.x,r.y,r.z||0)}e.length>t.count&&tt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Ro);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){bt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new F(-1/0,-1/0,-1/0),new F(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,n=t.length;i<n;i++){const r=t[i];pi.setFromBufferAttribute(r),this.morphTargetsRelative?(zs.addVectors(this.boundingBox.min,pi.min),this.boundingBox.expandByPoint(zs),zs.addVectors(this.boundingBox.max,pi.max),this.boundingBox.expandByPoint(zs)):(this.boundingBox.expandByPoint(pi.min),this.boundingBox.expandByPoint(pi.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&bt('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new ko);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){bt("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new F,1/0);return}if(e){const i=this.boundingSphere.center;if(pi.setFromBufferAttribute(e),t)for(let r=0,o=t.length;r<o;r++){const a=t[r];sl.setFromBufferAttribute(a),this.morphTargetsRelative?(zs.addVectors(pi.min,sl.min),pi.expandByPoint(zs),zs.addVectors(pi.max,sl.max),pi.expandByPoint(zs)):(pi.expandByPoint(sl.min),pi.expandByPoint(sl.max))}pi.getCenter(i);let n=0;for(let r=0,o=e.count;r<o;r++)zs.fromBufferAttribute(e,r),n=Math.max(n,i.distanceToSquared(zs));if(t)for(let r=0,o=t.length;r<o;r++){const a=t[r],l=this.morphTargetsRelative;for(let c=0,h=a.count;c<h;c++)zs.fromBufferAttribute(a,c),l&&(Jo.fromBufferAttribute(e,c),zs.add(Jo)),n=Math.max(n,i.distanceToSquared(zs))}this.boundingSphere.radius=Math.sqrt(n),isNaN(this.boundingSphere.radius)&&bt('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){bt("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const i=t.position,n=t.normal,r=t.uv;let o=this.getAttribute("tangent");(o===void 0||o.count!==i.count)&&(o=new Ns(new Float32Array(4*i.count),4),this.setAttribute("tangent",o));const a=[],l=[];for(let b=0;b<i.count;b++)a[b]=new F,l[b]=new F;const c=new F,h=new F,d=new F,u=new nt,p=new nt,f=new nt,_=new F,g=new F;function m(b,z,T){c.fromBufferAttribute(i,b),h.fromBufferAttribute(i,z),d.fromBufferAttribute(i,T),u.fromBufferAttribute(r,b),p.fromBufferAttribute(r,z),f.fromBufferAttribute(r,T),h.sub(c),d.sub(c),p.sub(u),f.sub(u);const A=1/(p.x*f.y-f.x*p.y);isFinite(A)&&(_.copy(h).multiplyScalar(f.y).addScaledVector(d,-p.y).multiplyScalar(A),g.copy(d).multiplyScalar(p.x).addScaledVector(h,-f.x).multiplyScalar(A),a[b].add(_),a[z].add(_),a[T].add(_),l[b].add(g),l[z].add(g),l[T].add(g))}let w=this.groups;w.length===0&&(w=[{start:0,count:e.count}]);for(let b=0,z=w.length;b<z;++b){const T=w[b],A=T.start,E=T.count;for(let O=A,R=A+E;O<R;O+=3)m(e.getX(O+0),e.getX(O+1),e.getX(O+2))}const y=new F,M=new F,v=new F,S=new F;function x(b){v.fromBufferAttribute(n,b),S.copy(v);const z=a[b];y.copy(z),y.sub(v.multiplyScalar(v.dot(z))).normalize(),M.crossVectors(S,z);const A=M.dot(l[b])<0?-1:1;o.setXYZW(b,y.x,y.y,y.z,A)}for(let b=0,z=w.length;b<z;++b){const T=w[b],A=T.start,E=T.count;for(let O=A,R=A+E;O<R;O+=3)x(e.getX(O+0)),x(e.getX(O+1)),x(e.getX(O+2))}this._transformed=!0}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let i=this.getAttribute("normal");if(i===void 0||i.count!==t.count)i=new Ns(new Float32Array(t.count*3),3),this.setAttribute("normal",i);else for(let u=0,p=i.count;u<p;u++)i.setXYZ(u,0,0,0);const n=new F,r=new F,o=new F,a=new F,l=new F,c=new F,h=new F,d=new F;if(e)for(let u=0,p=e.count;u<p;u+=3){const f=e.getX(u+0),_=e.getX(u+1),g=e.getX(u+2);n.fromBufferAttribute(t,f),r.fromBufferAttribute(t,_),o.fromBufferAttribute(t,g),h.subVectors(o,r),d.subVectors(n,r),h.cross(d),a.fromBufferAttribute(i,f),l.fromBufferAttribute(i,_),c.fromBufferAttribute(i,g),a.add(h),l.add(h),c.add(h),i.setXYZ(f,a.x,a.y,a.z),i.setXYZ(_,l.x,l.y,l.z),i.setXYZ(g,c.x,c.y,c.z)}else for(let u=0,p=t.count;u<p;u+=3)n.fromBufferAttribute(t,u+0),r.fromBufferAttribute(t,u+1),o.fromBufferAttribute(t,u+2),h.subVectors(o,r),d.subVectors(n,r),h.cross(d),i.setXYZ(u+0,h.x,h.y,h.z),i.setXYZ(u+1,h.x,h.y,h.z),i.setXYZ(u+2,h.x,h.y,h.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,i=e.count;t<i;t++)zs.fromBufferAttribute(e,t),zs.normalize(),e.setXYZ(t,zs.x,zs.y,zs.z)}toNonIndexed(){function e(a,l){const c=a.array,h=a.itemSize,d=a.normalized,u=new c.constructor(l.length*h);let p=0,f=0;for(let _=0,g=l.length;_<g;_++){a.isInterleavedBufferAttribute?p=l[_]*a.data.stride+a.offset:p=l[_]*h;for(let m=0;m<h;m++)u[f++]=c[p++]}return new Ns(u,h,d)}if(this.index===null)return tt("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new ps,i=this.index.array,n=this.attributes;for(const a in n){const l=n[a],c=e(l,i);t.setAttribute(a,c)}const r=this.morphAttributes;for(const a in r){const l=[],c=r[a];for(let h=0,d=c.length;h<d;h++){const u=c[h],p=e(u,i);l.push(p)}t.morphAttributes[a]=l}t.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let a=0,l=o.length;a<l;a++){const c=o[a];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const n={};let r=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],h=[];for(let d=0,u=c.length;d<u;d++){const p=c[d];h.push(p.toJSON(e.data))}h.length>0&&(n[l]=h,r=!0)}r&&(e.data.morphAttributes=n,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const a=this.boundingSphere;return a!==null&&(e.data.boundingSphere=a.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone());const n=e.attributes;for(const c in n){const h=n[c];this.setAttribute(c,h.clone(t))}const r=e.morphAttributes;for(const c in r){const h=[],d=r[c];for(let u=0,p=d.length;u<p;u++)h.push(d[u].clone(t));this.morphAttributes[c]=h}this.morphTargetsRelative=e.morphTargetsRelative;const o=e.groups;for(let c=0,h=o.length;c<h;c++){const d=o[c];this.addGroup(d.start,d.count,d.materialIndex)}const a=e.boundingBox;a!==null&&(this.boundingBox=a.clone());const l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}class lL{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=Am,this.updateRanges=[],this.version=0,this.uuid=Gr()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,i){e*=this.stride,i*=t.stride;for(let n=0,r=this.stride;n<r;n++)this.array[e+n]=t.array[i+n];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Gr()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),i=new this.constructor(t,this.stride);return i.setUsage(this.usage),i}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Gr()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const Ks=new F;class Ed{constructor(e,t,i,n=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=i,this.normalized=n}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,i=this.data.count;t<i;t++)Ks.fromBufferAttribute(this,t),Ks.applyMatrix4(e),this.setXYZ(t,Ks.x,Ks.y,Ks.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)Ks.fromBufferAttribute(this,t),Ks.applyNormalMatrix(e),this.setXYZ(t,Ks.x,Ks.y,Ks.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)Ks.fromBufferAttribute(this,t),Ks.transformDirection(e),this.setXYZ(t,Ks.x,Ks.y,Ks.z);return this}getComponent(e,t){let i=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(i=vn(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=Pt(i,this.array)),this.data.array[e*this.data.stride+this.offset+t]=i,this}setX(e,t){return this.normalized&&(t=Pt(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=Pt(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=Pt(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=Pt(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=vn(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=vn(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=vn(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=vn(t,this.array)),t}setXY(e,t,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=Pt(t,this.array),i=Pt(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=i,this}setXYZ(e,t,i,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=Pt(t,this.array),i=Pt(i,this.array),n=Pt(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=i,this.data.array[e+2]=n,this}setXYZW(e,t,i,n,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=Pt(t,this.array),i=Pt(i,this.array),n=Pt(n,this.array),r=Pt(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=i,this.data.array[e+2]=n,this.data.array[e+3]=r,this}clone(e){if(e===void 0){Od("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let r=0;r<this.itemSize;r++)t.push(this.data.array[n+r])}return new Ns(new this.array.constructor(t),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new Ed(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){Od("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let r=0;r<this.itemSize;r++)t.push(this.data.array[n+r])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}let cL=0;class or extends Io{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:cL++}),this.uuid=Gr(),this.name="",this.type="Material",this.blending=Mo,this.side=Hr,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Wp,this.blendDst=Fp,this.blendEquation=co,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Ye(0,0,0),this.blendAlpha=0,this.depthFunc=Da,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=MM,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Uo,this.stencilZFail=Uo,this.stencilZPass=Uo,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){tt(`Material: parameter '${t}' has value of undefined.`);continue}const n=this[t];if(n===void 0){tt(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}n&&n.isColor?n.set(i):n&&n.isVector2&&i&&i.isVector2||n&&n.isEuler&&i&&i.isEuler||n&&n.isVector3&&i&&i.isVector3?n.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==Mo&&(i.blending=this.blending),this.side!==Hr&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==Wp&&(i.blendSrc=this.blendSrc),this.blendDst!==Fp&&(i.blendDst=this.blendDst),this.blendEquation!==co&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==Da&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==MM&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Uo&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Uo&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Uo&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.allowOverride===!1&&(i.allowOverride=!1),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function n(r){const o=[];for(const a in r){const l=r[a];delete l.metadata,o.push(l)}return o}if(t){const r=n(e.textures),o=n(e.images);r.length>0&&(i.textures=r),o.length>0&&(i.images=o)}return i}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new Ye().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(typeof e.vertexColors=="number"?this.vertexColors=e.vertexColors>0:this.vertexColors=e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let i=e.normalScale;Array.isArray(i)===!1&&(i=[i,i]),this.normalScale=new nt().fromArray(i)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new nt().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const n=t.length;i=new Array(n);for(let r=0;r!==n;++r)i[r]=t[r].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class cc extends or{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Ye(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}let Qo;const il=new F,ea=new F,ta=new F,sa=new nt,nl=new nt,I1=new At,Wc=new F,rl=new F,Fc=new F,RM=new nt,hf=new nt,kM=new nt;class ru extends ss{constructor(e=new cc){if(super(),this.isSprite=!0,this.type="Sprite",Qo===void 0){Qo=new ps;const t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),i=new lL(t,5);Qo.setIndex([0,1,2,0,2,3]),Qo.setAttribute("position",new Ed(i,3,0,!1)),Qo.setAttribute("uv",new Ed(i,2,3,!1))}this.geometry=Qo,this.material=e,this.center=new nt(.5,.5),this.count=1}raycast(e,t){e.camera===null&&bt('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),ea.setFromMatrixScale(this.matrixWorld),I1.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),ta.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&ea.multiplyScalar(-ta.z);const i=this.material.rotation;let n,r;i!==0&&(r=Math.cos(i),n=Math.sin(i));const o=this.center;Uc(Wc.set(-.5,-.5,0),ta,o,ea,n,r),Uc(rl.set(.5,-.5,0),ta,o,ea,n,r),Uc(Fc.set(.5,.5,0),ta,o,ea,n,r),RM.set(0,0),hf.set(1,0),kM.set(1,1);let a=e.ray.intersectTriangle(Wc,rl,Fc,!1,il);if(a===null&&(Uc(rl.set(-.5,.5,0),ta,o,ea,n,r),hf.set(0,1),a=e.ray.intersectTriangle(Wc,Fc,rl,!1,il),a===null))return;const l=e.ray.origin.distanceTo(il);l<e.near||l>e.far||t.push({distance:l,point:il.clone(),uv:Li.getInterpolation(il,Wc,rl,Fc,RM,hf,kM,new nt),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}}function Uc(s,e,t,i,n,r){sa.subVectors(s,t).addScalar(.5).multiply(i),n!==void 0?(nl.x=r*sa.x-n*sa.y,nl.y=n*sa.x+r*sa.y):nl.copy(sa),s.copy(e),s.x+=nl.x,s.y+=nl.y,s.applyMatrix4(I1)}const Gn=new F,df=new F,$c=new F,pr=new F,uf=new F,jc=new F,ff=new F;class ou{constructor(e=new F,t=new F(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Gn)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Gn.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Gn.copy(this.origin).addScaledVector(this.direction,t),Gn.distanceToSquared(e))}distanceSqToSegment(e,t,i,n){df.copy(e).add(t).multiplyScalar(.5),$c.copy(t).sub(e).normalize(),pr.copy(this.origin).sub(df);const r=e.distanceTo(t)*.5,o=-this.direction.dot($c),a=pr.dot(this.direction),l=-pr.dot($c),c=pr.lengthSq(),h=Math.abs(1-o*o);let d,u,p,f;if(h>0)if(d=o*l-a,u=o*a-l,f=r*h,d>=0)if(u>=-f)if(u<=f){const _=1/h;d*=_,u*=_,p=d*(d+o*u+2*a)+u*(o*d+u+2*l)+c}else u=r,d=Math.max(0,-(o*u+a)),p=-d*d+u*(u+2*l)+c;else u=-r,d=Math.max(0,-(o*u+a)),p=-d*d+u*(u+2*l)+c;else u<=-f?(d=Math.max(0,-(-o*r+a)),u=d>0?-r:Math.min(Math.max(-r,-l),r),p=-d*d+u*(u+2*l)+c):u<=f?(d=0,u=Math.min(Math.max(-r,-l),r),p=u*(u+2*l)+c):(d=Math.max(0,-(o*r+a)),u=d>0?r:Math.min(Math.max(-r,-l),r),p=-d*d+u*(u+2*l)+c);else u=o>0?-r:r,d=Math.max(0,-(o*u+a)),p=-d*d+u*(u+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,d),n&&n.copy(df).addScaledVector($c,u),p}intersectSphere(e,t){Gn.subVectors(e.center,this.origin);const i=Gn.dot(this.direction),n=Gn.dot(Gn)-i*i,r=e.radius*e.radius;if(n>r)return null;const o=Math.sqrt(r-n),a=i-o,l=i+o;return l<0?null:a<0?this.at(l,t):this.at(a,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,n,r,o,a,l;const c=1/this.direction.x,h=1/this.direction.y,d=1/this.direction.z,u=this.origin;return c>=0?(i=(e.min.x-u.x)*c,n=(e.max.x-u.x)*c):(i=(e.max.x-u.x)*c,n=(e.min.x-u.x)*c),h>=0?(r=(e.min.y-u.y)*h,o=(e.max.y-u.y)*h):(r=(e.max.y-u.y)*h,o=(e.min.y-u.y)*h),i>o||r>n||((r>i||isNaN(i))&&(i=r),(o<n||isNaN(n))&&(n=o),d>=0?(a=(e.min.z-u.z)*d,l=(e.max.z-u.z)*d):(a=(e.max.z-u.z)*d,l=(e.min.z-u.z)*d),i>l||a>n)||((a>i||i!==i)&&(i=a),(l<n||n!==n)&&(n=l),n<0)?null:this.at(i>=0?i:n,t)}intersectsBox(e){return this.intersectBox(e,Gn)!==null}intersectTriangle(e,t,i,n,r){uf.subVectors(t,e),jc.subVectors(i,e),ff.crossVectors(uf,jc);let o=this.direction.dot(ff),a;if(o>0){if(n)return null;a=1}else if(o<0)a=-1,o=-o;else return null;pr.subVectors(this.origin,e);const l=a*this.direction.dot(jc.crossVectors(pr,jc));if(l<0)return null;const c=a*this.direction.dot(uf.cross(pr));if(c<0||l+c>o)return null;const h=-a*pr.dot(ff);return h<0?null:this.at(h/o,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class T_ extends or{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Ye(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new qr,this.combine=d1,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const NM=new At,to=new ou,Hc=new ko,BM=new F,Vc=new F,qc=new F,Kc=new F,pf=new F,Yc=new F,GM=new F,Xc=new F;class ci extends ss{constructor(e=new ps,t=new T_){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=n.length;r<o;r++){const a=n[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}getVertexPosition(e,t){const i=this.geometry,n=i.attributes.position,r=i.morphAttributes.position,o=i.morphTargetsRelative;t.fromBufferAttribute(n,e);const a=this.morphTargetInfluences;if(r&&a){Yc.set(0,0,0);for(let l=0,c=r.length;l<c;l++){const h=a[l],d=r[l];h!==0&&(pf.fromBufferAttribute(d,e),o?Yc.addScaledVector(pf,h):Yc.addScaledVector(pf.sub(t),h))}t.add(Yc)}return t}raycast(e,t){const i=this.geometry,n=this.material,r=this.matrixWorld;n!==void 0&&(i.boundingSphere===null&&i.computeBoundingSphere(),Hc.copy(i.boundingSphere),Hc.applyMatrix4(r),to.copy(e.ray).recast(e.near),!(Hc.containsPoint(to.origin)===!1&&(to.intersectSphere(Hc,BM)===null||to.origin.distanceToSquared(BM)>(e.far-e.near)**2))&&(NM.copy(r).invert(),to.copy(e.ray).applyMatrix4(NM),!(i.boundingBox!==null&&to.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,to)))}_computeIntersections(e,t,i){let n;const r=this.geometry,o=this.material,a=r.index,l=r.attributes.position,c=r.attributes.uv,h=r.attributes.uv1,d=r.attributes.normal,u=r.groups,p=r.drawRange;if(a!==null)if(Array.isArray(o))for(let f=0,_=u.length;f<_;f++){const g=u[f],m=o[g.materialIndex],w=Math.max(g.start,p.start),y=Math.min(a.count,Math.min(g.start+g.count,p.start+p.count));for(let M=w,v=y;M<v;M+=3){const S=a.getX(M),x=a.getX(M+1),b=a.getX(M+2);n=Zc(this,m,e,i,c,h,d,S,x,b),n&&(n.faceIndex=Math.floor(M/3),n.face.materialIndex=g.materialIndex,t.push(n))}}else{const f=Math.max(0,p.start),_=Math.min(a.count,p.start+p.count);for(let g=f,m=_;g<m;g+=3){const w=a.getX(g),y=a.getX(g+1),M=a.getX(g+2);n=Zc(this,o,e,i,c,h,d,w,y,M),n&&(n.faceIndex=Math.floor(g/3),t.push(n))}}else if(l!==void 0)if(Array.isArray(o))for(let f=0,_=u.length;f<_;f++){const g=u[f],m=o[g.materialIndex],w=Math.max(g.start,p.start),y=Math.min(l.count,Math.min(g.start+g.count,p.start+p.count));for(let M=w,v=y;M<v;M+=3){const S=M,x=M+1,b=M+2;n=Zc(this,m,e,i,c,h,d,S,x,b),n&&(n.faceIndex=Math.floor(M/3),n.face.materialIndex=g.materialIndex,t.push(n))}}else{const f=Math.max(0,p.start),_=Math.min(l.count,p.start+p.count);for(let g=f,m=_;g<m;g+=3){const w=g,y=g+1,M=g+2;n=Zc(this,o,e,i,c,h,d,w,y,M),n&&(n.faceIndex=Math.floor(g/3),t.push(n))}}}}function hL(s,e,t,i,n,r,o,a){let l;if(e.side===li?l=i.intersectTriangle(o,r,n,!0,a):l=i.intersectTriangle(n,r,o,e.side===Hr,a),l===null)return null;Xc.copy(a),Xc.applyMatrix4(s.matrixWorld);const c=t.ray.origin.distanceTo(Xc);return c<t.near||c>t.far?null:{distance:c,point:Xc.clone(),object:s}}function Zc(s,e,t,i,n,r,o,a,l,c){s.getVertexPosition(a,Vc),s.getVertexPosition(l,qc),s.getVertexPosition(c,Kc);const h=hL(s,e,t,i,Vc,qc,Kc,GM);if(h){const d=new F;Li.getBarycoord(GM,Vc,qc,Kc,d),n&&(h.uv=Li.getInterpolatedAttribute(n,a,l,c,d,new nt)),r&&(h.uv1=Li.getInterpolatedAttribute(r,a,l,c,d,new nt)),o&&(h.normal=Li.getInterpolatedAttribute(o,a,l,c,d,new F),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const u={a,b:l,c,normal:new F,materialIndex:0};Li.getNormal(Vc,qc,Kc,u.normal),h.face=u,h.barycoord=d}return h}class C1 extends Hs{constructor(e=null,t=1,i=1,n,r,o,a,l,c=Ps,h=Ps,d,u){super(null,o,a,l,c,h,n,r,d,u),this.isDataTexture=!0,this.image={data:e,width:t,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Pr extends Ns{constructor(e,t,i,n=1){super(e,t,i),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=n}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const ia=new At,PM=new At,Jc=[],LM=new Ro,dL=new At,ol=new ci,al=new ko;class D_ extends ci{constructor(e,t,i){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new Pr(new Float32Array(i*16),16),this.instanceColor=null,this.morphTexture=null,this.count=i,this.boundingBox=null,this.boundingSphere=null;for(let n=0;n<i;n++)this.setMatrixAt(n,dL)}computeBoundingBox(){const e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new Ro),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,ia),LM.copy(e.boundingBox).applyMatrix4(ia),this.boundingBox.union(LM)}computeBoundingSphere(){const e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new ko),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,ia),al.copy(e.boundingSphere).applyMatrix4(ia),this.boundingSphere.union(al)}copy(e,t){return super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),e.morphTexture!==null&&(this.morphTexture=e.morphTexture.clone()),e.instanceColor!==null&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}getColorAt(e,t){return this.instanceColor===null?t.setRGB(1,1,1):t.fromArray(this.instanceColor.array,e*3)}getMatrixAt(e,t){return t.fromArray(this.instanceMatrix.array,e*16)}getMorphAt(e,t){const i=t.morphTargetInfluences,n=this.morphTexture.source.data.data,r=i.length+1,o=e*r+1;for(let a=0;a<i.length;a++)i[a]=n[o+a]}raycast(e,t){const i=this.matrixWorld,n=this.count;if(ol.geometry=this.geometry,ol.material=this.material,ol.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),al.copy(this.boundingSphere),al.applyMatrix4(i),e.ray.intersectsSphere(al)!==!1))for(let r=0;r<n;r++){this.getMatrixAt(r,ia),PM.multiplyMatrices(i,ia),ol.matrixWorld=PM,ol.raycast(e,Jc);for(let o=0,a=Jc.length;o<a;o++){const l=Jc[o];l.instanceId=r,l.object=this,t.push(l)}Jc.length=0}}setColorAt(e,t){return this.instanceColor===null&&(this.instanceColor=new Pr(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),t.toArray(this.instanceColor.array,e*3),this}setMatrixAt(e,t){return t.toArray(this.instanceMatrix.array,e*16),this}setMorphAt(e,t){const i=t.morphTargetInfluences,n=i.length+1;this.morphTexture===null&&(this.morphTexture=new C1(new Float32Array(n*this.count),n,this.count,w_,on));const r=this.morphTexture.source.data.data;let o=0;for(let c=0;c<i.length;c++)o+=i[c];const a=this.geometry.morphTargetsRelative?1:1-o,l=n*e;return r[l]=a,r.set(i,l+1),this}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}}const mf=new F,uL=new F,fL=new at;class Sr{constructor(e=new F(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,i,n){return this.normal.set(e,t,i),this.constant=n,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,i){const n=mf.subVectors(i,t).cross(uL.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(n,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,i=!0){const n=e.delta(mf),r=this.normal.dot(n);if(r===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const o=-(e.start.dot(this.normal)+this.constant)/r;return i===!0&&(o<0||o>1)?null:t.copy(e.start).addScaledVector(n,o)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||fL.getNormalMatrix(e),n=this.coplanarPoint(mf).applyMatrix4(e),r=this.normal.applyMatrix3(i).normalize();return this.constant=-n.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const so=new ko,pL=new nt(.5,.5),Qc=new F;class I_{constructor(e=new Sr,t=new Sr,i=new Sr,n=new Sr,r=new Sr,o=new Sr){this.planes=[e,t,i,n,r,o]}set(e,t,i,n,r,o){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(i),a[3].copy(n),a[4].copy(r),a[5].copy(o),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=yn,i=!1){const n=this.planes,r=e.elements,o=r[0],a=r[1],l=r[2],c=r[3],h=r[4],d=r[5],u=r[6],p=r[7],f=r[8],_=r[9],g=r[10],m=r[11],w=r[12],y=r[13],M=r[14],v=r[15];if(n[0].setComponents(c-o,p-h,m-f,v-w).normalize(),n[1].setComponents(c+o,p+h,m+f,v+w).normalize(),n[2].setComponents(c+a,p+d,m+_,v+y).normalize(),n[3].setComponents(c-a,p-d,m-_,v-y).normalize(),i)n[4].setComponents(l,u,g,M).normalize(),n[5].setComponents(c-l,p-u,m-g,v-M).normalize();else if(n[4].setComponents(c-l,p-u,m-g,v-M).normalize(),t===yn)n[5].setComponents(c+l,p+u,m+g,v+M).normalize();else if(t===ec)n[5].setComponents(l,u,g,M).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),so.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),so.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(so)}intersectsSprite(e){so.center.set(0,0,0);const t=pL.distanceTo(e.center);return so.radius=.7071067811865476+t,so.applyMatrix4(e.matrixWorld),this.intersectsSphere(so)}intersectsSphere(e){const t=this.planes,i=e.center,n=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(i)<n)return!1;return!0}intersectsBox(e){const t=this.planes;for(let i=0;i<6;i++){const n=t[i];if(Qc.x=n.normal.x>0?e.max.x:e.min.x,Qc.y=n.normal.y>0?e.max.y:e.min.y,Qc.z=n.normal.z>0?e.max.z:e.min.z,n.distanceToPoint(Qc)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class au extends or{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Ye(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const Ad=new F,Td=new F,WM=new At,ll=new ou,eh=new ko,gf=new F,FM=new F;class Dm extends ss{constructor(e=new ps,t=new au){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[0];for(let n=1,r=t.count;n<r;n++)Ad.fromBufferAttribute(t,n-1),Td.fromBufferAttribute(t,n),i[n]=i[n-1],i[n]+=Ad.distanceTo(Td);e.setAttribute("lineDistance",new Rt(i,1))}else tt("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){const i=this.geometry,n=this.matrixWorld,r=e.params.Line.threshold,o=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),eh.copy(i.boundingSphere),eh.applyMatrix4(n),eh.radius+=r,e.ray.intersectsSphere(eh)===!1)return;WM.copy(n).invert(),ll.copy(e.ray).applyMatrix4(WM);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),l=a*a,c=this.isLineSegments?2:1,h=i.index,u=i.attributes.position;if(h!==null){const p=Math.max(0,o.start),f=Math.min(h.count,o.start+o.count);for(let _=p,g=f-1;_<g;_+=c){const m=h.getX(_),w=h.getX(_+1),y=th(this,e,ll,l,m,w,_);y&&t.push(y)}if(this.isLineLoop){const _=h.getX(f-1),g=h.getX(p),m=th(this,e,ll,l,_,g,f-1);m&&t.push(m)}}else{const p=Math.max(0,o.start),f=Math.min(u.count,o.start+o.count);for(let _=p,g=f-1;_<g;_+=c){const m=th(this,e,ll,l,_,_+1,_);m&&t.push(m)}if(this.isLineLoop){const _=th(this,e,ll,l,f-1,p,f-1);_&&t.push(_)}}}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=n.length;r<o;r++){const a=n[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}}function th(s,e,t,i,n,r,o){const a=s.geometry.attributes.position;if(Ad.fromBufferAttribute(a,n),Td.fromBufferAttribute(a,r),t.distanceSqToSegment(Ad,Td,gf,FM)>i)return;gf.applyMatrix4(s.matrixWorld);const c=e.ray.origin.distanceTo(gf);if(!(c<e.near||c>e.far))return{distance:c,point:FM.clone().applyMatrix4(s.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:s}}const UM=new F,$M=new F;class Im extends Dm{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[];for(let n=0,r=t.count;n<r;n+=2)UM.fromBufferAttribute(t,n),$M.fromBufferAttribute(t,n+1),i[n]=n===0?0:i[n-1],i[n+1]=i[n]+UM.distanceTo($M);e.setAttribute("lineDistance",new Rt(i,1))}else tt("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class mL extends or{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Ye(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const jM=new At,Cm=new ou,sh=new ko,ih=new F;class gL extends ss{constructor(e=new ps,t=new mL){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){const i=this.geometry,n=this.matrixWorld,r=e.params.Points.threshold,o=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),sh.copy(i.boundingSphere),sh.applyMatrix4(n),sh.radius+=r,e.ray.intersectsSphere(sh)===!1)return;jM.copy(n).invert(),Cm.copy(e.ray).applyMatrix4(jM);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),l=a*a,c=i.index,d=i.attributes.position;if(c!==null){const u=Math.max(0,o.start),p=Math.min(c.count,o.start+o.count);for(let f=u,_=p;f<_;f++){const g=c.getX(f);ih.fromBufferAttribute(d,g),HM(ih,g,l,n,e,t,this)}}else{const u=Math.max(0,o.start),p=Math.min(d.count,o.start+o.count);for(let f=u,_=p;f<_;f++)ih.fromBufferAttribute(d,f),HM(ih,f,l,n,e,t,this)}}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=n.length;r<o;r++){const a=n[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}}function HM(s,e,t,i,n,r,o){const a=Cm.distanceSqToPoint(s);if(a<t){const l=new F;Cm.closestPointToPoint(s,l),l.applyMatrix4(i);const c=n.ray.origin.distanceTo(l);if(c<n.near||c>n.far)return;r.push({distance:c,distanceToRay:Math.sqrt(a),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:o})}}class R1 extends Hs{constructor(e=[],t=Eo,i,n,r,o,a,l,c,h){super(e,t,i,n,r,o,a,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class k1 extends Hs{constructor(e,t,i,n,r,o,a,l,c){super(e,t,i,n,r,o,a,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Ca extends Hs{constructor(e,t,i=Tn,n,r,o,a=Ps,l=Ps,c,h=nr,d=1){if(h!==nr&&h!==fo)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const u={width:e,height:t,depth:d};super(u,n,r,o,a,l,h,i,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new E_(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class _L extends Ca{constructor(e,t=Tn,i=Eo,n,r,o=Ps,a=Ps,l,c=nr){const h={width:e,height:e,depth:1},d=[h,h,h,h,h,h];super(e,e,t,i,n,r,o,a,l,c),this.image=d,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class N1 extends Hs{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class hc extends ps{constructor(e=1,t=1,i=1,n=1,r=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:n,heightSegments:r,depthSegments:o};const a=this;n=Math.floor(n),r=Math.floor(r),o=Math.floor(o);const l=[],c=[],h=[],d=[];let u=0,p=0;f("z","y","x",-1,-1,i,t,e,o,r,0),f("z","y","x",1,-1,i,t,-e,o,r,1),f("x","z","y",1,1,e,i,t,n,o,2),f("x","z","y",1,-1,e,i,-t,n,o,3),f("x","y","z",1,-1,e,t,i,n,r,4),f("x","y","z",-1,-1,e,t,-i,n,r,5),this.setIndex(l),this.setAttribute("position",new Rt(c,3)),this.setAttribute("normal",new Rt(h,3)),this.setAttribute("uv",new Rt(d,2));function f(_,g,m,w,y,M,v,S,x,b,z){const T=M/x,A=v/b,E=M/2,O=v/2,R=S/2,C=x+1,k=b+1;let G=0,L=0;const W=new F;for(let ee=0;ee<k;ee++){const X=ee*A-O;for(let he=0;he<C;he++){const Ae=he*T-E;W[_]=Ae*w,W[g]=X*y,W[m]=R,c.push(W.x,W.y,W.z),W[_]=0,W[g]=0,W[m]=S>0?1:-1,h.push(W.x,W.y,W.z),d.push(he/x),d.push(1-ee/b),G+=1}}for(let ee=0;ee<b;ee++)for(let X=0;X<x;X++){const he=u+X+C*ee,Ae=u+X+C*(ee+1),Pe=u+(X+1)+C*(ee+1),De=u+(X+1)+C*ee;l.push(he,Ae,De),l.push(Ae,Pe,De),L+=6}a.addGroup(p,L,z),p+=L,u+=G}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new hc(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class C_ extends ps{constructor(e=1,t=32,i=0,n=Math.PI*2){super(),this.type="CircleGeometry",this.parameters={radius:e,segments:t,thetaStart:i,thetaLength:n},t=Math.max(3,t);const r=[],o=[],a=[],l=[],c=new F,h=new nt;o.push(0,0,0),a.push(0,0,1),l.push(.5,.5);for(let d=0,u=3;d<=t;d++,u+=3){const p=i+d/t*n;c.x=e*Math.cos(p),c.y=e*Math.sin(p),o.push(c.x,c.y,c.z),a.push(0,0,1),h.x=(o[u]/e+1)/2,h.y=(o[u+1]/e+1)/2,l.push(h.x,h.y)}for(let d=1;d<=t;d++)r.push(d,d+1,0);this.setIndex(r),this.setAttribute("position",new Rt(o,3)),this.setAttribute("normal",new Rt(a,3)),this.setAttribute("uv",new Rt(l,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new C_(e.radius,e.segments,e.thetaStart,e.thetaLength)}}class R_ extends ps{constructor(e=1,t=1,i=1,n=32,r=1,o=!1,a=0,l=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:i,radialSegments:n,heightSegments:r,openEnded:o,thetaStart:a,thetaLength:l};const c=this;n=Math.floor(n),r=Math.floor(r);const h=[],d=[],u=[],p=[];let f=0;const _=[],g=i/2;let m=0;w(),o===!1&&(e>0&&y(!0),t>0&&y(!1)),this.setIndex(h),this.setAttribute("position",new Rt(d,3)),this.setAttribute("normal",new Rt(u,3)),this.setAttribute("uv",new Rt(p,2));function w(){const M=new F,v=new F;let S=0;const x=(t-e)/i;for(let b=0;b<=r;b++){const z=[],T=b/r,A=T*(t-e)+e;for(let E=0;E<=n;E++){const O=E/n,R=O*l+a,C=Math.sin(R),k=Math.cos(R);v.x=A*C,v.y=-T*i+g,v.z=A*k,d.push(v.x,v.y,v.z),M.set(C,x,k).normalize(),u.push(M.x,M.y,M.z),p.push(O,1-T),z.push(f++)}_.push(z)}for(let b=0;b<n;b++)for(let z=0;z<r;z++){const T=_[z][b],A=_[z+1][b],E=_[z+1][b+1],O=_[z][b+1];(e>0||z!==0)&&(h.push(T,A,O),S+=3),(t>0||z!==r-1)&&(h.push(A,E,O),S+=3)}c.addGroup(m,S,0),m+=S}function y(M){const v=f,S=new nt,x=new F;let b=0;const z=M===!0?e:t,T=M===!0?1:-1;for(let E=1;E<=n;E++)d.push(0,g*T,0),u.push(0,T,0),p.push(.5,.5),f++;const A=f;for(let E=0;E<=n;E++){const R=E/n*l+a,C=Math.cos(R),k=Math.sin(R);x.x=z*k,x.y=g*T,x.z=z*C,d.push(x.x,x.y,x.z),u.push(0,T,0),S.x=C*.5+.5,S.y=k*.5*T+.5,p.push(S.x,S.y),f++}for(let E=0;E<n;E++){const O=v+E,R=A+E;M===!0?h.push(R,R+1,O):h.push(R+1,R,O),b+=3}c.addGroup(m,b,M===!0?1:2),m+=b}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new R_(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class k_ extends ps{constructor(e=[],t=[],i=1,n=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:i,detail:n};const r=[],o=[];a(n),c(i),h(),this.setAttribute("position",new Rt(r,3)),this.setAttribute("normal",new Rt(r.slice(),3)),this.setAttribute("uv",new Rt(o,2)),n===0?this.computeVertexNormals():this.normalizeNormals();function a(w){const y=new F,M=new F,v=new F;for(let S=0;S<t.length;S+=3)p(t[S+0],y),p(t[S+1],M),p(t[S+2],v),l(y,M,v,w)}function l(w,y,M,v){const S=v+1,x=[];for(let b=0;b<=S;b++){x[b]=[];const z=w.clone().lerp(M,b/S),T=y.clone().lerp(M,b/S),A=S-b;for(let E=0;E<=A;E++)E===0&&b===S?x[b][E]=z:x[b][E]=z.clone().lerp(T,E/A)}for(let b=0;b<S;b++)for(let z=0;z<2*(S-b)-1;z++){const T=Math.floor(z/2);z%2===0?(u(x[b][T+1]),u(x[b+1][T]),u(x[b][T])):(u(x[b][T+1]),u(x[b+1][T+1]),u(x[b+1][T]))}}function c(w){const y=new F;for(let M=0;M<r.length;M+=3)y.x=r[M+0],y.y=r[M+1],y.z=r[M+2],y.normalize().multiplyScalar(w),r[M+0]=y.x,r[M+1]=y.y,r[M+2]=y.z}function h(){const w=new F;for(let y=0;y<r.length;y+=3){w.x=r[y+0],w.y=r[y+1],w.z=r[y+2];const M=g(w)/2/Math.PI+.5,v=m(w)/Math.PI+.5;o.push(M,1-v)}f(),d()}function d(){for(let w=0;w<o.length;w+=6){const y=o[w+0],M=o[w+2],v=o[w+4],S=Math.max(y,M,v),x=Math.min(y,M,v);S>.9&&x<.1&&(y<.2&&(o[w+0]+=1),M<.2&&(o[w+2]+=1),v<.2&&(o[w+4]+=1))}}function u(w){r.push(w.x,w.y,w.z)}function p(w,y){const M=w*3;y.x=e[M+0],y.y=e[M+1],y.z=e[M+2]}function f(){const w=new F,y=new F,M=new F,v=new F,S=new nt,x=new nt,b=new nt;for(let z=0,T=0;z<r.length;z+=9,T+=6){w.set(r[z+0],r[z+1],r[z+2]),y.set(r[z+3],r[z+4],r[z+5]),M.set(r[z+6],r[z+7],r[z+8]),S.set(o[T+0],o[T+1]),x.set(o[T+2],o[T+3]),b.set(o[T+4],o[T+5]),v.copy(w).add(y).add(M).divideScalar(3);const A=g(v);_(S,T+0,w,A),_(x,T+2,y,A),_(b,T+4,M,A)}}function _(w,y,M,v){v<0&&w.x===1&&(o[y]=w.x-1),M.x===0&&M.z===0&&(o[y]=v/2/Math.PI+.5)}function g(w){return Math.atan2(w.z,-w.x)}function m(w){return Math.atan2(-w.y,Math.sqrt(w.x*w.x+w.z*w.z))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new k_(e.vertices,e.indices,e.radius,e.detail)}}class N_ extends k_{constructor(e=1,t=0){const i=(1+Math.sqrt(5))/2,n=[-1,i,0,1,i,0,-1,-i,0,1,-i,0,0,-1,i,0,1,i,0,-1,-i,0,1,-i,i,0,-1,i,0,1,-i,0,-1,-i,0,1],r=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];super(n,r,e,t),this.type="IcosahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new N_(e.radius,e.detail)}}class lu extends ps{constructor(e=1,t=1,i=1,n=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:i,heightSegments:n};const r=e/2,o=t/2,a=Math.floor(i),l=Math.floor(n),c=a+1,h=l+1,d=e/a,u=t/l,p=[],f=[],_=[],g=[];for(let m=0;m<h;m++){const w=m*u-o;for(let y=0;y<c;y++){const M=y*d-r;f.push(M,-w,0),_.push(0,0,1),g.push(y/a),g.push(1-m/l)}}for(let m=0;m<l;m++)for(let w=0;w<a;w++){const y=w+c*m,M=w+c*(m+1),v=w+1+c*(m+1),S=w+1+c*m;p.push(y,M,S),p.push(M,v,S)}this.setIndex(p),this.setAttribute("position",new Rt(f,3)),this.setAttribute("normal",new Rt(_,3)),this.setAttribute("uv",new Rt(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new lu(e.width,e.height,e.widthSegments,e.heightSegments)}}class cu extends ps{constructor(e=1,t=32,i=16,n=0,r=Math.PI*2,o=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:i,phiStart:n,phiLength:r,thetaStart:o,thetaLength:a},t=Math.max(3,Math.floor(t)),i=Math.max(2,Math.floor(i));const l=Math.min(o+a,Math.PI);let c=0;const h=[],d=new F,u=new F,p=[],f=[],_=[],g=[];for(let m=0;m<=i;m++){const w=[],y=m/i,M=o+y*a,v=e*Math.cos(M),S=Math.sqrt(e*e-v*v);let x=0;m===0&&o===0?x=.5/t:m===i&&l===Math.PI&&(x=-.5/t);for(let b=0;b<=t;b++){const z=b/t,T=n+z*r;d.x=-S*Math.cos(T),d.y=v,d.z=S*Math.sin(T),f.push(d.x,d.y,d.z),u.copy(d).normalize(),_.push(u.x,u.y,u.z),g.push(z+x,1-y),w.push(c++)}h.push(w)}for(let m=0;m<i;m++)for(let w=0;w<t;w++){const y=h[m][w+1],M=h[m][w],v=h[m+1][w],S=h[m+1][w+1];(m!==0||o>0)&&p.push(y,M,S),(m!==i-1||l<Math.PI)&&p.push(M,v,S)}this.setIndex(p),this.setAttribute("position",new Rt(f,3)),this.setAttribute("normal",new Rt(_,3)),this.setAttribute("uv",new Rt(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new cu(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}function Ra(s){const e={};for(const t in s){e[t]={};for(const i in s[t]){const n=s[t][i];if(VM(n))n.isRenderTargetTexture?(tt("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][i]=null):e[t][i]=n.clone();else if(Array.isArray(n))if(VM(n[0])){const r=[];for(let o=0,a=n.length;o<a;o++)r[o]=n[o].clone();e[t][i]=r}else e[t][i]=n.slice();else e[t][i]=n}}return e}function Zs(s){const e={};for(let t=0;t<s.length;t++){const i=Ra(s[t]);for(const n in i)e[n]=i[n]}return e}function VM(s){return s&&(s.isColor||s.isMatrix3||s.isMatrix4||s.isVector2||s.isVector3||s.isVector4||s.isTexture||s.isQuaternion)}function bL(s){const e=[];for(let t=0;t<s.length;t++)e.push(s[t].clone());return e}function B1(s){const e=s.getRenderTarget();return e===null?s.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:Mt.workingColorSpace}const ML={clone:Ra,merge:Zs};var vL=`void main() {
|
|
107
107
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
108
108
|
}`,wL=`void main() {
|
|
@@ -4345,7 +4345,7 @@ void main() {
|
|
|
4345
4345
|
`),!1}return t.outcome_write(n),n.envelopes.length>0&&n.envelopes.every(r=>r.status==="ok")}function V5(s){for(const e of s.envelopes){if(e.model?.kind!=="fs.acl")continue;const t=e.model.data[0];return t===void 0?null:{users:t.usernames??[],groups:t.groups??[],public:t.public===!0}}return null}function q5(s,e){return s.split(`
|
|
4346
4346
|
`).map(t=>t.trim().split(":")).filter(t=>t.length>=4&&(t[3]??"").split(",").includes(e)).map(t=>t[0]??"").filter(t=>t!=="")}function K5(s){return/^(u|user|g|group|o|other):/.test(s)?s:`u:${s}:r`}function Y5(s,e){return e.kind==="public"?`setfacl -m o::- feed_${s}`:`setfacl -x ${e.kind==="user"?"u":"g"}:${ln(e.name)} feed_${s}`}function hh(s){return s.kind==="public"?"PUBLIC":s.kind==="group"?`group ${s.name}`:s.name}function X5(s,e){const t={silent:!0,observe:!1},i=async c=>{try{return V5(await s.client.line_execute(`getfacl feed_${c}`,t))}catch{return null}},n=async()=>{const c=e.promptUser();if(c===null)return[];try{const h=await s.client.line_execute("cat /etc/group",t);return q5(h.envelopes.map(d=>d.rendered).join(""),c)}catch{return[]}},r=async(c,h,d)=>{await e.askOnPane_await(c,{kind:"confirm",message:`Stop sharing feed_${h} with ${hh(d)}? `})==="y"&&await ba(s,Y5(h,d))&&e.changed(h)};return{holders_read:i,holders_build:(c,h,d)=>{const u=document.createElement("span");u.className="holder-marks";const p=[...d.users.map(f=>({kind:"user",name:f})),...d.groups.map(f=>({kind:"group",name:f})),...d.public?[{kind:"public"}]:[]];if(p.length===0)return u.textContent="SHARED WITH NOBODY",u;u.append("SHARED WITH ");for(const f of p){const _=document.createElement("span");_.className=`holder-mark holder-${f.kind}`,_.title=hh(f);const g=document.createElement("span");g.className="holder-mark-name",g.textContent=hh(f),_.append(g);const m=document.createElement("span");m.className="holder-mark-x",m.title=`stop sharing with ${hh(f)} (asks first)`,m.textContent="×",m.addEventListener("click",w=>{w.stopPropagation(),r(c,h,f)}),_.append(m),u.append(_)}return u},share_choose:async(c,h)=>{for(;;){const[d,u]=await Promise.all([i(h),n()]),p=d??{groups:[],public:!1},f=[{value:"o::r",label:"EVERYONE",held:p.public},...u.map(g=>({value:`g:${g}:r`,label:g,held:p.groups.includes(g)}))],_=(await e.askOnPane_await(c,{kind:"choose",message:`Share feed_${h} with a group, everyone, or a user: `,choices:f,commit:"SHARE",close:"DONE"})??"").trim();if(_===""||!await ba(s,`setfacl -m ${K5(_)} feed_${h}`))return;e.changed(h)}},rename:async(c,h,d)=>{const u=(await e.askOnPane_await(c,{kind:"text",message:`Rename feed_${h} to: `,suggest:d,commit:"RENAME"})??"").trim();u===""||u===d||await ba(s,W_(`/proc/jobs/feed_${h}/title`,u))&&e.changed(h)}}}function Z5(s){for(const e of s.envelopes){if(e.model?.kind!=="fs.listing")continue;return(e.model.data[0]?.items??[]).map(i=>String(i.name??"")).filter(i=>i!=="")}return[]}function J5(s,e,t){const i=`setfattr -n tag -v ${ln(e)} feed_${s}`;return t.includes(e)?[i]:[`mkdir ${ln(`/proc/tags/${e}`)}`,i]}function Q5(s,e){const t=async()=>{try{return Z5(await s.client.line_execute("ls /proc/tags",{silent:!0,observe:!1}))}catch{return[]}};return{tag_choose:async(r,o,a)=>{const l=new Set(a);for(;;){const c=await t(),h=c.map(_=>({value:_,held:l.has(_)})),d=c.filter(_=>!l.has(_)).join(", "),p=(await e.askOnPane_await(r,{kind:"choose",message:`Tag feed_${o}${d===""?"":` (${d})`}, or a new tag: `,choices:h,commit:"TAG",close:"DONE"})??"").trim();if(p===""||p.includes("/"))return;if(l.has(p))continue;let f=!0;for(const _ of J5(o,p,c))if(f=await ba(s,_),!f)break;if(!f)return;l.add(p),e.tags_changed(o)}},tag_remove:async(r,o)=>{const a=await ba(s,`setfattr -x tag -v ${ln(o)} feed_${r}`);return a&&e.tags_changed(r),a}}}function ej(s,e){return{tags:Q5(s,{askOnPane_await:e.askOnPane_await,tags_changed:e.changed}),access:X5(s,e)}}function tj(s){for(const e of s.envelopes){if(e.model?.kind!=="fs.xattr")continue;return e.model.data[0]?.tags??[]}return[]}function wx(s,e,t){const{panels:i,subjects:n}=s,{tags:r,access:o}=t;return{feed_verbs:a=>{const l={feedId:a.id},c={note:()=>s.terminal.line_run(`edit /proc/jobs/feed_${a.id}/note`),tag:()=>{r.tag_choose(e,a.id,a.tags??[])},rename:()=>{o.rename(e,a.id,a.title)},share:()=>{o.share_choose(e,a.id)},delete:()=>s.terminal.line_run(`feed rm feed_${a.id}`)};return n1.rules.filter(h=>h.offered(l)).map(h=>({label:h.label(l),run:()=>c[h.name]?.()}))},feed_indicated:a=>{n.regard_write(e,{address:`/proc/jobs/feed_${a.id}`,modelKind:"feed"}),o.holders_read(a.id).then(l=>{i.get("dag",e)?.rowReadout_show(a.id,l===null?"ACCESS UNREAD":o.holders_build(e,a.id,l))})},feed_untag:(a,l)=>{r.tag_remove(a,l)},feed_entered:a=>{const l={silent:!0,observe:!1},c=h=>h!==null&&h.envelopes.every(d=>d.status==="ok")?h.envelopes.map(d=>d.rendered).join("").replace(/\x1b\[[0-9;]*m/g,""):null;Promise.all([s.client.line_execute(`cat /proc/jobs/feed_${a}/note`,l).catch(()=>null),s.client.line_execute(`getfattr feed_${a}`,l).catch(()=>null),s.client.line_execute(`cat /proc/jobs/feed_${a}/title`,l).catch(()=>null)]).then(([h,d,u])=>{(i.get("dag",e)??i.get("universe",e))?.feedMarks_show(a,{note:c(h),tags:d===null?[]:tj(d),title:(c(u)??"").trim()})})},feed_note:a=>s.terminal.line_run(`edit /proc/jobs/feed_${a}/note`),feed_tag:(a,l)=>{r.tag_choose(e,a,l)},feed_rename:(a,l)=>{o.rename(e,a,l)}}}const sj=256*1024*1024;function ij(s,e){const t=e.split("/").filter(o=>o.length>0).pop()??"download";if(s===null)return t;const i=/filename\*\s*=\s*UTF-8''([^;]+)/i.exec(s);if(i!==null)try{const o=decodeURIComponent((i[1]??"").trim());if(o.length>0)return o}catch{}const r=/filename\s*=\s*"([^"]*)"/i.exec(s)?.[1]??"";return r.length>0?r:t}function $v(s){return s.redirected?"the session asked to log in again — nothing was saved":s.status===410?"cancelled — nothing was saved":s.ok?s.headers.get("content-disposition")===null?"the session answered with something other than the file — nothing was saved":null:s.status===404?"the session could not read that file — nothing was saved":`the session refused the file (HTTP ${s.status}) — nothing was saved`}function jv(s,e){const t=document.createElement("a");t.href=s,t.download=e,t.rel="noopener",document.body.append(t),t.click(),t.remove()}function yx(){return`dl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function nj(s,e,t=fetch,i=yx()){const n=`${s}&dl=${encodeURIComponent(i)}`;let r;try{r=await t(`${n}&probe=1`,{method:"HEAD",credentials:"same-origin"})}catch(p){return{ok:!1,reason:`the session did not answer (${p instanceof Error?p.message:String(p)}) — nothing was saved`}}const o=$v(r);if(o!==null)return{ok:!1,reason:o};const a=ij(r.headers.get("content-disposition"),e),l=Number(r.headers.get("content-length")??NaN);if(!Number.isFinite(l)||l>sj)return jv(n,a),{ok:!0,name:a,bytes:Number.isFinite(l)?l:null,streamed:!0};let c;try{c=await t(n,{credentials:"same-origin"})}catch(p){return{ok:!1,reason:`the session did not answer (${p instanceof Error?p.message:String(p)}) — nothing was saved`}}const h=$v(c);if(h!==null)return{ok:!1,reason:h};const d=await c.blob(),u=URL.createObjectURL(d);return jv(u,a),setTimeout(()=>URL.revokeObjectURL(u),6e4),{ok:!0,name:a,bytes:d.size,streamed:!1}}const rj=1e3,oj=5e3,aj=3,lj=2e4;function fl(s){const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1e3&&i<e.length-1;)t/=1e3,i+=1;return`${i===0?t.toFixed(0):t.toFixed(1)} ${e[i]}`}function dh(s){const e=Math.max(0,Math.round(s/1e3)),t=Math.floor(e/3600),i=Math.floor(e%3600/60),n=String(e%60).padStart(2,"0");return t>0?`${t}:${String(i).padStart(2,"0")}:${n}`:`${i}:${n}`}function cj(s,e){switch(s.phase){case"opening":return`WAITING FOR CUBE · ${dh(s.elapsedMs)}`;case"ready":return"CUBE ANSWERED · HANDING TO THE BROWSER";case"streaming":{if(s.bytes===0)return`WAITING FOR CUBE'S FIRST BYTE · ${dh(s.elapsedMs)}`;const t=[s.size!==void 0?`${fl(s.bytes)} OF ${fl(s.size)}`:fl(s.bytes)];return s.size!==void 0&&s.size>0&&t.push(`${Math.floor(100*s.bytes/s.size)}%`),e!==null&&e>0&&(t.push(`${fl(e)}/S`),s.size!==void 0&&t.push(`${dh(1e3*(s.size-s.bytes)/e)} LEFT`)),t.join(" · ")}case"done":return`DONE · ${fl(s.bytes)} IN ${dh(s.elapsedMs)}`;case"failed":return`FAILED · ${s.reason??"the session did not say why"}`;case"cancelled":return"CANCELLED"}}function Hv(s){return s==="done"||s==="failed"||s==="cancelled"}function Vv(s,e,t){const i=new URL(s,window.location.href),n=i.searchParams.get("token");return i.search="",i.searchParams.set(e,t),n!==null&&i.searchParams.set("token",n),i.toString()}function hj(){let s=document.querySelector(".transfer-stack");return s===null&&(s=document.createElement("div"),s.className="transfer-stack",s.setAttribute("role","status"),document.body.appendChild(s)),s}function dj(s,e,t,i=fetch){const n=document.createElement("div");n.className="transfer-row",n.dataset.download=t,n.dataset.phase="opening";const r=document.createElement("span");r.className="transfer-name",r.textContent=s,r.title=s;const o=document.createElement("span");o.className="transfer-bar";const a=document.createElement("span");a.className="transfer-fill",o.appendChild(a);const l=document.createElement("span");l.className="transfer-words",l.textContent="ASKING THE SESSION";const c=document.createElement("button");c.type="button",c.className="transfer-action",c.textContent="CANCEL",n.append(r,o,l,c),hj().appendChild(n);let h=null,d=null,u=!1,p=null;const f=[],_=()=>n.remove(),g=()=>{u=!0,h!==null&&clearTimeout(h),c.textContent="CLOSE",c.title="dismiss this row",d=setTimeout(_,lj)},m=x=>{const b=Date.now();for(f.push({at:b,bytes:x});f.length>1&&b-(f[0]?.at??b)>6e3;)f.shift();const z=f[0];return z===void 0||b-z.at<900?null:(x-z.bytes)*1e3/(b-z.at)};let w=!1,y=0;const M=x=>{n.dataset.phase=x.phase;const b=cj(x,x.phase==="streaming"?m(x.bytes):null);l.textContent=w&&!Hv(x.phase)?`CANCELLING · ${b}`:b;const z=x.phase==="done"?1:x.size!==void 0&&x.size>0?x.bytes/x.size:0;a.style.width=`${(100*z).toFixed(1)}%`,Hv(x.phase)&&g()},v=async x=>{const b=new AbortController,z=setTimeout(()=>b.abort(),oj);try{const T=await i(Vv(e,x,t),{credentials:"same-origin",cache:"no-store",signal:b.signal});return T.ok?await T.json():"unknown"}catch{return null}finally{clearTimeout(z)}},S=async()=>{if(u)return;const x=await v("progress");if(!u){if(x===null)y+=1,y>=aj&&(l.textContent="LOST TOUCH WITH THE SESSION · STILL ASKING");else if(x==="unknown"){if(y=0,p??=Date.now(),Date.now()-p>5e3){n.dataset.phase="handed",l.textContent="HANDED TO THE BROWSER · SEE ITS DOWNLOADS",g();return}}else y=0,p=null,M(x);u||(h=setTimeout(()=>{S()},rj))}};return c.addEventListener("click",()=>{if(u){_();return}c.disabled=!0,w=!0,l.textContent="CANCELLING",v("cancel").then(x=>{c.disabled=!1,!u&&(x===null?(w=!1,l.textContent="THE CANCEL GOT NO ANSWER FROM THE SESSION · PRESS CANCEL AGAIN"):x==="unknown"?(w=!1,n.dataset.phase="handed",l.textContent="THE SESSION DOES NOT KNOW THIS DOWNLOAD · CANCEL IT IN THE BROWSER'S DOWNLOADS",g()):M(x))})}),S(),{element:n,show:M,fail:x=>{u||i(Vv(e,"progress",t),{credentials:"same-origin",cache:"no-store"}).then(async b=>b.ok?await b.json():null).catch(()=>null).then(b=>{u||M(b!==null&&b.phase==="failed"?b:{phase:"failed",bytes:0,reason:x,elapsedMs:0})})},stop:()=>{u=!0,h!==null&&clearTimeout(h),d!==null&&clearTimeout(d)}}}const Sx=/\.(csv|tsv)$/i;function qv(s){return s.replace(/\x1b\[[0-9;:]*[A-Za-z]/g,"")}function zx(s){return Bp.test(s)||_d.test(s)}function Fm(s){const e=/_(\d+)\/data\/?$/.exec(s);return e===null?null:parseInt(e[1]??"",10)}function Fl(s){const e=s.match(/\/(?:feeds|jobs)\/feed_(\d+)(?:\/|$)/);return e===null?null:Number(e[1])}function uj(s){return/^\/(proc|net|etc|usr)(\/|$)/.test(s)}function fj(s){for(const e of s.envelopes){const t=e.model;if(typeof t!="object"||t===null)continue;const i=t.data;if(t.kind!=="fs.acl"||!Array.isArray(i))continue;const n=[];for(const r of i)Array.isArray(r.usernames)&&n.push(...r.usernames.map(String)),Array.isArray(r.groups)&&n.push(...r.groups.map(o=>`group ${String(o)}`)),r.public===!0&&n.push("PUBLIC");return n.length===0?"SHARED WITH NOBODY":`SHARED WITH ${n.join(", ")}`}return"ACCESS UNREAD"}function pj(s,e){const{panels:t,subjects:i}=s,n=new Map,r=new Map,o=new Map,a=z=>{const T=e.downloadUrl_build(z),A=yx(),E=z.split("/").filter(R=>R.length>0).pop()??z,O=dj(E,T,A);s.terminal.line_note(`download: asking the session for ${E}`),nj(T,z,fetch,A).then(R=>{R.ok||O.fail(R.reason),s.terminal.line_note(R.ok?`download: ${R.name}${R.streamed?" — handed to the browser; its progress is on the transfer row":""}`:`download: ${z}: ${R.reason}`)})},l=z=>s.client.line_execute(`cat "${z}"`,{silent:!0,observe:!1}).then(T=>{if(!T.envelopes.some(O=>O.status==="error"))return{ok:!0,text:qv(T.envelopes.map(O=>O.rendered).join(`
|
|
4347
4347
|
`))};const E=T.envelopes.flatMap(O=>(O.errors??[]).map(R=>R.message)).concat(T.envelopes.map(O=>O.renderedErr??"")).map(O=>qv(O).trim()).filter(O=>O!=="").join(`
|
|
4348
|
-
`);return{ok:!1,text:E===""?"the session refused this read and said nothing further":E}}),c=async(z,T)=>{const A=await fetch(e.vfsUrl_build(z));if(!A.ok||A.body===null)return(await l(z)).text.slice(0,T);const E=A.body.getReader(),O=new TextDecoder;let R="";for(;R.length<T;){const{done:C,value:k}=await E.read();if(C)break;R+=O.decode(k,{stream:!0})}return E.cancel().catch(()=>{}),R.slice(0,T)},h=async z=>{const T=/_id(\d+)$/.exec(z)?.[1]??z.replace(/^.*\//,""),A=await s.client.line_execute(`pipeline diagram ${T}`,{silent:!0,observe:!1});for(const E of A.envelopes){if(E.model?.kind!==Cr.pipelineDiagram)continue;const O=Jg.safeParse(E.model.data);if(O.success)return O.data.nodes.map(R=>({id:R.id,parentIds:[...R.parentIds,...R.joinParentIds??[]]}))}return null},d={imageUrl:e.vfsUrl_build,download:a,textHead:c,pipelineGlimpse:h},u=(z,T,A)=>{const E=A==="~"?"ls ~":`ls "${A}"`;s.client.line_execute(E,{silent:!0,observe:!1}).then(O=>{for(const R of O.envelopes)T.envelope_observe(R);if(A!=="~"&&T.path_current()!==A.replace(/\/+$/,"")){const R=O.envelopes.find(k=>k.status==="error"),C=R!==void 0?$z(R):"the session answered no listing";T.listing_fail(C),s.terminal.line_note(`files: ${A}: ${C}`)}},O=>{const R=O instanceof Error?O.message:String(O);T.listing_fail(R),s.terminal.line_note(`files: ${A}: ${R}`)})},p=(z,T,A)=>{const E=T.path_current();E!==null&&n.get(z)?.push(E),u(z,T,A)},f=(z,T)=>{const A=n.get(z)?.pop();A!==void 0&&u(z,T,A)},_=z=>{o.get(z)?.()},g=(z,T)=>{r.set(z,T),_(z);const A=t.get("files",z);A?.follow_set(T),T&&A!==void 0&&s.client.line_execute("ls",{silent:!0,observe:!1}).then(E=>{for(const O of E.envelopes)A.envelope_observe(O)})},m=(z,T)=>{const A=t.get("files",z);A!==void 0&&(r.get(z)===!0?s.terminal.line_run("ls"):u(z,A,T))},w=(z,T)=>{e.askOnPane_await(z,{message:`New directory in ${T}: `,kind:"text",commit:"MAKE IT"}).then(A=>{const E=(A??"").trim();E!==""&&(s.terminal.line_run(`mkdir "${T}/${E}"`),m(z,T))})},y=async(z,T,A)=>{for(const E of A){const O=`${T}/${E.name}`;s.terminal.line_note(`putting ${E.name} in ${T}…`);try{const R=await fetch(e.vfsUrl_build(O),{method:"POST",body:E});if(!R.ok){s.terminal.line_note(`upload: ${E.name}: ${(await R.text()).trim()||R.statusText}`);continue}s.terminal.line_note(`✓ ${O}`)}catch(R){s.terminal.line_note(`upload: ${E.name}: ${R instanceof Error?R.message:String(R)}`)}}m(z,T)},M=(z,T,A)=>{if(A.kind==="dir"){r.get(z)===!0?s.terminal.line_run(`cd "${A.path}"`):p(z,T,A.path);return}if(A.kind==="plugin"||A.kind==="pipeline"){e.binEntry_show(z,T,A.path,A.kind);return}if(zx(A.path)){e.image_open(z,A.path).then(E=>s.terminal.line_note(E));return}if(i.regard_write(z,{address:A.path,modelKind:"fs.file"}),!i.groupHasViewer(z)){if(tu(A.path)){T.contentImage_show(A.path,e.vfsUrl_build(A.path));return}l(A.path).then(E=>{if(!E.ok){T.contentRefused_show(A.path,E.text);return}Sx.test(A.path)?T.contentTable_show(A.path,E.text):T.content_show(A.path,E.text)})}},v=()=>{const z=e.template_stamp("tpl-pane-files").querySelector(".files-body");if(z===null)throw new Error("tpl-pane-files has no files-body");return z},S=(z,T,A)=>{const E=`"${A}"`,O=T.type==="dir"||T.type==="vfs"||T.type==="job",R=Fl(A),C={kind:T.type==="plugin"||T.type==="pipeline"?"catalogue":O&&Iu(A,T.name)?"seriesFolder":T.type==="file"?"file":"directory",feed:R,node:R===null?null:Fm(A),bound:e.catalogue_find(z)!==void 0,projection:uj(A),editable:T.type==="file"&&MR(A)},k={image:()=>{e.image_open(z,A).then(G=>s.terminal.line_note(G))},download:()=>a(A),link:()=>{const G=qy(window.location.origin,A);(t.get("files",z)?.link_copy(A)??navigator.clipboard.writeText(G).then(()=>!0,()=>!1)).then(W=>s.terminal.line_note(W?`link copied: ${G}`:`link (copy it): ${G}`))},process:()=>e.process_open(z,{input:A,feed:R,node:R===null?null:Fm(A)}),gather:()=>e.cohort_gather([{kind:O?"dir":"file",seriesUID:A,description:T.name,imagery:Iu(A,T.name),modality:Iu(A,T.name)?"MR":"—",patient:e.promptUser()??"",vfsPath:A,folderPath:A}]),run:()=>e.run_press(z,T.name,T.type==="pipeline"?"pipeline":"plugin"),edit:()=>{const G=vx(A),L=H5(T.name,T.size,bR);if(L===null){e.verbLine_run(z,G);return}e.askOnPane_await(z,{kind:"confirm",message:L}).then(W=>{W==="y"&&e.verbLine_run(z,G)})},move:()=>e.verbLine_run(z,`mv ${E}`),copy:()=>e.verbLine_run(z,`cp ${E}`),delete:()=>e.verbLine_run(z,`rm ${O?"-ri":"-i"} ${E}`),share:()=>e.verbLine_run(z,`setfacl ${E}`)};return s1.rules.filter(G=>G.offered(C)).map(G=>({label:G.label(C),run:()=>k[G.name]?.()}))},x=(z,T)=>{const A=T.map(([k])=>k),E=A.map(k=>`"${k}"`).join(" "),O=[];for(const k of A){const G=Fl(k);G!==null&&!O.includes(G)&&O.push(G)}const R={count:A.length,feeds:O},C={delete:()=>e.verbLine_run(z,`rm -rI ${E}`),move:()=>s.terminal.line_run(`mv -t ${E}`),copy:()=>s.terminal.line_run(`cp -t ${E}`),share:()=>s.terminal.line_run(`setfacl ${O.map(k=>`feed_${k}`).join(" ")}`)};return i1.rules.filter(k=>k.offered(R)).map(k=>({label:k.label(R),run:()=>C[k.name]?.()}))};return{previewProvider:d,fileText_fetch:l,file_save:a,rootedListing_show:u,listing_refresh:m,directory_make:w,files_deliver:y,follows:z=>r.get(z)===!0,follow_set:g,cwdBind_sync_register:(z,T)=>{o.set(z,T)},cwdBind_sync:_,rooted_walk:p,rooted_back:f,filesBody_stamp:v,rowVerbs_build:S,instance_build:(z,T,A=!1)=>{const E=e.template_stamp("tpl-pane-files"),O=new Hz(e.pane_find(E,".files-panel"),C=>M(z,O,C),d,{catalogue:A});O.selectionVerbs_declare(C=>x(z,C)),O.rowVerbs_declare((C,k)=>S(z,C,k),(C,k)=>{i.regard_write(z,{address:k,modelKind:"fs.file"}),Fl(k)!==null&&s.client.line_execute(`getfacl "${k}"`,{silent:!0,observe:!1}).then(G=>{O.rowReadout_show(k,fj(G))}).catch(()=>{O.rowReadout_show(k,"ACCESS UNREAD")})}),t.set("files",z,O);const R=e.promptUser();return R!==null&&R!==""&&O.home_set(`/home/${R}`),n.set(z,[]),r.set(z,T),_(z),O.follow_set(T),{id:z,kind:"files",mount:E,dispose:()=>{t.delete(z),n.delete(z),i.pane_leave(z)}}}}}function mj(s,e){const t=sn("tpl-pane-universe"),i=new j5({canvas:Js(t,".universe-canvas"),title:Js(t,".universe-title"),state:t.querySelector(".pane-state"),empty:Js(t,".universe-empty"),projectionPill:t.querySelector(".universe-projection"),refreshPill:t.querySelector(".universe-refresh"),replayPill:t.querySelector(".universe-replay"),scalePill:t.querySelector(".universe-scale"),viewPill:t.querySelector(".universe-view"),gravityPill:t.querySelector(".universe-gravity"),densityPill:t.querySelector(".universe-density"),drawPill:t.querySelector(".universe-draw"),captionsPill:t.querySelector(".universe-captions"),arrangementPill:t.querySelector(".universe-arrangement"),facts:t.querySelector(".universe-facts"),backPill:t.querySelector(".universe-back"),openPill:t.querySelector(".universe-open"),frame:t.querySelector(".mode-frame")},{watch_set:(n,r)=>{r?s.client().watch_send(n):s.client().unwatch_send(n)},...(({feed_entered:n,feed_note:r,feed_tag:o,feed_rename:a,feed_untag:l})=>({feed_entered:n,feed_note:r,feed_tag:o,feed_rename:a,feed_untag:l}))(wx(s.context(),e,s.feedVerbs())),command_run:n=>{s.client().line_execute(n,{silent:!0,observe:!1}).then(r=>{for(const o of r.envelopes)i.envelope_observe(o)})},feed_dag:async n=>{const r=await s.client().line_execute(`feed diagram feed_${n}`,{silent:!0,observe:!1});for(const o of r.envelopes){if(o.model?.kind!==Cr.feedDag)continue;const a=Qg.safeParse(o.model.data);if(a.success)return a.data}return null},node_enter:n=>{s.terminal().line_run(`cd "${n}"`)},node_dive:n=>{s.nodeOverlay_open(e,n.replace(/\/data$/,""))},node_process:n=>{const r=Fl(n.vfsPath)??(/\/feed_(\d+)(?:\/|$)/.exec(n.vfsPath)===null?null:Number(/\/feed_(\d+)(?:\/|$)/.exec(n.vfsPath)[1])),o=s.promptUser()===null?n.vfsPath:n.vfsPath.replace(/^\/proc\/jobs\//,`/home/${s.promptUser()}/feeds/`);s.process_open(e,{input:o,feed:r,node:n.instanceId})},feed_open:n=>{s.runs_show(),s.dag_primary().feed_enter(n)},plugin_open:n=>{(async()=>{const r=await s.client().line_execute("ls /bin",{silent:!0,observe:!1}),o=[];for(const l of r.envelopes){if(l.model?.kind!=="fs.listing")continue;const c=l.model.data,h=Array.isArray(c)?c:[c];for(const d of h)for(const u of d.items??[])o.push(u.name)}const a=o.filter(l=>l.startsWith(`${n}-v`)).sort((l,c)=>l.localeCompare(c,void 0,{numeric:!0})).pop();if(a===void 0){s.terminal().line_note(`universe: ${n} is not in /bin`);return}et("gutter-files").click(),s.binEntry_show("files",s.panels().get("files","files"),`/bin/${a}`,"plugin")})().catch(r=>{s.terminal().line_note(`universe: could not open ${n} in /bin: ${r instanceof Error?r.message:String(r)}`)})},note:n=>s.terminal().line_note(n)},Vy());return s.panels().set("universe",e,i),{id:e,kind:"universe",mount:t,dispose:()=>{s.panels().delete(e),s.subjects().pane_leave(e),i.dispose()}}}function gj(s,e,t){const i=sn("tpl-pane-dag"),n=new b5(Js(i,".dag-canvas"),Js(i,".dag-title"),Js(i,".dag-facts"),Js(i,".dag-empty"),Js(i,".dag-strategy"),Js(i,".dag-feedlist"),{command_run:r=>{s.client().line_execute(r,{silent:!0,observe:!1}).then(o=>{for(const a of o.envelopes)n.envelope_observe(a)})},watch_set:(r,o)=>{o?s.client().watch_send(r):s.client().unwatch_send(r)},node_enter:r=>{s.terminal().line_run(`cd "${r}"`)},node_dive:r=>{s.nodeOverlay_open(e,r.replace(/\/data$/,""))},node_regard:r=>{s.subjects().regard_write(e,{address:r,modelKind:"feed.node"})},node_process:r=>{const o=Fl(r.vfsPath)??(/\/feed_(\d+)(?:\/|$)/.exec(r.vfsPath)===null?null:Number(/\/feed_(\d+)(?:\/|$)/.exec(r.vfsPath)[1])),a=s.promptUser()===null?r.vfsPath:r.vfsPath.replace(/^\/proc\/jobs\//,`/home/${s.promptUser()}/feeds/`);s.process_open(e,{input:a,feed:o,node:r.instanceId})},feed_regard:r=>{s.subjects().regard_write(e,{address:r,modelKind:"feed"})},...wx(s.context(),e,s.feedVerbs()),...t?{feed_shown:()=>s.dag_summon()}:{}});return s.panels().set("dag",e,n),{id:e,kind:"dag",mount:i,dispose:()=>{s.nodeOverlay().dispose(e),s.panels().delete(e),s.subjects().pane_leave(e),n.dispose()}}}function _j(s){return{universe_build:e=>mj(s,e),dag_build:(e,t)=>gj(s,e,t)}}const xx=new Set(["files"]);function bj(s){xx.add(s)}function Kv(s){return xx.has(s)}const Ox=new Map,Na=new Map;let Mj=0;function fn(s,e){Ox.set(s,e)}function vj(s){const e=Ox.get(s);if(e===void 0)throw new Error(`no pane factory registered for kind '${s}'`);const t=e(`${s}-${Mj++}`);return Na.set(t.id,t),t}function uh(s){Na.set(s.id,s)}function jh(s){return Na.get(s)}function Hh(){return[...Na.values()]}function Ds(s){const e=Na.get(s);e!==void 0&&(Na.delete(s),e.dispose?.(),e.mount.remove())}class wj{byId=new Map;set(e,t,i){this.byId.set(t,{kind:e,panel:i})}get(e,t){const i=this.byId.get(t);return i!==void 0&&i.kind===e?i.panel:void 0}has(e,t){return this.byId.get(t)?.kind===e}delete(e){return this.byId.delete(e)}ids(e){return this.entries(e).map(([t])=>t)}entries(e){const t=[];for(const[i,n]of this.byId)n.kind===e&&t.push([i,n.panel]);return t}values(e){return this.entries(e).map(([,t])=>t)}idOf(e,t){for(const[i,n]of this.byId)if(n.kind===e&&n.panel===t)return i;return null}}const yj=/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed/i;function F_(s){const e=s instanceof Error?s.message:String(s??"");return yj.test(e)}const Ma={before:"ARGUS has been updated in the background — ",refresh:"refresh",after:" this page"},Sj=`${Ma.before}${Ma.refresh}${Ma.after}`,Cd="ARGUS UPDATED IN THE BACKGROUND · REFRESH THIS PAGE";function zj(s,e=document.body){let t=!1;const i=()=>{if(t)return;t=!0,s(`argus: ${Sj} (what failed to load was part of the old build)`);const n=document.createElement("div");n.className="stale-page",n.setAttribute("role","alert");const r=document.createElement("span");r.className="stale-page-words";const o=document.createElement("button");o.type="button",o.className="stale-page-reload",o.textContent=Ma.refresh,o.title="load the argus the server has now",o.addEventListener("click",()=>{window.location.reload()}),r.append(document.createTextNode(Ma.before),o,document.createTextNode(Ma.after)),n.append(r),e.appendChild(n)};window.addEventListener("vite:preloadError",()=>{i()}),window.addEventListener("unhandledrejection",n=>{F_(n.reason)&&i()})}const xj=[{label:"",tag:"PatientName"},{label:"MRN",tag:"PatientID"},{label:"ACC",tag:"AccessionNumber"},{label:"",tag:"StudyDescription"},{label:"",tag:"SeriesDescription"},{label:"",tag:"StudyDate"},{label:"",tag:"PatientAge"},{label:"",tag:"PatientSex"}],Oj=256*1024*1024;function fh(s){const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1024&&i<e.length-1;)t/=1024,i++;return i===0?`${s} B`:`${t.toFixed(1)} ${e[i]}`}function Ej(s){const e=s.toUpperCase();return e==="MR"||e==="CT"||e==="PT"?e:"OT"}class Aj{pane;field;title;modeSpan;stateSpan;layoutPills=new Map;overlayPill;colormapPill;savePill;loadPill;retryPill;presetPill;focusMark;guardBytes=Oj;forced=!1;pendingLayout=null;progressNote=null;overlayNote=null;probeNote=null;overlay=!1;overlayLines=[];presetIndex=-1;toolPills=new Map;handlers;engine=null;series=null;siblings=[];colormap="gray";tool="wl";constructor(e,t){this.handlers=t,this.pane=e,this.field=mi(e,".image-field"),this.title=mi(e,".pane-title"),this.modeSpan=mi(e,".pane-mode"),this.stateSpan=mi(e,".pane-state");for(const i of e.querySelectorAll(".image-layout")){const n=i.dataset.layout??"single";this.layoutPills.set(n,i),i.addEventListener("click",()=>{this.layout_set(n)})}this.overlayPill=mi(e,".image-overlay"),this.overlayPill.addEventListener("click",()=>{this.overlay_set(!this.overlay)}),this.colormapPill=mi(e,".image-colormap"),this.savePill=mi(e,".image-save"),this.loadPill=mi(e,".image-load"),this.retryPill=mi(e,".image-retry"),this.presetPill=mi(e,".image-preset"),this.focusMark=mi(e,".image-focus"),this.field.tabIndex=0,this.colormapPill.addEventListener("click",()=>{this.colormap_cycle()}),this.savePill.addEventListener("click",()=>{this.annotations_save()}),this.loadPill.addEventListener("click",()=>{this.load_press()}),this.retryPill.addEventListener("click",()=>{this.retry_press()}),this.presetPill.addEventListener("click",()=>this.preset_cycle()),mi(e,".image-tags").addEventListener("click",()=>this.handlers.tags_open());for(const i of w0){const n=mi(e,`.image-tool[data-tool="${i}"]`);this.toolPills.set(i,n),n.addEventListener("click",()=>{this.tool_set(i)})}this.toolPills_paint(),this.field.addEventListener("mousedown",()=>{this.field.focus(),this.focusMark_paint(!0)}),this.field.addEventListener("focusin",()=>this.focusMark_paint(!0)),this.field.addEventListener("focusout",i=>{(!(i.relatedTarget instanceof Node)||!this.field.contains(i.relatedTarget))&&this.focusMark_paint(!1)}),this.field.addEventListener("keydown",i=>{if(i.key==="Escape"){this.field_release(),i.stopPropagation();return}i.stopPropagation()})}field_hasFocus(){return document.activeElement instanceof Node&&this.field.contains(document.activeElement)}field_release(){return this.field_hasFocus()?(document.activeElement.blur(),this.focusMark_paint(!1),!0):!1}async series_show(e,t={}){if(this.engine_dispose(),this.series=e,this.forced=t.force===!0,this.pendingLayout=null,this.loadPill.hidden=!0,this.retryPill.hidden=!0,this.presets_paint(e.modality),this.siblings=t.siblings??[],this.pane.dataset.modality=Ej(e.modality),this.title.textContent=`IMAGE ${e.modality.toUpperCase()} ${e.seriesDescription}`.trim(),this.title.title=this.title.textContent,this.siblings.length>1){const o=this.siblings.findIndex(a=>a.path===e.path)+1;this.handlers.note(`image: series ${o} of ${this.siblings.length} in this study; image series <n> switches`)}const i=await this.chunk_import(()=>Xl(()=>import("./cornerstoneEngine-BZwM3FCO.js").then(o=>o.b2),__vite__mapDeps([0,1,2,3]),import.meta.url));if(i===null)return;const{CornerstoneEngine:n}=i,r=new n(this.engineHost_get(),e,t.startAt??1);await this.engine_open(r),this.engine===r&&(this.guard_trips()?(this.loadPill.hidden=!1,this.stateSpan.textContent=`SERIES ${fh(e.bytes)} · LOAD FOR STACK`,this.handlers.note(`image: ${fh(e.bytes)} to fetch before the stack scrolls; press LOAD, image load, or image --force <path>`)):r.slices_fill(),await this.annotations_reload(r,e))}async annotations_reload(e,t){let i=0;for(const n of t.annotations.filter(r=>/\.dcm$/i.test(r))){if(this.engine!==e)return;const r=n.split("/").pop()??n;try{const o=await fetch(this.handlers.source.url_resolve(n));if(!o.ok){this.handlers.note(`image: ${r}: HTTP ${o.status}`);continue}const a=await e.annotations_import(await o.arrayBuffer());i+=a,this.handlers.note(a>0?`image: ${a} measurement${a===1?"":"s"} from ${r}`:`image: ${r}: no measurements this engine can place`)}catch(o){this.handlers.note(`image: ${r}: ${o instanceof Error?o.message:String(o)}`)}}this.pane.dataset.annotations=String(i)}async volume_show(e){this.engine_dispose(),this.series=null,this.siblings=[],this.pane.dataset.modality="NIFTI",this.title.textContent=`IMAGE ${e.split("/").pop()??""}`,this.title.title=e,this.forced=!0,this.loadPill.hidden=!0,this.retryPill.hidden=!0,this.presets_paint("NIFTI");const t=await this.chunk_import(()=>Xl(()=>import("./niivueEngine-CDj3oRPj.js"),__vite__mapDeps([4,1]),import.meta.url));if(t===null)return;const{NiivueEngine:i}=t;await this.engine_open(new i(this.engineHost_get(),e))}async chunk_import(e){try{const t=await e();if(t!==void 0)return t}catch(t){if(!F_(t))throw t}return Ts(this.stateSpan,"stale",Cd),this.handlers.note(`image: ${Cd.toLowerCase()} — the viewer's code is of an older build than the server has`),null}opening_show(e){const t=e.replace(/\/$/,"").split("/").pop()??e;this.stateSpan.textContent="OPENING",this.progress_show({label:`OPENING ${t}`,done:0,total:0})}opening_fail(e,t){this.stateSpan.textContent=t,this.progress_show({label:t,done:0,total:0});const i=this.progressNote;i!==null&&(i.classList.add("image-working-failed"),i.querySelector(".image-working-count").textContent=e)}siblings_get(){return this.siblings}series_get(){return this.series}state_get(){return this.engine===null?null:{...this.engine.state_get(),colormap:this.colormap,path:this.series?.path??null,guard:this.guardBytes,waiting:this.pendingLayout}}async layout_set(e){if(this.engine===null)return!1;if(e!=="single"&&this.guard_trips())return this.pendingLayout=e,this.loadPill.hidden=!1,this.stateSpan.textContent=`SERIES ${fh(this.series?.bytes??0)} · LOAD FOR ${e.toUpperCase()}`,this.handlers.note(`image: ${fh(this.series?.bytes??0)} to fetch for ${e}; press LOAD, image load, or image --force <path>`),!1;const t=this.engine.state_get().layout;return this.layoutPills_paint(e),this.modeSpan.textContent=e==="single"?"":e.toUpperCase(),this.overlay_hide(),await this.engine.layout_set(e)?(this.progress_show(null),this.overlay_paint(),this.toolPills_paint(),!0):(this.progress_show(null),this.layoutPills_paint(t),this.modeSpan.textContent=t==="single"?"":t.toUpperCase(),this.handlers.note(`image: layout ${e}: not offered by ${this.engine.name}`),!1)}layoutPills_paint(e){for(const[t,i]of this.layoutPills)i.classList.toggle("rail-off",t!==e)}guard_trips(){return this.guardBytes!==null&&!this.forced&&this.engine?.name==="cornerstone"&&(this.series?.bytes??0)>this.guardBytes}async load_press(){this.forced=!0,this.loadPill.hidden=!0,this.retryPill.hidden=!0;const e=this.pendingLayout;return this.pendingLayout=null,e!==null?this.layout_set(e):this.engine===null||this.engine.state_get().filled?!1:this.engine.slices_fill()}guard_set(e){this.guardBytes=e}guard_get(){return this.guardBytes}preset_cycle(){const e=this.presets_select(this.series?.modality??"NIFTI");if(e.length===0)return;this.presetIndex=(this.presetIndex+1)%e.length;const t=e[this.presetIndex];t!==void 0&&this.wl_set(t.lower,t.upper)&&(this.presetPill.textContent=t.name.toUpperCase())}presets_select(e){const t=e.toUpperCase();return yz.filter(i=>i.modalities.length===0||i.modalities.includes(t))}presets_paint(e){this.presetIndex=-1;const t=this.presets_select(e);this.presetPill.hidden=t.length===0,this.presetPill.textContent="PRESET"}slice_set(e){if(this.engine===null)return!1;const t=this.engine.slice_set(e);return t||this.handlers.note(`image: slice ${e}: not offered in ${this.engine.state_get().layout} layout by ${this.engine.name}`),t}wl_set(e,t){if(this.engine===null)return!1;const i=this.engine.wl_set(e,t);return i||this.handlers.note(`image: wl: not offered by ${this.engine.name}`),i}ghost_set(e){if(this.engine===null)return!1;const t=this.engine.ghost_set(e);return t||this.handlers.note("image: ghost applies to the SLAB layout"),t}wlPreset_set(e){const t=this.series?.modality??"NIFTI",i=r7(e,t);return i===void 0?(this.handlers.note(`image: wl preset ${e}: none for ${t}`),!1):this.wl_set(i.lower,i.upper)}colormap_set(e){return this.engine===null?!1:this.engine.colormap_set(e)?(this.colormap=e,this.colormapPill.textContent=e.toUpperCase(),!0):(this.handlers.note(`image: colormap ${e}: not offered by ${this.engine.name}`),!1)}tool_set(e){return this.engine===null?!1:this.engine.tool_set(e)?(this.tool=e,this.toolPills_paint(),!0):(this.handlers.note(`image: ${e}: not offered by ${this.engine.name}`),!1)}async annotations_save(){if(this.engine===null)return!1;const e=this.series?.seriesInstanceUID,t=/^(\/home\/[^/]+)\//.exec(this.series?.path??"")?.[1];if(e===void 0||t===void 0)return this.handlers.note("image: save: this series has no UID to file an annotation under"),!1;const i=await this.engine.annotations_export();if(i===null)return this.handlers.note(`image: save: nothing measured, or ${this.engine.name} writes no report`),!1;const n=`${t}/annotations/${e}/measurements.dcm`,r=await this.handlers.file_put(n,i);return this.handlers.note(r===200?`✓ ${n}`:`image: save: ${n}: HTTP ${r}`),r===200}dispose(){this.engine_dispose()}async colormap_cycle(){const e=Ch[(Ch.indexOf(this.colormap)+1)%Ch.length]??"gray";this.colormap_set(e)}async engine_open(e){this.engine=e,this.field.replaceChildren(),this.progressNote=null,this.overlayNote=null,this.probeNote=null,this.layoutPills_paint("single"),this.modeSpan.textContent="",this.colormapPill.textContent=this.colormap.toUpperCase();try{await e.open(this.field)}catch(i){this.stateSpan.textContent="REFUSED",this.handlers.note(`image: ${i instanceof Error?i.message:String(i)}`);return}const t=e.state_get().layout;this.layoutPills_paint(t),this.modeSpan.textContent=t==="single"?"":t.toUpperCase(),e.tool_set(this.tool),this.toolPills_paint(),this.progress_show(null),this.overlay_fill()}engine_dispose(){this.engine?.dispose(),this.engine=null,this.progressNote=null,this.overlayNote=null,this.probeNote=null,this.field.replaceChildren(),this.stateSpan.textContent=""}retryPill_paint(){const e=this.engine===null?0:this.engine.state_get().refused,t=this.engine?.refused_retry!==void 0;this.retryPill.hidden=!t||e===0,this.retryPill.disabled||(this.retryPill.textContent=`RETRY ${e}`)}async retry_press(){if(!(this.engine?.refused_retry===void 0||this.retryPill.disabled)){this.retryPill.disabled=!0,this.retryPill.textContent="ASKING…";try{await this.engine.refused_retry()}finally{this.retryPill.disabled=!1,this.retryPill_paint()}}}engineHost_get(){return{source:this.handlers.source,readout_set:e=>{this.stateSpan.textContent=e,this.retryPill_paint()},progress_set:e=>this.progress_show(e),note:this.handlers.note,regard:e=>{this.handlers.regard(e),this.overlaySlice_paint()},probe_set:e=>this.probe_show(e)}}probe_show(e){if(e===null){this.probeNote?.remove(),this.probeNote=null;return}if(this.probeNote===null||this.probeNote.parentElement===null){const t=document.createElement("div");t.className="image-probe-note",this.field.appendChild(t),this.probeNote=t}this.probeNote.textContent=e}overlaySlice_paint(){const e=this.overlayNote?.querySelector(".image-overlay-slice")??null;if(e===null||this.engine===null)return;const t=this.engine.state_get();e.textContent=t.slices>1?`SLICE ${Math.max(1,t.slice)} OF ${t.slices}`:"",e.hidden=t.slices<=1}progress_show(e){if(e===null){this.progressNote?.remove(),this.progressNote=null;return}if(this.progressNote===null||this.progressNote.parentElement===null){const o=document.createElement("div");o.className="image-working",o.innerHTML='<span class="image-working-label"></span><span class="image-working-track"><span class="image-working-fill"></span></span><span class="image-working-count"></span>',this.field.appendChild(o),this.progressNote=o}const t=this.progressNote;t.classList.remove("image-working-failed");const i=e.total>0,n=i?Math.min(1,e.done/e.total):0;t.querySelector(".image-working-label").textContent=e.label,t.querySelector(".image-working-count").textContent=i?`${e.done} / ${e.total} · ${Math.round(n*100)}%`:"";const r=t.querySelector(".image-working-fill");r.classList.toggle("image-working-pacing",!i),r.style.width=i?`${Math.round(n*100)}%`:""}async overlay_set(e){if(this.overlay=e,this.overlayPill.textContent=e?"OVERLAY ON":"OVERLAY OFF",this.overlayPill.classList.toggle("rail-off",!e),!e){this.overlay_hide();return}await this.overlay_fill()}overlay_hide(){this.overlayNote?.remove(),this.overlayNote=null}async overlay_fill(){if(!this.overlay||this.series===null)return;const e=this.series.files[0]??this.series.path,t=await this.handlers.tags_read(e);if(t===null){this.handlers.note(`image: overlay: ${e}: no header to read`);return}this.overlayLines=xj.flatMap(i=>{const r=(t.constant.find(o=>o.name===i.tag)?.value??"").trim();return r===""?[]:[i.label===""?r:`${i.label} ${r}`]}),this.overlay_paint()}overlay_paint(){if(!this.overlay||this.overlayLines.length===0)return;this.overlay_hide();const e=document.createElement("div");e.className="image-overlay-note";const t=document.createElement("span");t.className="image-overlay-slice",e.appendChild(t);for(const i of this.overlayLines){const n=document.createElement("span");n.textContent=i,e.appendChild(n)}this.field.appendChild(e),this.overlayNote=e,this.overlaySlice_paint()}toolPills_paint(){const e=new Set(this.engine?.toolsOffered_get()??w0),t=this.engine!==null?this.engine.state_get().primaryTool:this.tool;for(const[i,n]of this.toolPills){const r=e.has(i);n.classList.toggle("rail-na",!r),n.classList.toggle("rail-off",r&&i!==t),n.disabled=!r}}focusMark_paint(e){this.focusMark.hidden=!e,this.pane.classList.toggle("image-field-focused",e)}}function mi(s,e){const t=s.querySelector(e);if(t===null)throw new Error(`image pane: missing ${e}`);return t}const Ex=["patient","study","series","image","equipment","meta","private","other","varying"],Tj=new Set(["meta","private"]),Yv="••••";class Dj{pane;title;modeSpan;redactBlock;listing;handlers;redact=!0;model=null;groups=[];constructor(e,t){this.handlers=t,this.pane=e,this.title=ph(e,".pane-title"),this.modeSpan=ph(e,".pane-mode"),this.redactBlock=ph(e,".tags-redact"),this.redactBlock.addEventListener("click",()=>this.redact_set(!this.redact));const i=ph(e,".tags-panel");this.listing=new sr({mount:i,traits:this.groupTraits_declare(),key:n=>n.group,chrome:{root:e,prefix:"tags"},caps:"root",row:{className:()=>"tags-group-row",groupClassName:n=>`tags-group tags-group-${n.group}`,decorate:n=>{n.title="fold this group open or shut (it keeps its place)"}},child:ma(n=>n.rows,{traits:this.tagTraits_declare(),key:n=>n.key,activatable:n=>n.items.length>0,row:{className:n=>`tags-row${n.phi?" tags-phi":""}`,groupClassName:()=>"tags-sequence",decorate:(n,r)=>{n.title=r.items.length>0?`${r.name}: fold the sequence open or shut`:`${r.tag} ${r.name}`}},child:ma(n=>n.items,{traits:this.itemTraits_declare(),key:n=>n.key,row:{className:()=>"tags-item-row",groupClassName:()=>"tags-item"},child:ma(n=>n.rows,{traits:this.tagTraits_declare(),key:n=>n.key,activatable:()=>!1,row:{className:n=>`tags-row tags-row-deep${n.phi?" tags-phi":""}`}})})}),state:n=>this.stateLine_compose(n),empty:()=>kj("NO TAGS")}),this.redactBlock_paint(),this.listing.rows_set([],{field:"tags"})}model_show(e){this.model=e,this.title.textContent=`TAGS ${Cj(e)}`,this.pane.dataset.modality=Rj(e),this.groups=Ij(e),this.listing.rows_set([{key:e.path,rows:this.groups}],{field:e.path}),this.listing.open_set(0,this.groups.map(t=>t.group).filter(t=>!Tj.has(t))),this.modeSpan.textContent=e.subject==="folder"?"FOLDER":""}path_get(){return this.model?.path??null}redact_get(){return this.redact}redact_set(e){this.redact=e,this.redactBlock_paint(),this.model!==null&&this.listing.rows_set([{key:this.model.path,rows:this.groups}],{field:this.model.path})}filter_set(e){if(e===null){this.listing.filter_toggle(!1);return}this.listing.filter_toggle(!0),this.listing.filter_set(e)}stateLine_compose(e){const t=this.groups.reduce((n,r)=>n+r.rows.length,0),i=[];return this.model!==null&&this.model.subject==="folder"&&(i.push(this.model.read===this.model.of?`${this.model.read} FILES`:`${this.model.read} OF ${this.model.of} FILES`),this.model.refused.length>0&&i.push(`REFUSED ${this.model.refused.length}`)),i.push(e.filter!==""?e.filter:`${t} TAGS`),this.redact&&i.push("REDACTED"),i.join(" · ")}redactBlock_paint(){this.redactBlock.textContent=this.redact?"REDACT ON":"REDACT OFF",this.redactBlock.classList.toggle("rail-off",!this.redact),this.pane.classList.toggle("tags-redacted",this.redact)}value_cell(e){const t=document.createElement("span");if(t.className="tags-value",e.phi&&this.redact)return t.textContent=Yv,t.title="identifying value, redacted; the REDACT block on the frame reveals it",t;if(t.textContent=e.value,e.decoded!==void 0){const i=document.createElement("span");i.className="tags-decoded",i.textContent=` ${e.decoded}`,t.appendChild(i)}if(e.distinct!==void 0){const i=document.createElement("span");i.className="tags-decoded",i.textContent=` (${e.distinct} distinct)`,t.appendChild(i)}return t}groupTraits_declare(){return[Cf(()=>!0),{key:"group",label:"GROUP",className:"tags-group-name",width:"minmax(12em, 1fr)",cell:e=>e.group.toUpperCase(),compare:e=>Ex.indexOf(e.group)},{key:"count",label:"TAGS",className:"tags-group-count",width:"5em",cell:e=>String(e.rows.length),compare:e=>e.rows.length}]}tagTraits_declare(){return[Cf(e=>e.items.length>0),{key:"tag",label:"TAG",className:"tags-tag",width:"7em",cell:e=>e.tag,compare:e=>e.tag},{key:"name",label:"NAME",className:"tags-name",width:"minmax(8em, 1.4fr)",cell:e=>e.name,compare:e=>e.name.toLowerCase()},{key:"vr",label:"VR",className:"tags-vr",width:"2.4em",cell:e=>e.vr,compare:e=>e.vr},{key:"value",label:"VALUE",className:"tags-value-cell",width:"minmax(6em, 2fr)",cell:e=>this.value_cell(e),compare:e=>(e.phi&&this.redact?Yv:`${e.value} ${e.decoded??""}`).toLowerCase()}]}itemTraits_declare(){return[Cf(()=>!0),{key:"item",label:"ITEM",className:"tags-item-name",width:"minmax(12em, 1fr)",cell:e=>`ITEM ${e.index}`,compare:e=>e.index},{key:"count",label:"TAGS",className:"tags-group-count",width:"5em",cell:e=>String(e.rows.length),compare:e=>e.rows.length}]}}function Cf(s){return{key:"fold",label:"",className:"tags-fold",capped:!1,width:"1.4em",cell:e=>{const t=document.createElement("span");return t.className=s(e)?"tags-fold":"tags-fold tags-fold-none",t}}}function Ij(s){const e=new Map;for(const t of s.constant){const i=t.group;e.has(i)||e.set(i,[]),e.get(i)?.push(Ax(t,`${i}/${t.tag}`))}return s.varying.length>0&&e.set("varying",s.varying.map(t=>({tag:t.tag,name:t.name,vr:t.vr,value:t.distinct===1?t.first:`${t.first} .. ${t.last}`,phi:t.phi,items:[],distinct:t.distinct,key:`varying/${t.tag}`}))),Ex.filter(t=>e.has(t)).map(t=>({group:t,rows:e.get(t)??[]}))}function Ax(s,e){return{tag:s.tag,name:s.name,vr:s.vr,value:s.value,...s.decoded!==void 0?{decoded:s.decoded}:{},phi:s.phi,items:(s.items??[]).map((t,i)=>({index:i+1,key:`${e}/${i+1}`,rows:t.map(n=>Ax(n,`${e}/${i+1}/${n.tag}`))})),key:e}}function Cj(s){const e=s.path.replace(/\/$/,"").split("/").pop()??s.path;if(s.subject==="folder")return e.length>24?`${e.slice(0,22)}…`:e;const t=/^(\d+)-/.exec(e)?.[1];return t!==void 0?`INSTANCE ${Number(t)}`:e.length>24?`${e.slice(0,22)}…`:e}function Rj(s){const e=(s.constant.find(t=>t.name==="Modality")?.value??"").toUpperCase();return e==="MR"||e==="CT"||e==="PT"?e:"OT"}function kj(s){const e=document.createElement("div");return e.className="tags-note",e.textContent=s,e}function ph(s,e){const t=s.querySelector(e);if(t===null)throw new Error(`tags pane: missing ${e}`);return t}function Nj(s,e){const t=sn("tpl-pane-image"),i=new Aj(t,{source:{url_resolve:n=>s.vfsUrl_build(n)},note:n=>s.terminal().line_note(n),regard:n=>s.subjects().regard_write(e,{address:n,modelKind:"dicom.instance"}),file_put:async(n,r)=>{try{return(await fetch(s.vfsUrl_build(n),{method:"POST",body:r})).status}catch{return 0}},tags_read:n=>U_(s,n),tags_open:()=>{s.terminal().line_note(Tx(s,e))}});return s.panels().set("image",e,i),{id:e,kind:"image",mount:t,dispose:()=>{i.dispose(),s.panels().delete(e),s.subjects().pane_leave(e)}}}function Bj(s,e){const t=sn("tpl-pane-tags"),i=new Dj(t,{note:n=>s.terminal().line_note(n)});return s.panels().set("tags",e,i),{id:e,kind:"tags",mount:t,dispose:()=>{s.panels().delete(e),s.subjects().pane_leave(e)}}}async function U_(s,e){try{const t=await s.client().line_execute(`dcm tags "${e}"`,{silent:!0,observe:!1});for(const i of t.envelopes){if(i.model?.kind!==ua.tags)continue;const n=iz.safeParse(i.model.data);if(n.success)return n.data}}catch{}return null}function Gj(s,e,t){const i=s.panels().get("tags",e);i===void 0||i.path_get()===t||U_(s,t).then(n=>{if(n===null){s.terminal().line_note(`tags: ${t}: not a readable DICOM file`);return}s.panels().get("tags",e)?.model_show(n)})}function Tx(s,e){const t=new Set(s.layout().panes_shown()),i=s.subjects().group_resolve(e);for(const r of s.panels().ids("tags"))if(t.has(r)&&s.subjects().group_resolve(r)===i)return s.layout().focus_set(r),"image tags";if(!t.has(e))return"image tags: the image pane is not on stage";const n=s.instance_spawn("tags",e);return s.layout().leaf_split(e,s.desktop().replayPlace_get()?.dir??"col",n.id,s.desktop().replayPlace_get()?.before??!1)?(s.birth_record(n.id,e,s.desktop().replayPlace_get()?.dir??"col",s.desktop().replayPlace_get()?.before??!1),"image tags"):(Ds(n.id),s.layout().mount_remove(n.id),"image tags: could not open beside the image pane")}async function Um(s,e){try{const t=await s.client().line_execute(`dcm series "${e}"`,{silent:!0,observe:!1});for(const i of t.envelopes){if(i.model?.kind!==ua.series)continue;const n=nz.safeParse(i.model.data);if(n.success)return n.data}}catch{}return null}async function Dx(s,e){try{const t=await s.client().line_execute(`ls "${e}"`,{silent:!0,observe:!1});for(const i of t.envelopes){if(i.model?.kind!=="fs.listing")continue;const n=i.model.data,r=(Array.isArray(n)?n[0]:n)??{},o=(r.path??e).replace(/\/$/,"");return(r.items??[]).filter(a=>a.type==="dir").map(a=>`${o}/${a.name}`)}}catch{}return[]}function Ix(s,e,t){const i=l=>{t!==void 0&&s.subjects().regard_write(l,t)};if(e!==null&&s.panels().has("image",e))return i(e),s.panels().get("image",e)??null;const n=new Set(s.layout().panes_shown());if(t!==void 0){for(const[l,c]of s.panels().entries("image"))if(n.has(l)&&s.subjects().regard_get(l)?.address===t.address)return i(l),c}const r=e!==null?s.subjects().group_resolve(e):null;for(const[l,c]of s.panels().entries("image"))if(n.has(l)&&r!==null&&s.subjects().group_resolve(l)===r)return c;const o=e!==null&&n.has(e)?e:s.errandHost_find();if(o===null)return null;const a=s.instance_spawn("image",e??void 0);return s.layout().leaf_split(o,s.desktop().replayPlace_get()?.dir??"col",a.id,s.desktop().replayPlace_get()?.before??!1)?(s.birth_record(a.id,o,s.desktop().replayPlace_get()?.dir??"col",s.desktop().replayPlace_get()?.before??!1),i(a.id),s.panels().get("image",a.id)??null):(Ds(a.id),s.layout().mount_remove(a.id),null)}async function Pj(s,e,t,i={},n){s.launcher_yield();const r=e!==null?void 0:Bp.test(t)?{address:t,modelKind:"image.volume"}:{address:_d.test(t)?t.slice(0,t.lastIndexOf("/")):t.replace(/\/$/,""),modelKind:"dicom.series"},o=Ix(s,e,r);if(o===null)return"image: no pane to open beside";const a=s.panels().idOf("image",o);if(a!==null&&n?.(a),Bp.test(t))return o.opening_show(t),o.volume_show(t),`image ${t}`;const l=_d.test(t),c=l?t.slice(0,t.lastIndexOf("/")):t.replace(/\/$/,"");o.opening_show(c);let h=await Um(s,c),d=[];if(h===null&&!l){const p=(await Dx(s,c)).slice(0,32);for(const f of p){const _=await Um(s,f);if(_!==null){d=p.map(g=>({path:g,label:g.split("/").pop()??g})),h=_;break}}}if(h===null)return o.opening_fail(t,"NOT A READABLE SERIES"),`image: ${t}: not a readable DICOM series, study, or volume`;const u=l?Math.max(1,h.files.indexOf(t)+1):1;return o.series_show(h,{siblings:d,startAt:u,...i.force===!0?{force:!0}:{}}),`image ${h.path}${d.length>1?` (1 of ${d.length} series)`:""}`}function Lj(s){return{imageInstance_build:e=>Nj(s,e),tagsInstance_build:e=>Bj(s,e),tags_ask:e=>U_(s,e),tagsPane_follow:(e,t)=>Gj(s,e,t),tagsPane_open:e=>Tx(s,e),series_ask:e=>Um(s,e),subfolders_ask:e=>Dx(s,e),imagePane_resolve:(e,t)=>Ix(s,e,t),image_open:(e,t,i={},n)=>Pj(s,e,t,i,n)}}function Wj(s){return{primaries:[s.panes.dag_build("dag",!0),s.panes.universe_build("universe"),{id:"pacs",kind:"pacs",mount:s.pacsMount}],domains:["dag","pacs"],presets:[["pacs",()=>({pane:"pacs"})],["dag",()=>({pane:"dag"})],["universe",()=>({pane:"universe"})]],factories:[["dag",e=>s.panes.dag_build(e,!1)],["universe",s.panes.universe_build],["image",s.dicom.imageInstance_build],["tags",s.dicom.tagsInstance_build],["gather",s.gather_build]]}}function Fj(s){return async()=>{const e=await s.ask("proc feeds");let t=[];for(const u of e.envelopes){const p=u.model;if(p===void 0||p.kind!==Op)continue;const f=xp.safeParse(p.data);f.success&&(t=f.data.feeds)}const n=t.length===0&&e.envelopes.some(u=>u.status==="error")?"INDEX WARMING":`${t.length} FEEDS`,r=t.filter(u=>/error/i.test(u.status)).length,o=t.filter(u=>/running|scheduled|created|started/i.test(u.status)).length,a={key:"universe",name:"UNIVERSE",hue:"--honey",numeral:"",figures:[{text:n}],rows:[],verb:"SEE THE SPACE",about:Si.universe,enter:()=>s.universe_show()},l={key:"analyses",name:"ANALYSES",hue:"--october-sunset",numeral:"3",figures:[{text:n},...o>0?[{text:`${o} RUNNING`}]:[],...r>0?[{text:`${r} ERRORED`,errored:!0,open:()=>s.runs_show("status:error")}]:[]],rows:t.slice(0,6).map(u=>({text:`${u.id} ${u.title}`,errored:/error/i.test(u.status),open:()=>s.feed_enter(u.id)})),verb:"OPEN THE ROSTER",about:Si.analyses,enter:()=>s.runs_show()},c=s.pacs_query(),h={key:"pacs",name:"PACS",hue:"--daybreak",numeral:"4",figures:[{text:c===""?"NO ANSWER":"ANSWERED"}],rows:c===""?[{text:"pacs query PatientID:…",open:()=>s.line_offer("pacs query PatientID:")},{text:"pacs query AccessionNumber:…",open:()=>s.line_offer("pacs query AccessionNumber:")}]:[{text:c.slice(0,48)}],verb:"ASK A PACS",about:Si.pacs,enter:()=>s.pacs_open()},d=s.cloud_enter===null?null:{key:"cloud",name:"CLOUD",hue:"--daybreak",numeral:"",figures:[{text:"OCI"}],rows:[{text:"entered as READ · look only",open:s.cloud_enter},{text:"MANAGE · asks your password when a line would act",open:s.cloud_enter}],verb:"ENTER CLOUD MANAGEMENT",about:Si.cloud,enter:s.cloud_enter};return{lead:{tile:l,weight:t.length},afterFiles:[h],afterPanes:d===null?[a]:[a,d],about:{files:{text:"Your ChRIS home: uploads, results and what others shared with you."}}}}}const Cx=[["chris user add","users"],["chris deploy","chris deploy"],["net new","net new"],["net build","net build"],["vm new","vm new"],["vm build","vm build"]],Xv=/^--[a-z][a-z0-9-]*$/,Uj=["changed","not yet","ready","done"];function $_(s){const e=[];let t="",i=null,n=!1;for(const r of s){if(i!==null){r===i?i=null:t+=r;continue}if(r==="'"||r==='"'){i=r,n=!0;continue}if(/\s/.test(r)){(t!==""||n)&&e.push(t),t="",n=!1;continue}t+=r}return(t!==""||n)&&e.push(t),e}function Zv(s){return s===""?"''":/[\s'"]/.test(s)?`'${s.replace(/'/g,"'\\''")}'`:s}function j_(s){const e=$_(s);for(const[t,i]of Cx)if(t.split(" ").every((r,o)=>e[o]===r))return i;return"other"}function Hn(s){const e=$_(s),t=j_(s),i=t==="other"?Math.min(1,e.length):Cx.find(([,a])=>a===t)?.[0].split(" ").length??1,n=e.slice(0,i);let r=null;const o=[];for(let a=i;a<e.length;a++){const l=e[a];if(Xv.test(l)){const c=e[a+1];c!==void 0&&!Xv.test(c)?(o.push([l,c]),a++):o.push([l,""])}else r===null&&(r=l)}return{verb:n,subject:r,options:o}}function H_(s){const e=[...s.verb];s.subject!==null&&e.push(Zv(s.subject));for(const[t,i]of s.options)e.push(t),i!==""&&e.push(Zv(i));return e.join(" ")}function mh(s,e,t){const i=Hn(s),n=i.options.filter(([r])=>r!==e);if(t!==""){const r=i.options.findIndex(([o])=>o===e);r===-1?n.push([e,t]):n.splice(r,0,[e,t])}return H_({...i,options:n})}function wn(s,e){return Hn(s).options.find(([t])=>t===e)?.[1]??null}function $j(s){for(const e of Uj)if(s.some(t=>t.state===e))return e;return null}function jj(s){const e=j_(s);return e==="users"?"USERS":e!=="other"?e.toUpperCase():$_(s).slice(0,2).join(" ").toUpperCase()||"—"}function Vh(s){const e=[];let t=null;for(const i of s){const n=j_(i.text);if(n==="users"){t===null?(t=[i],e.push({key:"users",label:"USERS",kind:n,lines:t,state:null,running:null})):t.push(i);continue}e.push({key:`line-${i.number}`,label:jj(i.text),kind:n,lines:[i],state:i.state,running:i.running})}return e.map(i=>({...i,state:$j(i.lines),running:i.lines.find(n=>n.running!==null)?.running??null}))}function qh(s){return s.find(e=>e.running!==null)}function Hj(s){return s==="net build"||s==="vm build"||s==="chris deploy"||s==="users"}function Kh(s,e){return s.split(`
|
|
4348
|
+
`);return{ok:!1,text:E===""?"the session refused this read and said nothing further":E}}),c=async(z,T)=>{const A=await fetch(e.vfsUrl_build(z));if(!A.ok||A.body===null)return(await l(z)).text.slice(0,T);const E=A.body.getReader(),O=new TextDecoder;let R="";for(;R.length<T;){const{done:C,value:k}=await E.read();if(C)break;R+=O.decode(k,{stream:!0})}return E.cancel().catch(()=>{}),R.slice(0,T)},h=async z=>{const T=/_id(\d+)$/.exec(z)?.[1]??z.replace(/^.*\//,""),A=await s.client.line_execute(`pipeline diagram ${T}`,{silent:!0,observe:!1});for(const E of A.envelopes){if(E.model?.kind!==Cr.pipelineDiagram)continue;const O=Jg.safeParse(E.model.data);if(O.success)return O.data.nodes.map(R=>({id:R.id,parentIds:[...R.parentIds,...R.joinParentIds??[]]}))}return null},d={imageUrl:e.vfsUrl_build,download:a,textHead:c,pipelineGlimpse:h},u=(z,T,A)=>{const E=A==="~"?"ls ~":`ls "${A}"`;s.client.line_execute(E,{silent:!0,observe:!1}).then(O=>{for(const R of O.envelopes)T.envelope_observe(R);if(A!=="~"&&T.path_current()!==A.replace(/\/+$/,"")){const R=O.envelopes.find(k=>k.status==="error"),C=R!==void 0?$z(R):"the session answered no listing";T.listing_fail(C),s.terminal.line_note(`files: ${A}: ${C}`)}},O=>{const R=O instanceof Error?O.message:String(O);T.listing_fail(R),s.terminal.line_note(`files: ${A}: ${R}`)})},p=(z,T,A)=>{const E=T.path_current();E!==null&&n.get(z)?.push(E),u(z,T,A)},f=(z,T)=>{const A=n.get(z)?.pop();A!==void 0&&u(z,T,A)},_=z=>{o.get(z)?.()},g=(z,T)=>{r.set(z,T),_(z);const A=t.get("files",z);A?.follow_set(T),T&&A!==void 0&&s.client.line_execute("ls",{silent:!0,observe:!1}).then(E=>{for(const O of E.envelopes)A.envelope_observe(O)})},m=(z,T)=>{const A=t.get("files",z);A!==void 0&&(r.get(z)===!0?s.terminal.line_run("ls"):u(z,A,T))},w=(z,T)=>{e.askOnPane_await(z,{message:`New directory in ${T}: `,kind:"text",commit:"MAKE IT"}).then(A=>{const E=(A??"").trim();E!==""&&(s.terminal.line_run(`mkdir "${T}/${E}"`),m(z,T))})},y=async(z,T,A)=>{for(const E of A){const O=`${T}/${E.name}`;s.terminal.line_note(`putting ${E.name} in ${T}…`);try{const R=await fetch(e.vfsUrl_build(O),{method:"POST",body:E});if(!R.ok){s.terminal.line_note(`upload: ${E.name}: ${(await R.text()).trim()||R.statusText}`);continue}s.terminal.line_note(`✓ ${O}`)}catch(R){s.terminal.line_note(`upload: ${E.name}: ${R instanceof Error?R.message:String(R)}`)}}m(z,T)},M=(z,T,A)=>{if(A.kind==="dir"){r.get(z)===!0?s.terminal.line_run(`cd "${A.path}"`):p(z,T,A.path);return}if(A.kind==="plugin"||A.kind==="pipeline"){e.binEntry_show(z,T,A.path,A.kind);return}if(zx(A.path)){e.image_open(z,A.path).then(E=>s.terminal.line_note(E));return}if(i.regard_write(z,{address:A.path,modelKind:"fs.file"}),!i.groupHasViewer(z)){if(tu(A.path)){T.contentImage_show(A.path,e.vfsUrl_build(A.path));return}l(A.path).then(E=>{if(!E.ok){T.contentRefused_show(A.path,E.text);return}Sx.test(A.path)?T.contentTable_show(A.path,E.text):T.content_show(A.path,E.text)})}},v=()=>{const z=e.template_stamp("tpl-pane-files").querySelector(".files-body");if(z===null)throw new Error("tpl-pane-files has no files-body");return z},S=(z,T,A)=>{const E=`"${A}"`,O=T.type==="dir"||T.type==="vfs"||T.type==="job",R=Fl(A),C={kind:T.type==="plugin"||T.type==="pipeline"?"catalogue":O&&Iu(A,T.name)?"seriesFolder":T.type==="file"?"file":"directory",feed:R,node:R===null?null:Fm(A),bound:e.catalogue_find(z)!==void 0,projection:uj(A),editable:T.type==="file"&&MR(A)},k={image:()=>{e.image_open(z,A).then(G=>s.terminal.line_note(G))},download:()=>a(A),link:()=>{const G=qy(window.location.origin,A);(t.get("files",z)?.link_copy(A)??navigator.clipboard.writeText(G).then(()=>!0,()=>!1)).then(W=>s.terminal.line_note(W?`link copied: ${G}`:`link (copy it): ${G}`))},process:()=>e.process_open(z,{input:A,feed:R,node:R===null?null:Fm(A)}),gather:()=>e.cohort_gather([{kind:O?"dir":"file",seriesUID:A,description:T.name,imagery:Iu(A,T.name),modality:Iu(A,T.name)?"MR":"—",patient:e.promptUser()??"",vfsPath:A,folderPath:A}]),run:()=>e.run_press(z,T.name,T.type==="pipeline"?"pipeline":"plugin"),edit:()=>{const G=vx(A),L=H5(T.name,T.size,bR);if(L===null){e.verbLine_run(z,G);return}e.askOnPane_await(z,{kind:"confirm",message:L}).then(W=>{W==="y"&&e.verbLine_run(z,G)})},move:()=>e.verbLine_run(z,`mv ${E}`),copy:()=>e.verbLine_run(z,`cp ${E}`),delete:()=>e.verbLine_run(z,`rm ${O?"-ri":"-i"} ${E}`),share:()=>e.verbLine_run(z,`setfacl ${E}`)};return s1.rules.filter(G=>G.offered(C)).map(G=>({label:G.label(C),run:()=>k[G.name]?.()}))},x=(z,T)=>{const A=T.map(([k])=>k),E=A.map(k=>`"${k}"`).join(" "),O=[];for(const k of A){const G=Fl(k);G!==null&&!O.includes(G)&&O.push(G)}const R={count:A.length,feeds:O},C={delete:()=>e.verbLine_run(z,`rm -rI ${E}`),move:()=>s.terminal.line_run(`mv -t ${E}`),copy:()=>s.terminal.line_run(`cp -t ${E}`),share:()=>s.terminal.line_run(`setfacl ${O.map(k=>`feed_${k}`).join(" ")}`)};return i1.rules.filter(k=>k.offered(R)).map(k=>({label:k.label(R),run:()=>C[k.name]?.()}))};return{previewProvider:d,fileText_fetch:l,file_save:a,rootedListing_show:u,listing_refresh:m,directory_make:w,files_deliver:y,follows:z=>r.get(z)===!0,follow_set:g,cwdBind_sync_register:(z,T)=>{o.set(z,T)},cwdBind_sync:_,rooted_walk:p,rooted_back:f,filesBody_stamp:v,rowVerbs_build:S,instance_build:(z,T,A=!1)=>{const E=e.template_stamp("tpl-pane-files"),O=new Hz(e.pane_find(E,".files-panel"),C=>M(z,O,C),d,{catalogue:A});O.selectionVerbs_declare(C=>x(z,C)),O.rowVerbs_declare((C,k)=>S(z,C,k),(C,k)=>{i.regard_write(z,{address:k,modelKind:"fs.file"}),Fl(k)!==null&&s.client.line_execute(`getfacl "${k}"`,{silent:!0,observe:!1}).then(G=>{O.rowReadout_show(k,fj(G))}).catch(()=>{O.rowReadout_show(k,"ACCESS UNREAD")})}),t.set("files",z,O);const R=e.promptUser();return R!==null&&R!==""&&O.home_set(`/home/${R}`),n.set(z,[]),r.set(z,T),_(z),O.follow_set(T),{id:z,kind:"files",mount:E,dispose:()=>{t.delete(z),n.delete(z),i.pane_leave(z)}}}}}function mj(s,e){const t=sn("tpl-pane-universe"),i=new j5({canvas:Js(t,".universe-canvas"),title:Js(t,".universe-title"),state:t.querySelector(".pane-state"),empty:Js(t,".universe-empty"),projectionPill:t.querySelector(".universe-projection"),refreshPill:t.querySelector(".universe-refresh"),replayPill:t.querySelector(".universe-replay"),scalePill:t.querySelector(".universe-scale"),viewPill:t.querySelector(".universe-view"),gravityPill:t.querySelector(".universe-gravity"),densityPill:t.querySelector(".universe-density"),drawPill:t.querySelector(".universe-draw"),captionsPill:t.querySelector(".universe-captions"),arrangementPill:t.querySelector(".universe-arrangement"),facts:t.querySelector(".universe-facts"),backPill:t.querySelector(".universe-back"),openPill:t.querySelector(".universe-open"),frame:t.querySelector(".mode-frame")},{watch_set:(n,r)=>{r?s.client().watch_send(n):s.client().unwatch_send(n)},...(({feed_entered:n,feed_note:r,feed_tag:o,feed_rename:a,feed_untag:l})=>({feed_entered:n,feed_note:r,feed_tag:o,feed_rename:a,feed_untag:l}))(wx(s.context(),e,s.feedVerbs())),command_run:n=>{s.client().line_execute(n,{silent:!0,observe:!1}).then(r=>{for(const o of r.envelopes)i.envelope_observe(o)})},feed_dag:async n=>{const r=await s.client().line_execute(`feed diagram feed_${n}`,{silent:!0,observe:!1});for(const o of r.envelopes){if(o.model?.kind!==Cr.feedDag)continue;const a=Qg.safeParse(o.model.data);if(a.success)return a.data}return null},node_enter:n=>{s.terminal().line_run(`cd "${n}"`)},node_dive:n=>{s.nodeOverlay_open(e,n.replace(/\/data$/,""))},node_process:n=>{const r=Fl(n.vfsPath)??(/\/feed_(\d+)(?:\/|$)/.exec(n.vfsPath)===null?null:Number(/\/feed_(\d+)(?:\/|$)/.exec(n.vfsPath)[1])),o=s.promptUser()===null?n.vfsPath:n.vfsPath.replace(/^\/proc\/jobs\//,`/home/${s.promptUser()}/feeds/`);s.process_open(e,{input:o,feed:r,node:n.instanceId})},feed_open:n=>{s.runs_show(),s.dag_primary().feed_enter(n)},plugin_open:n=>{(async()=>{const r=await s.client().line_execute("ls /bin",{silent:!0,observe:!1}),o=[];for(const l of r.envelopes){if(l.model?.kind!=="fs.listing")continue;const c=l.model.data,h=Array.isArray(c)?c:[c];for(const d of h)for(const u of d.items??[])o.push(u.name)}const a=o.filter(l=>l.startsWith(`${n}-v`)).sort((l,c)=>l.localeCompare(c,void 0,{numeric:!0})).pop();if(a===void 0){s.terminal().line_note(`universe: ${n} is not in /bin`);return}et("gutter-files").click(),s.binEntry_show("files",s.panels().get("files","files"),`/bin/${a}`,"plugin")})().catch(r=>{s.terminal().line_note(`universe: could not open ${n} in /bin: ${r instanceof Error?r.message:String(r)}`)})},note:n=>s.terminal().line_note(n)},Vy());return s.panels().set("universe",e,i),{id:e,kind:"universe",mount:t,dispose:()=>{s.panels().delete(e),s.subjects().pane_leave(e),i.dispose()}}}function gj(s,e,t){const i=sn("tpl-pane-dag"),n=new b5(Js(i,".dag-canvas"),Js(i,".dag-title"),Js(i,".dag-facts"),Js(i,".dag-empty"),Js(i,".dag-strategy"),Js(i,".dag-feedlist"),{command_run:r=>{s.client().line_execute(r,{silent:!0,observe:!1}).then(o=>{for(const a of o.envelopes)n.envelope_observe(a)})},watch_set:(r,o)=>{o?s.client().watch_send(r):s.client().unwatch_send(r)},node_enter:r=>{s.terminal().line_run(`cd "${r}"`)},node_dive:r=>{s.nodeOverlay_open(e,r.replace(/\/data$/,""))},node_regard:r=>{s.subjects().regard_write(e,{address:r,modelKind:"feed.node"})},node_process:r=>{const o=Fl(r.vfsPath)??(/\/feed_(\d+)(?:\/|$)/.exec(r.vfsPath)===null?null:Number(/\/feed_(\d+)(?:\/|$)/.exec(r.vfsPath)[1])),a=s.promptUser()===null?r.vfsPath:r.vfsPath.replace(/^\/proc\/jobs\//,`/home/${s.promptUser()}/feeds/`);s.process_open(e,{input:a,feed:o,node:r.instanceId})},feed_regard:r=>{s.subjects().regard_write(e,{address:r,modelKind:"feed"})},...wx(s.context(),e,s.feedVerbs()),...t?{feed_shown:()=>s.dag_summon()}:{}});return s.panels().set("dag",e,n),{id:e,kind:"dag",mount:i,dispose:()=>{s.nodeOverlay().dispose(e),s.panels().delete(e),s.subjects().pane_leave(e),n.dispose()}}}function _j(s){return{universe_build:e=>mj(s,e),dag_build:(e,t)=>gj(s,e,t)}}const xx=new Set(["files"]);function bj(s){xx.add(s)}function Kv(s){return xx.has(s)}const Ox=new Map,Na=new Map;let Mj=0;function fn(s,e){Ox.set(s,e)}function vj(s){const e=Ox.get(s);if(e===void 0)throw new Error(`no pane factory registered for kind '${s}'`);const t=e(`${s}-${Mj++}`);return Na.set(t.id,t),t}function uh(s){Na.set(s.id,s)}function jh(s){return Na.get(s)}function Hh(){return[...Na.values()]}function Ds(s){const e=Na.get(s);e!==void 0&&(Na.delete(s),e.dispose?.(),e.mount.remove())}class wj{byId=new Map;set(e,t,i){this.byId.set(t,{kind:e,panel:i})}get(e,t){const i=this.byId.get(t);return i!==void 0&&i.kind===e?i.panel:void 0}has(e,t){return this.byId.get(t)?.kind===e}delete(e){return this.byId.delete(e)}ids(e){return this.entries(e).map(([t])=>t)}entries(e){const t=[];for(const[i,n]of this.byId)n.kind===e&&t.push([i,n.panel]);return t}values(e){return this.entries(e).map(([,t])=>t)}idOf(e,t){for(const[i,n]of this.byId)if(n.kind===e&&n.panel===t)return i;return null}}const yj=/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed/i;function F_(s){const e=s instanceof Error?s.message:String(s??"");return yj.test(e)}const Ma={before:"ARGUS has been updated in the background — ",refresh:"refresh",after:" this page"},Sj=`${Ma.before}${Ma.refresh}${Ma.after}`,Cd="ARGUS UPDATED IN THE BACKGROUND · REFRESH THIS PAGE";function zj(s,e=document.body){let t=!1;const i=()=>{if(t)return;t=!0,s(`argus: ${Sj} (what failed to load was part of the old build)`);const n=document.createElement("div");n.className="stale-page",n.setAttribute("role","alert");const r=document.createElement("span");r.className="stale-page-words";const o=document.createElement("button");o.type="button",o.className="stale-page-reload",o.textContent=Ma.refresh,o.title="load the argus the server has now",o.addEventListener("click",()=>{window.location.reload()}),r.append(document.createTextNode(Ma.before),o,document.createTextNode(Ma.after)),n.append(r),e.appendChild(n)};window.addEventListener("vite:preloadError",()=>{i()}),window.addEventListener("unhandledrejection",n=>{F_(n.reason)&&i()})}const xj=[{label:"",tag:"PatientName"},{label:"MRN",tag:"PatientID"},{label:"ACC",tag:"AccessionNumber"},{label:"",tag:"StudyDescription"},{label:"",tag:"SeriesDescription"},{label:"",tag:"StudyDate"},{label:"",tag:"PatientAge"},{label:"",tag:"PatientSex"}],Oj=256*1024*1024;function fh(s){const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1024&&i<e.length-1;)t/=1024,i++;return i===0?`${s} B`:`${t.toFixed(1)} ${e[i]}`}function Ej(s){const e=s.toUpperCase();return e==="MR"||e==="CT"||e==="PT"?e:"OT"}class Aj{pane;field;title;modeSpan;stateSpan;layoutPills=new Map;overlayPill;colormapPill;savePill;loadPill;retryPill;presetPill;focusMark;guardBytes=Oj;forced=!1;pendingLayout=null;progressNote=null;overlayNote=null;probeNote=null;overlay=!1;overlayLines=[];presetIndex=-1;toolPills=new Map;handlers;engine=null;series=null;siblings=[];colormap="gray";tool="wl";constructor(e,t){this.handlers=t,this.pane=e,this.field=mi(e,".image-field"),this.title=mi(e,".pane-title"),this.modeSpan=mi(e,".pane-mode"),this.stateSpan=mi(e,".pane-state");for(const i of e.querySelectorAll(".image-layout")){const n=i.dataset.layout??"single";this.layoutPills.set(n,i),i.addEventListener("click",()=>{this.layout_set(n)})}this.overlayPill=mi(e,".image-overlay"),this.overlayPill.addEventListener("click",()=>{this.overlay_set(!this.overlay)}),this.colormapPill=mi(e,".image-colormap"),this.savePill=mi(e,".image-save"),this.loadPill=mi(e,".image-load"),this.retryPill=mi(e,".image-retry"),this.presetPill=mi(e,".image-preset"),this.focusMark=mi(e,".image-focus"),this.field.tabIndex=0,this.colormapPill.addEventListener("click",()=>{this.colormap_cycle()}),this.savePill.addEventListener("click",()=>{this.annotations_save()}),this.loadPill.addEventListener("click",()=>{this.load_press()}),this.retryPill.addEventListener("click",()=>{this.retry_press()}),this.presetPill.addEventListener("click",()=>this.preset_cycle()),mi(e,".image-tags").addEventListener("click",()=>this.handlers.tags_open());for(const i of w0){const n=mi(e,`.image-tool[data-tool="${i}"]`);this.toolPills.set(i,n),n.addEventListener("click",()=>{this.tool_set(i)})}this.toolPills_paint(),this.field.addEventListener("mousedown",()=>{this.field.focus(),this.focusMark_paint(!0)}),this.field.addEventListener("focusin",()=>this.focusMark_paint(!0)),this.field.addEventListener("focusout",i=>{(!(i.relatedTarget instanceof Node)||!this.field.contains(i.relatedTarget))&&this.focusMark_paint(!1)}),this.field.addEventListener("keydown",i=>{if(i.key==="Escape"){this.field_release(),i.stopPropagation();return}i.stopPropagation()})}field_hasFocus(){return document.activeElement instanceof Node&&this.field.contains(document.activeElement)}field_release(){return this.field_hasFocus()?(document.activeElement.blur(),this.focusMark_paint(!1),!0):!1}async series_show(e,t={}){if(this.engine_dispose(),this.series=e,this.forced=t.force===!0,this.pendingLayout=null,this.loadPill.hidden=!0,this.retryPill.hidden=!0,this.presets_paint(e.modality),this.siblings=t.siblings??[],this.pane.dataset.modality=Ej(e.modality),this.title.textContent=`IMAGE ${e.modality.toUpperCase()} ${e.seriesDescription}`.trim(),this.title.title=this.title.textContent,this.siblings.length>1){const o=this.siblings.findIndex(a=>a.path===e.path)+1;this.handlers.note(`image: series ${o} of ${this.siblings.length} in this study; image series <n> switches`)}const i=await this.chunk_import(()=>Xl(()=>import("./cornerstoneEngine-BleRTwP7.js").then(o=>o.b2),__vite__mapDeps([0,1,2,3]),import.meta.url));if(i===null)return;const{CornerstoneEngine:n}=i,r=new n(this.engineHost_get(),e,t.startAt??1);await this.engine_open(r),this.engine===r&&(this.guard_trips()?(this.loadPill.hidden=!1,this.stateSpan.textContent=`SERIES ${fh(e.bytes)} · LOAD FOR STACK`,this.handlers.note(`image: ${fh(e.bytes)} to fetch before the stack scrolls; press LOAD, image load, or image --force <path>`)):r.slices_fill(),await this.annotations_reload(r,e))}async annotations_reload(e,t){let i=0;for(const n of t.annotations.filter(r=>/\.dcm$/i.test(r))){if(this.engine!==e)return;const r=n.split("/").pop()??n;try{const o=await fetch(this.handlers.source.url_resolve(n));if(!o.ok){this.handlers.note(`image: ${r}: HTTP ${o.status}`);continue}const a=await e.annotations_import(await o.arrayBuffer());i+=a,this.handlers.note(a>0?`image: ${a} measurement${a===1?"":"s"} from ${r}`:`image: ${r}: no measurements this engine can place`)}catch(o){this.handlers.note(`image: ${r}: ${o instanceof Error?o.message:String(o)}`)}}this.pane.dataset.annotations=String(i)}async volume_show(e){this.engine_dispose(),this.series=null,this.siblings=[],this.pane.dataset.modality="NIFTI",this.title.textContent=`IMAGE ${e.split("/").pop()??""}`,this.title.title=e,this.forced=!0,this.loadPill.hidden=!0,this.retryPill.hidden=!0,this.presets_paint("NIFTI");const t=await this.chunk_import(()=>Xl(()=>import("./niivueEngine-Dd9ONOnD.js"),__vite__mapDeps([4,1]),import.meta.url));if(t===null)return;const{NiivueEngine:i}=t;await this.engine_open(new i(this.engineHost_get(),e))}async chunk_import(e){try{const t=await e();if(t!==void 0)return t}catch(t){if(!F_(t))throw t}return Ts(this.stateSpan,"stale",Cd),this.handlers.note(`image: ${Cd.toLowerCase()} — the viewer's code is of an older build than the server has`),null}opening_show(e){const t=e.replace(/\/$/,"").split("/").pop()??e;this.stateSpan.textContent="OPENING",this.progress_show({label:`OPENING ${t}`,done:0,total:0})}opening_fail(e,t){this.stateSpan.textContent=t,this.progress_show({label:t,done:0,total:0});const i=this.progressNote;i!==null&&(i.classList.add("image-working-failed"),i.querySelector(".image-working-count").textContent=e)}siblings_get(){return this.siblings}series_get(){return this.series}state_get(){return this.engine===null?null:{...this.engine.state_get(),colormap:this.colormap,path:this.series?.path??null,guard:this.guardBytes,waiting:this.pendingLayout}}async layout_set(e){if(this.engine===null)return!1;if(e!=="single"&&this.guard_trips())return this.pendingLayout=e,this.loadPill.hidden=!1,this.stateSpan.textContent=`SERIES ${fh(this.series?.bytes??0)} · LOAD FOR ${e.toUpperCase()}`,this.handlers.note(`image: ${fh(this.series?.bytes??0)} to fetch for ${e}; press LOAD, image load, or image --force <path>`),!1;const t=this.engine.state_get().layout;return this.layoutPills_paint(e),this.modeSpan.textContent=e==="single"?"":e.toUpperCase(),this.overlay_hide(),await this.engine.layout_set(e)?(this.progress_show(null),this.overlay_paint(),this.toolPills_paint(),!0):(this.progress_show(null),this.layoutPills_paint(t),this.modeSpan.textContent=t==="single"?"":t.toUpperCase(),this.handlers.note(`image: layout ${e}: not offered by ${this.engine.name}`),!1)}layoutPills_paint(e){for(const[t,i]of this.layoutPills)i.classList.toggle("rail-off",t!==e)}guard_trips(){return this.guardBytes!==null&&!this.forced&&this.engine?.name==="cornerstone"&&(this.series?.bytes??0)>this.guardBytes}async load_press(){this.forced=!0,this.loadPill.hidden=!0,this.retryPill.hidden=!0;const e=this.pendingLayout;return this.pendingLayout=null,e!==null?this.layout_set(e):this.engine===null||this.engine.state_get().filled?!1:this.engine.slices_fill()}guard_set(e){this.guardBytes=e}guard_get(){return this.guardBytes}preset_cycle(){const e=this.presets_select(this.series?.modality??"NIFTI");if(e.length===0)return;this.presetIndex=(this.presetIndex+1)%e.length;const t=e[this.presetIndex];t!==void 0&&this.wl_set(t.lower,t.upper)&&(this.presetPill.textContent=t.name.toUpperCase())}presets_select(e){const t=e.toUpperCase();return yz.filter(i=>i.modalities.length===0||i.modalities.includes(t))}presets_paint(e){this.presetIndex=-1;const t=this.presets_select(e);this.presetPill.hidden=t.length===0,this.presetPill.textContent="PRESET"}slice_set(e){if(this.engine===null)return!1;const t=this.engine.slice_set(e);return t||this.handlers.note(`image: slice ${e}: not offered in ${this.engine.state_get().layout} layout by ${this.engine.name}`),t}wl_set(e,t){if(this.engine===null)return!1;const i=this.engine.wl_set(e,t);return i||this.handlers.note(`image: wl: not offered by ${this.engine.name}`),i}ghost_set(e){if(this.engine===null)return!1;const t=this.engine.ghost_set(e);return t||this.handlers.note("image: ghost applies to the SLAB layout"),t}wlPreset_set(e){const t=this.series?.modality??"NIFTI",i=r7(e,t);return i===void 0?(this.handlers.note(`image: wl preset ${e}: none for ${t}`),!1):this.wl_set(i.lower,i.upper)}colormap_set(e){return this.engine===null?!1:this.engine.colormap_set(e)?(this.colormap=e,this.colormapPill.textContent=e.toUpperCase(),!0):(this.handlers.note(`image: colormap ${e}: not offered by ${this.engine.name}`),!1)}tool_set(e){return this.engine===null?!1:this.engine.tool_set(e)?(this.tool=e,this.toolPills_paint(),!0):(this.handlers.note(`image: ${e}: not offered by ${this.engine.name}`),!1)}async annotations_save(){if(this.engine===null)return!1;const e=this.series?.seriesInstanceUID,t=/^(\/home\/[^/]+)\//.exec(this.series?.path??"")?.[1];if(e===void 0||t===void 0)return this.handlers.note("image: save: this series has no UID to file an annotation under"),!1;const i=await this.engine.annotations_export();if(i===null)return this.handlers.note(`image: save: nothing measured, or ${this.engine.name} writes no report`),!1;const n=`${t}/annotations/${e}/measurements.dcm`,r=await this.handlers.file_put(n,i);return this.handlers.note(r===200?`✓ ${n}`:`image: save: ${n}: HTTP ${r}`),r===200}dispose(){this.engine_dispose()}async colormap_cycle(){const e=Ch[(Ch.indexOf(this.colormap)+1)%Ch.length]??"gray";this.colormap_set(e)}async engine_open(e){this.engine=e,this.field.replaceChildren(),this.progressNote=null,this.overlayNote=null,this.probeNote=null,this.layoutPills_paint("single"),this.modeSpan.textContent="",this.colormapPill.textContent=this.colormap.toUpperCase();try{await e.open(this.field)}catch(i){this.stateSpan.textContent="REFUSED",this.handlers.note(`image: ${i instanceof Error?i.message:String(i)}`);return}const t=e.state_get().layout;this.layoutPills_paint(t),this.modeSpan.textContent=t==="single"?"":t.toUpperCase(),e.tool_set(this.tool),this.toolPills_paint(),this.progress_show(null),this.overlay_fill()}engine_dispose(){this.engine?.dispose(),this.engine=null,this.progressNote=null,this.overlayNote=null,this.probeNote=null,this.field.replaceChildren(),this.stateSpan.textContent=""}retryPill_paint(){const e=this.engine===null?0:this.engine.state_get().refused,t=this.engine?.refused_retry!==void 0;this.retryPill.hidden=!t||e===0,this.retryPill.disabled||(this.retryPill.textContent=`RETRY ${e}`)}async retry_press(){if(!(this.engine?.refused_retry===void 0||this.retryPill.disabled)){this.retryPill.disabled=!0,this.retryPill.textContent="ASKING…";try{await this.engine.refused_retry()}finally{this.retryPill.disabled=!1,this.retryPill_paint()}}}engineHost_get(){return{source:this.handlers.source,readout_set:e=>{this.stateSpan.textContent=e,this.retryPill_paint()},progress_set:e=>this.progress_show(e),note:this.handlers.note,regard:e=>{this.handlers.regard(e),this.overlaySlice_paint()},probe_set:e=>this.probe_show(e)}}probe_show(e){if(e===null){this.probeNote?.remove(),this.probeNote=null;return}if(this.probeNote===null||this.probeNote.parentElement===null){const t=document.createElement("div");t.className="image-probe-note",this.field.appendChild(t),this.probeNote=t}this.probeNote.textContent=e}overlaySlice_paint(){const e=this.overlayNote?.querySelector(".image-overlay-slice")??null;if(e===null||this.engine===null)return;const t=this.engine.state_get();e.textContent=t.slices>1?`SLICE ${Math.max(1,t.slice)} OF ${t.slices}`:"",e.hidden=t.slices<=1}progress_show(e){if(e===null){this.progressNote?.remove(),this.progressNote=null;return}if(this.progressNote===null||this.progressNote.parentElement===null){const o=document.createElement("div");o.className="image-working",o.innerHTML='<span class="image-working-label"></span><span class="image-working-track"><span class="image-working-fill"></span></span><span class="image-working-count"></span>',this.field.appendChild(o),this.progressNote=o}const t=this.progressNote;t.classList.remove("image-working-failed");const i=e.total>0,n=i?Math.min(1,e.done/e.total):0;t.querySelector(".image-working-label").textContent=e.label,t.querySelector(".image-working-count").textContent=i?`${e.done} / ${e.total} · ${Math.round(n*100)}%`:"";const r=t.querySelector(".image-working-fill");r.classList.toggle("image-working-pacing",!i),r.style.width=i?`${Math.round(n*100)}%`:""}async overlay_set(e){if(this.overlay=e,this.overlayPill.textContent=e?"OVERLAY ON":"OVERLAY OFF",this.overlayPill.classList.toggle("rail-off",!e),!e){this.overlay_hide();return}await this.overlay_fill()}overlay_hide(){this.overlayNote?.remove(),this.overlayNote=null}async overlay_fill(){if(!this.overlay||this.series===null)return;const e=this.series.files[0]??this.series.path,t=await this.handlers.tags_read(e);if(t===null){this.handlers.note(`image: overlay: ${e}: no header to read`);return}this.overlayLines=xj.flatMap(i=>{const r=(t.constant.find(o=>o.name===i.tag)?.value??"").trim();return r===""?[]:[i.label===""?r:`${i.label} ${r}`]}),this.overlay_paint()}overlay_paint(){if(!this.overlay||this.overlayLines.length===0)return;this.overlay_hide();const e=document.createElement("div");e.className="image-overlay-note";const t=document.createElement("span");t.className="image-overlay-slice",e.appendChild(t);for(const i of this.overlayLines){const n=document.createElement("span");n.textContent=i,e.appendChild(n)}this.field.appendChild(e),this.overlayNote=e,this.overlaySlice_paint()}toolPills_paint(){const e=new Set(this.engine?.toolsOffered_get()??w0),t=this.engine!==null?this.engine.state_get().primaryTool:this.tool;for(const[i,n]of this.toolPills){const r=e.has(i);n.classList.toggle("rail-na",!r),n.classList.toggle("rail-off",r&&i!==t),n.disabled=!r}}focusMark_paint(e){this.focusMark.hidden=!e,this.pane.classList.toggle("image-field-focused",e)}}function mi(s,e){const t=s.querySelector(e);if(t===null)throw new Error(`image pane: missing ${e}`);return t}const Ex=["patient","study","series","image","equipment","meta","private","other","varying"],Tj=new Set(["meta","private"]),Yv="••••";class Dj{pane;title;modeSpan;redactBlock;listing;handlers;redact=!0;model=null;groups=[];constructor(e,t){this.handlers=t,this.pane=e,this.title=ph(e,".pane-title"),this.modeSpan=ph(e,".pane-mode"),this.redactBlock=ph(e,".tags-redact"),this.redactBlock.addEventListener("click",()=>this.redact_set(!this.redact));const i=ph(e,".tags-panel");this.listing=new sr({mount:i,traits:this.groupTraits_declare(),key:n=>n.group,chrome:{root:e,prefix:"tags"},caps:"root",row:{className:()=>"tags-group-row",groupClassName:n=>`tags-group tags-group-${n.group}`,decorate:n=>{n.title="fold this group open or shut (it keeps its place)"}},child:ma(n=>n.rows,{traits:this.tagTraits_declare(),key:n=>n.key,activatable:n=>n.items.length>0,row:{className:n=>`tags-row${n.phi?" tags-phi":""}`,groupClassName:()=>"tags-sequence",decorate:(n,r)=>{n.title=r.items.length>0?`${r.name}: fold the sequence open or shut`:`${r.tag} ${r.name}`}},child:ma(n=>n.items,{traits:this.itemTraits_declare(),key:n=>n.key,row:{className:()=>"tags-item-row",groupClassName:()=>"tags-item"},child:ma(n=>n.rows,{traits:this.tagTraits_declare(),key:n=>n.key,activatable:()=>!1,row:{className:n=>`tags-row tags-row-deep${n.phi?" tags-phi":""}`}})})}),state:n=>this.stateLine_compose(n),empty:()=>kj("NO TAGS")}),this.redactBlock_paint(),this.listing.rows_set([],{field:"tags"})}model_show(e){this.model=e,this.title.textContent=`TAGS ${Cj(e)}`,this.pane.dataset.modality=Rj(e),this.groups=Ij(e),this.listing.rows_set([{key:e.path,rows:this.groups}],{field:e.path}),this.listing.open_set(0,this.groups.map(t=>t.group).filter(t=>!Tj.has(t))),this.modeSpan.textContent=e.subject==="folder"?"FOLDER":""}path_get(){return this.model?.path??null}redact_get(){return this.redact}redact_set(e){this.redact=e,this.redactBlock_paint(),this.model!==null&&this.listing.rows_set([{key:this.model.path,rows:this.groups}],{field:this.model.path})}filter_set(e){if(e===null){this.listing.filter_toggle(!1);return}this.listing.filter_toggle(!0),this.listing.filter_set(e)}stateLine_compose(e){const t=this.groups.reduce((n,r)=>n+r.rows.length,0),i=[];return this.model!==null&&this.model.subject==="folder"&&(i.push(this.model.read===this.model.of?`${this.model.read} FILES`:`${this.model.read} OF ${this.model.of} FILES`),this.model.refused.length>0&&i.push(`REFUSED ${this.model.refused.length}`)),i.push(e.filter!==""?e.filter:`${t} TAGS`),this.redact&&i.push("REDACTED"),i.join(" · ")}redactBlock_paint(){this.redactBlock.textContent=this.redact?"REDACT ON":"REDACT OFF",this.redactBlock.classList.toggle("rail-off",!this.redact),this.pane.classList.toggle("tags-redacted",this.redact)}value_cell(e){const t=document.createElement("span");if(t.className="tags-value",e.phi&&this.redact)return t.textContent=Yv,t.title="identifying value, redacted; the REDACT block on the frame reveals it",t;if(t.textContent=e.value,e.decoded!==void 0){const i=document.createElement("span");i.className="tags-decoded",i.textContent=` ${e.decoded}`,t.appendChild(i)}if(e.distinct!==void 0){const i=document.createElement("span");i.className="tags-decoded",i.textContent=` (${e.distinct} distinct)`,t.appendChild(i)}return t}groupTraits_declare(){return[Cf(()=>!0),{key:"group",label:"GROUP",className:"tags-group-name",width:"minmax(12em, 1fr)",cell:e=>e.group.toUpperCase(),compare:e=>Ex.indexOf(e.group)},{key:"count",label:"TAGS",className:"tags-group-count",width:"5em",cell:e=>String(e.rows.length),compare:e=>e.rows.length}]}tagTraits_declare(){return[Cf(e=>e.items.length>0),{key:"tag",label:"TAG",className:"tags-tag",width:"7em",cell:e=>e.tag,compare:e=>e.tag},{key:"name",label:"NAME",className:"tags-name",width:"minmax(8em, 1.4fr)",cell:e=>e.name,compare:e=>e.name.toLowerCase()},{key:"vr",label:"VR",className:"tags-vr",width:"2.4em",cell:e=>e.vr,compare:e=>e.vr},{key:"value",label:"VALUE",className:"tags-value-cell",width:"minmax(6em, 2fr)",cell:e=>this.value_cell(e),compare:e=>(e.phi&&this.redact?Yv:`${e.value} ${e.decoded??""}`).toLowerCase()}]}itemTraits_declare(){return[Cf(()=>!0),{key:"item",label:"ITEM",className:"tags-item-name",width:"minmax(12em, 1fr)",cell:e=>`ITEM ${e.index}`,compare:e=>e.index},{key:"count",label:"TAGS",className:"tags-group-count",width:"5em",cell:e=>String(e.rows.length),compare:e=>e.rows.length}]}}function Cf(s){return{key:"fold",label:"",className:"tags-fold",capped:!1,width:"1.4em",cell:e=>{const t=document.createElement("span");return t.className=s(e)?"tags-fold":"tags-fold tags-fold-none",t}}}function Ij(s){const e=new Map;for(const t of s.constant){const i=t.group;e.has(i)||e.set(i,[]),e.get(i)?.push(Ax(t,`${i}/${t.tag}`))}return s.varying.length>0&&e.set("varying",s.varying.map(t=>({tag:t.tag,name:t.name,vr:t.vr,value:t.distinct===1?t.first:`${t.first} .. ${t.last}`,phi:t.phi,items:[],distinct:t.distinct,key:`varying/${t.tag}`}))),Ex.filter(t=>e.has(t)).map(t=>({group:t,rows:e.get(t)??[]}))}function Ax(s,e){return{tag:s.tag,name:s.name,vr:s.vr,value:s.value,...s.decoded!==void 0?{decoded:s.decoded}:{},phi:s.phi,items:(s.items??[]).map((t,i)=>({index:i+1,key:`${e}/${i+1}`,rows:t.map(n=>Ax(n,`${e}/${i+1}/${n.tag}`))})),key:e}}function Cj(s){const e=s.path.replace(/\/$/,"").split("/").pop()??s.path;if(s.subject==="folder")return e.length>24?`${e.slice(0,22)}…`:e;const t=/^(\d+)-/.exec(e)?.[1];return t!==void 0?`INSTANCE ${Number(t)}`:e.length>24?`${e.slice(0,22)}…`:e}function Rj(s){const e=(s.constant.find(t=>t.name==="Modality")?.value??"").toUpperCase();return e==="MR"||e==="CT"||e==="PT"?e:"OT"}function kj(s){const e=document.createElement("div");return e.className="tags-note",e.textContent=s,e}function ph(s,e){const t=s.querySelector(e);if(t===null)throw new Error(`tags pane: missing ${e}`);return t}function Nj(s,e){const t=sn("tpl-pane-image"),i=new Aj(t,{source:{url_resolve:n=>s.vfsUrl_build(n)},note:n=>s.terminal().line_note(n),regard:n=>s.subjects().regard_write(e,{address:n,modelKind:"dicom.instance"}),file_put:async(n,r)=>{try{return(await fetch(s.vfsUrl_build(n),{method:"POST",body:r})).status}catch{return 0}},tags_read:n=>U_(s,n),tags_open:()=>{s.terminal().line_note(Tx(s,e))}});return s.panels().set("image",e,i),{id:e,kind:"image",mount:t,dispose:()=>{i.dispose(),s.panels().delete(e),s.subjects().pane_leave(e)}}}function Bj(s,e){const t=sn("tpl-pane-tags"),i=new Dj(t,{note:n=>s.terminal().line_note(n)});return s.panels().set("tags",e,i),{id:e,kind:"tags",mount:t,dispose:()=>{s.panels().delete(e),s.subjects().pane_leave(e)}}}async function U_(s,e){try{const t=await s.client().line_execute(`dcm tags "${e}"`,{silent:!0,observe:!1});for(const i of t.envelopes){if(i.model?.kind!==ua.tags)continue;const n=iz.safeParse(i.model.data);if(n.success)return n.data}}catch{}return null}function Gj(s,e,t){const i=s.panels().get("tags",e);i===void 0||i.path_get()===t||U_(s,t).then(n=>{if(n===null){s.terminal().line_note(`tags: ${t}: not a readable DICOM file`);return}s.panels().get("tags",e)?.model_show(n)})}function Tx(s,e){const t=new Set(s.layout().panes_shown()),i=s.subjects().group_resolve(e);for(const r of s.panels().ids("tags"))if(t.has(r)&&s.subjects().group_resolve(r)===i)return s.layout().focus_set(r),"image tags";if(!t.has(e))return"image tags: the image pane is not on stage";const n=s.instance_spawn("tags",e);return s.layout().leaf_split(e,s.desktop().replayPlace_get()?.dir??"col",n.id,s.desktop().replayPlace_get()?.before??!1)?(s.birth_record(n.id,e,s.desktop().replayPlace_get()?.dir??"col",s.desktop().replayPlace_get()?.before??!1),"image tags"):(Ds(n.id),s.layout().mount_remove(n.id),"image tags: could not open beside the image pane")}async function Um(s,e){try{const t=await s.client().line_execute(`dcm series "${e}"`,{silent:!0,observe:!1});for(const i of t.envelopes){if(i.model?.kind!==ua.series)continue;const n=nz.safeParse(i.model.data);if(n.success)return n.data}}catch{}return null}async function Dx(s,e){try{const t=await s.client().line_execute(`ls "${e}"`,{silent:!0,observe:!1});for(const i of t.envelopes){if(i.model?.kind!=="fs.listing")continue;const n=i.model.data,r=(Array.isArray(n)?n[0]:n)??{},o=(r.path??e).replace(/\/$/,"");return(r.items??[]).filter(a=>a.type==="dir").map(a=>`${o}/${a.name}`)}}catch{}return[]}function Ix(s,e,t){const i=l=>{t!==void 0&&s.subjects().regard_write(l,t)};if(e!==null&&s.panels().has("image",e))return i(e),s.panels().get("image",e)??null;const n=new Set(s.layout().panes_shown());if(t!==void 0){for(const[l,c]of s.panels().entries("image"))if(n.has(l)&&s.subjects().regard_get(l)?.address===t.address)return i(l),c}const r=e!==null?s.subjects().group_resolve(e):null;for(const[l,c]of s.panels().entries("image"))if(n.has(l)&&r!==null&&s.subjects().group_resolve(l)===r)return c;const o=e!==null&&n.has(e)?e:s.errandHost_find();if(o===null)return null;const a=s.instance_spawn("image",e??void 0);return s.layout().leaf_split(o,s.desktop().replayPlace_get()?.dir??"col",a.id,s.desktop().replayPlace_get()?.before??!1)?(s.birth_record(a.id,o,s.desktop().replayPlace_get()?.dir??"col",s.desktop().replayPlace_get()?.before??!1),i(a.id),s.panels().get("image",a.id)??null):(Ds(a.id),s.layout().mount_remove(a.id),null)}async function Pj(s,e,t,i={},n){s.launcher_yield();const r=e!==null?void 0:Bp.test(t)?{address:t,modelKind:"image.volume"}:{address:_d.test(t)?t.slice(0,t.lastIndexOf("/")):t.replace(/\/$/,""),modelKind:"dicom.series"},o=Ix(s,e,r);if(o===null)return"image: no pane to open beside";const a=s.panels().idOf("image",o);if(a!==null&&n?.(a),Bp.test(t))return o.opening_show(t),o.volume_show(t),`image ${t}`;const l=_d.test(t),c=l?t.slice(0,t.lastIndexOf("/")):t.replace(/\/$/,"");o.opening_show(c);let h=await Um(s,c),d=[];if(h===null&&!l){const p=(await Dx(s,c)).slice(0,32);for(const f of p){const _=await Um(s,f);if(_!==null){d=p.map(g=>({path:g,label:g.split("/").pop()??g})),h=_;break}}}if(h===null)return o.opening_fail(t,"NOT A READABLE SERIES"),`image: ${t}: not a readable DICOM series, study, or volume`;const u=l?Math.max(1,h.files.indexOf(t)+1):1;return o.series_show(h,{siblings:d,startAt:u,...i.force===!0?{force:!0}:{}}),`image ${h.path}${d.length>1?` (1 of ${d.length} series)`:""}`}function Lj(s){return{imageInstance_build:e=>Nj(s,e),tagsInstance_build:e=>Bj(s,e),tags_ask:e=>U_(s,e),tagsPane_follow:(e,t)=>Gj(s,e,t),tagsPane_open:e=>Tx(s,e),series_ask:e=>Um(s,e),subfolders_ask:e=>Dx(s,e),imagePane_resolve:(e,t)=>Ix(s,e,t),image_open:(e,t,i={},n)=>Pj(s,e,t,i,n)}}function Wj(s){return{primaries:[s.panes.dag_build("dag",!0),s.panes.universe_build("universe"),{id:"pacs",kind:"pacs",mount:s.pacsMount}],domains:["dag","pacs"],presets:[["pacs",()=>({pane:"pacs"})],["dag",()=>({pane:"dag"})],["universe",()=>({pane:"universe"})]],factories:[["dag",e=>s.panes.dag_build(e,!1)],["universe",s.panes.universe_build],["image",s.dicom.imageInstance_build],["tags",s.dicom.tagsInstance_build],["gather",s.gather_build]]}}function Fj(s){return async()=>{const e=await s.ask("proc feeds");let t=[];for(const u of e.envelopes){const p=u.model;if(p===void 0||p.kind!==Op)continue;const f=xp.safeParse(p.data);f.success&&(t=f.data.feeds)}const n=t.length===0&&e.envelopes.some(u=>u.status==="error")?"INDEX WARMING":`${t.length} FEEDS`,r=t.filter(u=>/error/i.test(u.status)).length,o=t.filter(u=>/running|scheduled|created|started/i.test(u.status)).length,a={key:"universe",name:"UNIVERSE",hue:"--honey",numeral:"",figures:[{text:n}],rows:[],verb:"SEE THE SPACE",about:Si.universe,enter:()=>s.universe_show()},l={key:"analyses",name:"ANALYSES",hue:"--october-sunset",numeral:"3",figures:[{text:n},...o>0?[{text:`${o} RUNNING`}]:[],...r>0?[{text:`${r} ERRORED`,errored:!0,open:()=>s.runs_show("status:error")}]:[]],rows:t.slice(0,6).map(u=>({text:`${u.id} ${u.title}`,errored:/error/i.test(u.status),open:()=>s.feed_enter(u.id)})),verb:"OPEN THE ROSTER",about:Si.analyses,enter:()=>s.runs_show()},c=s.pacs_query(),h={key:"pacs",name:"PACS",hue:"--daybreak",numeral:"4",figures:[{text:c===""?"NO ANSWER":"ANSWERED"}],rows:c===""?[{text:"pacs query PatientID:…",open:()=>s.line_offer("pacs query PatientID:")},{text:"pacs query AccessionNumber:…",open:()=>s.line_offer("pacs query AccessionNumber:")}]:[{text:c.slice(0,48)}],verb:"ASK A PACS",about:Si.pacs,enter:()=>s.pacs_open()},d=s.cloud_enter===null?null:{key:"cloud",name:"CLOUD",hue:"--daybreak",numeral:"",figures:[{text:"OCI"}],rows:[{text:"enter as READ · look only",open:s.cloud_enter},{text:"a line that would act asks your password · MANAGE then",open:s.cloud_enter}],verb:"ENTER YOUR CLOUD SESSION",about:Si.cloud,enter:s.cloud_enter};return{lead:{tile:l,weight:t.length},afterFiles:[h],afterPanes:d===null?[a]:[a,d],about:{files:{text:"Your ChRIS home: uploads, results and what others shared with you."}}}}}const Cx=[["chris user add","users"],["chris deploy","chris deploy"],["net new","net new"],["net build","net build"],["vm new","vm new"],["vm build","vm build"]],Xv=/^--[a-z][a-z0-9-]*$/,Uj=["changed","not yet","ready","done"];function $_(s){const e=[];let t="",i=null,n=!1;for(const r of s){if(i!==null){r===i?i=null:t+=r;continue}if(r==="'"||r==='"'){i=r,n=!0;continue}if(/\s/.test(r)){(t!==""||n)&&e.push(t),t="",n=!1;continue}t+=r}return(t!==""||n)&&e.push(t),e}function Zv(s){return s===""?"''":/[\s'"]/.test(s)?`'${s.replace(/'/g,"'\\''")}'`:s}function j_(s){const e=$_(s);for(const[t,i]of Cx)if(t.split(" ").every((r,o)=>e[o]===r))return i;return"other"}function Hn(s){const e=$_(s),t=j_(s),i=t==="other"?Math.min(1,e.length):Cx.find(([,a])=>a===t)?.[0].split(" ").length??1,n=e.slice(0,i);let r=null;const o=[];for(let a=i;a<e.length;a++){const l=e[a];if(Xv.test(l)){const c=e[a+1];c!==void 0&&!Xv.test(c)?(o.push([l,c]),a++):o.push([l,""])}else r===null&&(r=l)}return{verb:n,subject:r,options:o}}function H_(s){const e=[...s.verb];s.subject!==null&&e.push(Zv(s.subject));for(const[t,i]of s.options)e.push(t),i!==""&&e.push(Zv(i));return e.join(" ")}function mh(s,e,t){const i=Hn(s),n=i.options.filter(([r])=>r!==e);if(t!==""){const r=i.options.findIndex(([o])=>o===e);r===-1?n.push([e,t]):n.splice(r,0,[e,t])}return H_({...i,options:n})}function wn(s,e){return Hn(s).options.find(([t])=>t===e)?.[1]??null}function $j(s){for(const e of Uj)if(s.some(t=>t.state===e))return e;return null}function jj(s){const e=j_(s);return e==="users"?"USERS":e!=="other"?e.toUpperCase():$_(s).slice(0,2).join(" ").toUpperCase()||"—"}function Vh(s){const e=[];let t=null;for(const i of s){const n=j_(i.text);if(n==="users"){t===null?(t=[i],e.push({key:"users",label:"USERS",kind:n,lines:t,state:null,running:null})):t.push(i);continue}e.push({key:`line-${i.number}`,label:jj(i.text),kind:n,lines:[i],state:i.state,running:i.running})}return e.map(i=>({...i,state:$j(i.lines),running:i.lines.find(n=>n.running!==null)?.running??null}))}function qh(s){return s.find(e=>e.running!==null)}function Hj(s){return s==="net build"||s==="vm build"||s==="chris deploy"||s==="users"}function Kh(s,e){return s.split(`
|
|
4349
4349
|
`).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map((i,n)=>{const r=e[n];return{number:n+1,text:i,state:r?.state??null,detail:r?.detail??"",running:r?.running??null}})}function Yh(s){const e=t=>s.filter(i=>i.state===t).length;return{done:e("done"),ready:e("ready"),changed:e("changed"),notYet:e("not yet"),total:s.length}}function Xh(s){const e=[];return s.done>0&&e.push(`${s.done} DONE`),s.ready>0&&e.push(`${s.ready} READY`),s.changed>0&&e.push(`${s.changed} CHANGED`),s.notYet>0&&e.push(`${s.notYet} NOT YET`),e.length===0?s.total===0?"NOTHING READ":`${s.total} LINES`:e.join(" · ")}function $n(s){return(s.split("/").pop()??s).replace(/\.mise$/,"")}function Zh(s){return s.match(/^\/scripts\/([^/]+)\//)?.[1]??""}function Rf(s){return Zh(s)==="mine"?s:`/scripts/mine/${$n(s)}.mise`}function Jv(s){return`${s.map(e=>e.text).join(`
|
|
4350
4350
|
`)}
|
|
4351
4351
|
`}function Qv(s){const e=i=>{const n=wn(s,i);return n===null||n===""||Number.isNaN(Number(n))?null:Number(n)},t=wn(s,"--data-backup");return{net:wn(s,"--net"),open:wn(s,"--open"),vcpu:e("--vcpu"),memory:e("--memory"),disk:e("--disk"),data:e("--data"),dataBackup:t==="daily"||t==="none"?t:null,os:wn(s,"--os")}}function Vj(s,e={vcpu:64,memory:512,gb:2048}){return[{word:"--vcpu",label:"vCPU",unit:"",min:s.vcpu.min,max:Math.min(s.vcpu.max,e.vcpu),step:s.vcpu.step},{word:"--memory",label:"MEMORY",unit:"GiB",min:s.memory.min,max:Math.min(s.memory.max,e.memory),step:1},{word:"--disk",label:"DISK",unit:"GB",min:s.disk.min,max:Math.min(s.disk.max,e.gb),step:10},{word:"--data",label:"DATA",unit:"GB",min:s.data.min,max:Math.min(s.data.max,e.gb),step:10}]}function qj(s,e){return s.memory.perVcpu===null?{min:s.memory.min,max:s.memory.max}:{min:Math.max(s.memory.min,Math.ceil(e*s.memory.perVcpu.min)),max:Math.min(s.memory.max,Math.floor(e*s.memory.perVcpu.max))}}function Kj(s){const e=Hn(s);return H_({...e,verb:["vm","cost"]})}function kf(s,e){if(s===null)return"NOT PRICED";const t=s.machineHour+s.dataHour;return`${ew(t,s.currency,3)}/H · ${ew(t*e,s.currency,2)} A MONTH`}function ew(s,e,t){return`${e==="USD"?"$":`${e} `}${s.toFixed(t)}`}function Rx(s){const e=s.filter(t=>t!==null);return e.length===0?null:e.reduce((t,i)=>({machineHour:t.machineHour+i.machineHour,dataHour:t.dataHour+i.dataHour,currency:i.currency}),{machineHour:0,dataHour:0,currency:e[0]?.currency??"USD"})}function Yj(s){return`${s.vcpu} vCPU · ${s.memory} GiB · disk ${s.disk} GB · data ${s.data} GB${s.dataBackup==="daily"?" · daily backups":""}`}function Xj(s,e,t,i){const n=[["--email",e]];return t!==""&&n.push(["--password-file",t]),i!==""&&n.push(["--on",i]),H_({verb:["chris","user","add"],subject:s,options:n})}function Zj(s){return/\[y\/N\]|\[Y\/n\]|\(y\/n\)|continue\?/i.test(s)?"yes-no":/type (the|its) name|name typed back|type .* to go on/i.test(s)?"name":"text"}function Jj(s){const e=Math.max(0,Math.floor(s/1e3));if(e<60)return`${e} s`;const t=Math.floor(e/60);return t<60?`${t} m ${String(e%60).padStart(2,"0")} s`:`${Math.floor(t/60)} h ${String(t%60).padStart(2,"0")} m`}const Qj=1500;function e6(s,e){return new Promise(t=>{const i=setTimeout(()=>t(null),e);s.then(n=>{clearTimeout(i),t(n)},()=>{clearTimeout(i),t(null)})})}const t6=["expired","failed","error"];function tc(s,e,t){for(const i of s.envelopes){if(i.model?.kind!==e)continue;const n=t(i.model.data);if(n.success&&n.data!==void 0)return n.data}return null}function s6(s){return s===null?"REGION":s.includes(":")?s.slice(s.indexOf(":")+1):s}function i6(s){return s.limit.replace(new RegExp(`^(standard-)?${s.family.toLowerCase()}-`),"").replace(/-count$/,"")}function n6(s){const e=s.available===null?`${s.value} PERMITTED`:`${s.available} / ${s.value} FREE`;return`${s.family.toUpperCase()} ${s6(s.zone)} ${i6(s)} ${e}`}function gh(s,e){return`${e==="USD"?"$":`${e} `}${s.toFixed(2)}`}async function r6(s){let e=null,t=null;try{e=tc(await s("vm status"),s2,i=>r2.safeParse(i))}catch{return[]}if(e===null)return[];try{t=tc(await s("vm cost"),Rp,i=>kp.safeParse(i))}catch{t=null}return e.vms.map(i=>({row:i,rate:t?.vms.find(n=>n.name===i.name)?.cost??null}))}function tw(s,e){const t=new RegExp(`^vm new ${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`);return s.find(i=>i.lines.some(n=>t.test(n)))?.path??null}async function o6(s){const e=n=>{for(const r of n.envelopes){if(r.model?.kind!=="fs.listing"||!Array.isArray(r.model.data))continue;const a=r.model.data[0]?.items;return Array.isArray(a)?a:[]}return[]},t=[];let i=[];try{i=e(await s("ls /scripts")).map(n=>n.name)}catch{return t}for(const n of i){let r=[];try{r=e(await s(`ls /scripts/${n}`)).filter(o=>o.type==="script"||o.name.endsWith(".mise")).map(o=>o.name)}catch{continue}for(const o of r){const a=`/scripts/${n}/${o}`;let l="NOT READ",c=null,h=[];try{const d=tc(await s(`play ${a} --status`),mz,u=>gz.safeParse(u));if(d!==null){h=d.lines.map(p=>p.text);const u=Kh(h.join(`
|
|
@@ -4355,7 +4355,7 @@ void main() {
|
|
|
4355
4355
|
`):r.length>0?"A feed is being indexed on its first visit; it opens when the walk completes.":"",this.fields.latency.textContent=e.lastCommandDurationMs>0?`${e.lastCommandDurationMs}MS`:""}progress_observe(e){M6(this.running,e),this.activity_paint()}activity_clear(){this.running.clear(),this.activity_paint()}connection_show(e){this.fields.lamp.textContent=e?"ONLINE":"OFFLINE",this.fields.lamp.classList.toggle("lamp-online",e),this.fields.lamp.classList.toggle("lamp-offline",!e),e||this.activity_clear()}activity_paint(){if(this.running.size===0){this.activityTimer!==null&&(clearInterval(this.activityTimer),this.activityTimer=null),this.fields.activity.textContent="";return}const e=()=>{const t=Nf[this.activityFrame]??Nf[0];this.fields.activity.textContent=`${t} ${this.running.size} RUNNING`};e(),this.activityTimer===null&&(this.activityTimer=window.setInterval(()=>{this.activityFrame=(this.activityFrame+1)%Nf.length,e()},v6))}}function gr(s,e){const t=s.getElementById(e);if(t===null)throw new Error(`status bar: no element with id '${e}'`);return t}const y6=3e3;class S6{mount;clock;line_send;lane=void 0;cube=void 0;beatAt=null;constructor(e,t=()=>Date.now(),i){this.mount=e,this.clock=t,this.line_send=i,this.render()}telemetry_show(e={}){this.beatAt=this.clock(),e.lane!==void 0&&(this.lane=e.lane),e.cube!==void 0&&(this.cube=e.cube),this.render()}tick(){this.render()}rows_compose(){const e=[],t=this.lane;if(t===void 0)e.push({label:"LANE",value:"—",title:"The daemon has not said what holds its lane (an older daemon).",degraded:!1});else if(t.running===null)e.push({label:"LANE",value:t.waiting>0?`IDLE · ${t.waiting} WAITING`:"IDLE",title:"The serialized command lane: nothing is executing.",degraded:!1});else{const r=(t.running.sinceMs/1e3).toFixed(1);e.push({label:"LANE",value:`${t.running.line} · ${r} S${t.waiting>0?` · ${t.waiting} WAITING`:""}`,title:`The command holding the lane${t.running.surface?`, from surface ${t.running.surface}`:""}; every other command waits behind it.`,degraded:t.running.sinceMs>=1e4})}const i=t?.questions??[];if(i.length>0){const r=i.reduce((o,a)=>o.sinceMs>=a.sinceMs?o:a);e.push({label:"ASKING",value:`${i.length} · ${r.message.trim()} · ${(r.sinceMs/1e3).toFixed(0)} S`,title:"Questions open in the session. A command waiting on one has stepped out of the lane; it resumes when answered on the surface that asked.",degraded:!1})}for(const r of t?.joblets??[])e.push({label:`%${r.number}`,value:`${r.line} · ${r.waiting?`WAITING · FG %${r.number} TO ANSWER`:"RUNNING"}`,title:`Joblet %${r.number}, run in the background: its log is /proc/joblets/${r.number}/log.`,degraded:r.waiting,stop:`kill %${r.number}`});if(this.beatAt===null)e.push({label:"BEAT",value:"NONE YET",title:"No telemetry heartbeat has landed.",degraded:!1});else{const r=Math.max(0,this.clock()-this.beatAt);e.push({label:"BEAT",value:`${(r/1e3).toFixed(1)} S AGO`,title:"The age of the last telemetry heartbeat; the daemon beats once a second while a surface is attached.",degraded:r>=y6})}const n=this.cube;if(n===void 0)e.push({label:"CUBE",value:"NO PAGE TIMED",title:"CUBE's pace is known once a page of a list has been fetched.",degraded:!1});else{const r=n.msPerPage>0?Math.round(6e4/n.msPerPage):0;e.push({label:"CUBE",value:`${(n.msPerPage/1e3).toFixed(1)} S/PAGE · ${r} PAGES/MIN`,title:`The median of the last ${n.samples} page fetches (100 rows each).`,degraded:!1})}return e}render(){const e=this.rows_compose();this.mount.replaceChildren();for(const t of e){const i=document.createElement("div");i.className="lane-row telemetry-row",i.classList.toggle("status-degraded",t.degraded),i.title=t.title;const n=document.createElement("span");n.className="telemetry-label",n.textContent=t.label;const r=document.createElement("span");if(r.className="telemetry-value",r.textContent=t.value,i.append(n,r),t.stop!==void 0&&this.line_send!==void 0){const o=document.createElement("button");o.type="button",o.className="lane-stop",o.textContent="STOP",o.title=t.stop;const a=this.line_send,l=t.stop;o.addEventListener("click",()=>a(l)),i.appendChild(o)}this.mount.appendChild(i)}}}const z6=[2,3,3,2,2,11,2,2],x6=4,sw=300,O6=2600,E6=650;class A6{wrapper;cells=[];bootedAt=Date.now();telemetry={jobsLoaded:0,jobsTotal:0,feeds:0,lastLatencyMs:0,latencySumMs:0,lastExitCode:0,commandsRun:0,opsActive:0,opsDone:0,opsFailed:0,itemsCurrent:0,itemsTotal:0,connected:0};activeOperations=new Set;telemetryRows=[];constructor(e){if(this.wrapper=e,e===null){window.setInterval(()=>this.beat_paint(),sw);return}const t=this.narrowSources_list(),i=this.wideSources_list();let n=0,r=0;for(const o of z6){const a=document.createElement("div");a.className="data-column";for(let l=1;l<=x6;l++){const c=document.createElement("div");c.className=`dc-row-${l}`;let h;o>=6?(h=i[r%i.length],r++):(h=t[n%t.length],n++);const d={element:c,width:o,source:h??(()=>0)};c.textContent=iw(d.source(),o),a.appendChild(c),this.cells.push(d)}e.appendChild(a)}window.setInterval(()=>this.beat_paint(),sw),this.sweep_start()}promptContext_observe(e){const t=e.procWarmup;t!==void 0&&(this.telemetry.jobsLoaded=t.loaded,this.telemetry.jobsTotal=t.total??t.loaded);const i=e.procIndex;i!==void 0&&(t===void 0&&(this.telemetry.jobsLoaded=i.jobs,this.telemetry.jobsTotal=i.jobs),this.telemetry.feeds=i.feeds),e.lastCommandDurationMs>0&&(this.telemetry.lastLatencyMs=e.lastCommandDurationMs,this.telemetry.latencySumMs+=e.lastCommandDurationMs,this.telemetry.commandsRun++),this.telemetry.lastExitCode=e.lastExitCode}progress_observe(e){const t=`${e.operation}:${e.itemId??""}`;if(e.phase==="complete"||e.phase==="failed"){const i=`${e.operation}:`;for(const n of[...this.activeOperations])(n===t||n.startsWith(i))&&this.activeOperations.delete(n);e.status==="error"||e.phase==="failed"?this.telemetry.opsFailed++:this.telemetry.opsDone++}else e.itemId!==void 0&&e.status!==void 0&&["done","error","unconfirmed","stalled","timeout"].includes(e.status)?this.activeOperations.delete(t):this.activeOperations.add(t);this.telemetry.opsActive=this.activeOperations.size,e.current!==void 0&&(this.telemetry.itemsCurrent=e.current),e.total!==void 0&&(this.telemetry.itemsTotal=e.total)}index_observe(e){this.telemetry.jobsLoaded=e.jobs,this.telemetry.jobsTotal=e.jobs,this.telemetry.feeds=e.feeds}connection_show(e){this.telemetry.connected=e?1:0,this.wrapper?.classList.toggle("dc-stale",!e)}telemetryPanel_bind(e){const t=this.telemetry,i=[["LINK",()=>t.connected===1?"ONLINE":"OFFLINE"],["JOBS INDEXED",()=>`${t.jobsLoaded} / ${t.jobsTotal}`],["FEEDS VISIBLE",()=>String(t.feeds)],["OPS ACTIVE",()=>String(t.opsActive)],["OPS DONE",()=>String(t.opsDone)],["OPS FAILED",()=>String(t.opsFailed)],["ITEMS",()=>`${t.itemsCurrent} / ${t.itemsTotal}`],["LAST COMMAND",()=>`${t.lastLatencyMs} MS`],["LATENCY SUM",()=>`${t.latencySumMs} MS`],["COMMANDS RUN",()=>String(t.commandsRun)],["LAST EXIT",()=>String(t.lastExitCode)],["UPTIME",()=>`${this.uptimeSeconds_get()} S`]];for(const[n,r]of i){const o=document.createElement("div");o.className="telemetry-row";const a=document.createElement("span");a.className="telemetry-label",a.textContent=n;const l=document.createElement("span");l.className="telemetry-value",l.textContent=r(),o.append(a,l),e.appendChild(o),this.telemetryRows.push({element:l,source:r})}}narrowSources_list(){const e=this.telemetry;return[()=>e.jobsLoaded,()=>e.feeds,()=>e.lastLatencyMs,()=>e.opsActive,()=>e.opsDone,()=>e.jobsTotal,()=>e.itemsCurrent,()=>e.itemsTotal,()=>e.opsFailed,()=>e.commandsRun,()=>e.lastExitCode,()=>new Date().getSeconds(),()=>this.uptimeSeconds_get()]}wideSources_list(){return[()=>Math.floor(Date.now()/1e3),()=>this.uptimeSeconds_get(),()=>this.telemetry.latencySumMs,()=>T6()]}uptimeSeconds_get(){return Math.floor((Date.now()-this.bootedAt)/1e3)}beat_paint(){for(const e of this.cells){const t=iw(e.source(),e.width);e.element.textContent!==t&&(e.element.textContent=t)}for(const e of this.telemetryRows){const t=e.source();e.element.textContent!==t&&(e.element.textContent=t)}}sweep_start(){if(this.wrapper===null)return;const e=Array.from(this.wrapper.querySelectorAll(".data-column"));window.setInterval(()=>{const t=e[Math.floor(Math.random()*e.length)];t!==void 0&&(t.classList.add("dc-sweep"),window.setTimeout(()=>t.classList.remove("dc-sweep"),E6))},O6)}}function iw(s,e){const t=String(Math.max(0,Math.floor(s)));return t.length>e?t.slice(t.length-e):t.padStart(e,"0")}function T6(){const s=new Date;return s.getHours()*1e4+s.getMinutes()*100+s.getSeconds()}const D6=2e4;class I6{scene;nameplate;command_run;names=[];cursor=0;timer=null;seen=new Map;constructor(e,t,i){this.nameplate=t,this.command_run=i,this.scene=new uu(e,{},{ambient:!0}),new MutationObserver(()=>this.scene.palette_refresh()).observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),new MutationObserver(()=>{window.setTimeout(()=>this.scene.size_fit(),60)}).observe(document.body,{attributes:!0,attributeFilter:["data-header"]}),window.addEventListener("resize",()=>this.scene.size_fit())}names_set(e){this.names=e,this.cursor=0,this.timer!==null&&(window.clearInterval(this.timer),this.timer=null),e.length!==0&&(this.next_request(),e.length>1&&(this.timer=window.setInterval(()=>this.next_request(),D6)))}envelope_observe(e){if(e.model?.kind!==Cr.pipelineDiagram)return;const t=Jg.safeParse(e.model.data);if(!t.success)return;const i=t.data;this.seen.set(i.name,i),this.model_stage(i)}model_stage(e){this.nameplate.textContent=e.name,this.scene.graph_set({nodes:e.nodes.map(t=>({id:t.id,label:t.label,parentIds:t.parentIds,joinParentIds:t.joinParentIds}))}),this.scene.size_fit()}next_request(){const e=this.names[this.cursor%this.names.length];if(this.cursor++,e===void 0)return;const t=this.seen.get(e);if(t!==void 0){this.model_stage(t);return}this.command_run(`pipeline diagram ${e}`)}}function C6(s,e){s.line_execute("ls /bin",{silent:!0,observe:!1}).then(t=>{const r=(t.envelopes.find(o=>o.model?.kind==="fs.listing")?.model?.data??[]).flatMap(o=>o.items).filter(o=>o.type==="pipeline").map(o=>o.name);e.names_set(r)})}const nw=new Set(["layout","slice","series","wl","colormap","save","tags","load","guard","ghost","state"]);function R6(s,e,t,i,n){if(t==="layout")return no(s,e,".dag-strategy",i.toUpperCase())?`layout ${i}`:"dag layout ranked|molecule";if(t==="projection")return no(s,e,".dag-projection",i.toUpperCase())?`projection ${i}`:"dag projection 2d|3d";if(t==="scale")return no(s,e,".dag-scale",i.toUpperCase())?`scale ${i}`:"dag scale time|size";if(t==="hue")return no(s,e,".dag-hue",i.toUpperCase())?`hue ${i}`:"dag hue status|compute";const r=(o,a,l,c)=>{const h=i.toLowerCase();return h==="on"||h==="off"?no(s,e,o,h==="on"?l:c)?`${a} ${h}`:`dag ${a}: no mode frame`:h!==""?`dag ${a} on|off`:jn(s,e,o)?`${a} toggled`:`dag ${a}: no mode frame`};if(t==="pulse")return r(".dag-pulse","pulse","PULSE ON","PULSE OFF");if(t==="census")return r(".dag-census","census","CENSUS","SHAPE");if(t==="gravity")return r(".dag-gravity","gravity","GRAVITY ON","GRAVITY OFF");if(t==="draw")return no(s,e,".dag-draw",i.toUpperCase())?`draw ${i}`:"dag draw spheres|stars";if(t==="select")return i===""?"dag select <feed or job>":s.dag_jump(e,i)?`selecting ${i}`:"dag select: no RUNS pane (view runs)";if(t==="enter")return i===""?"dag enter <job>":s.dag_jump(e,i,!0)?`entering ${i}`:"dag enter: no RUNS pane (view runs)";if(t==="refresh")return kh(s,e,"REFRESH")?"refreshing":"dag refresh: no DAG pane";if(t==="physics"){const o=i,a=s.paneMount_get(e),l=a?.querySelector(".pane-dag")??a;if(l===null)return"dag physics: no DAG pane";if(o==="reset")return l.dispatchEvent(new CustomEvent("argus:dag-physics",{detail:"reset"})),"physics reset";const c=(n[2]??"on").toLowerCase()!=="off";return["charge","link","collide","gravity"].includes(o)?(l.dispatchEvent(new CustomEvent("argus:dag-physics",{detail:{term:o,on:c}})),`physics ${o} ${c?"on":"off"}`):`dag physics: unknown term '${o}' (charge|link|collide|gravity|reset)`}return`dag: unknown verb '${t}' (layout|projection|scale|hue|draw|pulse|census|gravity|select|enter|physics|refresh)`}function k6(s,e,t){return t==="enter"?kh(s,e,"ENTER NODE")?"entering node":"node enter: no DAG drawer":t==="back"?kh(s,e,"BACK")?"node back":"node back: no DAG drawer":t==="immerse"?s.node_immerse(e)?"immersing":"node immerse: nothing indicated":t==="clear"?kh(s,e,"CLEAR DETAIL")?"detail cleared":"node clear: no DAG drawer":`node: unknown verb '${t}' (enter|immerse|back|clear)`}function N6(s){return{subjects:{runs:null,node:null,dag:null,universe:null,pacs:new Set(["sort","filter"]),tags:new Set(["redact","filter"]),image:nw},views:{runs:{button:"gutter-runs",primary:"dag"},pacs:{button:"gutter-tools",primary:"pacs"}},claims:{runs:".empty-go-dag",pacs:".empty-go-pacs"},listings:{runs:{selector:".pane-dag",named:"DAG"},pacs:{selector:"#pacs-workspace",named:"PACS"}},chords:[{after:"1",key:"2",topic:"claim",selector:".empty-go-dag",does:"claim an empty pane as RUNS"},{after:"1",key:"3",topic:"claim",selector:".empty-go-pacs",does:"claim an empty pane as PACS"}],lines:[{after:"view",line:"runs enter <feedId> · sort <col> [asc|desc] · filter <text>|off"},{after:"view",line:"node enter · immerse · back · clear (the indicated node)"},{after:"view",line:"dag [@id] layout ranked|molecule · projection 2d|3d · scale time|size · hue status|compute · draw spheres|stars · pulse [on|off] · census [on|off] · gravity [on|off] · select <feed or job> · enter <job> · physics charge|link|collide|gravity on|off · physics reset · refresh"},{after:"file",line:"pacs sort <col> [asc|desc] · filter <text>|off (the results listing; every other pacs verb is the session's)"},{after:"file",line:"image [@id] [--force] <path> · layout single|mpr|3d|slab · slice <n> · series <n> · wl <lo> <hi> · wl preset <name> · colormap gray|hot|jet|cool · save · tags · load · guard <bytes>|off · ghost <0..1>|off · state"},{after:"file",line:"tags [@id] redact on|off · filter <text>|off (the pane that follows an image pane's slice)"}],run:(e,t,i)=>{const n=s(),{subject:r,words:o}=t,a=(o[0]??"").toLowerCase(),l=(o[1]??"").toLowerCase();if(r==="runs"){if(a==="enter"){const h=parseInt(l.replace(/^feed_/,""),10);return Number.isNaN(h)?"runs enter <feedId>":(n.feed_enter(h),`entering feed_${h}`)}return`runs: unknown verb '${a}' (enter)`}if(!["dag","image","tags","universe","node"].includes(r))return;const c=i();if(c===null)return`${r}: no target pane (nothing focused?)`;if(r==="dag")return R6(n,c,a,l,o);if(r==="image"){const h=o.filter(d=>d!=="--force");return nw.has((h[0]??"").toLowerCase())?n.image_control(c,a,o.slice(1)):null}return r==="tags"?n.tags_control(c,a,o.slice(1)):r==="universe"?n.universe_control(c,a,o.slice(1)):k6(n,c,a)}}}function sc(s,e){if("pane"in s)return s.pane===e?[]:null;const t=sc(s.first,e);if(t!==null)return[{node:s,side:"first"},...t];const i=sc(s.second,e);return i!==null?[{node:s,side:"second"},...i]:null}function ic(s,e,t){if(s===e)return t;if("pane"in s)return null;const i=ic(s.first,e,t);if(i!==null)return{...s,first:i};const n=ic(s.second,e,t);return n!==null?{...s,second:n}:null}function rw(s,e,t){const i=sc(s,e);if(i===null||i.length===0)return"lone";const n=Fi[t].axis,r=Fi[t].place==="after"?"first":"second",o=i[i.length-1];let a=null;for(let d=i.length-1;d>=0;d-=1){const u=i[d];if(u.node.dir===n&&u.side===r){a=u.side==="first"?u.node.second:u.node.first;break}}if(a===null){if(o.node.dir===n)return"edge";a=o.side==="first"?o.node.second:o.node.first}const l=kd(s,e);if(l===null)return"lone";const c={pane:e};return ic(l,a,r==="first"?{dir:n,ratio:.5,first:a,second:c}:{dir:n,ratio:.5,first:c,second:a})??"edge"}const ow="argus-layout";class B6{root;mounts;presets=new Map;prefs={};activePreset="";tree=null;focusedPane=null;renderObserver=null;previousFocus=null;constructor(e,t){this.root=e,this.mounts=t;try{const i=window.localStorage.getItem(ow);this.prefs=i!==null?JSON.parse(i):{}}catch{this.prefs={}}}renderObserver_set(e){this.renderObserver=e}preset_register(e,t){this.presets.set(e,t)}mount_register(e,t){this.mounts.set(e,t)}mount_remove(e){this.mounts.delete(e),this.focusedPane===e&&(this.focusedPane=null)}leaf_split(e,t,i,n=!1){if(this.tree===null)return!1;const r=Rd(this.tree,e,{dir:t,ratio:.5,first:n?{pane:i}:{pane:e},second:n?{pane:e}:{pane:i}});return r===null?!1:(this.tree=r,this.focus_move(i),this.render(),!0)}leaf_move(e,t){if(this.tree===null)return"lone";const i=rw(this.tree,e,t);return typeof i=="string"?i:(this.tree=i,this.focus_move(e),this.render(),!0)}focus_move(e){this.focusedPane!==null&&this.focusedPane!==e&&(this.previousFocus=this.focusedPane),this.focusedPane=e}focus_last(){const e=this.previousFocus;return e===null||!this.panes_shown().includes(e)?null:(this.focus_set(e),e)}leaf_flip(e){if(this.tree===null)return!1;const t=sc(this.tree,e);if(t===null||t.length===0)return!1;const i=t[t.length-1],n={...i.node,dir:i.node.dir==="col"?"row":"col"},r=ic(this.tree,i.node,n);return r===null?!1:(this.tree=r,this.render(),!0)}leaf_resize(e,t,i=.05){if(this.tree===null)return!1;const n=sc(this.tree,e);if(n===null||n.length===0)return!1;const r=Fi[t].axis;for(let o=n.length-1;o>=0;o-=1){const a=n[o];if(a.node.dir!==r)continue;const l=Fi[t].place==="after",c=Math.min(.85,Math.max(.15,a.node.ratio+(l?i:-i))),h={...a.node,ratio:c},d=ic(this.tree,a.node,h);return d===null?!1:(this.tree=d,this.ratio_remember(n.slice(0,o).map(u=>u.side==="first"?"0":"1").join(""),c),this.render(),!0)}return!1}move_possible(e,t){return this.tree!==null&&typeof rw(this.tree,e,t)!="string"}leaf_replace(e,t){if(this.tree===null)return!1;const i=Rd(this.tree,e,{pane:t});return i===null?!1:(this.tree=i,this.focusedPane===e&&(this.focusedPane=t),this.render(),!0)}leaf_close(e){if(this.tree===null||"pane"in this.tree)return!1;const t=kd(this.tree,e);return t===null?!1:(this.tree=t,this.focusedPane===e&&(this.focusedPane=null),this.render(),!0)}focused_get(){return this.focusedPane}savedPreset_get(){return this.prefs.preset!==void 0&&this.presets.has(this.prefs.preset)?this.prefs.preset:null}activePreset_get(){return this.activePreset}preset_has(e){return this.presets.has(e)}preset_apply(e){const t=this.presets.get(e);t!==void 0&&(this.activePreset=e,this.prefs.preset=e,this.prefs_save(),this.tree=this.ratios_restore(t(),e,""),this.render(),this.root.classList.remove("layout-arrive"),this.root.offsetWidth,this.root.classList.add("layout-arrive"))}tree_get(){return this.tree===null?null:JSON.parse(JSON.stringify(this.tree))}tree_set(e){this.tree=this.ratios_restore(e,this.activePreset,""),this.render()}panes_shown(){const e=[],t=i=>{if(i!==null){if("pane"in i){e.push(i.pane);return}t(i.first),t(i.second)}};return t(this.tree),e}render(){if(this.tree!==null){for(const e of this.mounts.values())e.remove();this.root.replaceChildren(this.node_render(this.tree,"")),this.focus_reconcile(),this.renderObserver?.()}}focus_reconcile(){const e=this.panes_shown();if(this.focusedPane!==null&&e.includes(this.focusedPane))return;const t=e[0];if(t===void 0)return;const i=this.focusedPane;this.focusedPane=null,this.focus_set(t),i!==null&&(this.previousFocus=i)}node_render(e,t){if("pane"in e){const a=document.createElement("div");a.className="layout-leaf",a.dataset.leaf=e.pane;const l=this.mounts.get(e.pane);return l!==void 0&&(a.appendChild(l),l.style.display="",a.addEventListener("mousedown",()=>this.focus_set(e.pane),{capture:!0}),e.pane===this.focusedPane&&a.classList.add("pane-focused")),a}const i=document.createElement("div");i.className=`layout-split layout-${e.dir}`;const n=this.node_render(e.first,`${t}0`),r=this.node_render(e.second,`${t}1`);n.style.flex=`${e.ratio} 1 0`,r.style.flex=`${1-e.ratio} 1 0`;const o=document.createElement("div");return o.className="layout-divider",this.divider_wire(o,i,e,n,r,t),i.append(n,o,r),i}divider_wire(e,t,i,n,r,o){let a=!1;e.addEventListener("mousedown",l=>{a=!0,l.preventDefault()}),window.addEventListener("mousemove",l=>{if(!a)return;const c=t.getBoundingClientRect(),h=i.dir==="col"?(l.clientX-c.left)/c.width:(l.clientY-c.top)/c.height;i.ratio=Math.min(.85,Math.max(.15,h)),n.style.flex=`${i.ratio} 1 0`,r.style.flex=`${1-i.ratio} 1 0`}),window.addEventListener("mouseup",()=>{a&&(a=!1,this.ratio_remember(o,i.ratio),this.renderObserver?.())})}focus_set(e){if(this.focusedPane===e)return;this.focusedPane!==null&&(this.previousFocus=this.focusedPane),this.focusedPane=e,document.body.dataset.focus=e;for(const i of this.root.querySelectorAll(".layout-leaf"))i.classList.remove("pane-focused");this.mounts.get(e)?.parentElement?.classList.add("pane-focused")}ratios_restore(e,t,i){if("pane"in e)return e;const n=this.prefs.ratios?.[`${t}:${i}`];return{...e,ratio:n??e.ratio,first:this.ratios_restore(e.first,t,`${i}0`),second:this.ratios_restore(e.second,t,`${i}1`)}}ratio_remember(e,t){this.prefs.ratios={...this.prefs.ratios??{},[`${this.activePreset}:${e}`]:t},this.prefs_save()}prefs_save(){try{window.localStorage.setItem(ow,JSON.stringify(this.prefs))}catch{}}}function Rd(s,e,t){if("pane"in s)return s.pane===e?t:null;const i=Rd(s.first,e,t);if(i!==null)return{...s,first:i};const n=Rd(s.second,e,t);return n!==null?{...s,second:n}:null}function kd(s,e){if("pane"in s)return null;if("pane"in s.first&&s.first.pane===e)return s.second;if("pane"in s.second&&s.second.pane===e)return s.first;const t=kd(s.first,e);if(t!==null)return{...s,first:t};const i=kd(s.second,e);return i!==null?{...s,second:i}:null}const G6=4e3;function P6(s){const e=new WeakMap,t=(a,l)=>{const c=s.paneInstance_get(a)?.mount.querySelector(".pane-state")??null;if(c===null)return;const h=e.get(c);h!==void 0&&clearTimeout(h);const d={text:c.textContent??"",className:c.className};Ts(c,"note",l),e.set(c,setTimeout(()=>{e.delete(c),c.textContent===l&&(c.className=d.className,c.textContent=d.text)},G6))};return{bar_note:t,move:(a,l)=>{const c=s.layout.leaf_move(a,l);return c==="lone"?"pane move: the only pane on stage":c==="edge"?`pane move ${l}: already ${Fi[l].edge}`:(t(a,`MOVED ${l.toUpperCase()}`),s.sound("audio3"),`moved ${l}`)},flip:a=>s.layout.leaf_flip(a)?(t(a,"FLIPPED"),s.sound("audio3"),"flipped"):"pane flip: the only pane on stage",resize:(a,l,c)=>s.layout.leaf_resize(a,l,c)?`resized ${Fi[l].focusWord}`:`pane resize ${Fi[l].focusWord}: no boundary that way`,chordKeys_format:(a,l)=>{const c=zn.filter(h=>h.selector===a&&h.move===!0===l).map(h=>h.key);return c.length===0?"":` [keys ${c.join(" ")}]`}}}const L6={image:"viewer",view:"viewer",dir:"files",fs:"files",tags:"tags",empty:"pane",domain:"dag",catalogue:"catalogue",graph:"dag",gather:"gather",edit:"editor"},Bf=240;function W6(s,e){const{layout:t,panels:i,paneInstance_get:n,dormant:r}=s,o=new Map;let a=!1,l=null;const c=y=>n(y)?.kind??null,h=(y,M,v,S,x)=>{o.set(y,{parent:M,dir:v,before:S,...x!==void 0?{binding:x}:{}})},d=y=>{if(y==="pacs")return"⊞";if(y==="dag")return"⋔";const M=c(y);return M==="image"?"▣":M==="tags"?"≣":M==="edit"?"✎":"▤"},u=y=>{if(y.length===0)return;const M=[];for(const A of y){const E=n(A)?.mount;if(E===void 0)continue;const O=E.getBoundingClientRect();O.width>0&&O.height>0&&M.push({id:A,left:O.left,top:O.top,width:O.width,height:O.height})}if(M.length===0)return;const v=Math.min(...M.map(A=>A.left)),S=Math.min(...M.map(A=>A.top)),x=Math.max(...M.map(A=>A.left+A.width))-v,b=Math.max(...M.map(A=>A.top+A.height))-S;if(x<=0||b<=0)return;const z=Bf/x,T=Math.max(40,Math.min(260,Math.round(b*z)));try{const A=document.createElement("canvas");A.width=Bf,A.height=T;const E=A.getContext("2d");if(E===null)return;const R=getComputedStyle(document.documentElement).getPropertyValue("--harvestgold").trim()||"#c9a15a";E.fillStyle="#05070a",E.fillRect(0,0,Bf,T);for(const C of M){const k=Math.round((C.left-v)*z),G=Math.round((C.top-S)*z),L=Math.max(6,Math.round(C.width*z)),W=Math.max(6,Math.round(C.height*z)),ee=n(C.id)?.mount.querySelector("canvas");if(ee!=null&&ee.width>0){const X=Math.min(L/ee.width,W/ee.height),he=Math.round(ee.width*X),Ae=Math.round(ee.height*X);E.fillStyle="#000",E.fillRect(k,G,L,W),E.drawImage(ee,k+Math.round((L-he)/2),G+Math.round((W-Ae)/2),he,Ae)}else E.fillStyle="rgba(255,255,255,0.05)",E.fillRect(k,G,L,W),E.fillStyle=R,E.font=`${Math.max(9,Math.min(28,Math.round(Math.min(L,W)*.5)))}px serif`,E.textAlign="center",E.textBaseline="middle",E.fillText(d(C.id),k+L/2,G+W/2+1);E.strokeStyle="rgba(255,255,255,0.22)",E.lineWidth=1,E.strokeRect(k+.5,G+.5,L-1,W-1)}return A.toDataURL("image/png")}catch{return}},p=(y,M,v)=>{const S=c(y),x=o.get(y),b={dir:x?.dir??"col",side:OG(x?.before??!1)};if(Kv(y)){const T=M==="dag"?"runs":M,A=M==="pacs"?e.pacsQuery_get():null,E=M==="dag"?i.get("dag","dag"):void 0,O=E!==void 0&&E.graph_isShown()?E.feed_get():null,R=O!==null&&E!==void 0?E.view_lines():[],C=O!==null?E?.feedTitle_get():void 0;return{action:{op:"domain",domain:T,...A!==null?{query:A}:{},...O!==null?{feed:O}:{},...R.length>0?{view:R}:{}},...C!==void 0?{label:C}:{}}}if(x?.binding==="fs"||x?.binding==="view"||x?.binding==="empty")return{action:{op:x.binding,target:v,...b}};if(S==="image"){const T=i.get("image",y),A=T?.state_get()??null;if(T===void 0||A===null||A.path===null)return null;const E=[];A.layout!=="single"&&E.push(`image layout ${A.layout}`),A.colormap!==void 0&&A.colormap!=="gray"&&E.push(`image colormap ${A.colormap}`),A.voi!==void 0&&A.voi!==null&&E.push(`image wl ${A.voi.lower} ${A.voi.upper}`),A.slice>1&&E.push(`image slice ${A.slice}`),A.ghost!==void 0&&A.ghost!==null&&A.layout==="slab"&&E.push(`image ghost ${A.ghost}`);const O=T.series_get(),R=[O?.seriesDescription??"",O?.modality??""].filter(C=>C!=="");return{action:{op:"image",path:A.path,target:v,...b,...E.length>0?{view:E}:{}},anchor:A.path,...R.length>0?{label:R.join(" · ")}:{}}}const z=e.catalogue_find(y);if(z!==void 0){const T=i.get("files",y)?.commandLine_get()??"";return{action:{op:"catalogue",input:z.input,target:v,...b,...z.feed!==null?{feed:z.feed}:{},...z.node!==null?{node:z.node}:{},...T!==""?{line:T}:{}},label:`PROCESS ${z.input.split("/").filter(Boolean).pop()??z.input}`}}if(S==="files"){const T=i.get("files",y)?.path_current()??null;return typeof T!="string"||T.length===0?null:{action:{op:"dir",path:T,target:v,...b}}}if(S==="gather"){const T=i.get("gather",y);if(T===void 0)return null;const A=[...T.entries_get()],E=T.name_get(),O=T.feed_get();return{action:{op:"gather",series:A,target:v,...b,...E!==null?{name:E}:{},...O!==null?{feed:O.feedId,root:{instance:O.rootInstanceId,path:O.path}}:{}},label:E??`GATHER · ${A.length} series`}}if(S==="dag"){const T=i.get("dag",y)?.feed_get()??null;return T===null?null:{action:{op:"graph",feed:T,target:v,...b}}}if(S==="tags")return{action:{op:"tags",target:v,...b}};if(S==="edit"){const T=i.get("edit",y)?.path_get()??null;return T===null?null:{action:{op:"edit",path:T,target:v,...b},label:`EDIT ${T.split("/").pop()??T}`}}return null},f=()=>{if(a)return;const y=new Set(t.panes_shown()),M=t.activePreset_get();if(M==="panes"||M==="launcher")return;const v=Hh().map(W=>W.id).filter(W=>y.has(W)),S=new Map;let x,b;const z=[];for(const W of v){const ee=S.get(o.get(W)?.parent??"")??0,X=p(W,M,ee);X!==null&&(S.set(W,z.length),z.push(X.action),X.anchor!==void 0?x===void 0&&(x=X.anchor,X.label!==void 0&&(b=X.label)):X.label!==void 0&&b===void 0&&(b=X.label))}const T=z.filter(W=>W.op!=="domain"||W.feed!==void 0);if(T.length===0)return;const A=u(v),E=W=>{if("pane"in W){const he=S.get(W.pane);return he===void 0?null:{leaf:he}}const ee=E(W.first),X=E(W.second);return ee===null?X:X===null?ee:{dir:W.dir,ratio:W.ratio,first:ee,second:X}},O=t.tree_get(),R=O===null?null:E(O),C=[...new Set(T.map(W=>L6[W.op]??"pane"))];let k,G,L;if(x!==void 0)k=x,G=b??x.split("/").pop()??x,L={address:x,modelKind:"dicom.series"};else{const W=T.map(he=>he.path).find(he=>he!==void 0),ee=T.map(he=>he.path??(he.input!==void 0?`catalogue:${he.input}`:he.series!==void 0?`gather:${he.series.map(Ae=>Ae.seriesUID).join(",")}`:he.feed!==void 0?`feed:${he.feed}`:he.op)).sort().join("|"),X=M==="dag"?"RUNS":M.toUpperCase();k=`${M}:${ee}`,G=b!==void 0&&b!==""?b:W!==void 0?W.split("/").pop()??W:`${X} · ${T.length+1} panes`,L={address:k,modelKind:"argus.desktop"}}r.add({id:k,label:G,regard:L,members:C,actions:z,...R===null?{}:{shape:R},...A===void 0?{}:{thumbnail:A},lastTouched:Date.now()})},_=()=>{const y=new Set(t.panes_shown());for(const M of Hh())y.has(M.id)||Kv(M.id)||M.id==="panes"||M.id==="launcher"||M.id==="universe"||(Ds(M.id),t.mount_remove(M.id));e.stage_relight()},g=y=>{f(),t.preset_apply(y),_()},m=(y,M)=>{const v=z=>Hh().filter(T=>t.panes_shown().includes(T.id)&&c(T.id)===z).map(T=>T.id),S={dir:y.dir??"col",before:y.side==="before"},x=z=>{l=S;try{return z()}finally{l=null}},b=(z,T)=>v(z).find(A=>!T.has(A))??null;if(y.op==="domain"){const z=y.domain==="runs"?"dag":y.domain==="pacs"?"pacs":"files";if(g(z),y.query!==void 0&&s.terminal.line_run(y.query),y.feed!==void 0){const T=y.feed,A=y.view??[],E=i.get("dag","dag");if(E?.feed_enter(T),A.length>0&&E!==void 0){const O=R=>{if(E.graph_isShown()&&E.feed_get()===T){for(const C of A)s.terminal.line_run(C);return}R>0&&window.setTimeout(()=>O(R-1),250)};O(240)}}return z}if(M!==null&&t.focus_set(M),y.op==="image"&&y.path!==void 0){let z=null;const T=y.path,A=x(()=>e.image_open(null,T,{},R=>{z=R})),E=y.view,O=z;return E!==void 0&&E.length>0&&O!==null&&A.then(()=>{for(const R of E)t.focus_set(O),s.terminal.line_run(R)}).catch(()=>{}),z}if(y.op==="dir"&&y.path!==void 0){const z=new Set(v("files")),T=y.path;return x(()=>e.dir_open(T)),b("files",z)}if(y.op==="tags"){const z=new Set(v("tags"));return x(()=>s.terminal.line_run("image tags")),b("tags",z)}if(y.op==="catalogue"&&y.input!==void 0){const z=()=>e.catalogueIds().filter(O=>t.panes_shown().includes(O)),T=new Set(z()),A=y.input;x(()=>e.process_open(M??"files",{input:A,feed:y.feed??null,node:y.node??null}));const E=z().find(O=>!T.has(O))??null;return E!==null&&y.line!==void 0&&i.get("files",E)?.commandLine_set(y.line),E}if(y.op==="gather"&&y.series!==void 0){const z=[...y.series],T=x(()=>e.gather_open(z,M??"pacs"));return T!==null&&y.name!==void 0&&i.get("gather",T)?.name_set(y.name),T}if(y.op==="graph"&&y.feed!==void 0){const z=new Set(v("dag")),T=y.feed;return x(()=>e.feed_open(M??"files",T)),b("dag",z)}if(y.op==="edit"&&y.path!==void 0){const z=y.path;return x(()=>e.edit_open(z))}return y.op==="fs"||y.op==="view"||y.op==="empty"?M===null?null:e.pillPane_spawn(M,y.op,S.dir,S.before):null};return{birth_record:h,replayPlace_get:()=>l,replaying:()=>a,strip_capture:u,capture:f,orphans_dispose:_,domain_enter:g,restore:async y=>{const M=r.get(y);if(!(M===void 0||M.actions===void 0)){r.dismiss(y),a=!0;try{const v=[];for(const S of M.actions){const x=v[S.target??0]??null;v.push(m(S,x))}if(M.shape!==void 0){const S=b=>{if("leaf"in b){const A=v[b.leaf]??null;return A===null?null:{pane:A}}const z=S(b.first),T=S(b.second);return z===null?T:T===null?z:{dir:b.dir,ratio:b.ratio,first:z,second:T}},x=S(M.shape);x!==null&&!("pane"in x)&&t.tree_set(x)}}finally{a=!1,e.stage_relight()}}}}}const F6=2200;function U6(s){return/\x1b\[/.test(s)?Wn(s):oi(s).replace(/("[^&]*")/g,'<span class="man-str">$1</span>').replace(/(^|\s)(--?[a-zA-Z][\w-]*)/g,'$1<span class="man-flag">$2</span>').replace(/^(\s{0,2})([A-Za-z_ ]+):(\s)/gm,'$1<span class="man-key">$2:</span>$3').replace(/^([A-Z][A-Z ]{2,})$/gm,'<span class="man-head">$1</span>')}function $6(s,e,t,i){if(s===void 0)return[];const n=s.arguments??[],r=[{label:"NODE",value:`${s.label} · @${s.id}`},{label:"PLUGIN",value:s.pluginName},...s.pluginVersion!==void 0?[{label:"VERSION",value:s.pluginVersion}]:[]];if(e){const o=HG(s.label,s.id,i);r.push(...n.length===0?[{label:"ARGUMENTS",value:"none — this node runs on the plugin's defaults"}]:n.map(a=>({label:a.name,value:String(a.value??""),...t?{edit:{flag:`--${o}.${a.name}`,type:typeof a.value=="boolean"?"boolean":"string",placeholder:String(a.value??"")}}:{}})))}else r.push({label:"ARGUMENTS",value:n.length===0?"none":`${n.length} — open the node to read them`});return r}function j6(s,e,t){const i=[{label:"PLUGIN",value:s.name},{label:"VERSION",value:s.version},{label:"TYPE",value:s.type.toUpperCase()}],n=s.parameters;if(!e)return i.push({label:"PARAMETERS",value:n.length===0?"none":`${n.length} — open the node to read them`}),i;if(n.length===0)return i.push({label:"PARAMETERS",value:"none — this plugin takes no arguments"}),i;for(const r of n){const o=[r.type];r.optional||o.push("required");const a=r.default===void 0||r.default===null?"":String(r.default);a!==""&&o.push(`default ${a}`);const l=o.join(" · ");i.push({label:r.flag,value:r.help===void 0?l:`${l} — ${r.help}`,...t?{edit:{flag:r.flag,type:r.type,placeholder:a}}:{}})}return i}function aw(s,e,t,i){s.replaceChildren(),s.classList.toggle("dag-facts-immersed",t);for(const{label:n,value:r,edit:o}of e){const a=document.createElement("div");a.className="telemetry-row";const l=document.createElement("span");if(l.className="telemetry-label",l.textContent=n,a.appendChild(l),o===void 0||i===null){const c=document.createElement("span");c.className="telemetry-value",c.textContent=r,a.appendChild(c)}else{const c=UG(i.line_get(),o.flag),h=document.createElement("input");h.className="telemetry-input",h.spellcheck=!1,h.autocomplete="off",h.title=`${o.flag} — ${r}`,o.type==="boolean"?(h.type="checkbox",h.checked=c===!0,h.addEventListener("change",()=>{i.line_set(aM(i.line_get(),o.flag,h.checked?!0:null))})):(h.type="text",h.placeholder=o.placeholder,h.value=c===null||c===!0?"":c,h.addEventListener("input",()=>{i.line_set(aM(i.line_get(),o.flag,h.value))}));const d=document.createElement("span");d.className="telemetry-hint",d.textContent=r,a.append(h,d)}s.appendChild(a)}}function H6(s,e,t,i){const n=s.closest(".files-body"),r=n?.querySelector(".diagram-strategy")??null,o=n?.querySelector(".diagram-projection")??null,a=n?.querySelector(".diagram-pulse")??null,l=i===void 0?null:n?.querySelector(".diagram-run")??null,c=()=>i?.(),h=()=>{const f=[];e.strategy_get()!=="ranked"&&f.push("MOLECULE"),e.projection_get()!=="3d"&&f.push("2D"),t.mode_annunciate(f.join(" · "))},d=()=>{e.strategy_set(e.strategy_get()==="ranked"?"molecule":"ranked"),r!==null&&(r.textContent=e.strategy_get().toUpperCase()),h()},u=()=>{e.projection_set(e.projection_get()==="3d"?"2d":"3d"),o!==null&&(o.textContent=e.projection_get().toUpperCase()),h()},p=()=>{e.wave_start(),a?.classList.add("pulse-running"),window.setTimeout(()=>a?.classList.remove("pulse-running"),F6)};return r!==null&&(r.textContent=e.strategy_get().toUpperCase()),o!==null&&(o.textContent=e.projection_get().toUpperCase()),r?.addEventListener("click",d),o?.addEventListener("click",u),a?.addEventListener("click",p),l?.addEventListener("click",c),h(),()=>{r?.removeEventListener("click",d),o?.removeEventListener("click",u),a?.removeEventListener("click",p),l?.removeEventListener("click",c),a?.classList.remove("pulse-running")}}function V6(s,e){let t=null;const i=(c,h,d,u)=>{let p=null,f=null;const _=c.contentHtml_show(h,"",{diagram:!0,release:()=>{t=null,f?.(),f=null,c.mode_annunciate(""),p?.dispose(),p=null}});_!==null&&d().then(g=>{if(!_.isConnected)return;if(g===null||g.nodes.length===0){_.textContent="NOTHING TO DRAW FOR THIS ENTRY",_.classList.add("files-diagram-empty");return}g.text!==""&&c.contentText_set(g.text);const m=document.createElement("div");m.className="dag-facts",ai(m),_.appendChild(m);const w=new uu(_,{select:v=>g.facts_show(m,v.id,!1,u),activate:v=>y(v),deselect:()=>m.replaceChildren()},{}),y=v=>{w.flight_into(v.id,()=>{t={scene:w,facts:m},g.facts_show(m,v.id,!0,u)})};p=w,w.graph_set({nodes:g.nodes},{wave:!1}),w.size_fit(),f=H6(_,w,c,u===null?void 0:u.run);const M=g.nodes.length===1?g.nodes[0]:void 0;M!==void 0&&y(M)})},n=async c=>{const h=/_id(\d+)$/.exec(c)?.[1]??c.replace(/^.*\//,""),[d,u]=await Promise.all([s.client.line_execute(`cat "${c}"`,{silent:!0,observe:!1}),s.client.line_execute(`pipeline diagram ${h}`,{silent:!0,observe:!1})]),p=d.envelopes.map(f=>f.rendered).join(`
|
|
4356
4356
|
`);for(const f of u.envelopes){if(f.model?.kind!==Cr.pipelineDiagram)continue;const _=Jg.safeParse(f.model.data);if(!_.success)continue;const g=new Map(_.data.nodes.map(m=>[m.id,m]));return{text:U6(p),nodes:_.data.nodes.map(m=>({id:m.id,label:m.label,parentIds:m.parentIds,joinParentIds:m.joinParentIds})),facts_show:(m,w,y,M)=>{const v=_.data.nodes.map(S=>S.label);aw(m,$6(g.get(w),y,M!==null,v),y,M)}}}return null},r=async c=>{const h=c.replace(/^.*\//,""),d=await s.client.line_execute(`plugin info "${h}"`,{silent:!0,observe:!1});for(const u of d.envelopes){if(u.model?.kind!==aN)continue;const p=oN.safeParse(u.model.data);if(!p.success)continue;const f=p.data;return{text:"",nodes:[{id:h,label:f.name,parentIds:[],joinParentIds:[]}],facts_show:(_,g,m,w)=>{aw(_,j6(f,m,w!==null),m,w)}}}return null},o=(c,h,d,u)=>{const p=e.catalogue_find(c);if(p===void 0)return null;const f=d.replace(/^.*\//,"");return t1(h.commandLine_get())!==f&&h.commandLine_set(Jz(p.input,f)),{line_get:()=>h.commandLine_get(),line_set:_=>h.commandLine_set(_),run:()=>e.run_press(c,f,u)}};return{entry_show:(c,h,d,u)=>{i(h,d,()=>u==="plugin"?r(d):n(d),o(c,h,d,u))},dive_leave:()=>{const c=t;return c===null?!1:(t=null,c.scene.flight_back(()=>{c.facts.classList.remove("dag-facts-immersed"),c.facts.replaceChildren()}),!0)}}}function q6(s,e){const{panels:t,paneInstance_get:i,subjects:n}=s,r=new Map,o=p=>t.get("dag",p)??t.get("universe",p),a=(p,f)=>{const _=r.get(p);if(_===void 0){f?.();return}r.delete(p),_.element.classList.remove("node-overlay-open");const g=()=>{_.element.remove(),f?.()},m=o(p);m!==void 0?m.flight_back(g):g()},l=(p,f,_,g,m)=>{if(m.kind==="dir"){const w=f.replace(/\/+$/,"");if(m.path!==w&&!m.path.startsWith(`${w}/`)){a(p),s.sound("audio3");return}const y=m.path.startsWith("/proc/jobs/")?(m.path.split("/").pop()??"").match(/_(\d+)$/):null;if(y!==null){const v=parseInt(y[1]??"",10);a(p,()=>{o(p)?.node_flyTo(v)!==!0&&c(p,m.path)});return}const M=_.path_current();M!==null&&g.push(M),e.rootedListing_show(p,_,m.path);return}if(n.regard_write(p,{address:m.path,modelKind:"fs.file"}),!n.groupHasViewer(p)){if(e.imagery_is(m.path)){e.image_open(p,m.path).then(w=>s.terminal.line_note(w));return}if(tu(m.path)){_.contentImage_show(m.path,e.vfsUrl_build(m.path));return}e.fileText_fetch(m.path).then(w=>{if(!w.ok){_.contentRefused_show(m.path,w.text);return}e.tableFile_is(m.path)?_.contentTable_show(m.path,w.text):_.content_show(m.path,w.text)})}},c=(p,f)=>{const g=i(p)?.mount?.querySelector(".dag-canvas, .universe-canvas")??null,m=r.get(p);if(m!==void 0&&!m.element.isConnected&&r.delete(p),g===null||r.has(p)){s.terminal.line_note(`dag: ${f}: ${g===null?"this pane has no scene to fly in":"a node is already open here"} — flew back out`),o(p)?.flight_back(()=>{});return}const w=document.createElement("div");w.className="node-overlay",w.setAttribute("aria-label",`inside ${f}`);const y=e.filesBody_stamp();y.classList.add("node-overlay-body");const M=document.createElement("button");M.type="button",M.className="strategy-pill node-overlay-exit",M.title="leave the node (Esc)",M.textContent="EXIT NODE",y.querySelector(".mode-frame")?.prepend(M),w.append(y);const v=y.querySelector(".files-panel");if(v===null)throw new Error("pane template is missing .files-panel");const S=[],x=new Hz(v,b=>l(p,f,x,S,b),e.previewProvider);x.rowVerbs_declare((b,z)=>e.rowVerbs_build(p,b,z),(b,z)=>{n.regard_write(p,{address:z,modelKind:"fs.file"})}),r.set(p,{element:w,panel:x,history:S}),x.ceiling_set(f,"EXIT NODE"),M.addEventListener("click",()=>{a(p),s.sound("audio3")}),g.appendChild(w),window.requestAnimationFrame(()=>w.classList.add("node-overlay-open")),e.rootedListing_show(p,x,f)};return{open:c,close:a,back:p=>{const f=r.get(p),_=f?.history.pop();f!==void 0&&_!==void 0&&e.rootedListing_show(p,f.panel,_)},escape:()=>{const p=[...r.keys()].pop();if(p===void 0)return!1;const f=r.get(p);return f!==void 0&&f.panel.content_isShown()?f.panel.listing_restore():a(p),!0},dispose:p=>{r.get(p)?.element.remove(),r.delete(p)}}}async function V_(s,e,t){if(s.ask_isOpen()){const o=s.ask_note(t.message),a=await Id(e,t);return o(t.kind==="secret"&&a!==null?"••••••":a),a}const i=Id(e,t).then(o=>({from:"pane",answer:o})),n=s.ask_open({message:t.message,kind:t.kind==="choose"?"text":t.kind,focus:!1,...t.suggest===void 0?{}:{suggest:t.suggest}}).then(o=>({from:"console",answer:o})),r=await Promise.race([i,n]);return r.from==="console"?gx():s.ask_settle(r.answer),r.answer}function K6(s,e){const{panels:t,paneInstance_get:i}=s;let n=null,r=null;const o=()=>{const{layout:u}=s,p=u.tree_get();if(p===null)return null;const f=[],_=m=>{if("pane"in m){f.push(m.pane);return}_(m.first),_(m.second)};_(p);const g=u.focused_get();return g!==null&&f.includes(g)?g:f[0]??null};return{errandHost_find:o,errand_open:async u=>{const{layout:p,terminal:f}=s,_=o();if(_===null)return null;const g=e.instance_spawn("files"),m=e.replayPlace_get();if(!p.leaf_split(_,m?.dir??"col",g.id,m?.before??!1))return Ds(g.id),p.mount_remove(g.id),null;e.birth_record(g.id,_,m?.dir??"col",m?.before??!1);const w=t.get("files",g.id),y=u.path?.anchor??"~";w!==void 0&&e.rootedListing_show(g.id,w,y);const M=g.mount.querySelector(".files-body");if(M===null)return Ds(g.id),p.mount_remove(g.id),null;const v=document.createElement("div");v.className="errand-bar",M.insertBefore(v,M.firstChild);const S=document.createElement("span");S.className="errand-caption",S.textContent=u.message.trim();const x=document.createElement("input");x.className="errand-path",x.spellcheck=!1;const b=document.createElement("button");b.className="pacs-capsule errand-commit",b.textContent=u.commit??"USE THIS",v.append(S,x,b);const z=()=>{const E=w?.path_current()??y,O=u.path?.suggest;x.value=u.path?.wantsDirectory===!0||O===void 0?E:`${E.replace(/\/$/,"")}/${O}`};z();let T=!1;x.addEventListener("input",()=>{T=!0});const A=()=>{T||z()};return g.mount.addEventListener("click",A),f.question_set(!0),new Promise(E=>{const O=R=>{g.mount.removeEventListener("click",A),f.question_set(!1),n=null,p.leaf_close(g.id),Ds(g.id),p.mount_remove(g.id),E(R)};n=()=>O(null),b.addEventListener("click",()=>O(x.value.trim()===""?null:x.value.trim())),x.addEventListener("keydown",R=>{R.key==="Enter"&&O(x.value.trim()===""?null:x.value.trim())})})},errand_abandon:()=>n===null?!1:(n(),!0),verbLine_run:(u,p)=>{r=u,s.terminal.line_run(p)},askingPane_take:()=>{const u=r;return r=null,u},askOnPane_await:async(u,p)=>{const{terminal:f}=s,_=i(u)?.mount;if(_===void 0){const g=e.questionSheet_ask?.(p)??null;return g!==null?g:(e.console_expose(),f.ask_open({message:p.message,kind:p.kind==="choose"?"text":p.kind,...p.suggest===void 0?{}:{suggest:p.suggest}}))}return V_(f,_,p)}}}class Y6{members=new Map;title=null;landed=null;watchers=new Set;watch(e){return this.watchers.add(e),()=>{this.watchers.delete(e)}}changed(){for(const e of[...this.watchers])e()}members_get(){return[...this.members.values()]}size(){return this.members.size}has(e){return this.members.has(e)}state_adopt(e,t,i){const n=JSON.stringify({members:e,name:t,feed:i}),r=JSON.stringify({members:[...this.members.values()],name:this.title,feed:this.landed});if(n!==r){this.members.clear();for(const o of e)this.members.set(o.seriesUID,o);this.title=t,this.landed=i,this.changed()}}name_get(){return this.title}feed_get(){return this.landed}}function lw(s){return(s.kind??"series")==="series"?void 0:s.vfsPath}const Gf="cohort";function X6(s){return/[",\n\r]/.test(s)?`"${s.split('"').join('""')}"`:s}function Z6(s){const e=document.createElement("p");return e.className="files-empty",e.textContent=s,e}class cw{handlers;title;cohort;greeted=!1;listing;cohortActions;seriesActions;constructor(e,t,i,n){this.handlers=i,this.cohort=n,n.watch(()=>{this.unsaved=!0,this.render()}),this.title=e.querySelector(".gather-title"),this.cohortActions=this.cohortActions_declare(),this.seriesActions=this.seriesActions_declare(),this.listing=new sr({mount:t,traits:this.cohortTraits_declare(),key:r=>r.key,chrome:{root:e,prefix:"gather"},control:"fold",actions:{of:()=>this.cohortActions},row:{className:()=>"gather-cohort-row",groupClassName:()=>"gather-cohort",decorate:r=>{r.title="the cohort: click for its verbs, the fold cell folds its series"}},child:ma(()=>[...this.cohort.members_get()].map(r=>({entry:r})),{traits:this.seriesTraits_declare(),key:r=>r.entry.seriesUID,address:r=>r.entry.vfsPath,actions:{of:()=>this.seriesActions},row:{className:()=>"gather-series",decorate:(r,o)=>{r.dataset.seriesuid=o.entry.seriesUID}}}),state:r=>this.stateLine_compose(r),empty:()=>Z6("NOTHING GATHERED")}),this.pullBlock=e.querySelector(".gather-pull"),this.pullBlock?.addEventListener("click",()=>this.cohort_pull()),this.emptyBlock=e.querySelector(".gather-remove"),this.emptyBlock?.addEventListener("click",()=>{this.cohort_clear()}),this.processBlock=e.querySelector(".gather-process"),this.processBlock?.addEventListener("click",()=>{this.cohort_process()}),this.render()}pullBlock=null;emptyBlock=null;unsaved=!1;processBlock=null;async cohort_clear(){if(this.cohort.size()!==0){if(this.unsaved){const e=await this.handlers.confirm_ask(`Save the cohort first? (${this.cohort.size()} ${this.cohort.size()===1?"member":"members"}, unsaved)`);if(e===null||e==="y"&&!await this.manifest_save())return}await this.handlers.verb_send("gather clear")}}away(){return[...this.cohort.members_get()].filter(e=>e.folderPath===void 0&&e.series?.pulled!==!0)}cohort_pull(){const e=this.away();if(e.length===0)return;const t=e.map(i=>`"${i.vfsPath}"`).join(" ");this.handlers.command_show(`pull ${t} &`)}render_now(){this.render()}has(e){return this.cohort.has(e)}entries_get(){return[...this.cohort.members_get()]}name_get(){return this.cohort.name_get()}feed_get(){return this.cohort.feed_get()}async name_set(e){e===null||e===this.cohort.name_get()||await this.handlers.verb_send(`gather name ${ln(e)}`)}member_remove(e){this.handlers.verb_send(`gather remove ${ln(e.vfsPath)}`)}render(){if(this.title!==null&&(this.title.textContent=this.cohort.name_get()===null?"GATHER":`GATHER · ${this.cohort.name_get()??""}`.toUpperCase()),this.listing.rows_set([{key:"gather",rows:[{key:Gf}]}],{field:"gather"}),this.cohort.size()>0&&this.listing.open_set(0,[Gf]),this.pullBlock!==null){const e=this.away().length;this.pullBlock.hidden=e===0,this.pullBlock.textContent=`PULL ${e}`}this.emptyBlock!==null&&(this.emptyBlock.hidden=this.cohort.size()===0,this.emptyBlock.textContent=`CLEAR ${this.cohort.size()}`),this.processBlock!==null&&(this.processBlock.hidden=this.cohort.size()===0),this.greeted||(this.greeted=!0,this.listing.row_indicate(Gf))}cohortTraits_declare(){return[{key:"fold",label:"",className:"pacs-fold",capped:!1,width:"5.2em",cell:()=>{const e=document.createElement("span");return e.className="pacs-fold",e}},{key:"name",label:"COHORT",className:"gather-cohort-name",width:"1fr",cell:()=>this.cohort.name_get()??"(unnamed — SAVE names it)"},{key:"series",label:"SERIES",className:"gather-cohort-count",width:"6em",cell:()=>String(this.series_count()),compare:()=>this.series_count()},{key:"patients",label:"PATIENTS",className:"gather-cohort-patients",width:"7em",cell:()=>String(this.patients_count()),compare:()=>this.patients_count()},{key:"feed",label:"FEED",className:"gather-cohort-feed",width:"7em",cell:()=>{if(this.cohort.feed_get()===null)return"—";const e=document.createElement("button");e.className="gather-feed listing-capsule listing-action-selected",e.textContent=`FEED ${this.cohort.feed_get()?.feedId??0}`,e.title="open the feed's graph beside the cohort";const t=this.cohort.feed_get()?.feedId??0;return e.addEventListener("click",i=>{i.stopPropagation(),this.handlers.feed_open(t)}),e},compare:()=>this.cohort.feed_get()?.feedId??-1}]}seriesTraits_declare(){const e=h1(n=>n.entry.series??{seriesUID:n.entry.seriesUID,description:n.entry.description??n.entry.vfsPath??"",modality:n.entry.modality,...n.entry.files===void 0?{}:{fileCount:n.entry.files},...n.entry.folderPath===void 0?{}:{pulled:!0,folderPath:n.entry.folderPath}},eP),t={key:"patient",label:"MRN",className:"gather-series-patient",width:"8em",cell:n=>n.entry.patient||"—"},i={key:"study",label:"STUDY",className:"gather-series-study",width:"14em",cell:n=>n.entry.study??"—"};return[...e.slice(0,1),i,t,...e.slice(1)]}cohortActions_declare(){const e=()=>({count:this.cohort.size(),feed:this.cohort.feed_get()?.feedId??null}),t={save:()=>{this.manifest_save()},export:()=>{this.cohort_export()},feed:()=>{this.feed_ensure()},process:()=>{this.cohort_process()},dismiss:()=>this.handlers.dismiss()};return o1.rules.map(i=>({label:i.label(e()),offered:()=>i.offered(e()),run:()=>t[i.name]?.()}))}seriesActions_declare(){const e=i=>({folderKnown:(i.entry.kind??"series")!=="series"||i.entry.folderPath!==void 0,imagery:(i.entry.kind??"series")==="series"||i.entry.imagery===!0,pullable:(i.entry.kind??"series")==="series"&&i.entry.folderPath===void 0&&i.entry.series?.pulled!==!0&&i.entry.vfsPath!==""}),t={remove:i=>this.member_remove(i.entry),pull:i=>this.handlers.command_show(`pull "${i.entry.vfsPath}" &`),image:i=>{const n=i.entry.folderPath??lw(i.entry);n!==void 0&&this.handlers.image_open(n)},process:i=>{const n=i.entry.folderPath??lw(i.entry);if(n!==void 0){this.handlers.process_open(n);return}this.handlers.note(`gather: ${i.entry.description||i.entry.seriesUID} is not in CUBE yet — PULL it first, then PROCESS it.`)}};return r1.rules.map(i=>({label:i.label({folderKnown:!0,pullable:!0}),offered:n=>i.offered(e(n)),run:n=>t[i.name]?.(n)}))}patients_count(){return new Set(this.cohort.members_get().filter(e=>(e.kind??"series")==="series").map(e=>e.patient)).size}series_count(){return this.cohort.members_get().filter(e=>(e.kind??"series")==="series").length}stateLine_compose(e){const t=this.cohort.members_get(),i=t.filter(a=>(a.kind??"series")!=="series").length,n=t.length-i,r=[];(n>0||i===0)&&r.push(`${n} SERIES`),i>0&&r.push(`${i} ${i===1?"PLACE":"PLACES"}`),i===0&&r.push(`${this.patients_count()} PATIENTS`);const o=[r.join(" · ")];return e.filter!==""&&o.push(e.filter),o.join(" · ")}async name_ensure(){if(this.cohort.name_get()!==null)return this.cohort.name_get();const t=(await this.handlers.name_ask(`gather-${new Date().toISOString().slice(0,10)}`)??"").trim();return t===""?null:(await this.handlers.verb_send(`gather name ${ln(t)}`),t)}async manifest_save(){if(this.cohort.size()===0)return!1;const e=await this.name_ensure();if(e===null)return!1;const t=JSON.stringify({name:e,gatheredAt:new Date().toISOString(),series:[...this.cohort.members_get()].map(i=>({seriesUID:i.seriesUID,description:i.description,modality:i.modality,patient:i.patient,vfsPath:i.vfsPath}))});return this.handlers.command_run("mkdir -p ~/gather"),this.handlers.command_show(`touch --withContents '${t}' ~/gather/${e}.json`),this.unsaved=!1,!0}async cohort_export(){if(this.cohort.size()===0)return;const e=await this.name_ensure();if(e===null)return;const t=[["patient","series","modality","seriesUID","path"].join(","),...[...this.cohort.members_get()].map(i=>[i.patient,i.description,i.modality,i.seriesUID,i.vfsPath].map(X6).join(","))];this.handlers.command_run("mkdir -p ~/gather"),this.handlers.command_show(`touch --withContents '${t.join(`
|
|
4357
4357
|
`)}' ~/gather/${e}.csv`)}async feed_ensure(){const e=this.cohort.feed_get();return e!==null?e:this.cohort.size()===0||await this.name_ensure()===null?null:(await this.handlers.verb_send("gather feed",!0),this.cohort.feed_get())}async cohort_process(){const e=await this.feed_ensure();e!==null&&this.handlers.cohort_process({input:e.path,feed:e.feedId,node:e.rootInstanceId})}}const hw="gather.cohort";function J6(s){return{kind:s.kind??"series",seriesUID:s.seriesUID??s.vfsPath,description:s.description??s.vfsPath.split("/").filter(Boolean).pop()??s.vfsPath,modality:s.modality??"—",patient:s.patient??"",vfsPath:s.vfsPath,...s.study===void 0?{}:{study:s.study},...s.imagery===void 0?{}:{imagery:s.imagery},...s.folderPath===void 0?{}:{folderPath:s.folderPath},...s.files===void 0?{}:{files:s.files}}}function Q6(s,e){const{panels:t,subjects:i}=s,n=new Y6;let r=null,o=!1;const a=M=>{if(M===null||typeof M!="object")return;const v=M,S=Array.isArray(v.series)?v.series.filter(b=>typeof b?.vfsPath=="string").map(J6):[],x=v.feed;r===null&&S.length>0&&(r=f()),n.state_adopt(S,typeof v.name=="string"?v.name:null,x??null),p(),e.stage_relight()},l=M=>{for(const v of M.envelopes)v.model?.kind===hw&&a(v.model.data)},c=async(M,v=!1)=>{const{terminal:S,client:x}=s;S.line_echo(M);let b;try{b=await x.line_execute(M,{silent:!0,operator:!0})}catch(z){S.output_write("err",`\x1B[31m${z instanceof Error?z.message:String(z)}\x1B[0m
|
|
4358
|
-
`);return}(v||b.envelopes.some(z=>z.status==="error"))&&S.outcome_write(b),l(b)},h=[],d=M=>{const v=h.length===0;for(const S of M)S.vfsPath!==""&&!h.includes(S.vfsPath)&&h.push(S.vfsPath);!v||h.length===0||queueMicrotask(()=>{const S=h.splice(0);S.length>0&&c(`gather add ${S.map(ln).join(" ")}`)})},u=(M,v,S)=>({command_run:x=>{s.client.line_execute(x,{silent:!0})},command_show:x=>s.terminal.line_run(x),note:x=>s.terminal.line_note(x),image_open:x=>{e.image_open(M(),x).then(b=>s.terminal.line_note(b))},process_open:x=>e.process_open(M(),{input:x,feed:null,node:null}),...v,...S,verb_send:c,cohort_process:x=>e.process_open(M(),x),feed_open:x=>e.feed_open(M(),x)}),p=()=>{const M=document.querySelector("#header-gather-pill");M!==null&&M.classList.toggle("panel-gather-empty",(r?.entries_get().length??0)===0)},f=()=>{const M=e.element_require("header-gather"),v=()=>e.errandHost_find()??"pacs",S=x=>V_(s.terminal,e.element_require("header-gather"),x);return new cw(M,e.pane_find(M,".gather-rows"),u(v,{name_ask:x=>S({message:"Cohort name: ",kind:"text",suggest:x,commit:"NAME IT"}),confirm_ask:async x=>{const b=await S({message:x,kind:"confirm"});return b==="y"||b==="n"?b:null}},{dismiss:()=>{document.body.dataset.header="away",o=!0,p()}}),n)};return{cohort:n,instance_build:M=>{const v=e.template_stamp("tpl-pane-gather"),S=new cw(v,e.pane_find(v,".gather-rows"),u(()=>M,{name_ask:x=>e.askOnPane_await(M,{message:"Cohort name: ",kind:"text",suggest:x,commit:"NAME IT"}),confirm_ask:async x=>{const b=await e.askOnPane_await(M,{message:x,kind:"confirm"});return b==="y"||b==="n"?b:null}},{dismiss:()=>{s.layout.leaf_close(M)||e.home_apply(),e.orphans_dispose(),e.stage_relight()}}),n);return t.set("gather",M,S),{id:M,kind:"gather",mount:v,dispose:()=>{t.delete(M),i.pane_leave(M)}}},has:M=>n.has(M),gather:M=>{r===null&&(r=f()),d(M);const v=document.body.dataset.header==="away";(!o||!v)&&(document.body.dataset.header="gather",o=!1),p()},open:(M,v="pacs")=>{const{layout:S}=s,x=new Set(S.panes_shown());let b=t.ids("gather").find(z=>x.has(z))??null;if(b===null){const z=x.has(v)?v:e.errandHost_find()??v,T=e.instance_spawn("gather","pacs"),A=e.replayPlace_get();if(!S.leaf_split(z,A?.dir??"row",T.id,A?.before??!1))return Ds(T.id),S.mount_remove(T.id),null;e.birth_record(T.id,z,A?.dir??"row",A?.before??!1),b=T.id}return t.get("gather",b)===void 0?null:(d(M),b)},stage:()=>{const{layout:M}=s,v=new Set(M.panes_shown()),S=t.ids("gather").find(x=>v.has(x))??null;if(S!==null)M.focus_set(S);else{const x=e.errandHost_find()??"pacs",b=e.instance_spawn("gather","pacs");if(!M.leaf_split(x,"col",b.id,!1)){Ds(b.id),M.mount_remove(b.id);return}e.birth_record(b.id,x,"col",!1),t.get("gather",b.id)?.render_now()}document.body.dataset.header="away",o=!0},annunciate:p,restore:async()=>{try{l(await s.client.line_execute("gather",{silent:!0,observe:!1}))}catch{}},envelope_observe:M=>{M.model?.kind===hw&&a(M.model.data)}}}class eH{mount;handlers;titleSpan;stateSpan;fieldSection;savePill;revertPill;focusMark;field=null;path=null;original="";saving=!1;fieldBuild=null;constructor(e,t){this.mount=e,this.handlers=t,this.titleSpan=e.querySelector(".pane-title"),this.stateSpan=e.querySelector(".pane-state"),this.fieldSection=this.element_require(".edit-field"),this.savePill=this.element_require(".edit-save"),this.revertPill=this.element_require(".edit-revert"),this.focusMark=e.querySelector(".edit-focus"),this.savePill.addEventListener("click",()=>{this.save()}),this.revertPill.addEventListener("click",()=>this.revert()),e.addEventListener("keydown",i=>{(i.ctrlKey||i.metaKey)&&!i.altKey&&i.key.toLowerCase()==="s"&&(i.preventDefault(),i.stopPropagation(),this.save())},{capture:!0}),this.fieldSection.addEventListener("mousedown",()=>this.focusMark_set(!0)),this.fieldSection.addEventListener("focusin",()=>this.focusMark_set(!0)),this.fieldSection.addEventListener("focusout",i=>{(!(i.relatedTarget instanceof Node)||!this.fieldSection.contains(i.relatedTarget))&&this.focusMark_set(!1)}),this.controls_sync()}opening_show(e){this.path=e,this.title_set(e),Ts(this.stateSpan,"wait","OPENING")}async content_show(e){this.path=e.path,this.original=e.content,this.title_set(e.path),this.fieldBuild??=this.field_build(e);const t=await this.fieldBuild;t!==null&&(t.text_get()!==this.original&&t.text_set(this.original),this.controls_sync(),t.focus(),this.focusMark_set(!0))}async field_build(e){let t;try{t=await Xl(()=>import("./field-BL_j7bBL.js"),__vite__mapDeps([5,6]),import.meta.url)}catch(i){if(!F_(i))throw i;return Ts(this.stateSpan,"stale",Cd),this.handlers.note(`edit: ${Cd.toLowerCase()} — the editor's code is of an older build than the server has`),null}return this.field=await t.editField_create(this.fieldSection,e.content,e.extension,()=>this.controls_sync()),this.field}opening_fail(e){Ts(this.stateSpan,"refused",`NOT OPENED · ${e.toUpperCase()}`)}async save(){if(this.field===null||this.path===null||this.saving)return!1;const e=this.field.text_get();if(e===this.original)return!0;this.saving=!0,this.controls_sync();let t=!1;try{t=await this.handlers.save(this.path,e)}finally{this.saving=!1}return t&&(this.original=e),this.controls_sync(),t||Ts(this.stateSpan,"refused","NOT SAVED · THE CONSOLE SAYS WHY"),t}revert(){this.field===null||!this.dirty_is()||(this.field.text_set(this.original),this.controls_sync())}dirty_is(){return this.field!==null&&this.field.text_get()!==this.original}path_get(){return this.path}field_release(){return this.field===null||!this.field.hasFocus()?!1:(this.field.blur(),this.focusMark_set(!1),!0)}dispose(){this.field?.destroy(),this.field=null}controls_sync(){const e=this.dirty_is();this.savePill.disabled=!e||this.saving,this.revertPill.disabled=!e||this.saving,this.mount.dataset.dirty=e?"yes":"no",this.field!==null&&(this.saving?Ts(this.stateSpan,"wait","SAVING"):e?Ts(this.stateSpan,"note","DIRTY"):Ts(this.stateSpan,"settled","SAVED"))}title_set(e){this.titleSpan!==null&&(this.titleSpan.textContent=`EDIT ${e.split("/").pop()??e}`.toUpperCase()),this.mount.title=e}focusMark_set(e){this.focusMark!==null&&(this.focusMark.hidden=!e)}element_require(e){const t=this.mount.querySelector(e);if(t===null)throw new Error(`edit pane: no ${e} in its template`);return t}}function tH(s,e){const{layout:t,panels:i,subjects:n}=s,r=async(d,u)=>{const p=await ba(s,W_(d,u));return p&&e.saved?.(d),p},o=d=>{const u=e.template_stamp("tpl-pane-edit"),p=new eH(u,{save:r,note:f=>s.terminal.line_note(f)});return i.set("edit",d,p),{id:d,kind:"edit",mount:u,dispose:()=>{p.dispose(),i.delete(d),n.pane_leave(d)}}},a=d=>{const u=new Set(t.panes_shown());for(const[p,f]of i.entries("edit"))if(u.has(p)&&f.path_get()===d)return p;return null},l=()=>{e.launcher_yield();const d=new Set(t.panes_shown()),u=t.focused_get(),p=u!==null&&d.has(u)?u:e.errandHost_find();if(p===null)return null;const f=e.instance_spawn("edit"),_=e.replayPlace_get();return t.leaf_split(p,_?.dir??"col",f.id,_?.before??!1)?(e.birth_record(f.id,p,_?.dir??"col",_?.before??!1),f.id):(Ds(f.id),t.mount_remove(f.id),null)};return{instance_build:o,edit_receive:d=>{const u=d.path??"";if(u==="")throw new Error("the editor pane needs the file it edits, and the request named none");const p=a(u)??l();if(p===null)return!1;const f=i.get("edit",p);return f===void 0?!1:(t.focus_set(p),f.dirty_is()?(s.terminal.line_note(`edit: ${u}: its pane has unsaved changes; they stand (REVERT reads the file again)`),!0):(f.content_show({path:u,content:d.content,extension:d.extension??Zg(u)}),!0))},edit_open:(d,u={})=>{const p=a(d)??l();if(p===null)return null;const f=i.get("edit",p);if(f===void 0)return null;t.focus_set(p),f.dirty_is()||f.opening_show(d);const _=vx(d);return u.visible===!0?(s.terminal.line_run(_),p):(s.client.line_execute(_,{silent:!0,observe:!1}).then(g=>{const m=g.envelopes.find(w=>w.status!=="ok");m!==void 0&&f.opening_fail((m.renderedErr??"").replace(/\x1b\[[0-9;]*m/g,"").trim()||"the kernel refused")}).catch(g=>f.opening_fail(g instanceof Error?g.message:String(g))),p)}}}class sH{listing;constructor(e){const t=e.querySelector(".help-panel");if(t===null)throw new Error("help pane: no .help-panel in its template");this.listing=new sr({mount:t,traits:this.traits_declare(),key:i=>i.key,chrome:{root:e,prefix:"help"},caps:"root",activatable:()=>!1,row:{className:i=>`help-row help-${i.topic}`}}),this.render()}traits_declare(){return[{key:"name",label:"KEY · VERB",className:"help-key",width:"minmax(9em, 12em)",cell:e=>e.name},{key:"does",label:"DOES",className:"help-does",width:"minmax(16em, 1fr)",cell:e=>e.does}]}render(){const e=o=>{const a=document.createElement("header");return a.className="files-path help-block-head",a.textContent=o,a},t=zn.map(o=>({key:`k:${o.key}`,name:o.key,does:o.does,topic:o.topic})),i=Ta.map((o,a)=>{const l=o.indexOf(" ");return{key:`v:${a}`,name:l<0?o:o.slice(0,l),does:l<0?"":o.slice(l+1).trim(),topic:"verb"}}),n=[{key:"g:games",name:"help games",does:"the /usr/games shelf — fortune, cal, weather and their kin, by category (type it in the console)",topic:"verb"}],r=[{key:"n:notes",name:"notes",does:"what the installed releases changed (notes pane opens it as a listing; the dashboard's WHAT'S NEW block too)",topic:"verb"}];this.listing.rows_set([{key:"keys",header:e("KEYS — Ctrl-B opens the focused pane's drawer; then one key presses one of its verbs"),rows:t},{key:"verbs",header:e("VERBS — the console language; the long form is docs/argus-lang.adoc"),rows:i},{key:"games",header:e("GAMES — the small pleasures, kept apart from the tools as BSD kept them"),rows:n},{key:"notes",header:e("NOTES — what changed, release by release"),rows:r}],{field:"help"})}}function iH(s,e){const{layout:t,panels:i,subjects:n}=s;return{instance_build:a=>{const l=e.template_stamp("tpl-pane-help");return i.set("help",a,new sH(l)),{id:a,kind:"help",mount:l,dispose:()=>{i.delete(a),n.pane_leave(a)}}},open:()=>{const a=i.ids("help").find(d=>t.panes_shown().includes(d));if(a!==void 0)return t.focus_set(a),"help: on stage";const l=e.launcher_active();e.launcher_yield();const c=t.focused_get()??"files",h=e.instance_spawn("help");return l&&t.leaf_replace("files",h.id)?(t.focus_set(h.id),"help: the keys and the verbs, as a pane (help keys, help verbs print them here)"):t.leaf_split(c,"col",h.id,!1)?(e.birth_record(h.id,c,"col",!1),"help: the keys and the verbs, as a pane (help keys, help verbs print them here)"):(Ds(h.id),t.mount_remove(h.id),"help: could not open a pane")}}}const Pf=["___________________ _-_ ","\\__(==========/_=_/ ____.---'---`---.____"," \\_ \\ \\----._________.----/"," \\ \\ / / `-_-' "," __,--`.`-'..'-_ "," /____ || "," `--.____,-' "];function nH(){const s=Pf[0].length;let e=Number.NaN,t=0;return{title:"SL",tick:60,step:i=>{Number.isNaN(e)&&(e=-s),e+=1,t+=1,e>i.cols+6&&(e=-s)},draw:(i,n)=>{const r=Math.max(0,Math.floor((i.rows-Pf.length)/2));Pf.forEach((a,l)=>i.text(Math.round(e),r+l,a,n.lit));const o=t%2===0?"-~=":"-=~";i.text(Math.round(e)-o.length,r+1,o,n.cool)}}}const dw="ハミヒーウシナモニサワツオリアホテマケメエカキムユラセネスタヌヘ0123456789Z:・.=*+-<>¦|";function rH(){const s=new Map;let e=0;return{title:"CMATRIX",tick:50,step:(t,i)=>{e+=1;for(let n=0;n<t.cols;n++){const r=s.get(n);if(r===void 0){i()<.02&&s.set(n,{row:-1,speed:1+Math.floor(i()*2),length:4+Math.floor(i()*12),glyphs:[]});continue}e%r.speed===0&&(r.row+=1,r.glyphs.unshift(dw[Math.floor(i()*dw.length)]),r.glyphs.length>r.length&&r.glyphs.pop(),r.row-r.length>t.rows&&s.delete(n))}},draw:(t,i)=>{for(const[n,r]of s)r.glyphs.forEach((o,a)=>{const l=a===0?"#ffffff":a<r.length/2?i.lit:i.dim;t.put(n,r.row-a,o,l)})}}}function oH(){const s=[];return{title:"RAIN",tick:70,step:(e,t)=>{t()<.9&&s.push({col:Math.floor(t()*e.cols),row:0,splash:0});for(const i of s)i.row<e.rows-1?i.row+=1:i.splash+=1;for(let i=s.length-1;i>=0;i--)s[i].splash>3&&s.splice(i,1)},draw:(e,t)=>{for(const i of s){if(i.splash===0){e.put(i.col,i.row,"|",t.cool);continue}const n=["o","O","( )"][i.splash-1];e.text(i.col-(n.length>>1),e.rows-1,n,t.dim)}}}}function aH(){const s=[],e=[];let t=0;return{title:"ASCIIQUARIUM",tick:90,step:(i,n)=>{if(t+=1,s.length<Math.max(3,i.cols/12)&&n()<.08){const r=n()<.5;s.push({col:r?-4:i.cols+1,row:2+Math.floor(n()*Math.max(1,i.rows-5)),right:r,speed:1+Math.floor(n()*2),hue:Math.floor(n()*3)})}for(const r of s)t%r.speed===0&&(r.col+=r.right?1:-1);for(let r=s.length-1;r>=0;r--){const o=s[r];(o.col<-5||o.col>i.cols+2)&&s.splice(r,1)}if(n()<.3){const r=s[Math.floor(n()*s.length)];r!==void 0&&e.push({col:r.col+(r.right?4:-1),row:r.row-1})}for(const r of e)r.row-=1;for(let r=e.length-1;r>=0;r--)e[r].row<1&&e.splice(r,1)},draw:(i,n)=>{const r=(t%4<2?"~^":"^~").repeat(i.cols>>1);i.text(0,0,r,n.cool);const o=[n.lit,n.cool,n.warn];for(const a of s)i.text(a.col,a.row,a.right?"><>":"<><",o[a.hue]);for(const a of e)i.put(a.col,a.row,a.row%2===0?"o":".",n.dim);for(let a=2;a<i.cols;a+=7){const l=(t>>2)%2===0?0:1;for(let c=0;c<3;c++)i.put(a+(c+l)%2,i.rows-2-c,c%2===0?"(":")",n.dim)}i.text(0,i.rows-1,"^".repeat(i.cols),n.dim)}}}const uw=[[[0,0],[1,0],[2,0],[3,0]],[[0,0],[1,0],[0,1],[1,1]],[[1,0],[0,1],[1,1],[2,1]],[[0,0],[1,0],[1,1],[2,1]],[[1,0],[2,0],[0,1],[1,1]],[[0,0],[0,1],[1,1],[2,1]],[[2,0],[0,1],[1,1],[2,1]]],po=10,wo=20;function lH(){return{well:Array.from({length:wo},()=>Array(po).fill(0)),piece:null,score:0,lines:0,over:!1}}function q_(s,e){return e.cells.every(([t,i])=>{const n=e.x+t,r=e.y+i;return n>=0&&n<po&&r<wo&&(r<0||s[r][n]===0)})}function Lf(s){const e=Math.max(...s.cells.flat())+1;return{...s,cells:s.cells.map(([t,i])=>[e-1-i,t])}}function cH(s,e){const t=Math.floor(e()*uw.length),i={cells:uw[t].map(n=>[n[0],n[1]]),x:3,y:0,kind:t+1};if(!q_(s.well,i)){s.over=!0;return}s.piece=i}function hH(s){const e=s.piece;if(e===null)return;e.cells.some(([,n])=>e.y+n<0)&&(s.over=!0);for(const[n,r]of e.cells){const o=e.y+r;o>=0&&(s.well[o][e.x+n]=e.kind)}const t=s.well.filter(n=>n.some(r=>r===0)),i=wo-t.length;for(;t.length<wo;)t.unshift(Array(po).fill(0));s.well=t,s.lines+=i,s.score+=[0,100,300,500,800][i]??800,s.piece=null}function $m(s,e){if(s.over)return;if(s.piece===null){cH(s,e);return}const t={...s.piece,y:s.piece.y+1};q_(s.well,t)?s.piece=t:hH(s)}function dH(s,e,t){if(s.over||s.piece===null)return!1;const i=s.piece,n=r=>q_(s.well,r)?(s.piece=r,!0):!1;switch(e){case"ArrowLeft":case"h":case"a":return n({...i,x:i.x-1}),!0;case"ArrowRight":case"l":case"d":return n({...i,x:i.x+1}),!0;case"ArrowUp":case"k":case"w":return n(Lf(i))||n({...Lf(i),x:i.x-1})||n({...Lf(i),x:i.x+1}),!0;case"ArrowDown":case"j":case"s":return $m(s,t),!0;case" ":{for(;s.piece!==null;)$m(s,t);return!0}default:return!1}}function uH(){const s=lH();let e=Math.random;return{title:"TETRIS",tick:500,step:(t,i)=>{e=i,$m(s,i)},draw:(t,i)=>{const n=Math.max(0,Math.floor((t.cols-(po*2+2))/2)),r=Math.max(0,Math.floor((t.rows-wo-1)/2)),o=["",i.cool,i.lit,i.warn,i.dim,i.lit,i.cool,i.warn];for(let a=0;a<wo;a++){t.put(n,r+a,"|",i.dim),t.put(n+po*2+1,r+a,"|",i.dim);for(let l=0;l<po;l++){const c=s.well[a][l];c!==0&&t.text(n+1+l*2,r+a,"[]",o[c])}}if(t.text(n,r+wo,"+"+"-".repeat(po*2)+"+",i.dim),s.piece!==null)for(const[a,l]of s.piece.cells){const c=s.piece.y+l;c>=0&&t.text(n+1+(s.piece.x+a)*2,r+c,"[]",o[s.piece.kind])}s.over&&t.text(n+2,r+9," GAME OVER ",i.warn)},key:t=>dH(s,t,e),status:()=>`${s.score} · ${s.lines} lines${s.over?" · OVER":""}`,over:()=>s.over}}function fH(s,e,t){const i=s>>1,n=e>>1,r={body:[[i,n],[i-1,n],[i-2,n]],food:[0,0],heading:"right",next:"right",score:0,over:!1,cols:s,rows:e};return kx(r,t),r}function kx(s,e){for(let t=0;t<1e3;t++){const i=[Math.floor(e()*s.cols),Math.floor(e()*s.rows)];if(!s.body.some(([n,r])=>n===i[0]&&r===i[1])){s.food=i;return}}}const pH={up:"down",down:"up",left:"right",right:"left"};function mH(s,e){pH[e]!==s.heading&&(s.next=e)}function gH(s,e){if(s.over)return;s.heading=s.next;const[t,i]=s.body[0],n=s.heading==="up"?[t,i-1]:s.heading==="down"?[t,i+1]:s.heading==="left"?[t-1,i]:[t+1,i],r=n[0]<0||n[1]<0||n[0]>=s.cols||n[1]>=s.rows,o=s.body.some(([a,l])=>a===n[0]&&l===n[1]);if(r||o){s.over=!0;return}s.body.unshift(n),n[0]===s.food[0]&&n[1]===s.food[1]?(s.score+=10,kx(s,e)):s.body.pop()}const _H={ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down",k:"up",w:"up",j:"down",s:"down",h:"left",a:"left",l:"right",d:"right"};function bH(){let s=null;return{title:"SNAKE",tick:140,step:(e,t)=>{s===null&&(s=fH(Math.max(8,e.cols>>1),Math.max(6,e.rows-1),t)),gH(s,t)},draw:(e,t)=>{s!==null&&(e.text(0,s.rows,"-".repeat(s.cols*2),t.dim),e.text(s.food[0]*2,s.food[1],"**",t.warn),s.body.forEach(([i,n],r)=>e.text(i*2,n,r===0?"@@":"oo",r===0?t.lit:t.cool)),s.over&&e.text(Math.max(0,s.cols-6),s.rows>>1," GAME OVER ",t.warn))},key:e=>{const t=_H[e];return t===void 0||s===null?!1:(mH(s,t),!0)},status:()=>s===null?"":`${s.score}${s.over?" · OVER":""}`,over:()=>s?.over??!1}}const Nx={sl:nH,cmatrix:rH,rain:oH,aquarium:aH,tetris:uH,snake:bH};function MH(s){return s in Nx}const vH=8,wH=26,Wf=1.8,yH=100,fw=24;function pw(s,e){let t=Math.floor(s/yH);return e/(t*Wf)<fw&&(t=Math.floor(e/fw/Wf)),t=Math.max(vH,Math.min(wH,t)),{w:t,h:Math.round(t*Wf)}}class SH{pane;field;canvas;state;focusMark;pausePill;program=null;name=null;paused=!1;timer=null;frame=null;observer;constructor(e){this.pane=e,this.field=pl(e,".games-field"),this.canvas=pl(e,".games-canvas"),this.state=e.querySelector(".pane-state"),this.focusMark=pl(e,".games-focus"),this.pausePill=pl(e,".games-pause"),this.field.tabIndex=0,this.pausePill.addEventListener("click",()=>this.pause_toggle()),pl(e,".games-restart").addEventListener("click",()=>{this.name!==null&&this.program_run(this.name)}),this.field.addEventListener("mousedown",()=>{this.field.focus(),this.focusMark_paint(!0)}),this.field.addEventListener("focusin",()=>this.focusMark_paint(!0)),this.field.addEventListener("focusout",t=>{(!(t.relatedTarget instanceof Node)||!this.field.contains(t.relatedTarget))&&this.focusMark_paint(!1)}),this.field.addEventListener("keydown",t=>this.key_handle(t)),this.observer=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>this.draw()),this.observer?.observe(this.field)}program_run(e){this.name=e,this.program=Nx[e](),this.paused=!1,this.pausePill.textContent="PAUSE",this.clock_start(),this.program.key!==void 0&&(this.field.focus(),this.focusMark_paint(!0)),this.draw()}program_name(){return this.name}paused_is(){return this.paused}pause_toggle(){this.program!==null&&(this.paused=!this.paused,this.pausePill.textContent=this.paused?"RESUME":"PAUSE",this.paused?this.clock_stop():this.clock_start(),this.state_paint())}field_hasFocus(){return document.activeElement instanceof Node&&this.field.contains(document.activeElement)}field_release(){return this.field_hasFocus()?(document.activeElement.blur(),this.focusMark_paint(!1),!0):!1}dispose(){this.clock_stop(),this.observer?.disconnect()}key_handle(e){if(e.key==="Escape"){this.field_release(),e.stopPropagation();return}if(this.program!==null){if(e.key===" "&&this.program.key===void 0){this.pause_toggle(),e.preventDefault(),e.stopPropagation();return}this.program.key?.(e.key)===!0&&(e.preventDefault(),this.draw()),e.stopPropagation()}}clock_start(){this.clock_stop();const e=this.program;e!==null&&(this.timer=setInterval(()=>{this.field.offsetParent!==null&&(e.step(this.size_measure(),Math.random),this.draw(),e.over?.()===!0&&this.clock_stop())},e.tick))}clock_stop(){this.timer!==null&&clearInterval(this.timer),this.timer=null}size_measure(){const e=this.field.getBoundingClientRect(),t=pw(e.width,e.height);return{cols:Math.max(10,Math.floor(e.width/t.w)),rows:Math.max(6,Math.floor(e.height/t.h))}}palette_read(){const e=getComputedStyle(this.pane),t=(i,n)=>e.getPropertyValue(i).trim()||n;return{lit:t("--harvestgold","#ffcc66"),dim:t("--butter","#ffff99"),warn:t("--tomato","#ff7766"),cool:t("--daybreak","#55aaff")}}draw(){this.frame===null&&(this.frame=requestAnimationFrame(()=>{this.frame=null,this.paint()}))}paint(){const e=this.program,t=this.canvas.getContext("2d");if(e===null||t===null)return;const i=this.field.getBoundingClientRect(),n=window.devicePixelRatio||1;(this.canvas.width!==Math.floor(i.width*n)||this.canvas.height!==Math.floor(i.height*n))&&(this.canvas.width=Math.floor(i.width*n),this.canvas.height=Math.floor(i.height*n)),t.setTransform(n,0,0,n,0,0),t.clearRect(0,0,i.width,i.height);const r=pw(i.width,i.height);t.font=`${r.h-2}px 'Share Tech Mono', monospace`,t.textBaseline="top";const o=this.size_measure(),a=(c,h,d,u)=>{c<0||h<0||c>=o.cols||h>=o.rows||(t.fillStyle=u,t.fillText(d,c*r.w,h*r.h))},l={cols:o.cols,rows:o.rows,put:a,text:(c,h,d,u)=>{[...d].forEach((p,f)=>{p!==" "&&a(c+f,h,p,u)})}};e.draw(l,this.palette_read()),this.state_paint()}state_paint(){if(this.state===null||this.program===null)return;const e=this.program.status?.()??"";this.state.textContent=[this.program.title,e,this.paused?"PAUSED":""].filter(t=>t!=="").join(" · ")}focusMark_paint(e){this.focusMark.hidden=!e,this.pane.classList.toggle("games-field-focused",e)}}function pl(s,e){const t=s.querySelector(e);if(t===null)throw new Error(`games pane: missing ${e}`);return t}function zH(s,e){const{layout:t,panels:i,subjects:n}=s;return{instance_build:a=>{const l=e.template_stamp("tpl-pane-games"),c=new SH(l);return i.set("games",a,c),{id:a,kind:"games",mount:l,dispose:()=>{c.dispose(),i.delete(a),n.pane_leave(a)}}},show:a=>{const l=typeof a=="object"&&a!==null?a.program:void 0;if(typeof l!="string"||!MH(l))return`games: no program named ${String(l)}`;const c=i.ids("games").find(f=>t.panes_shown().includes(f));if(c!==void 0)return t.focus_set(c),i.get("games",c)?.program_run(l),`games: ${l} on the GAMES pane`;const h=e.launcher_active();e.launcher_yield();const d=t.focused_get()??"files",u=e.instance_spawn("games");return(h?t.leaf_replace("files",u.id):t.leaf_split(d,"col",u.id,!1))?(h?t.focus_set(u.id):e.birth_record(u.id,d,"col",!1),i.get("games",u.id)?.program_run(l),`games: ${l} in a GAMES pane (Esc gives the keyboard back; its PAUSE and RESTART pills on the frame)`):(Ds(u.id),t.mount_remove(u.id),"games: could not open a pane")}}}function rt(s,e){const t=document.createElementNS("http://www.w3.org/2000/svg",s);for(const[i,n]of Object.entries(e))t.setAttribute(i,String(n));return t}const Er=["cruiser","raptor","talon","warbird"],xH={ship:'<g fill="currentColor"><ellipse cx="12" cy="6.5" rx="9" ry="4"/><rect x="9.5" y="9.5" width="5" height="6" rx="1"/><rect x="3" y="14" width="5" height="8" rx="2.2"/><rect x="16" y="14" width="5" height="8" rx="2.2"/><rect x="7" y="16" width="10" height="2.2" rx="1"/></g>',"klingon-cruiser":'<g fill="currentColor"><circle cx="12" cy="4" r="2.6"/><rect x="11" y="5.5" width="2" height="8.5"/><path d="M12 12.5 L22 20.5 L22.5 22.5 L17 19.2 L12 18 L7 19.2 L1.5 22.5 L2 20.5 Z"/><rect x="8.5" y="18.5" width="7" height="3.2" rx="1.2"/></g>',"klingon-raptor":'<path fill="currentColor" d="M12 1.5 L14 6.5 L22.5 10.5 L21.5 18 L19.5 12.5 L15 13.5 L14 20 L12 17 L10 20 L9 13.5 L4.5 12.5 L2.5 18 L1.5 10.5 L10 6.5 Z"/>',"klingon-talon":'<g fill="currentColor"><path d="M12 1.5 L13.6 11 L21.5 4.5 L19 15 L12 22 L5 15 L2.5 4.5 L10.4 11 Z"/><circle cx="12" cy="13.5" r="1.6" fill="#000"/></g>',"klingon-warbird":'<g fill="currentColor"><rect x="8.5" y="2" width="7" height="3.2" rx="1.6"/><rect x="11.1" y="4.5" width="1.8" height="7"/><path d="M1.5 13 Q12 6 22.5 13 L22 20 Q17 15.5 14 17 L12 22 L10 17 Q7 15.5 2 20 Z"/></g>',base:'<g fill="currentColor"><path d="M12 1.5 L17 12 L12 22.5 L7 12 Z"/><rect x="1.5" y="10.8" width="21" height="2.4" rx="1.2"/><circle cx="12" cy="12" r="3" fill="#000"/></g>',inhabited:'<circle cx="12" cy="12" r="7.5" fill="currentColor"/><path d="M4.5 12 Q12 15.5 19.5 12" fill="none" stroke="#000" stroke-width="1.6"/><path d="M5.5 8.5 Q12 11 18.5 8.5" fill="none" stroke="#000" stroke-width="1.2" opacity="0.6"/>',star:'<g stroke="currentColor" stroke-width="1.8" stroke-linecap="round" fill="none"><path d="M12 2 V22 M2 12 H22 M4.9 4.9 L19.1 19.1 M19.1 4.9 L4.9 19.1"/></g><circle cx="12" cy="12" r="2.6" fill="currentColor"/>',hole:'<g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M12 12 m0 -2.5 a2.5 2.5 0 1 1 -2.5 2.5"/><path d="M12 12 m0 -6 a6 6 0 1 1 -6 6"/><path d="M12 12 m0 -9.5 a9.5 9.5 0 1 1 -9.5 9.5" opacity="0.5"/></g>',supernova:'<g fill="currentColor"><path d="M10 8.536 A4 4 0 0 1 14 8.536 L17.5 2.474 A11 11 0 0 0 6.5 2.474 Z"/><path d="M10 8.536 A4 4 0 0 1 14 8.536 L17.5 2.474 A11 11 0 0 0 6.5 2.474 Z" transform="rotate(120 12 12)"/><path d="M10 8.536 A4 4 0 0 1 14 8.536 L17.5 2.474 A11 11 0 0 0 6.5 2.474 Z" transform="rotate(240 12 12)"/><circle cx="12" cy="12" r="2.4"/></g>'},Ul="tm-";function Bx(s,e=null){return s==="klingon"?`${Ul}klingon-${e!==null&&Er.includes(e)?e:Er[0]}`:`${Ul}${s}`}function OH(){if(document.getElementById(`${Ul}ship`)!==null)return null;const s=rt("svg",{class:"tm-defs",width:0,height:0,"aria-hidden":"true"}),e=rt("defs",{});for(const[i,n]of Object.entries(xH)){const r=rt("symbol",{id:`${Ul}${i}`,viewBox:"0 0 24 24"});r.innerHTML=n,e.append(r)}const t=(i,n)=>{const r=rt("radialGradient",{id:`${Ul}${i}`});for(const[o,a,l]of n){const c=rt("stop",{offset:o});c.setAttribute("style",`stop-color: ${a}; stop-opacity: ${l}`),r.append(c)}return r};return e.append(t("halo",[[0,"var(--butter)",.9],[.35,"var(--harvestgold)",.5],[1,"var(--harvestgold)",0]]),t("halo-nova",[[0,"var(--butter)",.9],[.3,"var(--pumpkin-pie)",.6],[1,"var(--pumpkin-pie)",0]]),t("halo-mars",[[0,"var(--butter)",.8],[.3,"var(--mars)",.6],[1,"var(--mars)",0]]),t("photon-core",[[0,"#fff",1],[.35,"#ffd27a",1],[1,"#ff6a1a",1]]),t("photon-halo",[[0,"#ff6a1a",.55],[1,"#ff6a1a",0]])),s.append(e),s}function K_(s,e,t=null,i=0){const n=rt("g",{class:`tm-mark tm-mark-${s}`});return n.append(rt("use",{href:`#${Bx(s,t)}`,x:-e.size/2,y:-e.size/2,width:e.size,height:e.size,class:"tm-symbol"})),Gx(n,e.cx,e.cy,i),n}function Gx(s,e,t,i=0){s.setAttribute("transform",i===0?`translate(${e} ${t})`:`translate(${e} ${t}) rotate(${i})`)}function Y_(s,e=null){const t=rt("svg",{viewBox:"0 0 24 24",class:`tm-icon tm-icon-${s}`,"aria-hidden":"true"});return t.append(rt("use",{href:`#${Bx(s,e)}`})),t}const _h={ship:"E",klingon:"K",base:"#",inhabited:"@",star:"*",hole:" ",supernova:"///"},EH=[{kind:"ship",name:"ENTERPRISE"},{kind:"klingon",name:"KLINGON"},{kind:"base",name:"STARBASE"},{kind:"inhabited",name:"INHABITED"},{kind:"star",name:"STAR"},{kind:"hole",name:"BLACK HOLE"},{kind:"supernova",name:"SUPERNOVA"}],AH=/^Klingon at (\d+),(\d+) moves to (\d+),(\d+)/,TH=/^Klingon at (\d+),(\d+) escapes to quadrant/,DH=/\*\*\* Klingon at (\d+),(\d+) destroyed \*\*\*/;class $l{marks=new Map;mark_find(e){return this.marks.get($l.key_format(e))??null}line_hear(e){const t=AH.exec(e);if(t!==null){const n=`${t[1]},${t[2]}`,r=this.marks.get(n);return this.marks.delete(n),r!==void 0&&this.marks.set(`${t[3]},${t[4]}`,r),!0}const i=TH.exec(e)??DH.exec(e);return i!==null?(this.marks.delete(`${i[1]},${i[2]}`),!0):!1}reconcile(e,t={}){t.reset===!0&&this.marks.clear();const i=new Set(e.map(n=>$l.key_format(n)));for(const n of[...this.marks.keys()])i.has(n)||this.marks.delete(n);e.forEach((n,r)=>{const o=$l.key_format(n);if(t.byOrder===!0){this.marks.set(o,Er[r%Er.length]);return}this.marks.has(o)||this.marks.set(o,this.leastWorn_get())})}clear(){this.marks.clear()}leastWorn_get(){const e=new Map(Er.map(i=>[i,0]));for(const i of this.marks.values())e.set(i,(e.get(i)??0)+1);let t=Er[0];for(const i of Er)(e.get(i)??0)<(e.get(t)??0)&&(t=i);return t}static key_format(e){return`${e.x},${e.y}`}}function IH(s,e,t,i){const n=Math.max(0,Math.min(100,100*s/Math.max(1,e)));return i?{className:"tb-ring tb-ring-docked",width:.09,percent:n}:t?{className:`tb-ring ${n>60?"tb-ring-full":n>30?"tb-ring-mid":"tb-ring-low"}`,width:.025+.085*n/100,percent:n}:{className:"tb-ring tb-ring-down",width:.02,percent:n}}function q(s,e,t){const i=document.createElement(s);return i.className=e,t!==void 0&&(i.textContent=t),i}function ei(s,e,t){const i=q("button",`tb-pill ${s}`,e);return i.type="button",i.addEventListener("click",t),i}const CH=16;class Px{constructor(e,t,i){this.onCommit=i,this.size=e;const n=e/2;this.root=q("div","tb-wheel");const r=rt("svg",{width:e,height:e,viewBox:`0 0 ${e} ${e}`,role:"img","aria-label":t});r.classList.add("tb-wheel-face"),r.append(rt("circle",{cx:n,cy:n,r:n-4,class:"tb-wheel-rim"})),r.append(rt("circle",{cx:n,cy:n,r:(n-4)*.66,class:"tb-wheel-ring"})),r.append(rt("circle",{cx:n,cy:n,r:(n-4)*.33,class:"tb-wheel-ring"}));for(let l=0;l<36;l++){const c=l*Math.PI/18,h=l%3===0,d=n-4-(h?12:7);r.append(rt("line",{x1:n+d*Math.sin(c),y1:n-d*Math.cos(c),x2:n+(n-4)*Math.sin(c),y2:n-(n-4)*Math.cos(c),class:h?"tb-wheel-tick-major":"tb-wheel-tick"}))}for(const l of[0,90,180,270]){const c=l*Math.PI/180,h=rt("text",{x:n+(n-26)*Math.sin(c),y:n-(n-26)*Math.cos(c)+4,"text-anchor":"middle",class:"tb-wheel-label"});h.textContent=String(l),r.append(h)}this.wedge=rt("path",{d:"",class:"tb-wheel-wedge"}),r.append(this.wedge),this.marks=rt("g",{class:"tb-wheel-marks"}),r.append(this.marks),this.needle=rt("line",{x1:n,y1:n,x2:n,y2:14,class:"tb-wheel-needle"}),r.append(this.needle),r.append(rt("circle",{cx:n,cy:n,r:6,class:"tb-wheel-hub"})),this.root.append(r);const o=q("div","tb-wheel-row");this.readout=q("span","tb-wheel-readout","0°"),this.commit=ei("tb-commit","SET COURSE",()=>this.onCommit(Math.round(this.degrees))),o.append(this.readout,this.commit),this.root.append(o);const a=l=>{const c=r.getBoundingClientRect(),h=l.clientX-c.left-c.width/2,d=l.clientY-c.top-c.height/2;this.degrees_set((Math.atan2(h,-d)*180/Math.PI+360)%360)};r.addEventListener("pointerdown",l=>{r.setPointerCapture(l.pointerId),a(l)}),r.addEventListener("pointermove",l=>{l.buttons!==0&&a(l)})}onCommit;root;needle;marks;wedge;readout;commit;degrees=0;wedgeHalf=null;size;degrees_set(e){this.degrees=e;const t=this.size/2,i=e*Math.PI/180;this.needle.setAttribute("x2",String(t+(t-14)*Math.sin(i))),this.needle.setAttribute("y2",String(t-(t-14)*Math.cos(i))),this.readout.textContent=`${Math.round(e)}°`,this.wedge_draw()}degrees_get(){return this.degrees}wedge_set(e){this.wedgeHalf=e,this.wedge_draw()}wedge_draw(){if(this.wedgeHalf===null){this.wedge.setAttribute("d","");return}const e=this.size/2,t=e-14,i=(this.degrees-this.wedgeHalf)*Math.PI/180,n=(this.degrees+this.wedgeHalf)*Math.PI/180,r=e+t*Math.sin(i),o=e-t*Math.cos(i),a=e+t*Math.sin(n),l=e-t*Math.cos(n);this.wedge.setAttribute("d",`M ${e} ${e} L ${r} ${o} A ${t} ${t} 0 0 1 ${a} ${l} Z`)}marks_set(e){this.marks.replaceChildren();const t=this.size/2;for(const i of e){const n=i.bearing*Math.PI/180,r=(t-4)*.8,o=t+r*Math.sin(n),a=t-r*Math.cos(n),l=i.kind==="klingon"?i.bearing+180:0,c=K_(i.kind,{cx:o,cy:a,size:CH},i.variant??null,l);c.classList.add("tb-wheel-mark",`tb-wheel-mark-${i.kind}`);const h=rt("title",{});h.textContent=i.label,c.append(h),this.marks.append(c)}}lit_set(e,t="SET COURSE"){this.root.classList.toggle("tb-lit",e),this.commit.disabled=!e,this.commit.textContent=t}}class Lr{constructor(e,t,i,n){this.digits=i,this.onCommit=n,this.root=q("div","tb-slider");const r=q("label","tb-slider-label",t);r.htmlFor=e,this.input=document.createElement("input"),this.input.type="range",this.input.id=e,this.input.className="tb-slider-input",this.input.addEventListener("input",()=>{this.shown_refresh(),this.onInput?.(this.value_get())});const o=q("div","tb-slider-column");this.ticks=q("div","tb-slider-ticks"),this.note=q("span","tb-slider-note"),o.append(this.input,this.ticks,this.note),this.shown=q("span","tb-slider-readout","—"),this.commit=ei("tb-commit","SET",()=>this.onCommit(this.value_get())),this.root.append(r,o,this.shown,this.commit)}digits;onCommit;root;input;shown;commit;note;ticks;onInput=null;range_set(e,t,i,n=0){const r=e.min??0,o=e.max??1;this.input.min=String(r),this.input.max=String(o),this.input.step=String(e.step??1),this.input.value=String(Math.min(o,Math.max(r,t))),this.note.textContent=i,this.ticks.replaceChildren();for(let a=0;a<n;a++){const l=r+(o-r)*a/Math.max(1,n-1);this.ticks.append(q("span","tb-slider-tick",Number.isInteger(l)?String(l):l.toFixed(1)))}this.shown_refresh()}input_listen(e){this.onInput=e}note_set(e){this.note.textContent=e}value_get(){return Number(this.input.value)}value_set(e){this.input.value=String(e),this.shown_refresh()}lit_set(e,t="SET"){this.root.classList.toggle("tb-lit",e),this.input.disabled=!e,this.commit.disabled=!e,this.commit.textContent=t}lit_is(){return this.root.classList.contains("tb-lit")}shown_refresh(){this.shown.textContent=this.value_get().toFixed(this.digits)}}class bh{root;buttons=[];note;constructor(e,t,i){this.root=q("div","tb-pillrow"),e!==""&&this.root.append(q("span","tb-slider-label",e));const n=q("div","tb-slider-column"),r=q("div","tb-pills");for(const o of t){const a=ei("tb-choice",o.label,()=>i(o.line,o.label));a.dataset.line=o.line,this.buttons.push(a),r.append(a)}this.note=q("span","tb-slider-note",""),n.append(r,this.note),this.root.append(n)}note_set(e){this.note.textContent=e}lit_set(e){this.root.classList.toggle("tb-lit",e);for(const t of this.buttons)t.disabled=!e}}const RH=["panel-3","panel-4","panel-5","panel-6"];function It(s,e,t){const i=document.createElement(s);return e!==""&&(i.className=e),t!==void 0&&(i.textContent=t),i}function mw(s,e){const t=It("div",e===""?"bar-panel":`bar-panel ${e}`);for(let i=s;i<s+5;i++)t.append(It("div",`bar-${i}`));return t}function gw(s,e){const t=It("div","lcars-terminal-header-bar files-header-bar"),i=It("div","lcars-bar-horizontal"),n=It("span","lcars-title",s),r=It("span","lcars-terminal-status",e);return i.append(n,r),t.append(i,It("div","lcars-bar-end bar-punctuation")),{strip:t,title:n,note:r}}function X_(s,e,t){const i=It("section",`takeover ${s.className}`);i.id=s.id;const n=It("div","takeover-gutter-head"),r=It("button","panel-1 takeover-brand");if(r.type="button",r.setAttribute("aria-label",s.brand.name),s.brand.mark){const E=It("span","brand-mark brand-mark-td");E.setAttribute("aria-hidden","true"),r.append(E)}const o=It("span","takeover-brand-words");o.append(It("span","takeover-brand-name",s.brand.name),It("span","takeover-brand-sub",s.brand.sub)),r.append(o);const a=It("div","panel-2 takeover-seat");n.append(r,a);const l=It("div","takeover-head"),c=It("div","takeover-face");l.append(It("div","banner",s.banner),c,mw(1,"first-bar-panel"));const h=It("div","takeover-top");h.append(n,l);const d=It("nav","takeover-gutter");d.setAttribute("aria-label",s.labels.views);const u=It("div",""),p=new Map;let f=s.views;const _=()=>{u.replaceChildren(),p.clear(),f.forEach((E,O)=>{const R=RH[O]??"panel-view",C=It("button",`${R}${E.destroy===!0?" takeover-view-destroy":""}`,E.label);C.type="button",C.dataset.view=E.key,C.addEventListener("click",()=>e(E.key)),p.set(E.key,C),u.append(C)}),u.append(It("div","panel-spacer"))};_();const g=It("div",""),m=It("button",`panel-7${s.leave.destroy===!0?" takeover-view-destroy":""}`,s.leave.label);m.type="button",m.addEventListener("click",t),g.append(m),d.append(u,g);const w=It("div","takeover-main"),y=It("main","takeover-stage"),M=gw(s.stage.title,s.stage.note),v=It("div","takeover-body"),S=It("div","takeover-aside"),x=gw(s.log.title,s.log.note),b=It("section","takeover-log");b.setAttribute("aria-label",s.labels.log),y.append(M.strip,v,S,x.strip,b),w.append(mw(6,""),y);const z=It("div","takeover-wrap");z.append(d,w),i.append(h,z);const T=E=>{for(const[O,R]of p){const C=O===E;R.classList.toggle("takeover-view-on",C),R.setAttribute("aria-current",C?"page":"false")}i.dataset.firstLit=E===f[0]?.key?"true":"false"},A=E=>{f=E,_()};return{root:i,seat:a,face:c,views:p,leave:m,stageTitle:M.title,stageNote:M.note,body:v,aside:S,logTitle:x.title,logNote:x.note,log:b,view_mark:T,views_set:A}}const kH=[[/Klingon attack:/,"incoming"],[/^HIT: \d+ units/,"hit"],[/CRITICAL HIT/,"hit"],[/\*\*\* Klingon at \d+,\d+ destroyed \*\*\*/,"explosion"],[/\*\*\*\*\* .* destroyed \*\*\*\*\*/,"explosion"],[/Starbase at \d+,\d+ destroyed/,"explosion"],[/Inhabited starsystem .* destroyed/,"explosion"],[/^Torpedo track/,"torpedo"],[/^Phaser bank \d+ fires:/,"phaser"],[/^Phasers locked on target/,"phaser"],[/^Starbase in \d+,\d+ responds/,"hail"],[/^Password verified; self destruct sequence continues/,"destruct"]];function NH(s){const e=[];for(const[t,i]of kH)t.test(s)&&!e.includes(i)&&e.push(i);return e}function BH(s,e){const t=[];if(s!==null&&s.condition.name!==e.condition.name)switch(e.condition.name){case"RED":t.push("redalert");break;case"YELLOW":t.push("yellowalert");break;case"DOCKED":t.push("dock");break;default:t.push("green");break}return s!==null&&(s.position.quadrant.x!==e.position.quadrant.x||s.position.quadrant.y!==e.position.quadrant.y)&&t.push("sensor"),t}function GH(s){switch(s){case"abandon":return"transporter";case"destruct":return"destruct";case"computer":return"thinking";default:return null}}function PH(s,e){return s!=="distance"?null:e==="impulse"?"impulse":e==="move"||e==="ram"?"warp":null}function Dr(s,e){return e==="computer"&&s==="MOVE"?"MOVE (COMPUTER)":e==="commit"?/^SET COURSE/.test(s)?"SET COURSE":"SLIDER SET":e==="choice"&&/^\d+°$/.test(s)?"BURST ANGLE":/^CANCEL/.test(s)?"CANCEL":s}const Rs=10,nc=8,LH="*",WH="#",Lx="E",FH="Q",UH="K",$H="@",Wx=" ",jH=7,HH=64,VH=63,qH=0,KH=1,YH=2,XH=3,ZH=[{name:"warp drive",person:"Scotty"},{name:"S.R. scanners",person:"Scotty"},{name:"L.R. scanners",person:"Scotty"},{name:"phasers",person:"Sulu"},{name:"photon tubes",person:"Sulu"},{name:"impulse engines",person:"Scotty"},{name:"shield control",person:"Sulu"},{name:"computer",person:"Spock"},{name:"subspace radio",person:"Uhura"},{name:"life support",person:"Scotty"},{name:"navigation system",person:"Chekov"},{name:"cloaking device",person:"Scotty"},{name:"transporter",person:"Scotty"},{name:"shuttlecraft",person:"Scotty"},{name:"*ERR 14*",person:"Nobody"},{name:"*ERR 15*",person:"Nobody"}],JH=["GREEN","DOCKED","YELLOW","RED"];function Jh(s,e){return(Math.atan2(e.y-s.y,-(e.x-s.x))*180/Math.PI+360)%360}function Nd(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function QH(s){switch(s){case Lx:case FH:return"ship";case UH:return"klingon";case WH:return"base";case LH:return"star";case $H:return"inhabited";case Wx:return"hole";default:return"empty"}}function e9(s){const e=new Map;for(const t of s)(t.evcode&VH)!==jH||(t.evcode&HH)!==0||e.set(t.systemname,t.date);return ZH.map((t,i)=>({index:i,name:t.name,person:t.person,repairAt:e.get(i)??null})).filter(t=>!t.name.startsWith("*"))}function t9(s){const e=s.Etc.nkling;switch(s.Ship.cond){case XH:return e===1?"1 Klingon in this quadrant":`${e} Klingons in this quadrant`;case YH:return s.Ship.energy<s.Param.energylow?"energy low":"Klingons near";case KH:return"docked at a starbase";case qH:default:return"all clear"}}function s9(s){const{Ship:e,Now:t,Game:i,Param:n,Etc:r,Sect:o,Quad:a}=s,l={x:e.quadx,y:e.quady},c={x:e.sectx,y:e.secty},h=[];for(let m=0;m<Rs;m++){const w=[];for(let y=0;y<Rs;y++){const M=o[m]?.[y]??Wx;w.push({x:m,y,kind:QH(M),glyph:M})}h.push(w)}const d=r.klingon.slice(0,r.nkling).map(m=>({x:m.x,y:m.y,bearing:Jh(c,m),range:Nd(c,m),power:m.power,mark:null})).sort((m,w)=>m.range-w.range),u=t.base.slice(0,t.bases).map(m=>({x:m.x,y:m.y}));let p=null;for(const m of u){const w=Nd(l,m);(p===null||w<p.range)&&(p={at:m,range:w,here:w===0})}const f=[];for(let m=0;m<nc;m++){const w=[];for(let y=0;y<nc;y++){const v=a[m]?.[y]?.scanned??-1,S=v<0?null:v>=1e3?"///":String(v).padStart(3,"0");w.push({x:m,y,here:m===l.x&&y===l.y,code:S,supernova:v>=1e3,klingons:v<0||v>=1e3?0:Math.floor(v/100),bases:v<0||v>=1e3?0:Math.floor(v%100/10)})}f.push(w)}const _=e9(s.Event),g=_.filter(m=>m.repairAt!==null).sort((m,w)=>(m.repairAt??0)-(w.repairAt??0));return{condition:{name:JH[e.cond]??"GREEN",why:t9(s)},ship:{shipName:e.shipname,energy:e.energy,energyMax:n.energy,shield:e.shield,shieldMax:n.shield,shieldsUp:e.shldup!==0,cloaked:e.cloaked!==0,torpedoes:e.torped,torpedoesMax:n.torped,reserves:e.reserves,reservesMax:n.reserves,crew:e.crew,warp:e.warp},mission:{stardate:t.date,timeLeft:t.time,klingonsLeft:t.klings,klingonsStart:n.klings,killed:i.killk,captives:i.captives,starbases:t.bases},position:{quadrant:l,sector:c},sectors:h,klingons:d,bases:u,nearestBase:p,chart:f,devices:_,damaged:g,game:{killk:i.killk,killb:i.killb,kills:i.kills,killinhab:i.killinhab,helps:i.helps,captives:i.captives,deaths:i.deaths,killed:i.killed!==0,skill:i.skill,won:s.Move.endgame>0,abandoned:e.ship!==Lx},param:{warptime:n.warptime,dockfac:n.dockfac,klingpwr:n.klingpwr,date:n.date}}}const i9=["novice","fair","good","expert","commodore","impossible"];function Fx(s){const{game:e,mission:t,param:i}=s,n=[];n.push({label:`${e.killk} Klingons killed`,points:Math.trunc(i.klingpwr/4)*e.killk});const r=Math.max(1,t.stardate-i.date),o=e.killk/r;return n.push({label:`kill rate ${o.toFixed(2)} Klingons/stardate`,points:Math.trunc(400*o)}),n.push({label:`penalty for ${t.klingonsLeft} Klingons remaining`,points:Math.trunc(-400*t.klingonsLeft/(e.killk+1))}),e.won&&n.push({label:`bonus for winning a ${i9[e.skill-1]??""} game`,points:100*e.skill}),e.killed&&n.push({label:"penalty for getting killed",points:-500}),n.push({label:`${e.killb} starbases killed`,points:-100*e.killb}),n.push({label:`${e.helps} calls for help`,points:-100*e.helps}),n.push({label:`${e.kills} stars destroyed`,points:-5*e.kills}),n.push({label:`${e.killinhab} inhabited starsystems destroyed`,points:-150*e.killinhab}),e.abandoned&&n.push({label:"penalty for abandoning ship",points:-200}),n.push({label:`${e.captives} Klingons captured`,points:3*e.captives}),n.push({label:`${e.deaths} casualties`,points:-e.deaths}),{items:n,total:n.reduce((a,l)=>a+l.points,0)}}function _w(s,e){const{quadrant:t,sector:i}=s.position,n=t.x+i.x/Rs-(e.quadrant.x+e.sector.x/Rs),r=e.quadrant.y+e.sector.y/Rs-(t.y+i.y/Rs);let o=Math.atan2(r,n);return o<0&&(o+=2*Math.PI),{course:Math.trunc(o*180/Math.PI+.5)%360,distance:Math.hypot(n,r)}}function n9(s,e,t){const{quadrant:i,sector:n}=s.position,r=e*Math.PI/180,o=Math.min(nc*Rs-1,Math.max(0,Math.round(i.x*Rs+n.x-Math.cos(r)*t*Rs))),a=Math.min(nc*Rs-1,Math.max(0,Math.round(i.y*Rs+n.y+Math.sin(r)*t*Rs)));return{quadrant:{x:Math.trunc(o/Rs),y:Math.trunc(a/Rs)},sector:{x:o%Rs,y:a%Rs}}}function Ux(s,e,t){const i=Math.trunc((s+.05)*e*e*e);return{stardates:t*s/(e*e),units:i,unitsShielded:2*i}}function r9(s){return{stardates:s/.095,units:Math.trunc(20+100*s)}}function $x(s){return Math.trunc(Math.pow(.9,s*10)*98+.5)}function bw(s,e){if(s.repairAt===null)return null;const t=s.repairAt-e.mission.stardate,i=e.condition.name==="DOCKED",n=i?1/e.param.dockfac:1,r=i?1:e.param.dockfac;return{inFlight:t*n+.005,docked:t*r+.005}}function jx(s,e){const t=[],i=(d,u)=>`${d>0?"+":d<0?"−":""}${Math.abs(d).toFixed(u)}`,n=e.mission.stardate-s.mission.stardate;Math.abs(n)>=.005&&t.push({label:"STARDATE",change:i(n,2),bad:!1});const r=e.ship.energy-s.ship.energy;r!==0&&t.push({label:"ENERGY",change:i(r,0),bad:r<0});const o=e.ship.shield-s.ship.shield;o!==0&&t.push({label:"SHIELDS",change:i(o,0),bad:o<0});const a=e.ship.torpedoes-s.ship.torpedoes;a!==0&&t.push({label:"TORPEDOES",change:i(a,0),bad:!1});const l=e.mission.klingonsLeft-s.mission.klingonsLeft;l!==0&&t.push({label:"KLINGONS",change:`${i(l,0)} · ${e.mission.klingonsLeft} LEFT`,bad:l>0});const c=e.damaged.filter(d=>!s.damaged.some(u=>u.index===d.index));c.length>0&&t.push({label:"DAMAGE",change:c.map(d=>d.name.toUpperCase()).join(" · "),bad:!0});const h=s.damaged.filter(d=>!e.damaged.some(u=>u.index===d.index));return h.length>0&&t.push({label:"REPAIRED",change:h.map(d=>d.name.toUpperCase()).join(" · "),bad:!1}),s.condition.name!==e.condition.name&&t.push({label:"CONDITION",change:e.condition.name,bad:e.condition.name==="RED"}),t}const o9=[["return to continue","return"],["What length game","length"],["What skill game","skill"],["Enter password verification","password-verify"],["Enter a password","password"],["Enter tournament code","tournament"],["Command","command"],["Torpedo course","torpedo-course"],["Course","course"],["course","bank-course"],["Distance","distance"],["distance","computer-distance"],["Warp factor","warp-factor"],["warp factor","computer-warp"],["How long","how-long"],["Manual or automatic","manual-automatic"],["Units to fire","units"],["units","bank-units"],["spread","spread"],["Do you want a burst","burst"],["burst angle","burst-angle"],["Up or down","up-down"],["Request","request"],["Quadrant","quadrant"],["q-y","quadrant-y"],["Sector","sector"],["s-y","sector-y"],["range","range"],["direction","direction"],["status report","status-report"],["Another game","another"]];function a9(s){const e=s.replace(/[:.\s]+$/,"");if(e==="")return"return";for(const[t,i]of o9)if(e.endsWith(t))return i;return/wise$|certain that is wise$|Shall we cancel our rest period$/.test(e)?"yes-no":"unknown"}const fu=[{id:"move",label:"MOVE",station:"helm",line:"m",asks:["course","distance"]},{id:"ram",label:"RAM",station:"helm",line:"ram",asks:["course","distance"]},{id:"warp",label:"WARP",station:"helm",line:"w",asks:["warp-factor"]},{id:"impulse",label:"IMPULSE",station:"helm",line:"i",asks:["course","distance"]},{id:"dock",label:"DOCK",station:"helm",line:"do",asks:[]},{id:"undock",label:"UNDOCK",station:"helm",line:"u",asks:[]},{id:"rest",label:"REST",station:"helm",line:"r",asks:["how-long"]},{id:"phasers",label:"PHASERS",station:"tactical",line:"p",asks:["manual-automatic","units"]},{id:"torpedo",label:"TORPEDO",station:"tactical",line:"t",asks:["torpedo-course","burst","burst-angle"]},{id:"shields",label:"SHIELDS",station:"tactical",line:"sh",asks:["up-down"]},{id:"cloak",label:"CLOAK",station:"tactical",line:"cl",asks:["up-down"]},{id:"capture",label:"CAPTURE",station:"tactical",line:"ca",asks:[]},{id:"visual",label:"VISUAL",station:"tactical",line:"v",asks:["direction"]},{id:"computer",label:"COMPUTER",station:"ship",line:"c",asks:["request"]},{id:"help",label:"CALL STARBASE",station:"ship",line:"help",asks:[]},{id:"dump",label:"DUMP",station:"ship",line:"dump",asks:[]},{id:"credits",label:"CREDITS",station:"ship",line:"cr",asks:[]},{id:"abandon",label:"ABANDON",station:"ship",line:"abandon",asks:[],grave:!0},{id:"destruct",label:"DESTRUCT",station:"ship",line:"destruct",asks:["password-verify"],grave:!0},{id:"terminate",label:"TERMINATE",station:"ship",line:"terminate",asks:[],grave:!0}];function ks(s,e){switch(s){case"return":return{kind:"auto"};case"length":return{kind:"pills",choices:[{label:"SHORT",line:"s"},{label:"MEDIUM",line:"m"},{label:"LONG",line:"l"},{label:"RESTART",line:"restart"}]};case"skill":return{kind:"pills",choices:[{label:"NOVICE",line:"n"},{label:"FAIR",line:"f"},{label:"GOOD",line:"g"},{label:"EXPERT",line:"e"},{label:"COMMODORE",line:"c"},{label:"IMPOSSIBLE",line:"i"}]};case"password":case"tournament":case"password-verify":return{kind:"auto"};case"course":case"torpedo-course":case"direction":case"bank-course":return{kind:"wheel",min:0,max:360,step:1,commit:"SET COURSE",cancel:"-1"};case"distance":return{kind:"slider",min:0,max:15,step:.1,commit:"ENGAGE",cancel:"-1"};case"computer-distance":case"range":return{kind:"slider",min:0,max:15,step:.1,commit:"SET"};case"warp-factor":return{kind:"slider",min:1,max:10,step:.1,commit:"SET WARP",cancel:"-1"};case"computer-warp":return{kind:"slider",min:1,max:10,step:.1,commit:"SET"};case"how-long":return{kind:"slider",min:0,max:Math.max(.1,e?.mission.timeLeft??15),step:.1,commit:"REST",cancel:"0"};case"manual-automatic":return{kind:"pills",choices:[{label:"MANUAL",line:"m"},{label:"AUTOMATIC",line:"a"}]};case"units":return{kind:"slider",min:0,max:Math.max(10,e?.ship.energy??5e3),step:10,commit:"FIRE",cancel:"0"};case"bank-units":return{kind:"slider",min:0,max:Math.max(10,e?.ship.energy??5e3),step:10,commit:"SET",cancel:"0"};case"spread":return{kind:"slider",min:0,max:1,step:.05,commit:"SET"};case"burst":case"status-report":case"another":case"yes-no":return{kind:"yesno",choices:[{label:"YES",line:"y"},{label:"NO",line:"n"}]};case"burst-angle":return{kind:"pills",choices:[1,2,3,5,8,10,12,15].map(t=>({label:`${t}°`,line:String(t)})),cancel:"0"};case"up-down":return{kind:"pills",choices:[{label:"UP",line:"u"},{label:"DOWN",line:"d"}]};case"request":return{kind:"pills",choices:[{label:"CHART",line:"ch"},{label:"TRAJECTORY",line:"t"},{label:"COURSE",line:"c"},{label:"MOVE",line:"m"},{label:"SCORE",line:"s"},{label:"PHASER EFFECT",line:"p"},{label:"WARP COST",line:"w"},{label:"IMPULSE COST",line:"i"},{label:"DISTRESS LIST",line:"d"}]};case"quadrant":case"quadrant-y":return{kind:"slider",min:0,max:nc-1,step:1,commit:"SET"};case"sector":case"sector-y":return{kind:"slider",min:0,max:Rs-1,step:1,commit:"SET"};default:return{kind:"text"}}}function l9(){return`argus${Math.floor(Math.random()*9e3+1e3)}`}class c9{constructor(e){this.hooks=e}hooks;open=null;lastCommand=null;password=l9();ended=!1;ask(e){const t=a9(e);return t==="return"?Promise.resolve(""):t==="password"||t==="tournament"||t==="password-verify"?Promise.resolve(this.password):(t==="command"&&(this.lastCommand=null),new Promise(i=>{this.open={question:{prompt:e,question:t,command:this.lastCommand},answer:i},this.hooks.question_changed(this.open.question)}))}question_get(){return this.open?.question??null}answer(e){if(this.open===null)return!1;const{answer:t}=this.open;return this.open=null,this.hooks.question_changed(null),t(e),!0}command_send(e){return this.open?.question.question!=="command"?!1:(this.lastCommand=e,this.answer(e.line))}abandon(){if(this.open===null)return!1;const{answer:e}=this.open;return this.open=null,this.hooks.question_changed(null),e(null),!0}text_take(e){this.hooks.text_written(e)}event_take(e,t){e==="games.trek.state"&&typeof t=="object"&&t!==null&&this.hooks.state_shown(t)}end(e){this.ended||(this.ended=!0,this.open=null,this.hooks.ended(e))}ended_is(){return this.ended}}const er={torpedoPoint:140,sector:170,burst:800,beam:900,rescan:350,flare:900,tail:300},h9=[[/^Torpedo track(?:, torpedo number \d+)?:/,()=>({kind:"torpedo-head"})],[/^\s*(\d+\.\d)\s+(\d+\.\d)\s*$/,s=>({kind:"torpedo-point",at:{x:Number(s[1]),y:Number(s[2])}})],[/^Torpedo missed|^Torpedo disappears into a black hole/,()=>({kind:"torpedo-end"})],[/\*\*\* Klingon at (\d+),(\d+) destroyed \*\*\*/,s=>({kind:"kill",at:gi(s,1)})],[/^Starbase at (\d+),(\d+) destroyed/,s=>({kind:"kill",at:gi(s,1)})],[/^Inhabited starsystem .* at (\d+),(\d+) destroyed/,s=>({kind:"kill",at:gi(s,1)})],[/^Unknown object . at (\d+),(\d+) destroyed/,s=>({kind:"kill",at:gi(s,1)})],[/Star at (\d+),(\d+) gone nova/,s=>({kind:"nova",at:gi(s,1)})],[/^Photon tubes misfire/,()=>({kind:"misfire"})],[/^(\d+) unit hit on Klingon at (\d+),(\d+)/,s=>({kind:"phaser",at:gi(s,2)})],[/^HIT: (\d+) units(?: from (\d+),(\d+))?(?:, shields absorb (\d+)%)?/,s=>({kind:"incoming",hit:Number(s[1]),from:s[2]===void 0?null:gi(s,2),absorb:s[4]===void 0?0:Number(s[4])})],[/^Klingon at (\d+),(\d+) moves to (\d+),(\d+)/,s=>({kind:"klingon-move",from:gi(s,1),to:gi(s,3)})],[/^Klingon at (\d+),(\d+) escapes to quadrant (\d+),(\d+)/,s=>({kind:"klingon-escape",from:gi(s,1),quadrant:gi(s,3)})],[/RED ALERT: supernova occurring at (\d+),(\d+)/,s=>({kind:"supernova",at:gi(s,1)})],[/^\s*in quadrant (\d+),(\d+)\.\s+Caution is advised/,s=>({kind:"supernova-report",quadrant:gi(s,1)})]];function gi(s,e){return{x:Number(s[e]),y:Number(s[e+1])}}function d9(s){for(const[e,t]of h9){const i=e.exec(s);if(i!==null)return t(i)}return null}class u9{constructor(e=f9){this.reduced=e}reduced;frames=[];running=!1;skipping=!1;waiting=new Set;played={};push(e){this.frames.push(e),this.pump()}skip(){if(!(this.frames.length===0&&!this.running)){this.skipping=!0;for(const e of this.waiting)e();this.waiting.clear()}}busy_is(){return this.running||this.frames.length>0}pending_count(){return this.frames.length}skipping_is(){return this.skipping}async settle(){for(;this.busy_is();)await new Promise(e=>{setTimeout(e,1)})}wait(e){return this.skipping||e<=0?Promise.resolve():new Promise(t=>{const i=setTimeout(()=>{this.waiting.delete(n),t()},e),n=()=>{clearTimeout(i),t()};this.waiting.add(n)})}async tween(e,t){const i=Mw();for(;!this.skipping;){const n=Math.min(1,(Mw()-i)/Math.max(1,e));if(t(n),n>=1)return;await p9(this)}t(1)}async pump(){if(!this.running){this.running=!0;try{for(;this.frames.length>0;){const e=this.frames.shift();this.played[e.kind]=(this.played[e.kind]??0)+1;const t=this.skipping||this.reduced();try{await e.run(t)}catch{}}}finally{this.running=!1,this.skipping=!1}}}}function f9(){return typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches}function Mw(){return typeof performance=="object"?performance.now():Date.now()}function p9(s){return typeof requestAnimationFrame=="function"?new Promise(e=>{requestAnimationFrame(()=>e())}):s.wait(16)}function Ba(s){return[s.y+.5,s.x+.5]}function Hx(s,e){return(Math.atan2(e.y-s.y,-(e.x-s.x))*180/Math.PI+360)%360}function m9(s,e,t=10){const i={x:s.quadrant.x*t+s.sector.x,y:s.quadrant.y*t+s.sector.y},n={x:e.quadrant.x*t+e.sector.x,y:e.quadrant.y*t+e.sector.y},r={x:n.x-i.x,y:n.y-i.y},o=(p,f,_)=>{let g=_?1/0:-1/0;for(const m of["x","y"]){if(r[m]===0)continue;const w=p[m]*t-.5,y=p[m]*t+t-.5,M=(w-f[m])/r[m],v=(y-f[m])/r[m];_?g=Math.min(g,Math.max(M,v)):g=Math.max(g,Math.min(M,v))}return Number.isFinite(g)?Math.max(0,Math.min(1,g)):_?1:0},a=o(s.quadrant,i,!0),l=o(e.quadrant,i,!1),c=.7,h={x:i.x+r.x*a-s.quadrant.x*t,y:i.y+r.y*a-s.quadrant.y*t},d={x:i.x+r.x*l-e.quadrant.x*t,y:i.y+r.y*l-e.quadrant.y*t},u=Math.hypot(r.x,r.y)||1;return{exit:{x:h.x+r.x/u*c,y:h.y+r.y/u*c},entry:{x:d.x-r.x/u*c,y:d.y-r.y/u*c}}}function pu(s,e=""){const t=rt("g",{class:`tb-motion ${e}`.trim()});return s.append(t),t}const g9=.7;async function ml(s,e,t,i,n,r={},o=!1){if(o)return;const a=pu(s,"tb-motion-slide"),[l,c]=Ba(i),[h,d]=Ba(n),u=r.hostile===!0?" tb-hostile":"";a.append(rt("line",{class:`tb-track${u}`,x1:l,y1:c,x2:h,y2:d}));const p=rt("line",{class:`tb-pulse tb-pulse-wide${u}`,x1:l,y1:c,x2:l,y2:c}),f=rt("line",{class:`tb-pulse tb-pulse-core${u}`,x1:l,y1:c,x2:l,y2:c}),_=r.heading??Hx(i,n),g=K_(t.kind,{cx:l,cy:c,size:g9},t.variant,_);g.classList.add(`tb-sector-${t.kind}`),a.append(p,f,g);const m=Math.max(1,Math.hypot(n.x-i.x,n.y-i.y));await e.tween(m*er.sector,w=>{const y=l+(h-l)*w,M=c+(d-c)*w,v=Math.max(0,w-.12),S=l+(h-l)*v,x=c+(d-c)*v;for(const b of[p,f])b.setAttribute("x1",String(S)),b.setAttribute("y1",String(x)),b.setAttribute("x2",String(y)),b.setAttribute("y2",String(M));Gx(g,y,M,_)}),a.remove()}async function vw(s,e,t,i,n,r=!1){if(r)return;const o=pu(s,"tb-motion-beam"),[a,l]=Ba(t),[c,h]=Ba(i),d=n?" tb-hostile":"";o.append(rt("line",{class:`tb-beam${d}`,x1:a,y1:l,x2:c,y2:h}),rt("line",{class:`tb-beam tb-beam-core${d}`,x1:a,y1:l,x2:c,y2:h})),await e.wait(er.beam),o.remove()}async function Mh(s,e,t,i,n=!1){if(n)return;const r=pu(s,`tb-motion-burst tb-burst tb-burst-${i}`),[o,a]=Ba(t),l=i==="misfire"?er.burst*.6:i==="supernova"?er.burst*1.6:er.burst;r.style.setProperty("--tb-ms",`${l}ms`),r.append(rt("circle",{class:"tb-burst-halo",cx:o,cy:a,r:.1}));const c=rt("g",{class:"tb-burst-spikes"}),h=i==="nova"||i==="supernova"?12:8,d=i==="misfire"?.6:i==="supernova"?1.8:i==="nova"?1.1:.95;for(let u=0;u<h;u++){const p=u/h*Math.PI*2+(h===8?Math.PI/8:0);c.append(rt("line",{class:"tb-burst-spike",x1:o+Math.cos(p)*.12,y1:a+Math.sin(p)*.12,x2:o+Math.cos(p)*d,y2:a+Math.sin(p)*d}))}r.append(c,rt("circle",{class:"tb-burst-core",cx:o,cy:a,r:.04})),await e.wait(l),r.remove()}async function _9(s,e,t=!1){if(t)return;const i=s.querySelector(".tb-ring");if(i===null)return;const n=rt("circle",{class:"tb-motion tb-ring-flare",cx:i.getAttribute("cx")??0,cy:i.getAttribute("cy")??0,r:.46});s.append(n),await e.wait(er.flare),n.remove()}class b9{layer;tail;photon;points=[];constructor(e,t){this.layer=pu(e,"tb-motion-torpedo"),this.tail=rt("g",{class:"tb-tail"}),this.photon=rt("g",{class:"tb-photon"}),this.photon.append(rt("circle",{class:"tb-photon-halo",cx:0,cy:0,r:.34}));const i=rt("g",{class:"tb-photon-pulses"});for(let o=0;o<10;o++){const a=rt("g",{transform:`rotate(${o*36})`});a.append(rt("rect",{x:.08,y:-.016,width:.2+o%3*.05,height:.032,rx:.006})),i.append(a)}this.photon.append(i,rt("circle",{class:"tb-photon-core",cx:0,cy:0,r:.12})),this.layer.append(this.tail,this.photon);const[n,r]=Ba(t);this.points.push([n,r]),this.photon.setAttribute("transform",`translate(${n} ${r})`)}async point_reach(e,t,i=!1){const[n,r]=[t.y,t.x];this.points.push([n,r]),this.photon.setAttribute("transform",`translate(${n} ${r})`),this.tail.replaceChildren();const o=this.points.slice(-4);for(let a=1;a<o.length;a++){const[l,c]=o[a-1],[h,d]=o[a];this.tail.append(rt("line",{class:"tb-tail-segment",x1:l,y1:c,x2:h,y2:d,"stroke-width":.03+.03*a,opacity:.25+.25*a}))}i||await e.wait(er.torpedoPoint)}async end(e,t=!1){this.photon.remove(),t||await e.wait(er.tail),this.layer.remove()}}function ww(s,e){s.classList.toggle("tb-rescan",e)}function M9(s,e){s.classList.remove("tb-bloom","tb-bloom-hostile"),s.offsetWidth,s.classList.add("tb-bloom"),e&&s.classList.add("tb-bloom-hostile"),s.addEventListener("animationend",()=>s.classList.remove("tb-bloom","tb-bloom-hostile"),{once:!0})}function wi(s,e){return s!==null&&e.includes(s.question)}function mu(s,e){const t=q("div","tb-station-head"),i=q("span","tb-station-step",""),n=ei("tb-grave tb-cancel","CANCEL",()=>{e.answer_send(n.dataset.line??"","CANCEL")});return n.hidden=!0,t.append(q("span","tb-station-name",s),i,q("span","tb-station-fill"),n),{root:t,step:i,cancel:n}}function gu(s,e,t,i){const n=t?.command??null,r=n!==null&&n.station===e&&t!==null&&t.question!=="command";s.step.textContent=r&&n!==null&&t!==null?`${n.label} · ${t.question.replace(/-/g," ").toUpperCase()}`:t?.question==="command"?"READY":"";const o=r?i?.cancel:void 0;s.cancel.hidden=o===void 0,s.cancel.dataset.line=o??"",s.cancel.textContent=n===null?"CANCEL":`CANCEL ${n.label}`}function Z_(s,e){const t=ei(`tb-command${s.grave===!0?" tb-grave":""}`,s.label,()=>{e.command_send(s)});return t.dataset.command=s.id,t}function Vx(s,e){const t=q("div","tb-pills tb-command-pills"),i=new Map;for(const n of fu.filter(r=>r.station===s)){const r=Z_(n,e);i.set(n.id,r),t.append(r)}return{root:t,pills:i}}function _u(s,e){for(const[t,i]of s)i.disabled=e?.question!=="command",i.classList.toggle("tb-pill-on",e?.command?.id===t)}function qx(s,e){const t=ei("tb-target","",e);return t.append(Y_("klingon",s.mark),document.createTextNode(`${s.x},${s.y}`)),t.title=`Klingon at ${s.x},${s.y}`,t}function jm(s,e){const t=q("span",s,e.supernova?"":e.code??"");return e.supernova&&t.append(Y_("supernova")),t}function Hm(s){return`quadrant ${s.x},${s.y}${s.supernova?" · supernova":s.code===null?" · unscanned":""}`}function Kx(s){const e=s.klingons.map(t=>({bearing:t.bearing,kind:"klingon",label:`Klingon at ${t.x},${t.y} · ${t.range.toFixed(1)} · ${Math.round(t.bearing)}°`,variant:t.mark}));for(const t of s.sectors)for(const i of t){if(i.kind!=="base")continue;const n=i.x-s.position.sector.x,r=i.y-s.position.sector.y;e.push({bearing:(Math.atan2(r,-n)*180/Math.PI+360)%360,kind:"base",label:`starbase at ${i.x},${i.y}`})}return e}class yw{root;wheel;distance;warp;rest;head;pills;readout=null;constructor(e,t,i){this.root=q("div","tb-station tb-station-helm"),this.head=mu("HELM",e);const n=Vx("helm",e);this.pills=n.pills;const r=q("div","tb-controls");this.wheel=new Px(t,"course wheel",a=>e.answer_send(String(a),"SET COURSE"));const o=q("div","tb-sliders");this.distance=new Lr(`${i}-distance`,"DISTANCE",1,a=>e.answer_send(a.toFixed(1),"SLIDER SET")),this.warp=new Lr(`${i}-warp`,"WARP FACTOR",1,a=>e.answer_send(a.toFixed(1),"SLIDER SET")),this.rest=new Lr(`${i}-rest`,"REST",1,a=>e.answer_send(a.toFixed(1),"SLIDER SET")),this.distance.input_listen(()=>this.arrival_note()),o.append(this.distance.root,this.warp.root,this.rest.root),r.append(this.wheel.root,o),this.root.append(this.head.root,n.root,r)}state_show(e){const t=this.readout===null;this.readout=e,this.wheel.marks_set(Kx(e)),this.warp.range_set(ks("warp-factor",e),e.ship.warp,"THE SHIP NOW · ABOVE 6 THE ENGINES MAY BURN",10),this.distance.range_set(ks("distance",e),t?1:this.distance.value_get(),"QUADRANTS · 0.1 IS ONE SECTOR",6),this.rest.range_set(ks("how-long",e),0,`STARDATES · ${e.mission.timeLeft.toFixed(1)} LEFT · REPAIRS RUN WHILE TIME PASSES`,2)}question_show(e){_u(this.pills,e);const t=e===null?null:ks(e.question,this.readout);gu(this.head,"helm",e,t),this.wheel.lit_set(wi(e,["course","direction"]),"SET COURSE"),this.distance.lit_set(wi(e,["distance"]),"ENGAGE"),this.warp.lit_set(wi(e,["warp-factor"]),"SET WARP"),this.rest.lit_set(wi(e,["how-long"]),"REST"),e?.question==="distance"&&this.arrival_note()}arrival_note(){if(this.readout===null)return;const e=this.distance.value_get(),t=n9(this.readout,this.wheel.degrees_get(),e),i=Ux(e,this.readout.ship.warp,this.readout.param.warptime);this.distance.note_set(`ARRIVES ${t.quadrant.x},${t.quadrant.y} / ${t.sector.x},${t.sector.y} · ${i.stardates.toFixed(2)} STARDATES AT WARP ${this.readout.ship.warp.toFixed(1)} · ${i.units} UNITS`)}}class Sw{constructor(e,t,i){this.host=e,this.root=q("div","tb-station tb-station-tactical"),this.head=mu("TACTICAL",e);const n=Vx("tactical",e);this.pills=n.pills;const r=q("div","tb-controls");this.wheel=new Px(t,"firing course wheel",l=>e.answer_send(String(l),"SET COURSE"));const o=q("div","tb-sliders");this.burst=new bh("BURST",ks("burst",null).choices??[],(l,c)=>e.answer_send(l,Dr(c,"choice"))),this.burstAngle=new bh("BURST ANGLE",ks("burst-angle",null).choices??[],(l,c)=>{this.wheel.wedge_set(Number(l)),e.answer_send(l,Dr(c,"choice"))}),this.manual=new bh("PHASERS",ks("manual-automatic",null).choices??[],(l,c)=>e.answer_send(l,Dr(c,"choice"))),this.units=new Lr(`${i}-units`,"UNITS",0,l=>e.answer_send(String(Math.round(l)),"SLIDER SET")),this.spread=new Lr(`${i}-spread`,"SPREAD",2,l=>e.answer_send(l.toFixed(2),"SLIDER SET")),this.upDown=new bh("SHIELDS",ks("up-down",null).choices??[],(l,c)=>e.answer_send(l,Dr(c,"choice")));const a=q("div","tb-fire-row");this.fire=ei("tb-fire","FIRE",()=>e.answer_send("0",null)),this.targets=q("div","tb-targets"),a.append(this.fire,this.targets),o.append(this.burst.root,this.burstAngle.root,this.manual.root,this.units.root,this.spread.root,this.upDown.root,a),r.append(this.wheel.root,o),this.root.append(this.head.root,n.root,r)}host;root;wheel;units;spread;head;pills;burst;burstAngle;manual;upDown;fire;targets;readout=null;state_show(e){this.readout=e,this.wheel.marks_set(Kx(e)),this.wheel.wedge_set(null),e.klingons[0]!==void 0&&this.wheel.degrees_set(e.klingons[0].bearing),this.units.range_set(ks("units",e),Math.min(e.ship.energy,Math.round(e.ship.energy/100)*10),`UP TO THE ${e.ship.energy} FREE`,6),this.spread.range_set(ks("spread",e),.5,"MANUAL PHASERS ONLY",3),this.burst.note_set(`${e.ship.torpedoes} TORPEDOES · A BURST FIRES 3`),this.upDown.note_set(`${e.ship.shieldsUp?"UP":"DOWN"} · ${e.ship.shield} OF ${e.ship.shieldMax} · REFILLS AT A STARBASE`);const t=this.pills.get("phasers");t!==void 0&&(t.classList.toggle("tb-barred",e.ship.shieldsUp),t.title=e.ship.shieldsUp?"Shields are up: phasers cannot fire through them. SHIELDS, then DOWN, first.":""),this.targets_draw(e)}question_show(e){_u(this.pills,e);const t=e===null?null:ks(e.question,this.readout);gu(this.head,"tactical",e,t),this.wheel.lit_set(wi(e,["torpedo-course","bank-course"]),"SET COURSE"),this.burst.lit_set(wi(e,["burst"])),this.burstAngle.lit_set(wi(e,["burst-angle"])),this.manual.lit_set(wi(e,["manual-automatic"])),this.units.lit_set(wi(e,["units","bank-units"]),e?.question==="units"?"FIRE":"SET BANK"),this.spread.lit_set(wi(e,["spread"])),this.upDown.lit_set(wi(e,["up-down"])),this.fire.disabled=!wi(e,["bank-units"]),this.fire.textContent="FIRE THE BANKS SET"}targets_draw(e){if(this.targets.replaceChildren(),e.klingons.length===0){this.targets.append(q("span","tb-note","NO KLINGONS IN THIS QUADRANT"));return}for(const t of["TARGET","RANGE","BEARING","PHASER HIT"])this.targets.append(q("span","tb-target-head",t));for(const t of e.klingons){const i=qx(t,()=>{this.host.voice.cue("scanner"),this.host.course_set(t.bearing,t.range/10)});this.targets.append(i,q("span","tb-target-cell",t.range.toFixed(1)),q("span","tb-target-cell",`${Math.round(t.bearing)}°`),q("span","tb-target-cell",`${$x(t.range/10)}%`))}}}class v9{root;rest;head;pills;damage;systems;since;inThatTime;readout=null;constructor(e){this.root=q("div","tb-view-body tb-view-engineering");const t=q("section","tb-panel tb-damage");t.append(q("span","tb-title","DAMAGE CONTROL"),q("span","tb-note","THE C'S REPORT · ALWAYS ON")),this.damage=q("div","tb-dc"),t.append(this.damage,q("span","tb-note","REPAIR TIMES IN STARDATES · REPAIRS RUN WHILE TIME PASSES · DOCKED, FASTER BY THE DOCK FACTOR"));const i=q("section","tb-panel tb-systems-section");i.append(q("span","tb-title","SHIP"),q("span","tb-note","ENERGY, SHIELDS, RESERVES")),this.systems=q("div","tb-systems"),i.append(this.systems,q("span","tb-title","SINCE THE LAST COMMAND")),this.since=q("div","tb-head-grid tb-since-grid"),i.append(this.since,q("span","tb-note","SHIELDS ARE UP OR DOWN IN TREK(6): THEIR ENERGY IS A READOUT, REFILLED AT A STARBASE"));const n=q("section","tb-panel tb-station tb-station-time");this.head=mu("REST",e);const r=q("div","tb-pills tb-command-pills");this.pills=new Map;for(const o of["rest","dock","undock"]){const a=fu.find(c=>c.id===o);if(a===void 0)continue;const l=Z_(a,e);this.pills.set(o,l),r.append(l)}this.rest=new Lr("tbe-rest","HOW LONG",1,o=>e.answer_send(o.toFixed(1),"SLIDER SET")),this.rest.input_listen(()=>this.inThatTime_note()),this.inThatTime=q("div","tb-in-that-time"),n.append(this.head.root,r,this.rest.root,q("span","tb-title","IN THAT TIME"),this.inThatTime),this.root.append(t,i,n)}state_show(e,t){this.readout=e,this.damage_draw(e),this.systems_draw(e),this.since.replaceChildren();const i=t===null?[]:jx(t,e);i.length===0&&this.since.append(q("span","tb-head-label","—"),q("span","tb-head-value","NOTHING MOVED"));for(const n of i)this.since.append(q("span","tb-head-label",n.label),q("span",`tb-head-value ${n.bad?"tb-bad":"tb-good"}`,n.change));this.rest.range_set(ks("how-long",e),this.rest.value_get(),`STARDATES · ${e.mission.timeLeft.toFixed(1)} LEFT`,4),this.inThatTime_note()}question_show(e){_u(this.pills,e);const t=e===null?null:ks(e.question,this.readout),i=e!==null&&(e.command===null||["rest","dock","undock"].includes(e.command.id))?e:null;gu(this.head,"helm",i,t),this.rest.lit_set(wi(e,["how-long"]),"REST")}damage_draw(e){this.damage.replaceChildren();for(const i of["DEVICE","","IN FLIGHT","DOCKED",""])this.damage.append(q("span","tb-dc-head",i));const t=Math.max(1,...e.damaged.map(i=>(i.repairAt??0)-e.mission.stardate));for(const i of e.devices){const n=bw(i,e),r=q("div","tb-bar-track"),o=q("div",`tb-bar-fill${n===null?" tb-bar-ok":" tb-bar-down"}`);o.style.width=n===null?"100%":`${Math.max(4,Math.min(100,Math.round(100*((i.repairAt??0)-e.mission.stardate)/t)))}%`,r.append(o),this.damage.append(q("span",`tb-dc-name${n===null?"":" tb-bad"}`,i.name.toUpperCase()),r,q("span","tb-dc-time",n===null?"—":n.inFlight.toFixed(2)),q("span","tb-dc-time",n===null?"—":n.docked.toFixed(2)),q("span",`tb-dc-state${n===null?" tb-good":" tb-bad"}`,n===null?"OK":"DOWN"))}}systems_draw(e){const{ship:t}=e;this.systems.replaceChildren();const i=(l,c,h,d,u)=>{const p=q("div","tb-bar-track"),f=q("div",`tb-bar-fill${u?" tb-bar-down":" tb-bar-ok"}`);f.style.width=`${Math.max(0,Math.min(100,Math.round(100*c/Math.max(1,h))))}%`,p.append(f),this.systems.append(q("span","tb-dc-name",l),p,q("span","tb-dc-time tb-sys-value",d))};i("ENERGY",t.energy,t.energyMax,`${t.energy} / ${t.energyMax}`,t.energy<t.energyMax/4),i("SHIELDS",t.shield,t.shieldMax,`${t.shieldsUp?"UP":"DOWN"} · ${t.shield} / ${t.shieldMax}`,t.shield<t.shieldMax/4),i("LIFE SUPPORT",t.reserves,t.reservesMax,`RESERVES ${t.reserves.toFixed(1)} / ${t.reservesMax.toFixed(1)}`,t.reserves<t.reservesMax/4);const n=q("div","tb-pips");for(let l=0;l<t.torpedoesMax;l++)n.append(q("span",`tb-pip${l<t.torpedoes?" tb-pip-on":""}`));this.systems.append(q("span","tb-dc-name","TORPEDOES"),n,q("span","tb-dc-time tb-sys-value",`${t.torpedoes} / ${t.torpedoesMax}`));const r=(l,c)=>{this.systems.append(q("span","tb-dc-name",l),q("span","tb-sys-text",c))};r("CREW",`${t.crew}${e.mission.captives>0?` · ${e.mission.captives} CAPTIVE`:" · BRIG EMPTY"}`);const o=e.damaged.some(l=>/warp/i.test(l.name));r("WARP",`${t.warp.toFixed(1)} · ENGINES ${o?"DOWN":"OK"}`);const a=e.damaged.some(l=>/cloak/i.test(l.name));r("CLOAK",`${t.cloaked?"ON":"OFF"} · DEVICE ${a?"DOWN":"OK"}`)}inThatTime_note(){if(this.readout===null)return;const e=this.rest.value_get();this.inThatTime.replaceChildren();const t=this.readout.damaged.filter(n=>(bw(n,this.readout)?.inFlight??1/0)<=e).map(n=>n.name.toUpperCase());this.inThatTime.append(q("span","tb-head-value tb-good",t.length===0?e>0?"NO REPAIR COMPLETES":"—":`${t.join(" · ")} REPAIRED`));const i=this.readout.klingons.length;i>0&&this.inThatTime.append(q("span","tb-head-value tb-bad",`${i} KLINGON${i===1?"":"S"} IN THE QUADRANT WILL FIRE · SPOCK MAY ASK TO CANCEL`))}}const zw=[{label:"CHART",line:"ch",asks:[]},{label:"TRAJECTORY",line:"t",asks:[]},{label:"COURSE",line:"c",asks:["quadrant","quadrant-y","sector","sector-y"]},{label:"MOVE",line:"m",asks:["quadrant","quadrant-y","sector","sector-y"]},{label:"SCORE",line:"s",asks:[]},{label:"PHASER EFFECT",line:"p",asks:["range"]},{label:"WARP COST",line:"w",asks:["computer-distance","computer-warp"]},{label:"IMPULSE COST",line:"i",asks:["computer-distance"]},{label:"DISTRESS LIST",line:"d",asks:[]}];class w9{constructor(e){this.host=e,this.root=q("div","tb-view-body tb-view-computer");const t=q("section","tb-panel tb-chart-section");t.append(q("span","tb-title","GALAXY · WHAT THE SHIP HAS SEEN"),q("span","tb-note","PRESS A QUADRANT: THE COURSE PANEL AIMS AT IT · HUNDREDS KLINGONS, TENS BASES, ONES STARS")),this.chart=q("div","tb-chart-big"),t.append(this.chart);const i=q("section","tb-station tb-station-computer");this.head=mu("COMPUTER",e);const n=q("div","tb-pills tb-command-pills");for(const d of zw){const u=ei("tb-command tb-request",d.label,()=>this.request_send(d));u.dataset.request=d.line,this.requestPills.push(u),n.append(u)}const r=q("div","tb-computer-panels"),o=q("div","tb-panel");o.append(q("span","tb-title","COURSE AND DISTANCE")),this.courseGrid=q("div","tb-head-grid");const a=q("div","tb-pills");a.append(ei("tb-commit tb-send-helm","SEND TO HELM",()=>this.helm_send()),ei("tb-commit tb-move-now","MOVE THERE NOW",()=>this.request_send(zw[3]))),o.append(this.courseGrid,a);const l=q("div","tb-panel");l.append(q("span","tb-title","WARP COST")),this.wcDistance=new Lr("tbc-distance","DISTANCE",2,()=>{}),this.wcWarp=new Lr("tbc-warp","WARP FACTOR",1,()=>{}),this.wcDistance.root.classList.add("tb-local"),this.wcWarp.root.classList.add("tb-local"),this.wcDistance.input_listen(()=>this.costs_note()),this.wcWarp.input_listen(()=>{this.warpTouched=!0,this.costs_note()}),this.wcResult=q("div","tb-head-grid"),l.append(this.wcDistance.root,this.wcWarp.root,this.wcResult);const c=q("div","tb-panel");c.append(q("span","tb-title","TRAJECTORY · KLINGONS HERE")),this.trajectory=q("div","tb-targets"),c.append(this.trajectory,q("span","tb-title","SCORE SO FAR")),this.score=q("div","tb-score"),c.append(this.score);const h=q("div","tb-panel tb-answer-panel");h.append(q("span","tb-title","THE COMPUTER ANSWERS")),this.answer=q("pre","tb-computer-answer","—"),h.append(this.answer),r.append(o,l,c,h),i.append(this.head.root,n,r),this.root.append(t,i)}host;root;head;chart;requestPills=[];courseGrid;wcDistance;wcWarp;wcResult;trajectory;score;answer;readout=null;target=null;open=null;warpTouched=!1;state_show(e){this.readout=e,this.target===null&&(this.target={quadrant:{...e.position.quadrant},sector:{...e.position.sector}}),this.chart_draw(e),this.wcWarp.range_set(ks("computer-warp",e),this.warpTouched?this.wcWarp.value_get():e.ship.warp,"THE SHIP'S NOW",4),this.wcDistance.range_set(ks("computer-distance",e),this.wcDistance.value_get(),"QUADRANTS · FILLED FROM THE COURSE",4),this.wcDistance.lit_set(!0,""),this.wcWarp.lit_set(!0,""),this.course_note(),this.trajectory_draw(e),this.score_draw(e)}question_show(e){this.open=e;const t=e===null?null:ks(e.question,this.readout);gu(this.head,"ship",e,t);const i=e?.question==="command"||e?.question==="request";for(const n of this.requestPills)n.disabled=!i}answer_take(e){if(e===null){this.answer.textContent="";return}this.answer.textContent=`${this.answer.textContent??""}${e}`.replace(/^\s*\n/,"")}sector_set(e){this.readout!==null&&(this.target={quadrant:this.target?.quadrant??{...this.readout.position.quadrant},sector:{x:e.x,y:e.y}},this.course_note())}request_send(e){const t=e.asks.map(n=>[n,this.plannedAnswer_derive(n)]);if(this.open?.question==="request"){this.host.plan_set(t),this.answer_take(null),this.host.answer_send(e.line,Dr(e.label,"computer")),this.host.voice.cue("thinking");return}const i=fu.find(n=>n.id==="computer");if(i===void 0||this.open?.question!=="command"){this.host.voice.cue("deny");return}this.host.plan_set([["request",e.line],...t]),this.answer_take(null),this.host.voice.pill(Dr(e.label,"computer")),this.host.command_send(i)}plannedAnswer_derive(e){const t=this.target,i=this.readout?.klingons[0];switch(e){case"quadrant":return String(t?.quadrant.x??0);case"quadrant-y":return String(t?.quadrant.y??0);case"sector":return String(t?.sector.x??0);case"sector-y":return String(t?.sector.y??0);case"range":return(i===void 0?this.wcDistance.value_get():i.range/10).toFixed(2);case"computer-distance":return this.wcDistance.value_get().toFixed(2);case"computer-warp":return this.wcWarp.value_get().toFixed(1);default:return""}}helm_send(){if(this.readout===null||this.target===null)return;const e=_w(this.readout,this.target);this.host.voice.pill("SEND TO HELM"),this.host.course_set(e.course,Math.round(e.distance*10)/10)}chart_draw(e){this.chart.replaceChildren(),this.chart.append(q("span","tb-srs-corner",""));for(let t=0;t<(e.chart[0]?.length??0);t++)this.chart.append(q("span","tb-srs-axis",String(t)));for(const t of e.chart){this.chart.append(q("span","tb-srs-axis",String(t[0]?.x??"")));for(const i of t)this.chart.append(this.quadrantButton_make(i))}}quadrantButton_make(e){const t=this.target?.quadrant.x===e.x&&this.target.quadrant.y===e.y,i=ei(`tb-cq${e.here?" tb-here":""}${e.klingons>0?" tb-hostile":""}${e.bases>0?" tb-based":""}${e.code===null?" tb-unscanned":""}${t?" tb-pressed":""}`,"",()=>{this.readout!==null&&(this.target={quadrant:{x:e.x,y:e.y},sector:this.target?.sector??{...this.readout.position.sector}},this.host.voice.cue("scanner"),this.chart_draw(this.readout),this.course_note())});return i.dataset.x=String(e.x),i.dataset.y=String(e.y),i.append(jm("tb-cq-code",e),q("span","tb-cq-at",`${e.x},${e.y}`)),i.title=Hm(e),i}course_note(){if(this.readout===null||this.target===null)return;const{position:e}=this.readout,t=_w(this.readout,this.target);this.courseGrid.replaceChildren(q("span","tb-head-label","FROM"),q("span","tb-head-value",`QUADRANT ${e.quadrant.x},${e.quadrant.y} · SECTOR ${e.sector.x},${e.sector.y}`),q("span","tb-head-label","TO"),q("span","tb-head-value",`QUADRANT ${this.target.quadrant.x},${this.target.quadrant.y} · SECTOR ${this.target.sector.x},${this.target.sector.y}`),q("span","tb-head-label","COURSE"),q("span","tb-head-value tb-course-value",`${t.course}°`),q("span","tb-head-label","DISTANCE"),q("span","tb-head-value tb-distance-value",t.distance.toFixed(2))),this.wcDistance.value_set(Math.round(t.distance*100)/100),this.costs_note()}costs_note(){if(this.readout===null)return;const e=this.wcDistance.value_get(),t=Ux(e,this.wcWarp.value_get(),this.readout.param.warptime),i=r9(e);this.wcResult.replaceChildren(q("span","tb-head-label","TIME"),q("span","tb-head-value",`${t.stardates.toFixed(2)} STARDATES`),q("span","tb-head-label","ENERGY"),q("span","tb-head-value",`${t.units} UNITS · ${t.unitsShielded} WITH SHIELDS UP`),q("span","tb-head-label","AT IMPULSE"),q("span","tb-head-value",`${i.stardates.toFixed(2)} STARDATES · ${i.units} UNITS`))}trajectory_draw(e){if(this.trajectory.replaceChildren(),e.klingons.length===0){this.trajectory.append(q("span","tb-note","NO KLINGONS IN THIS QUADRANT"));return}for(const t of["AT","COURSE","RANGE","PHASER HIT"])this.trajectory.append(q("span","tb-target-head",t));for(const t of e.klingons)this.trajectory.append(qx(t,()=>{this.host.voice.cue("scanner"),this.host.course_set(t.bearing,t.range/10)}),q("span","tb-target-cell",`${Math.round(t.bearing)}°`),q("span","tb-target-cell",t.range.toFixed(1)),q("span","tb-target-cell",`${$x(t.range/10)}%`))}score_draw(e){const t=Fx(e);this.score.replaceChildren();for(const i of t.items.filter(n=>n.points!==0||/killed|remaining/.test(n.label)))this.score.append(q("span","tb-score-label",i.label.toUpperCase()),q("span",`tb-score-points${i.points<0?" tb-bad":" tb-good"}`,`${i.points>0?"+":""}${i.points}`));this.score.append(q("span","tb-score-label tb-score-total","TOTAL"),q("span","tb-score-points tb-score-total",String(t.total)))}}const Ff=["bridge","helm","tactical","engineering","computer"],y9=400,S9="-0.6 -0.6 10.6 10.6",z9=.7,x9=/^S\.R\. scanners$/i,O9=/^L\.R\. scanners$/i,E9={ArrowUp:[-1,0],ArrowDown:[1,0],ArrowLeft:[0,-1],ArrowRight:[0,1]},A9=["length","skill","request","quadrant","quadrant-y","sector","sector-y","range","computer-distance","computer-warp","status-report","another","yes-no","unknown"];class T9{constructor(e,t){this.hooks=e,this.harness=new c9({question_changed:r=>{this.partial_flush(),this.question_show(r)},text_written:r=>this.text_take(r),state_shown:r=>this.state_show(r),ended:()=>{this.leaving||this.hooks.voice.cue("gameover")}}),this.frame=X_({id:"trek-bridge",className:"trek-bridge",brand:{name:"TREK",sub:"ARGUS · BSD TREK",mark:!1},banner:"TREK • THE BRIDGE",views:Ff.map(r=>({key:r,label:r.toUpperCase()})),leave:{label:"LEAVE BRIDGE",destroy:!0},stage:{title:"THE BRIDGE",note:"BRIDGE"},log:{title:"SHIP'S LOG",note:"READ ONLY"},labels:{views:"views",log:"ship's log"}},r=>{const o=Ff.find(a=>a===r);o!==void 0&&this.view_set(o)},()=>this.leave_ask()),this.frame.leave.classList.add("tb-leave"),this.root=this.frame.root,this.root.dataset.view="bridge",this.frame.view_mark("bridge"),this.root.setAttribute("aria-label","trek: the bridge");const i={},n=OH();n!==null&&this.root.append(n),this.gutter_build(i,t),this.frame.face.append(this.header_build(i)),this.frame.body.append(this.body_build(i)),this.strip_build(i),this.frame.aside.append(i.ask),this.frame.log.append(this.log_build(i)),this.leaveAsk_build(i),this.root.append(i.leaveAsk),this.parts=i,this.question_show(null)}hooks;root;frame;harness;readout=null;previous=null;view="bridge";nextDistance=null;plan=new Map;answering=!1;computerRunning=!1;leaving=!1;tracker=new $l;heading=0;pressedSector=null;scanDue=!1;fold=null;frames=new u9;shown=null;torpedo=null;trackPrinting=!1;partial="";lrsBloom=null;parts;stationHost_get(){return{answer_send:(e,t)=>this.answer_send(e,t),command_send:e=>this.command_send(e),plan_set:e=>{for(const[t,i]of e)this.plan.set(t,i)},course_set:(e,t)=>this.course_set(e,t),voice:this.hooks.voice}}gutter_build(e,t){e.seed=q("div","tb-seed",t===null?"RANDOM GALAXY":`SEED ${t}`),this.frame.seat.append(e.seed),e.views=new Map;for(const i of Ff){const n=this.frame.views.get(i);n!==void 0&&(n.classList.add("tb-view",`tb-view-${i}`),e.views.set(i,n))}}header_build(e){const t=q("header","tb-header"),i=q("section","tb-head-condition"),n=q("div","tb-condition");n.append(q("span","tb-condition-label","CONDITION")),e.condition=q("span","tb-condition-name","—"),n.append(e.condition),e.conditionWhy=q("div","tb-condition-why",""),i.append(n,e.conditionWhy);const r=p=>{const f=q("section","tb-head-section");f.append(q("span","tb-head-title",p));const _=q("div","tb-head-grid");return f.append(_),[f,_]},[o,a]=r("SHIP"),[l,c]=r("MISSION"),[h,d]=r("POSITION"),u=q("div","tb-head-grid tb-head-since");return l.append(q("span","tb-head-title","SINCE LAST COMMAND"),u),e.ship=a,e.mission=c,e.position=d,e.since=u,t.append(i,o,l,h),t}body_build(e){const t=this.stationHost_get(),i=q("main","tb-body");i.dataset.view="bridge",e.body=i;const n=q("section","tb-scans");n.append(q("span","tb-title","LONG RANGE")),e.lrs=q("div","tb-lrs"),n.append(e.lrs,q("span","tb-title","GALAXY · WHAT THE SHIP HAS SEEN")),e.chart=q("div","tb-chart"),n.append(e.chart);const r=q("section","tb-srs-section");e.srsTitle=q("span","tb-title","SHORT RANGE"),r.append(e.srsTitle),e.scan=rt("svg",{class:"tb-scan",viewBox:S9,role:"grid","aria-label":"short range scan"}),e.scan.addEventListener("keydown",l=>this.scan_key(l)),e.legend=this.legend_build(),r.append(e.scan,q("span","tb-note","PRESS A SECTOR: ITS COURSE AND DISTANCE FILL IN"),e.legend),e.shipPills=new Map;const o=q("div","tb-pills tb-ship-pills");o.append(q("span","tb-slider-label","SHIP"));for(const l of fu.filter(c=>c.station==="ship")){const c=Z_(l,t);e.shipPills.set(l.id,c),o.append(c)}r.append(o);const a=q("section","tb-stations");return e.helm=new yw(t,150,"tb"),e.tactical=new Sw(t,150,"tb"),a.append(e.helm.root,e.tactical.root),e.helmView=new yw(t,260,"tbh"),e.helmView.root.classList.add("tb-view-body","tb-view-helm"),e.tacticalView=new Sw(t,260,"tbt"),e.tacticalView.root.classList.add("tb-view-body","tb-view-tactical"),e.engineeringView=new v9(t),e.computerView=new w9(t),i.append(n,r,a,e.helmView.root,e.tacticalView.root,e.engineeringView.root,e.computerView.root),i}legend_build(){const e=q("div","tb-legend");for(const t of EH){const i=q("span",`tb-legend-item tb-legend-${t.kind}`),n=t.kind==="klingon"?Er:[null];for(const r of n)i.append(Y_(t.kind,r));i.append(q("span","tb-legend-glyph",_h[t.kind].trim()===""?"␠":_h[t.kind]),q("span","tb-legend-name",t.name)),e.append(i)}return e}strip_build(e){e.ask=q("div","tb-ask"),e.ask.hidden=!0,e.ask.setAttribute("role","dialog"),e.askText=q("span","tb-ask-text",""),e.askPills=q("div","tb-pills"),e.askInput=document.createElement("input"),e.askInput.type="text",e.askInput.className="tb-ask-input",e.askInput.setAttribute("aria-label","the answer");const t=e.askInput;e.askSend=ei("tb-commit","ANSWER",()=>this.answer_send(t.value,"ANSWER")),t.addEventListener("keydown",i=>{i.key==="Enter"&&this.answer_send(t.value,"ANSWER")}),e.ask.append(q("span","tb-ask-label","THE GAME ASKS"),e.askText,e.askPills,e.askInput,e.askSend)}log_build(e){const t=q("footer","tb-log-section");return e.log=q("div","tb-log"),e.log.setAttribute("aria-live","polite"),t.append(e.log),t}leaveAsk_build(e){e.leaveAsk=q("div","tb-leave-ask"),e.leaveAsk.hidden=!0,e.leaveAsk.setAttribute("role","dialog");const t=e.leaveAsk,i=ei("tb-grave","LEAVE · THE GAME ENDS",()=>{this.leaving=!0,this.hooks.voice.cue("close"),this.hooks.leave()}),n=ei("","STAY",()=>{t.hidden=!0});e.leaveAsk.append(q("span","tb-ask-label","LEAVE THE BRIDGE?"),q("span","tb-ask-text","The game ends where it stands; dump first to keep it."),i,n)}harness_get(){return this.harness}leave_ask(){this.frames.skip(),this.parts.leaveAsk.hidden&&this.hooks.voice.pill("LEAVE BRIDGE"),this.parts.leaveAsk.hidden=!1}frames_get(){return{played:{...this.frames.played},pending:this.frames.pending_count(),busy:this.frames.busy_is()}}frames_settle(){return this.frames.settle()}leaveAsk_isOpen(){return!this.parts.leaveAsk.hidden}leaveAsk_close(){this.parts.leaveAsk.hidden=!0}view_get(){return this.view}view_set(e){this.frames.skip(),this.view=e,this.root.dataset.view=e,this.parts.body.dataset.view=e,this.frame.view_mark(e);for(const[t,i]of this.parts.views)i.classList.toggle("tb-view-on",t===e);this.frame.stageNote.textContent=e.toUpperCase(),this.hooks.voice.pill(Dr(e.toUpperCase(),"view"))}readout_get(){return this.readout}command_send(e){if(this.frames.skip(),!this.harness.command_send(e))return this.hooks.voice.cue("deny"),!1;const t=GH(e.id);return t===null?this.hooks.voice.pill(Dr(e.label,"command")):this.hooks.voice.cue(t),this.nextDistance=null,this.computerRunning=e.id==="computer",this.computerRunning&&this.parts.computerView.answer_take(null),this.log_write(`Command: ${e.line}
|
|
4358
|
+
`);return}(v||b.envelopes.some(z=>z.status==="error"))&&S.outcome_write(b),l(b)},h=[],d=M=>{const v=h.length===0;for(const S of M)S.vfsPath!==""&&!h.includes(S.vfsPath)&&h.push(S.vfsPath);!v||h.length===0||queueMicrotask(()=>{const S=h.splice(0);S.length>0&&c(`gather add ${S.map(ln).join(" ")}`)})},u=(M,v,S)=>({command_run:x=>{s.client.line_execute(x,{silent:!0})},command_show:x=>s.terminal.line_run(x),note:x=>s.terminal.line_note(x),image_open:x=>{e.image_open(M(),x).then(b=>s.terminal.line_note(b))},process_open:x=>e.process_open(M(),{input:x,feed:null,node:null}),...v,...S,verb_send:c,cohort_process:x=>e.process_open(M(),x),feed_open:x=>e.feed_open(M(),x)}),p=()=>{const M=document.querySelector("#header-gather-pill");M!==null&&M.classList.toggle("panel-gather-empty",(r?.entries_get().length??0)===0)},f=()=>{const M=e.element_require("header-gather"),v=()=>e.errandHost_find()??"pacs",S=x=>V_(s.terminal,e.element_require("header-gather"),x);return new cw(M,e.pane_find(M,".gather-rows"),u(v,{name_ask:x=>S({message:"Cohort name: ",kind:"text",suggest:x,commit:"NAME IT"}),confirm_ask:async x=>{const b=await S({message:x,kind:"confirm"});return b==="y"||b==="n"?b:null}},{dismiss:()=>{document.body.dataset.header="away",o=!0,p()}}),n)};return{cohort:n,instance_build:M=>{const v=e.template_stamp("tpl-pane-gather"),S=new cw(v,e.pane_find(v,".gather-rows"),u(()=>M,{name_ask:x=>e.askOnPane_await(M,{message:"Cohort name: ",kind:"text",suggest:x,commit:"NAME IT"}),confirm_ask:async x=>{const b=await e.askOnPane_await(M,{message:x,kind:"confirm"});return b==="y"||b==="n"?b:null}},{dismiss:()=>{s.layout.leaf_close(M)||e.home_apply(),e.orphans_dispose(),e.stage_relight()}}),n);return t.set("gather",M,S),{id:M,kind:"gather",mount:v,dispose:()=>{t.delete(M),i.pane_leave(M)}}},has:M=>n.has(M),gather:M=>{r===null&&(r=f()),d(M);const v=document.body.dataset.header==="away";(!o||!v)&&(document.body.dataset.header="gather",o=!1),p()},open:(M,v="pacs")=>{const{layout:S}=s,x=new Set(S.panes_shown());let b=t.ids("gather").find(z=>x.has(z))??null;if(b===null){const z=x.has(v)?v:e.errandHost_find()??v,T=e.instance_spawn("gather","pacs"),A=e.replayPlace_get();if(!S.leaf_split(z,A?.dir??"row",T.id,A?.before??!1))return Ds(T.id),S.mount_remove(T.id),null;e.birth_record(T.id,z,A?.dir??"row",A?.before??!1),b=T.id}return t.get("gather",b)===void 0?null:(d(M),b)},stage:()=>{const{layout:M}=s,v=new Set(M.panes_shown()),S=t.ids("gather").find(x=>v.has(x))??null;if(S!==null)M.focus_set(S);else{const x=e.errandHost_find()??"pacs",b=e.instance_spawn("gather","pacs");if(!M.leaf_split(x,"col",b.id,!1)){Ds(b.id),M.mount_remove(b.id);return}e.birth_record(b.id,x,"col",!1),t.get("gather",b.id)?.render_now()}document.body.dataset.header="away",o=!0},annunciate:p,restore:async()=>{try{l(await s.client.line_execute("gather",{silent:!0,observe:!1}))}catch{}},envelope_observe:M=>{M.model?.kind===hw&&a(M.model.data)}}}class eH{mount;handlers;titleSpan;stateSpan;fieldSection;savePill;revertPill;focusMark;field=null;path=null;original="";saving=!1;fieldBuild=null;constructor(e,t){this.mount=e,this.handlers=t,this.titleSpan=e.querySelector(".pane-title"),this.stateSpan=e.querySelector(".pane-state"),this.fieldSection=this.element_require(".edit-field"),this.savePill=this.element_require(".edit-save"),this.revertPill=this.element_require(".edit-revert"),this.focusMark=e.querySelector(".edit-focus"),this.savePill.addEventListener("click",()=>{this.save()}),this.revertPill.addEventListener("click",()=>this.revert()),e.addEventListener("keydown",i=>{(i.ctrlKey||i.metaKey)&&!i.altKey&&i.key.toLowerCase()==="s"&&(i.preventDefault(),i.stopPropagation(),this.save())},{capture:!0}),this.fieldSection.addEventListener("mousedown",()=>this.focusMark_set(!0)),this.fieldSection.addEventListener("focusin",()=>this.focusMark_set(!0)),this.fieldSection.addEventListener("focusout",i=>{(!(i.relatedTarget instanceof Node)||!this.fieldSection.contains(i.relatedTarget))&&this.focusMark_set(!1)}),this.controls_sync()}opening_show(e){this.path=e,this.title_set(e),Ts(this.stateSpan,"wait","OPENING")}async content_show(e){this.path=e.path,this.original=e.content,this.title_set(e.path),this.fieldBuild??=this.field_build(e);const t=await this.fieldBuild;t!==null&&(t.text_get()!==this.original&&t.text_set(this.original),this.controls_sync(),t.focus(),this.focusMark_set(!0))}async field_build(e){let t;try{t=await Xl(()=>import("./field-DBwJhEgd.js"),__vite__mapDeps([5,6]),import.meta.url)}catch(i){if(!F_(i))throw i;return Ts(this.stateSpan,"stale",Cd),this.handlers.note(`edit: ${Cd.toLowerCase()} — the editor's code is of an older build than the server has`),null}return this.field=await t.editField_create(this.fieldSection,e.content,e.extension,()=>this.controls_sync()),this.field}opening_fail(e){Ts(this.stateSpan,"refused",`NOT OPENED · ${e.toUpperCase()}`)}async save(){if(this.field===null||this.path===null||this.saving)return!1;const e=this.field.text_get();if(e===this.original)return!0;this.saving=!0,this.controls_sync();let t=!1;try{t=await this.handlers.save(this.path,e)}finally{this.saving=!1}return t&&(this.original=e),this.controls_sync(),t||Ts(this.stateSpan,"refused","NOT SAVED · THE CONSOLE SAYS WHY"),t}revert(){this.field===null||!this.dirty_is()||(this.field.text_set(this.original),this.controls_sync())}dirty_is(){return this.field!==null&&this.field.text_get()!==this.original}path_get(){return this.path}field_release(){return this.field===null||!this.field.hasFocus()?!1:(this.field.blur(),this.focusMark_set(!1),!0)}dispose(){this.field?.destroy(),this.field=null}controls_sync(){const e=this.dirty_is();this.savePill.disabled=!e||this.saving,this.revertPill.disabled=!e||this.saving,this.mount.dataset.dirty=e?"yes":"no",this.field!==null&&(this.saving?Ts(this.stateSpan,"wait","SAVING"):e?Ts(this.stateSpan,"note","DIRTY"):Ts(this.stateSpan,"settled","SAVED"))}title_set(e){this.titleSpan!==null&&(this.titleSpan.textContent=`EDIT ${e.split("/").pop()??e}`.toUpperCase()),this.mount.title=e}focusMark_set(e){this.focusMark!==null&&(this.focusMark.hidden=!e)}element_require(e){const t=this.mount.querySelector(e);if(t===null)throw new Error(`edit pane: no ${e} in its template`);return t}}function tH(s,e){const{layout:t,panels:i,subjects:n}=s,r=async(d,u)=>{const p=await ba(s,W_(d,u));return p&&e.saved?.(d),p},o=d=>{const u=e.template_stamp("tpl-pane-edit"),p=new eH(u,{save:r,note:f=>s.terminal.line_note(f)});return i.set("edit",d,p),{id:d,kind:"edit",mount:u,dispose:()=>{p.dispose(),i.delete(d),n.pane_leave(d)}}},a=d=>{const u=new Set(t.panes_shown());for(const[p,f]of i.entries("edit"))if(u.has(p)&&f.path_get()===d)return p;return null},l=()=>{e.launcher_yield();const d=new Set(t.panes_shown()),u=t.focused_get(),p=u!==null&&d.has(u)?u:e.errandHost_find();if(p===null)return null;const f=e.instance_spawn("edit"),_=e.replayPlace_get();return t.leaf_split(p,_?.dir??"col",f.id,_?.before??!1)?(e.birth_record(f.id,p,_?.dir??"col",_?.before??!1),f.id):(Ds(f.id),t.mount_remove(f.id),null)};return{instance_build:o,edit_receive:d=>{const u=d.path??"";if(u==="")throw new Error("the editor pane needs the file it edits, and the request named none");const p=a(u)??l();if(p===null)return!1;const f=i.get("edit",p);return f===void 0?!1:(t.focus_set(p),f.dirty_is()?(s.terminal.line_note(`edit: ${u}: its pane has unsaved changes; they stand (REVERT reads the file again)`),!0):(f.content_show({path:u,content:d.content,extension:d.extension??Zg(u)}),!0))},edit_open:(d,u={})=>{const p=a(d)??l();if(p===null)return null;const f=i.get("edit",p);if(f===void 0)return null;t.focus_set(p),f.dirty_is()||f.opening_show(d);const _=vx(d);return u.visible===!0?(s.terminal.line_run(_),p):(s.client.line_execute(_,{silent:!0,observe:!1}).then(g=>{const m=g.envelopes.find(w=>w.status!=="ok");m!==void 0&&f.opening_fail((m.renderedErr??"").replace(/\x1b\[[0-9;]*m/g,"").trim()||"the kernel refused")}).catch(g=>f.opening_fail(g instanceof Error?g.message:String(g))),p)}}}class sH{listing;constructor(e){const t=e.querySelector(".help-panel");if(t===null)throw new Error("help pane: no .help-panel in its template");this.listing=new sr({mount:t,traits:this.traits_declare(),key:i=>i.key,chrome:{root:e,prefix:"help"},caps:"root",activatable:()=>!1,row:{className:i=>`help-row help-${i.topic}`}}),this.render()}traits_declare(){return[{key:"name",label:"KEY · VERB",className:"help-key",width:"minmax(9em, 12em)",cell:e=>e.name},{key:"does",label:"DOES",className:"help-does",width:"minmax(16em, 1fr)",cell:e=>e.does}]}render(){const e=o=>{const a=document.createElement("header");return a.className="files-path help-block-head",a.textContent=o,a},t=zn.map(o=>({key:`k:${o.key}`,name:o.key,does:o.does,topic:o.topic})),i=Ta.map((o,a)=>{const l=o.indexOf(" ");return{key:`v:${a}`,name:l<0?o:o.slice(0,l),does:l<0?"":o.slice(l+1).trim(),topic:"verb"}}),n=[{key:"g:games",name:"help games",does:"the /usr/games shelf — fortune, cal, weather and their kin, by category (type it in the console)",topic:"verb"}],r=[{key:"n:notes",name:"notes",does:"what the installed releases changed (notes pane opens it as a listing; the dashboard's WHAT'S NEW block too)",topic:"verb"}];this.listing.rows_set([{key:"keys",header:e("KEYS — Ctrl-B opens the focused pane's drawer; then one key presses one of its verbs"),rows:t},{key:"verbs",header:e("VERBS — the console language; the long form is docs/argus-lang.adoc"),rows:i},{key:"games",header:e("GAMES — the small pleasures, kept apart from the tools as BSD kept them"),rows:n},{key:"notes",header:e("NOTES — what changed, release by release"),rows:r}],{field:"help"})}}function iH(s,e){const{layout:t,panels:i,subjects:n}=s;return{instance_build:a=>{const l=e.template_stamp("tpl-pane-help");return i.set("help",a,new sH(l)),{id:a,kind:"help",mount:l,dispose:()=>{i.delete(a),n.pane_leave(a)}}},open:()=>{const a=i.ids("help").find(d=>t.panes_shown().includes(d));if(a!==void 0)return t.focus_set(a),"help: on stage";const l=e.launcher_active();e.launcher_yield();const c=t.focused_get()??"files",h=e.instance_spawn("help");return l&&t.leaf_replace("files",h.id)?(t.focus_set(h.id),"help: the keys and the verbs, as a pane (help keys, help verbs print them here)"):t.leaf_split(c,"col",h.id,!1)?(e.birth_record(h.id,c,"col",!1),"help: the keys and the verbs, as a pane (help keys, help verbs print them here)"):(Ds(h.id),t.mount_remove(h.id),"help: could not open a pane")}}}const Pf=["___________________ _-_ ","\\__(==========/_=_/ ____.---'---`---.____"," \\_ \\ \\----._________.----/"," \\ \\ / / `-_-' "," __,--`.`-'..'-_ "," /____ || "," `--.____,-' "];function nH(){const s=Pf[0].length;let e=Number.NaN,t=0;return{title:"SL",tick:60,step:i=>{Number.isNaN(e)&&(e=-s),e+=1,t+=1,e>i.cols+6&&(e=-s)},draw:(i,n)=>{const r=Math.max(0,Math.floor((i.rows-Pf.length)/2));Pf.forEach((a,l)=>i.text(Math.round(e),r+l,a,n.lit));const o=t%2===0?"-~=":"-=~";i.text(Math.round(e)-o.length,r+1,o,n.cool)}}}const dw="ハミヒーウシナモニサワツオリアホテマケメエカキムユラセネスタヌヘ0123456789Z:・.=*+-<>¦|";function rH(){const s=new Map;let e=0;return{title:"CMATRIX",tick:50,step:(t,i)=>{e+=1;for(let n=0;n<t.cols;n++){const r=s.get(n);if(r===void 0){i()<.02&&s.set(n,{row:-1,speed:1+Math.floor(i()*2),length:4+Math.floor(i()*12),glyphs:[]});continue}e%r.speed===0&&(r.row+=1,r.glyphs.unshift(dw[Math.floor(i()*dw.length)]),r.glyphs.length>r.length&&r.glyphs.pop(),r.row-r.length>t.rows&&s.delete(n))}},draw:(t,i)=>{for(const[n,r]of s)r.glyphs.forEach((o,a)=>{const l=a===0?"#ffffff":a<r.length/2?i.lit:i.dim;t.put(n,r.row-a,o,l)})}}}function oH(){const s=[];return{title:"RAIN",tick:70,step:(e,t)=>{t()<.9&&s.push({col:Math.floor(t()*e.cols),row:0,splash:0});for(const i of s)i.row<e.rows-1?i.row+=1:i.splash+=1;for(let i=s.length-1;i>=0;i--)s[i].splash>3&&s.splice(i,1)},draw:(e,t)=>{for(const i of s){if(i.splash===0){e.put(i.col,i.row,"|",t.cool);continue}const n=["o","O","( )"][i.splash-1];e.text(i.col-(n.length>>1),e.rows-1,n,t.dim)}}}}function aH(){const s=[],e=[];let t=0;return{title:"ASCIIQUARIUM",tick:90,step:(i,n)=>{if(t+=1,s.length<Math.max(3,i.cols/12)&&n()<.08){const r=n()<.5;s.push({col:r?-4:i.cols+1,row:2+Math.floor(n()*Math.max(1,i.rows-5)),right:r,speed:1+Math.floor(n()*2),hue:Math.floor(n()*3)})}for(const r of s)t%r.speed===0&&(r.col+=r.right?1:-1);for(let r=s.length-1;r>=0;r--){const o=s[r];(o.col<-5||o.col>i.cols+2)&&s.splice(r,1)}if(n()<.3){const r=s[Math.floor(n()*s.length)];r!==void 0&&e.push({col:r.col+(r.right?4:-1),row:r.row-1})}for(const r of e)r.row-=1;for(let r=e.length-1;r>=0;r--)e[r].row<1&&e.splice(r,1)},draw:(i,n)=>{const r=(t%4<2?"~^":"^~").repeat(i.cols>>1);i.text(0,0,r,n.cool);const o=[n.lit,n.cool,n.warn];for(const a of s)i.text(a.col,a.row,a.right?"><>":"<><",o[a.hue]);for(const a of e)i.put(a.col,a.row,a.row%2===0?"o":".",n.dim);for(let a=2;a<i.cols;a+=7){const l=(t>>2)%2===0?0:1;for(let c=0;c<3;c++)i.put(a+(c+l)%2,i.rows-2-c,c%2===0?"(":")",n.dim)}i.text(0,i.rows-1,"^".repeat(i.cols),n.dim)}}}const uw=[[[0,0],[1,0],[2,0],[3,0]],[[0,0],[1,0],[0,1],[1,1]],[[1,0],[0,1],[1,1],[2,1]],[[0,0],[1,0],[1,1],[2,1]],[[1,0],[2,0],[0,1],[1,1]],[[0,0],[0,1],[1,1],[2,1]],[[2,0],[0,1],[1,1],[2,1]]],po=10,wo=20;function lH(){return{well:Array.from({length:wo},()=>Array(po).fill(0)),piece:null,score:0,lines:0,over:!1}}function q_(s,e){return e.cells.every(([t,i])=>{const n=e.x+t,r=e.y+i;return n>=0&&n<po&&r<wo&&(r<0||s[r][n]===0)})}function Lf(s){const e=Math.max(...s.cells.flat())+1;return{...s,cells:s.cells.map(([t,i])=>[e-1-i,t])}}function cH(s,e){const t=Math.floor(e()*uw.length),i={cells:uw[t].map(n=>[n[0],n[1]]),x:3,y:0,kind:t+1};if(!q_(s.well,i)){s.over=!0;return}s.piece=i}function hH(s){const e=s.piece;if(e===null)return;e.cells.some(([,n])=>e.y+n<0)&&(s.over=!0);for(const[n,r]of e.cells){const o=e.y+r;o>=0&&(s.well[o][e.x+n]=e.kind)}const t=s.well.filter(n=>n.some(r=>r===0)),i=wo-t.length;for(;t.length<wo;)t.unshift(Array(po).fill(0));s.well=t,s.lines+=i,s.score+=[0,100,300,500,800][i]??800,s.piece=null}function $m(s,e){if(s.over)return;if(s.piece===null){cH(s,e);return}const t={...s.piece,y:s.piece.y+1};q_(s.well,t)?s.piece=t:hH(s)}function dH(s,e,t){if(s.over||s.piece===null)return!1;const i=s.piece,n=r=>q_(s.well,r)?(s.piece=r,!0):!1;switch(e){case"ArrowLeft":case"h":case"a":return n({...i,x:i.x-1}),!0;case"ArrowRight":case"l":case"d":return n({...i,x:i.x+1}),!0;case"ArrowUp":case"k":case"w":return n(Lf(i))||n({...Lf(i),x:i.x-1})||n({...Lf(i),x:i.x+1}),!0;case"ArrowDown":case"j":case"s":return $m(s,t),!0;case" ":{for(;s.piece!==null;)$m(s,t);return!0}default:return!1}}function uH(){const s=lH();let e=Math.random;return{title:"TETRIS",tick:500,step:(t,i)=>{e=i,$m(s,i)},draw:(t,i)=>{const n=Math.max(0,Math.floor((t.cols-(po*2+2))/2)),r=Math.max(0,Math.floor((t.rows-wo-1)/2)),o=["",i.cool,i.lit,i.warn,i.dim,i.lit,i.cool,i.warn];for(let a=0;a<wo;a++){t.put(n,r+a,"|",i.dim),t.put(n+po*2+1,r+a,"|",i.dim);for(let l=0;l<po;l++){const c=s.well[a][l];c!==0&&t.text(n+1+l*2,r+a,"[]",o[c])}}if(t.text(n,r+wo,"+"+"-".repeat(po*2)+"+",i.dim),s.piece!==null)for(const[a,l]of s.piece.cells){const c=s.piece.y+l;c>=0&&t.text(n+1+(s.piece.x+a)*2,r+c,"[]",o[s.piece.kind])}s.over&&t.text(n+2,r+9," GAME OVER ",i.warn)},key:t=>dH(s,t,e),status:()=>`${s.score} · ${s.lines} lines${s.over?" · OVER":""}`,over:()=>s.over}}function fH(s,e,t){const i=s>>1,n=e>>1,r={body:[[i,n],[i-1,n],[i-2,n]],food:[0,0],heading:"right",next:"right",score:0,over:!1,cols:s,rows:e};return kx(r,t),r}function kx(s,e){for(let t=0;t<1e3;t++){const i=[Math.floor(e()*s.cols),Math.floor(e()*s.rows)];if(!s.body.some(([n,r])=>n===i[0]&&r===i[1])){s.food=i;return}}}const pH={up:"down",down:"up",left:"right",right:"left"};function mH(s,e){pH[e]!==s.heading&&(s.next=e)}function gH(s,e){if(s.over)return;s.heading=s.next;const[t,i]=s.body[0],n=s.heading==="up"?[t,i-1]:s.heading==="down"?[t,i+1]:s.heading==="left"?[t-1,i]:[t+1,i],r=n[0]<0||n[1]<0||n[0]>=s.cols||n[1]>=s.rows,o=s.body.some(([a,l])=>a===n[0]&&l===n[1]);if(r||o){s.over=!0;return}s.body.unshift(n),n[0]===s.food[0]&&n[1]===s.food[1]?(s.score+=10,kx(s,e)):s.body.pop()}const _H={ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down",k:"up",w:"up",j:"down",s:"down",h:"left",a:"left",l:"right",d:"right"};function bH(){let s=null;return{title:"SNAKE",tick:140,step:(e,t)=>{s===null&&(s=fH(Math.max(8,e.cols>>1),Math.max(6,e.rows-1),t)),gH(s,t)},draw:(e,t)=>{s!==null&&(e.text(0,s.rows,"-".repeat(s.cols*2),t.dim),e.text(s.food[0]*2,s.food[1],"**",t.warn),s.body.forEach(([i,n],r)=>e.text(i*2,n,r===0?"@@":"oo",r===0?t.lit:t.cool)),s.over&&e.text(Math.max(0,s.cols-6),s.rows>>1," GAME OVER ",t.warn))},key:e=>{const t=_H[e];return t===void 0||s===null?!1:(mH(s,t),!0)},status:()=>s===null?"":`${s.score}${s.over?" · OVER":""}`,over:()=>s?.over??!1}}const Nx={sl:nH,cmatrix:rH,rain:oH,aquarium:aH,tetris:uH,snake:bH};function MH(s){return s in Nx}const vH=8,wH=26,Wf=1.8,yH=100,fw=24;function pw(s,e){let t=Math.floor(s/yH);return e/(t*Wf)<fw&&(t=Math.floor(e/fw/Wf)),t=Math.max(vH,Math.min(wH,t)),{w:t,h:Math.round(t*Wf)}}class SH{pane;field;canvas;state;focusMark;pausePill;program=null;name=null;paused=!1;timer=null;frame=null;observer;constructor(e){this.pane=e,this.field=pl(e,".games-field"),this.canvas=pl(e,".games-canvas"),this.state=e.querySelector(".pane-state"),this.focusMark=pl(e,".games-focus"),this.pausePill=pl(e,".games-pause"),this.field.tabIndex=0,this.pausePill.addEventListener("click",()=>this.pause_toggle()),pl(e,".games-restart").addEventListener("click",()=>{this.name!==null&&this.program_run(this.name)}),this.field.addEventListener("mousedown",()=>{this.field.focus(),this.focusMark_paint(!0)}),this.field.addEventListener("focusin",()=>this.focusMark_paint(!0)),this.field.addEventListener("focusout",t=>{(!(t.relatedTarget instanceof Node)||!this.field.contains(t.relatedTarget))&&this.focusMark_paint(!1)}),this.field.addEventListener("keydown",t=>this.key_handle(t)),this.observer=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>this.draw()),this.observer?.observe(this.field)}program_run(e){this.name=e,this.program=Nx[e](),this.paused=!1,this.pausePill.textContent="PAUSE",this.clock_start(),this.program.key!==void 0&&(this.field.focus(),this.focusMark_paint(!0)),this.draw()}program_name(){return this.name}paused_is(){return this.paused}pause_toggle(){this.program!==null&&(this.paused=!this.paused,this.pausePill.textContent=this.paused?"RESUME":"PAUSE",this.paused?this.clock_stop():this.clock_start(),this.state_paint())}field_hasFocus(){return document.activeElement instanceof Node&&this.field.contains(document.activeElement)}field_release(){return this.field_hasFocus()?(document.activeElement.blur(),this.focusMark_paint(!1),!0):!1}dispose(){this.clock_stop(),this.observer?.disconnect()}key_handle(e){if(e.key==="Escape"){this.field_release(),e.stopPropagation();return}if(this.program!==null){if(e.key===" "&&this.program.key===void 0){this.pause_toggle(),e.preventDefault(),e.stopPropagation();return}this.program.key?.(e.key)===!0&&(e.preventDefault(),this.draw()),e.stopPropagation()}}clock_start(){this.clock_stop();const e=this.program;e!==null&&(this.timer=setInterval(()=>{this.field.offsetParent!==null&&(e.step(this.size_measure(),Math.random),this.draw(),e.over?.()===!0&&this.clock_stop())},e.tick))}clock_stop(){this.timer!==null&&clearInterval(this.timer),this.timer=null}size_measure(){const e=this.field.getBoundingClientRect(),t=pw(e.width,e.height);return{cols:Math.max(10,Math.floor(e.width/t.w)),rows:Math.max(6,Math.floor(e.height/t.h))}}palette_read(){const e=getComputedStyle(this.pane),t=(i,n)=>e.getPropertyValue(i).trim()||n;return{lit:t("--harvestgold","#ffcc66"),dim:t("--butter","#ffff99"),warn:t("--tomato","#ff7766"),cool:t("--daybreak","#55aaff")}}draw(){this.frame===null&&(this.frame=requestAnimationFrame(()=>{this.frame=null,this.paint()}))}paint(){const e=this.program,t=this.canvas.getContext("2d");if(e===null||t===null)return;const i=this.field.getBoundingClientRect(),n=window.devicePixelRatio||1;(this.canvas.width!==Math.floor(i.width*n)||this.canvas.height!==Math.floor(i.height*n))&&(this.canvas.width=Math.floor(i.width*n),this.canvas.height=Math.floor(i.height*n)),t.setTransform(n,0,0,n,0,0),t.clearRect(0,0,i.width,i.height);const r=pw(i.width,i.height);t.font=`${r.h-2}px 'Share Tech Mono', monospace`,t.textBaseline="top";const o=this.size_measure(),a=(c,h,d,u)=>{c<0||h<0||c>=o.cols||h>=o.rows||(t.fillStyle=u,t.fillText(d,c*r.w,h*r.h))},l={cols:o.cols,rows:o.rows,put:a,text:(c,h,d,u)=>{[...d].forEach((p,f)=>{p!==" "&&a(c+f,h,p,u)})}};e.draw(l,this.palette_read()),this.state_paint()}state_paint(){if(this.state===null||this.program===null)return;const e=this.program.status?.()??"";this.state.textContent=[this.program.title,e,this.paused?"PAUSED":""].filter(t=>t!=="").join(" · ")}focusMark_paint(e){this.focusMark.hidden=!e,this.pane.classList.toggle("games-field-focused",e)}}function pl(s,e){const t=s.querySelector(e);if(t===null)throw new Error(`games pane: missing ${e}`);return t}function zH(s,e){const{layout:t,panels:i,subjects:n}=s;return{instance_build:a=>{const l=e.template_stamp("tpl-pane-games"),c=new SH(l);return i.set("games",a,c),{id:a,kind:"games",mount:l,dispose:()=>{c.dispose(),i.delete(a),n.pane_leave(a)}}},show:a=>{const l=typeof a=="object"&&a!==null?a.program:void 0;if(typeof l!="string"||!MH(l))return`games: no program named ${String(l)}`;const c=i.ids("games").find(f=>t.panes_shown().includes(f));if(c!==void 0)return t.focus_set(c),i.get("games",c)?.program_run(l),`games: ${l} on the GAMES pane`;const h=e.launcher_active();e.launcher_yield();const d=t.focused_get()??"files",u=e.instance_spawn("games");return(h?t.leaf_replace("files",u.id):t.leaf_split(d,"col",u.id,!1))?(h?t.focus_set(u.id):e.birth_record(u.id,d,"col",!1),i.get("games",u.id)?.program_run(l),`games: ${l} in a GAMES pane (Esc gives the keyboard back; its PAUSE and RESTART pills on the frame)`):(Ds(u.id),t.mount_remove(u.id),"games: could not open a pane")}}}function rt(s,e){const t=document.createElementNS("http://www.w3.org/2000/svg",s);for(const[i,n]of Object.entries(e))t.setAttribute(i,String(n));return t}const Er=["cruiser","raptor","talon","warbird"],xH={ship:'<g fill="currentColor"><ellipse cx="12" cy="6.5" rx="9" ry="4"/><rect x="9.5" y="9.5" width="5" height="6" rx="1"/><rect x="3" y="14" width="5" height="8" rx="2.2"/><rect x="16" y="14" width="5" height="8" rx="2.2"/><rect x="7" y="16" width="10" height="2.2" rx="1"/></g>',"klingon-cruiser":'<g fill="currentColor"><circle cx="12" cy="4" r="2.6"/><rect x="11" y="5.5" width="2" height="8.5"/><path d="M12 12.5 L22 20.5 L22.5 22.5 L17 19.2 L12 18 L7 19.2 L1.5 22.5 L2 20.5 Z"/><rect x="8.5" y="18.5" width="7" height="3.2" rx="1.2"/></g>',"klingon-raptor":'<path fill="currentColor" d="M12 1.5 L14 6.5 L22.5 10.5 L21.5 18 L19.5 12.5 L15 13.5 L14 20 L12 17 L10 20 L9 13.5 L4.5 12.5 L2.5 18 L1.5 10.5 L10 6.5 Z"/>',"klingon-talon":'<g fill="currentColor"><path d="M12 1.5 L13.6 11 L21.5 4.5 L19 15 L12 22 L5 15 L2.5 4.5 L10.4 11 Z"/><circle cx="12" cy="13.5" r="1.6" fill="#000"/></g>',"klingon-warbird":'<g fill="currentColor"><rect x="8.5" y="2" width="7" height="3.2" rx="1.6"/><rect x="11.1" y="4.5" width="1.8" height="7"/><path d="M1.5 13 Q12 6 22.5 13 L22 20 Q17 15.5 14 17 L12 22 L10 17 Q7 15.5 2 20 Z"/></g>',base:'<g fill="currentColor"><path d="M12 1.5 L17 12 L12 22.5 L7 12 Z"/><rect x="1.5" y="10.8" width="21" height="2.4" rx="1.2"/><circle cx="12" cy="12" r="3" fill="#000"/></g>',inhabited:'<circle cx="12" cy="12" r="7.5" fill="currentColor"/><path d="M4.5 12 Q12 15.5 19.5 12" fill="none" stroke="#000" stroke-width="1.6"/><path d="M5.5 8.5 Q12 11 18.5 8.5" fill="none" stroke="#000" stroke-width="1.2" opacity="0.6"/>',star:'<g stroke="currentColor" stroke-width="1.8" stroke-linecap="round" fill="none"><path d="M12 2 V22 M2 12 H22 M4.9 4.9 L19.1 19.1 M19.1 4.9 L4.9 19.1"/></g><circle cx="12" cy="12" r="2.6" fill="currentColor"/>',hole:'<g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M12 12 m0 -2.5 a2.5 2.5 0 1 1 -2.5 2.5"/><path d="M12 12 m0 -6 a6 6 0 1 1 -6 6"/><path d="M12 12 m0 -9.5 a9.5 9.5 0 1 1 -9.5 9.5" opacity="0.5"/></g>',supernova:'<g fill="currentColor"><path d="M10 8.536 A4 4 0 0 1 14 8.536 L17.5 2.474 A11 11 0 0 0 6.5 2.474 Z"/><path d="M10 8.536 A4 4 0 0 1 14 8.536 L17.5 2.474 A11 11 0 0 0 6.5 2.474 Z" transform="rotate(120 12 12)"/><path d="M10 8.536 A4 4 0 0 1 14 8.536 L17.5 2.474 A11 11 0 0 0 6.5 2.474 Z" transform="rotate(240 12 12)"/><circle cx="12" cy="12" r="2.4"/></g>'},Ul="tm-";function Bx(s,e=null){return s==="klingon"?`${Ul}klingon-${e!==null&&Er.includes(e)?e:Er[0]}`:`${Ul}${s}`}function OH(){if(document.getElementById(`${Ul}ship`)!==null)return null;const s=rt("svg",{class:"tm-defs",width:0,height:0,"aria-hidden":"true"}),e=rt("defs",{});for(const[i,n]of Object.entries(xH)){const r=rt("symbol",{id:`${Ul}${i}`,viewBox:"0 0 24 24"});r.innerHTML=n,e.append(r)}const t=(i,n)=>{const r=rt("radialGradient",{id:`${Ul}${i}`});for(const[o,a,l]of n){const c=rt("stop",{offset:o});c.setAttribute("style",`stop-color: ${a}; stop-opacity: ${l}`),r.append(c)}return r};return e.append(t("halo",[[0,"var(--butter)",.9],[.35,"var(--harvestgold)",.5],[1,"var(--harvestgold)",0]]),t("halo-nova",[[0,"var(--butter)",.9],[.3,"var(--pumpkin-pie)",.6],[1,"var(--pumpkin-pie)",0]]),t("halo-mars",[[0,"var(--butter)",.8],[.3,"var(--mars)",.6],[1,"var(--mars)",0]]),t("photon-core",[[0,"#fff",1],[.35,"#ffd27a",1],[1,"#ff6a1a",1]]),t("photon-halo",[[0,"#ff6a1a",.55],[1,"#ff6a1a",0]])),s.append(e),s}function K_(s,e,t=null,i=0){const n=rt("g",{class:`tm-mark tm-mark-${s}`});return n.append(rt("use",{href:`#${Bx(s,t)}`,x:-e.size/2,y:-e.size/2,width:e.size,height:e.size,class:"tm-symbol"})),Gx(n,e.cx,e.cy,i),n}function Gx(s,e,t,i=0){s.setAttribute("transform",i===0?`translate(${e} ${t})`:`translate(${e} ${t}) rotate(${i})`)}function Y_(s,e=null){const t=rt("svg",{viewBox:"0 0 24 24",class:`tm-icon tm-icon-${s}`,"aria-hidden":"true"});return t.append(rt("use",{href:`#${Bx(s,e)}`})),t}const _h={ship:"E",klingon:"K",base:"#",inhabited:"@",star:"*",hole:" ",supernova:"///"},EH=[{kind:"ship",name:"ENTERPRISE"},{kind:"klingon",name:"KLINGON"},{kind:"base",name:"STARBASE"},{kind:"inhabited",name:"INHABITED"},{kind:"star",name:"STAR"},{kind:"hole",name:"BLACK HOLE"},{kind:"supernova",name:"SUPERNOVA"}],AH=/^Klingon at (\d+),(\d+) moves to (\d+),(\d+)/,TH=/^Klingon at (\d+),(\d+) escapes to quadrant/,DH=/\*\*\* Klingon at (\d+),(\d+) destroyed \*\*\*/;class $l{marks=new Map;mark_find(e){return this.marks.get($l.key_format(e))??null}line_hear(e){const t=AH.exec(e);if(t!==null){const n=`${t[1]},${t[2]}`,r=this.marks.get(n);return this.marks.delete(n),r!==void 0&&this.marks.set(`${t[3]},${t[4]}`,r),!0}const i=TH.exec(e)??DH.exec(e);return i!==null?(this.marks.delete(`${i[1]},${i[2]}`),!0):!1}reconcile(e,t={}){t.reset===!0&&this.marks.clear();const i=new Set(e.map(n=>$l.key_format(n)));for(const n of[...this.marks.keys()])i.has(n)||this.marks.delete(n);e.forEach((n,r)=>{const o=$l.key_format(n);if(t.byOrder===!0){this.marks.set(o,Er[r%Er.length]);return}this.marks.has(o)||this.marks.set(o,this.leastWorn_get())})}clear(){this.marks.clear()}leastWorn_get(){const e=new Map(Er.map(i=>[i,0]));for(const i of this.marks.values())e.set(i,(e.get(i)??0)+1);let t=Er[0];for(const i of Er)(e.get(i)??0)<(e.get(t)??0)&&(t=i);return t}static key_format(e){return`${e.x},${e.y}`}}function IH(s,e,t,i){const n=Math.max(0,Math.min(100,100*s/Math.max(1,e)));return i?{className:"tb-ring tb-ring-docked",width:.09,percent:n}:t?{className:`tb-ring ${n>60?"tb-ring-full":n>30?"tb-ring-mid":"tb-ring-low"}`,width:.025+.085*n/100,percent:n}:{className:"tb-ring tb-ring-down",width:.02,percent:n}}function q(s,e,t){const i=document.createElement(s);return i.className=e,t!==void 0&&(i.textContent=t),i}function ei(s,e,t){const i=q("button",`tb-pill ${s}`,e);return i.type="button",i.addEventListener("click",t),i}const CH=16;class Px{constructor(e,t,i){this.onCommit=i,this.size=e;const n=e/2;this.root=q("div","tb-wheel");const r=rt("svg",{width:e,height:e,viewBox:`0 0 ${e} ${e}`,role:"img","aria-label":t});r.classList.add("tb-wheel-face"),r.append(rt("circle",{cx:n,cy:n,r:n-4,class:"tb-wheel-rim"})),r.append(rt("circle",{cx:n,cy:n,r:(n-4)*.66,class:"tb-wheel-ring"})),r.append(rt("circle",{cx:n,cy:n,r:(n-4)*.33,class:"tb-wheel-ring"}));for(let l=0;l<36;l++){const c=l*Math.PI/18,h=l%3===0,d=n-4-(h?12:7);r.append(rt("line",{x1:n+d*Math.sin(c),y1:n-d*Math.cos(c),x2:n+(n-4)*Math.sin(c),y2:n-(n-4)*Math.cos(c),class:h?"tb-wheel-tick-major":"tb-wheel-tick"}))}for(const l of[0,90,180,270]){const c=l*Math.PI/180,h=rt("text",{x:n+(n-26)*Math.sin(c),y:n-(n-26)*Math.cos(c)+4,"text-anchor":"middle",class:"tb-wheel-label"});h.textContent=String(l),r.append(h)}this.wedge=rt("path",{d:"",class:"tb-wheel-wedge"}),r.append(this.wedge),this.marks=rt("g",{class:"tb-wheel-marks"}),r.append(this.marks),this.needle=rt("line",{x1:n,y1:n,x2:n,y2:14,class:"tb-wheel-needle"}),r.append(this.needle),r.append(rt("circle",{cx:n,cy:n,r:6,class:"tb-wheel-hub"})),this.root.append(r);const o=q("div","tb-wheel-row");this.readout=q("span","tb-wheel-readout","0°"),this.commit=ei("tb-commit","SET COURSE",()=>this.onCommit(Math.round(this.degrees))),o.append(this.readout,this.commit),this.root.append(o);const a=l=>{const c=r.getBoundingClientRect(),h=l.clientX-c.left-c.width/2,d=l.clientY-c.top-c.height/2;this.degrees_set((Math.atan2(h,-d)*180/Math.PI+360)%360)};r.addEventListener("pointerdown",l=>{r.setPointerCapture(l.pointerId),a(l)}),r.addEventListener("pointermove",l=>{l.buttons!==0&&a(l)})}onCommit;root;needle;marks;wedge;readout;commit;degrees=0;wedgeHalf=null;size;degrees_set(e){this.degrees=e;const t=this.size/2,i=e*Math.PI/180;this.needle.setAttribute("x2",String(t+(t-14)*Math.sin(i))),this.needle.setAttribute("y2",String(t-(t-14)*Math.cos(i))),this.readout.textContent=`${Math.round(e)}°`,this.wedge_draw()}degrees_get(){return this.degrees}wedge_set(e){this.wedgeHalf=e,this.wedge_draw()}wedge_draw(){if(this.wedgeHalf===null){this.wedge.setAttribute("d","");return}const e=this.size/2,t=e-14,i=(this.degrees-this.wedgeHalf)*Math.PI/180,n=(this.degrees+this.wedgeHalf)*Math.PI/180,r=e+t*Math.sin(i),o=e-t*Math.cos(i),a=e+t*Math.sin(n),l=e-t*Math.cos(n);this.wedge.setAttribute("d",`M ${e} ${e} L ${r} ${o} A ${t} ${t} 0 0 1 ${a} ${l} Z`)}marks_set(e){this.marks.replaceChildren();const t=this.size/2;for(const i of e){const n=i.bearing*Math.PI/180,r=(t-4)*.8,o=t+r*Math.sin(n),a=t-r*Math.cos(n),l=i.kind==="klingon"?i.bearing+180:0,c=K_(i.kind,{cx:o,cy:a,size:CH},i.variant??null,l);c.classList.add("tb-wheel-mark",`tb-wheel-mark-${i.kind}`);const h=rt("title",{});h.textContent=i.label,c.append(h),this.marks.append(c)}}lit_set(e,t="SET COURSE"){this.root.classList.toggle("tb-lit",e),this.commit.disabled=!e,this.commit.textContent=t}}class Lr{constructor(e,t,i,n){this.digits=i,this.onCommit=n,this.root=q("div","tb-slider");const r=q("label","tb-slider-label",t);r.htmlFor=e,this.input=document.createElement("input"),this.input.type="range",this.input.id=e,this.input.className="tb-slider-input",this.input.addEventListener("input",()=>{this.shown_refresh(),this.onInput?.(this.value_get())});const o=q("div","tb-slider-column");this.ticks=q("div","tb-slider-ticks"),this.note=q("span","tb-slider-note"),o.append(this.input,this.ticks,this.note),this.shown=q("span","tb-slider-readout","—"),this.commit=ei("tb-commit","SET",()=>this.onCommit(this.value_get())),this.root.append(r,o,this.shown,this.commit)}digits;onCommit;root;input;shown;commit;note;ticks;onInput=null;range_set(e,t,i,n=0){const r=e.min??0,o=e.max??1;this.input.min=String(r),this.input.max=String(o),this.input.step=String(e.step??1),this.input.value=String(Math.min(o,Math.max(r,t))),this.note.textContent=i,this.ticks.replaceChildren();for(let a=0;a<n;a++){const l=r+(o-r)*a/Math.max(1,n-1);this.ticks.append(q("span","tb-slider-tick",Number.isInteger(l)?String(l):l.toFixed(1)))}this.shown_refresh()}input_listen(e){this.onInput=e}note_set(e){this.note.textContent=e}value_get(){return Number(this.input.value)}value_set(e){this.input.value=String(e),this.shown_refresh()}lit_set(e,t="SET"){this.root.classList.toggle("tb-lit",e),this.input.disabled=!e,this.commit.disabled=!e,this.commit.textContent=t}lit_is(){return this.root.classList.contains("tb-lit")}shown_refresh(){this.shown.textContent=this.value_get().toFixed(this.digits)}}class bh{root;buttons=[];note;constructor(e,t,i){this.root=q("div","tb-pillrow"),e!==""&&this.root.append(q("span","tb-slider-label",e));const n=q("div","tb-slider-column"),r=q("div","tb-pills");for(const o of t){const a=ei("tb-choice",o.label,()=>i(o.line,o.label));a.dataset.line=o.line,this.buttons.push(a),r.append(a)}this.note=q("span","tb-slider-note",""),n.append(r,this.note),this.root.append(n)}note_set(e){this.note.textContent=e}lit_set(e){this.root.classList.toggle("tb-lit",e);for(const t of this.buttons)t.disabled=!e}}const RH=["panel-3","panel-4","panel-5","panel-6"];function It(s,e,t){const i=document.createElement(s);return e!==""&&(i.className=e),t!==void 0&&(i.textContent=t),i}function mw(s,e){const t=It("div",e===""?"bar-panel":`bar-panel ${e}`);for(let i=s;i<s+5;i++)t.append(It("div",`bar-${i}`));return t}function gw(s,e){const t=It("div","lcars-terminal-header-bar files-header-bar"),i=It("div","lcars-bar-horizontal"),n=It("span","lcars-title",s),r=It("span","lcars-terminal-status",e);return i.append(n,r),t.append(i,It("div","lcars-bar-end bar-punctuation")),{strip:t,title:n,note:r}}function X_(s,e,t){const i=It("section",`takeover ${s.className}`);i.id=s.id;const n=It("div","takeover-gutter-head"),r=It("button","panel-1 takeover-brand");if(r.type="button",r.setAttribute("aria-label",s.brand.name),s.brand.mark){const E=It("span","brand-mark brand-mark-td");E.setAttribute("aria-hidden","true"),r.append(E)}const o=It("span","takeover-brand-words");o.append(It("span","takeover-brand-name",s.brand.name),It("span","takeover-brand-sub",s.brand.sub)),r.append(o);const a=It("div","panel-2 takeover-seat");n.append(r,a);const l=It("div","takeover-head"),c=It("div","takeover-face");l.append(It("div","banner",s.banner),c,mw(1,"first-bar-panel"));const h=It("div","takeover-top");h.append(n,l);const d=It("nav","takeover-gutter");d.setAttribute("aria-label",s.labels.views);const u=It("div",""),p=new Map;let f=s.views;const _=()=>{u.replaceChildren(),p.clear(),f.forEach((E,O)=>{const R=RH[O]??"panel-view",C=It("button",`${R}${E.destroy===!0?" takeover-view-destroy":""}`,E.label);C.type="button",C.dataset.view=E.key,C.addEventListener("click",()=>e(E.key)),p.set(E.key,C),u.append(C)}),u.append(It("div","panel-spacer"))};_();const g=It("div",""),m=It("button",`panel-7${s.leave.destroy===!0?" takeover-view-destroy":""}`,s.leave.label);m.type="button",m.addEventListener("click",t),g.append(m),d.append(u,g);const w=It("div","takeover-main"),y=It("main","takeover-stage"),M=gw(s.stage.title,s.stage.note),v=It("div","takeover-body"),S=It("div","takeover-aside"),x=gw(s.log.title,s.log.note),b=It("section","takeover-log");b.setAttribute("aria-label",s.labels.log),y.append(M.strip,v,S,x.strip,b),w.append(mw(6,""),y);const z=It("div","takeover-wrap");z.append(d,w),i.append(h,z);const T=E=>{for(const[O,R]of p){const C=O===E;R.classList.toggle("takeover-view-on",C),R.setAttribute("aria-current",C?"page":"false")}i.dataset.firstLit=E===f[0]?.key?"true":"false"},A=E=>{f=E,_()};return{root:i,seat:a,face:c,views:p,leave:m,stageTitle:M.title,stageNote:M.note,body:v,aside:S,logTitle:x.title,logNote:x.note,log:b,view_mark:T,views_set:A}}const kH=[[/Klingon attack:/,"incoming"],[/^HIT: \d+ units/,"hit"],[/CRITICAL HIT/,"hit"],[/\*\*\* Klingon at \d+,\d+ destroyed \*\*\*/,"explosion"],[/\*\*\*\*\* .* destroyed \*\*\*\*\*/,"explosion"],[/Starbase at \d+,\d+ destroyed/,"explosion"],[/Inhabited starsystem .* destroyed/,"explosion"],[/^Torpedo track/,"torpedo"],[/^Phaser bank \d+ fires:/,"phaser"],[/^Phasers locked on target/,"phaser"],[/^Starbase in \d+,\d+ responds/,"hail"],[/^Password verified; self destruct sequence continues/,"destruct"]];function NH(s){const e=[];for(const[t,i]of kH)t.test(s)&&!e.includes(i)&&e.push(i);return e}function BH(s,e){const t=[];if(s!==null&&s.condition.name!==e.condition.name)switch(e.condition.name){case"RED":t.push("redalert");break;case"YELLOW":t.push("yellowalert");break;case"DOCKED":t.push("dock");break;default:t.push("green");break}return s!==null&&(s.position.quadrant.x!==e.position.quadrant.x||s.position.quadrant.y!==e.position.quadrant.y)&&t.push("sensor"),t}function GH(s){switch(s){case"abandon":return"transporter";case"destruct":return"destruct";case"computer":return"thinking";default:return null}}function PH(s,e){return s!=="distance"?null:e==="impulse"?"impulse":e==="move"||e==="ram"?"warp":null}function Dr(s,e){return e==="computer"&&s==="MOVE"?"MOVE (COMPUTER)":e==="commit"?/^SET COURSE/.test(s)?"SET COURSE":"SLIDER SET":e==="choice"&&/^\d+°$/.test(s)?"BURST ANGLE":/^CANCEL/.test(s)?"CANCEL":s}const Rs=10,nc=8,LH="*",WH="#",Lx="E",FH="Q",UH="K",$H="@",Wx=" ",jH=7,HH=64,VH=63,qH=0,KH=1,YH=2,XH=3,ZH=[{name:"warp drive",person:"Scotty"},{name:"S.R. scanners",person:"Scotty"},{name:"L.R. scanners",person:"Scotty"},{name:"phasers",person:"Sulu"},{name:"photon tubes",person:"Sulu"},{name:"impulse engines",person:"Scotty"},{name:"shield control",person:"Sulu"},{name:"computer",person:"Spock"},{name:"subspace radio",person:"Uhura"},{name:"life support",person:"Scotty"},{name:"navigation system",person:"Chekov"},{name:"cloaking device",person:"Scotty"},{name:"transporter",person:"Scotty"},{name:"shuttlecraft",person:"Scotty"},{name:"*ERR 14*",person:"Nobody"},{name:"*ERR 15*",person:"Nobody"}],JH=["GREEN","DOCKED","YELLOW","RED"];function Jh(s,e){return(Math.atan2(e.y-s.y,-(e.x-s.x))*180/Math.PI+360)%360}function Nd(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function QH(s){switch(s){case Lx:case FH:return"ship";case UH:return"klingon";case WH:return"base";case LH:return"star";case $H:return"inhabited";case Wx:return"hole";default:return"empty"}}function e9(s){const e=new Map;for(const t of s)(t.evcode&VH)!==jH||(t.evcode&HH)!==0||e.set(t.systemname,t.date);return ZH.map((t,i)=>({index:i,name:t.name,person:t.person,repairAt:e.get(i)??null})).filter(t=>!t.name.startsWith("*"))}function t9(s){const e=s.Etc.nkling;switch(s.Ship.cond){case XH:return e===1?"1 Klingon in this quadrant":`${e} Klingons in this quadrant`;case YH:return s.Ship.energy<s.Param.energylow?"energy low":"Klingons near";case KH:return"docked at a starbase";case qH:default:return"all clear"}}function s9(s){const{Ship:e,Now:t,Game:i,Param:n,Etc:r,Sect:o,Quad:a}=s,l={x:e.quadx,y:e.quady},c={x:e.sectx,y:e.secty},h=[];for(let m=0;m<Rs;m++){const w=[];for(let y=0;y<Rs;y++){const M=o[m]?.[y]??Wx;w.push({x:m,y,kind:QH(M),glyph:M})}h.push(w)}const d=r.klingon.slice(0,r.nkling).map(m=>({x:m.x,y:m.y,bearing:Jh(c,m),range:Nd(c,m),power:m.power,mark:null})).sort((m,w)=>m.range-w.range),u=t.base.slice(0,t.bases).map(m=>({x:m.x,y:m.y}));let p=null;for(const m of u){const w=Nd(l,m);(p===null||w<p.range)&&(p={at:m,range:w,here:w===0})}const f=[];for(let m=0;m<nc;m++){const w=[];for(let y=0;y<nc;y++){const v=a[m]?.[y]?.scanned??-1,S=v<0?null:v>=1e3?"///":String(v).padStart(3,"0");w.push({x:m,y,here:m===l.x&&y===l.y,code:S,supernova:v>=1e3,klingons:v<0||v>=1e3?0:Math.floor(v/100),bases:v<0||v>=1e3?0:Math.floor(v%100/10)})}f.push(w)}const _=e9(s.Event),g=_.filter(m=>m.repairAt!==null).sort((m,w)=>(m.repairAt??0)-(w.repairAt??0));return{condition:{name:JH[e.cond]??"GREEN",why:t9(s)},ship:{shipName:e.shipname,energy:e.energy,energyMax:n.energy,shield:e.shield,shieldMax:n.shield,shieldsUp:e.shldup!==0,cloaked:e.cloaked!==0,torpedoes:e.torped,torpedoesMax:n.torped,reserves:e.reserves,reservesMax:n.reserves,crew:e.crew,warp:e.warp},mission:{stardate:t.date,timeLeft:t.time,klingonsLeft:t.klings,klingonsStart:n.klings,killed:i.killk,captives:i.captives,starbases:t.bases},position:{quadrant:l,sector:c},sectors:h,klingons:d,bases:u,nearestBase:p,chart:f,devices:_,damaged:g,game:{killk:i.killk,killb:i.killb,kills:i.kills,killinhab:i.killinhab,helps:i.helps,captives:i.captives,deaths:i.deaths,killed:i.killed!==0,skill:i.skill,won:s.Move.endgame>0,abandoned:e.ship!==Lx},param:{warptime:n.warptime,dockfac:n.dockfac,klingpwr:n.klingpwr,date:n.date}}}const i9=["novice","fair","good","expert","commodore","impossible"];function Fx(s){const{game:e,mission:t,param:i}=s,n=[];n.push({label:`${e.killk} Klingons killed`,points:Math.trunc(i.klingpwr/4)*e.killk});const r=Math.max(1,t.stardate-i.date),o=e.killk/r;return n.push({label:`kill rate ${o.toFixed(2)} Klingons/stardate`,points:Math.trunc(400*o)}),n.push({label:`penalty for ${t.klingonsLeft} Klingons remaining`,points:Math.trunc(-400*t.klingonsLeft/(e.killk+1))}),e.won&&n.push({label:`bonus for winning a ${i9[e.skill-1]??""} game`,points:100*e.skill}),e.killed&&n.push({label:"penalty for getting killed",points:-500}),n.push({label:`${e.killb} starbases killed`,points:-100*e.killb}),n.push({label:`${e.helps} calls for help`,points:-100*e.helps}),n.push({label:`${e.kills} stars destroyed`,points:-5*e.kills}),n.push({label:`${e.killinhab} inhabited starsystems destroyed`,points:-150*e.killinhab}),e.abandoned&&n.push({label:"penalty for abandoning ship",points:-200}),n.push({label:`${e.captives} Klingons captured`,points:3*e.captives}),n.push({label:`${e.deaths} casualties`,points:-e.deaths}),{items:n,total:n.reduce((a,l)=>a+l.points,0)}}function _w(s,e){const{quadrant:t,sector:i}=s.position,n=t.x+i.x/Rs-(e.quadrant.x+e.sector.x/Rs),r=e.quadrant.y+e.sector.y/Rs-(t.y+i.y/Rs);let o=Math.atan2(r,n);return o<0&&(o+=2*Math.PI),{course:Math.trunc(o*180/Math.PI+.5)%360,distance:Math.hypot(n,r)}}function n9(s,e,t){const{quadrant:i,sector:n}=s.position,r=e*Math.PI/180,o=Math.min(nc*Rs-1,Math.max(0,Math.round(i.x*Rs+n.x-Math.cos(r)*t*Rs))),a=Math.min(nc*Rs-1,Math.max(0,Math.round(i.y*Rs+n.y+Math.sin(r)*t*Rs)));return{quadrant:{x:Math.trunc(o/Rs),y:Math.trunc(a/Rs)},sector:{x:o%Rs,y:a%Rs}}}function Ux(s,e,t){const i=Math.trunc((s+.05)*e*e*e);return{stardates:t*s/(e*e),units:i,unitsShielded:2*i}}function r9(s){return{stardates:s/.095,units:Math.trunc(20+100*s)}}function $x(s){return Math.trunc(Math.pow(.9,s*10)*98+.5)}function bw(s,e){if(s.repairAt===null)return null;const t=s.repairAt-e.mission.stardate,i=e.condition.name==="DOCKED",n=i?1/e.param.dockfac:1,r=i?1:e.param.dockfac;return{inFlight:t*n+.005,docked:t*r+.005}}function jx(s,e){const t=[],i=(d,u)=>`${d>0?"+":d<0?"−":""}${Math.abs(d).toFixed(u)}`,n=e.mission.stardate-s.mission.stardate;Math.abs(n)>=.005&&t.push({label:"STARDATE",change:i(n,2),bad:!1});const r=e.ship.energy-s.ship.energy;r!==0&&t.push({label:"ENERGY",change:i(r,0),bad:r<0});const o=e.ship.shield-s.ship.shield;o!==0&&t.push({label:"SHIELDS",change:i(o,0),bad:o<0});const a=e.ship.torpedoes-s.ship.torpedoes;a!==0&&t.push({label:"TORPEDOES",change:i(a,0),bad:!1});const l=e.mission.klingonsLeft-s.mission.klingonsLeft;l!==0&&t.push({label:"KLINGONS",change:`${i(l,0)} · ${e.mission.klingonsLeft} LEFT`,bad:l>0});const c=e.damaged.filter(d=>!s.damaged.some(u=>u.index===d.index));c.length>0&&t.push({label:"DAMAGE",change:c.map(d=>d.name.toUpperCase()).join(" · "),bad:!0});const h=s.damaged.filter(d=>!e.damaged.some(u=>u.index===d.index));return h.length>0&&t.push({label:"REPAIRED",change:h.map(d=>d.name.toUpperCase()).join(" · "),bad:!1}),s.condition.name!==e.condition.name&&t.push({label:"CONDITION",change:e.condition.name,bad:e.condition.name==="RED"}),t}const o9=[["return to continue","return"],["What length game","length"],["What skill game","skill"],["Enter password verification","password-verify"],["Enter a password","password"],["Enter tournament code","tournament"],["Command","command"],["Torpedo course","torpedo-course"],["Course","course"],["course","bank-course"],["Distance","distance"],["distance","computer-distance"],["Warp factor","warp-factor"],["warp factor","computer-warp"],["How long","how-long"],["Manual or automatic","manual-automatic"],["Units to fire","units"],["units","bank-units"],["spread","spread"],["Do you want a burst","burst"],["burst angle","burst-angle"],["Up or down","up-down"],["Request","request"],["Quadrant","quadrant"],["q-y","quadrant-y"],["Sector","sector"],["s-y","sector-y"],["range","range"],["direction","direction"],["status report","status-report"],["Another game","another"]];function a9(s){const e=s.replace(/[:.\s]+$/,"");if(e==="")return"return";for(const[t,i]of o9)if(e.endsWith(t))return i;return/wise$|certain that is wise$|Shall we cancel our rest period$/.test(e)?"yes-no":"unknown"}const fu=[{id:"move",label:"MOVE",station:"helm",line:"m",asks:["course","distance"]},{id:"ram",label:"RAM",station:"helm",line:"ram",asks:["course","distance"]},{id:"warp",label:"WARP",station:"helm",line:"w",asks:["warp-factor"]},{id:"impulse",label:"IMPULSE",station:"helm",line:"i",asks:["course","distance"]},{id:"dock",label:"DOCK",station:"helm",line:"do",asks:[]},{id:"undock",label:"UNDOCK",station:"helm",line:"u",asks:[]},{id:"rest",label:"REST",station:"helm",line:"r",asks:["how-long"]},{id:"phasers",label:"PHASERS",station:"tactical",line:"p",asks:["manual-automatic","units"]},{id:"torpedo",label:"TORPEDO",station:"tactical",line:"t",asks:["torpedo-course","burst","burst-angle"]},{id:"shields",label:"SHIELDS",station:"tactical",line:"sh",asks:["up-down"]},{id:"cloak",label:"CLOAK",station:"tactical",line:"cl",asks:["up-down"]},{id:"capture",label:"CAPTURE",station:"tactical",line:"ca",asks:[]},{id:"visual",label:"VISUAL",station:"tactical",line:"v",asks:["direction"]},{id:"computer",label:"COMPUTER",station:"ship",line:"c",asks:["request"]},{id:"help",label:"CALL STARBASE",station:"ship",line:"help",asks:[]},{id:"dump",label:"DUMP",station:"ship",line:"dump",asks:[]},{id:"credits",label:"CREDITS",station:"ship",line:"cr",asks:[]},{id:"abandon",label:"ABANDON",station:"ship",line:"abandon",asks:[],grave:!0},{id:"destruct",label:"DESTRUCT",station:"ship",line:"destruct",asks:["password-verify"],grave:!0},{id:"terminate",label:"TERMINATE",station:"ship",line:"terminate",asks:[],grave:!0}];function ks(s,e){switch(s){case"return":return{kind:"auto"};case"length":return{kind:"pills",choices:[{label:"SHORT",line:"s"},{label:"MEDIUM",line:"m"},{label:"LONG",line:"l"},{label:"RESTART",line:"restart"}]};case"skill":return{kind:"pills",choices:[{label:"NOVICE",line:"n"},{label:"FAIR",line:"f"},{label:"GOOD",line:"g"},{label:"EXPERT",line:"e"},{label:"COMMODORE",line:"c"},{label:"IMPOSSIBLE",line:"i"}]};case"password":case"tournament":case"password-verify":return{kind:"auto"};case"course":case"torpedo-course":case"direction":case"bank-course":return{kind:"wheel",min:0,max:360,step:1,commit:"SET COURSE",cancel:"-1"};case"distance":return{kind:"slider",min:0,max:15,step:.1,commit:"ENGAGE",cancel:"-1"};case"computer-distance":case"range":return{kind:"slider",min:0,max:15,step:.1,commit:"SET"};case"warp-factor":return{kind:"slider",min:1,max:10,step:.1,commit:"SET WARP",cancel:"-1"};case"computer-warp":return{kind:"slider",min:1,max:10,step:.1,commit:"SET"};case"how-long":return{kind:"slider",min:0,max:Math.max(.1,e?.mission.timeLeft??15),step:.1,commit:"REST",cancel:"0"};case"manual-automatic":return{kind:"pills",choices:[{label:"MANUAL",line:"m"},{label:"AUTOMATIC",line:"a"}]};case"units":return{kind:"slider",min:0,max:Math.max(10,e?.ship.energy??5e3),step:10,commit:"FIRE",cancel:"0"};case"bank-units":return{kind:"slider",min:0,max:Math.max(10,e?.ship.energy??5e3),step:10,commit:"SET",cancel:"0"};case"spread":return{kind:"slider",min:0,max:1,step:.05,commit:"SET"};case"burst":case"status-report":case"another":case"yes-no":return{kind:"yesno",choices:[{label:"YES",line:"y"},{label:"NO",line:"n"}]};case"burst-angle":return{kind:"pills",choices:[1,2,3,5,8,10,12,15].map(t=>({label:`${t}°`,line:String(t)})),cancel:"0"};case"up-down":return{kind:"pills",choices:[{label:"UP",line:"u"},{label:"DOWN",line:"d"}]};case"request":return{kind:"pills",choices:[{label:"CHART",line:"ch"},{label:"TRAJECTORY",line:"t"},{label:"COURSE",line:"c"},{label:"MOVE",line:"m"},{label:"SCORE",line:"s"},{label:"PHASER EFFECT",line:"p"},{label:"WARP COST",line:"w"},{label:"IMPULSE COST",line:"i"},{label:"DISTRESS LIST",line:"d"}]};case"quadrant":case"quadrant-y":return{kind:"slider",min:0,max:nc-1,step:1,commit:"SET"};case"sector":case"sector-y":return{kind:"slider",min:0,max:Rs-1,step:1,commit:"SET"};default:return{kind:"text"}}}function l9(){return`argus${Math.floor(Math.random()*9e3+1e3)}`}class c9{constructor(e){this.hooks=e}hooks;open=null;lastCommand=null;password=l9();ended=!1;ask(e){const t=a9(e);return t==="return"?Promise.resolve(""):t==="password"||t==="tournament"||t==="password-verify"?Promise.resolve(this.password):(t==="command"&&(this.lastCommand=null),new Promise(i=>{this.open={question:{prompt:e,question:t,command:this.lastCommand},answer:i},this.hooks.question_changed(this.open.question)}))}question_get(){return this.open?.question??null}answer(e){if(this.open===null)return!1;const{answer:t}=this.open;return this.open=null,this.hooks.question_changed(null),t(e),!0}command_send(e){return this.open?.question.question!=="command"?!1:(this.lastCommand=e,this.answer(e.line))}abandon(){if(this.open===null)return!1;const{answer:e}=this.open;return this.open=null,this.hooks.question_changed(null),e(null),!0}text_take(e){this.hooks.text_written(e)}event_take(e,t){e==="games.trek.state"&&typeof t=="object"&&t!==null&&this.hooks.state_shown(t)}end(e){this.ended||(this.ended=!0,this.open=null,this.hooks.ended(e))}ended_is(){return this.ended}}const er={torpedoPoint:140,sector:170,burst:800,beam:900,rescan:350,flare:900,tail:300},h9=[[/^Torpedo track(?:, torpedo number \d+)?:/,()=>({kind:"torpedo-head"})],[/^\s*(\d+\.\d)\s+(\d+\.\d)\s*$/,s=>({kind:"torpedo-point",at:{x:Number(s[1]),y:Number(s[2])}})],[/^Torpedo missed|^Torpedo disappears into a black hole/,()=>({kind:"torpedo-end"})],[/\*\*\* Klingon at (\d+),(\d+) destroyed \*\*\*/,s=>({kind:"kill",at:gi(s,1)})],[/^Starbase at (\d+),(\d+) destroyed/,s=>({kind:"kill",at:gi(s,1)})],[/^Inhabited starsystem .* at (\d+),(\d+) destroyed/,s=>({kind:"kill",at:gi(s,1)})],[/^Unknown object . at (\d+),(\d+) destroyed/,s=>({kind:"kill",at:gi(s,1)})],[/Star at (\d+),(\d+) gone nova/,s=>({kind:"nova",at:gi(s,1)})],[/^Photon tubes misfire/,()=>({kind:"misfire"})],[/^(\d+) unit hit on Klingon at (\d+),(\d+)/,s=>({kind:"phaser",at:gi(s,2)})],[/^HIT: (\d+) units(?: from (\d+),(\d+))?(?:, shields absorb (\d+)%)?/,s=>({kind:"incoming",hit:Number(s[1]),from:s[2]===void 0?null:gi(s,2),absorb:s[4]===void 0?0:Number(s[4])})],[/^Klingon at (\d+),(\d+) moves to (\d+),(\d+)/,s=>({kind:"klingon-move",from:gi(s,1),to:gi(s,3)})],[/^Klingon at (\d+),(\d+) escapes to quadrant (\d+),(\d+)/,s=>({kind:"klingon-escape",from:gi(s,1),quadrant:gi(s,3)})],[/RED ALERT: supernova occurring at (\d+),(\d+)/,s=>({kind:"supernova",at:gi(s,1)})],[/^\s*in quadrant (\d+),(\d+)\.\s+Caution is advised/,s=>({kind:"supernova-report",quadrant:gi(s,1)})]];function gi(s,e){return{x:Number(s[e]),y:Number(s[e+1])}}function d9(s){for(const[e,t]of h9){const i=e.exec(s);if(i!==null)return t(i)}return null}class u9{constructor(e=f9){this.reduced=e}reduced;frames=[];running=!1;skipping=!1;waiting=new Set;played={};push(e){this.frames.push(e),this.pump()}skip(){if(!(this.frames.length===0&&!this.running)){this.skipping=!0;for(const e of this.waiting)e();this.waiting.clear()}}busy_is(){return this.running||this.frames.length>0}pending_count(){return this.frames.length}skipping_is(){return this.skipping}async settle(){for(;this.busy_is();)await new Promise(e=>{setTimeout(e,1)})}wait(e){return this.skipping||e<=0?Promise.resolve():new Promise(t=>{const i=setTimeout(()=>{this.waiting.delete(n),t()},e),n=()=>{clearTimeout(i),t()};this.waiting.add(n)})}async tween(e,t){const i=Mw();for(;!this.skipping;){const n=Math.min(1,(Mw()-i)/Math.max(1,e));if(t(n),n>=1)return;await p9(this)}t(1)}async pump(){if(!this.running){this.running=!0;try{for(;this.frames.length>0;){const e=this.frames.shift();this.played[e.kind]=(this.played[e.kind]??0)+1;const t=this.skipping||this.reduced();try{await e.run(t)}catch{}}}finally{this.running=!1,this.skipping=!1}}}}function f9(){return typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches}function Mw(){return typeof performance=="object"?performance.now():Date.now()}function p9(s){return typeof requestAnimationFrame=="function"?new Promise(e=>{requestAnimationFrame(()=>e())}):s.wait(16)}function Ba(s){return[s.y+.5,s.x+.5]}function Hx(s,e){return(Math.atan2(e.y-s.y,-(e.x-s.x))*180/Math.PI+360)%360}function m9(s,e,t=10){const i={x:s.quadrant.x*t+s.sector.x,y:s.quadrant.y*t+s.sector.y},n={x:e.quadrant.x*t+e.sector.x,y:e.quadrant.y*t+e.sector.y},r={x:n.x-i.x,y:n.y-i.y},o=(p,f,_)=>{let g=_?1/0:-1/0;for(const m of["x","y"]){if(r[m]===0)continue;const w=p[m]*t-.5,y=p[m]*t+t-.5,M=(w-f[m])/r[m],v=(y-f[m])/r[m];_?g=Math.min(g,Math.max(M,v)):g=Math.max(g,Math.min(M,v))}return Number.isFinite(g)?Math.max(0,Math.min(1,g)):_?1:0},a=o(s.quadrant,i,!0),l=o(e.quadrant,i,!1),c=.7,h={x:i.x+r.x*a-s.quadrant.x*t,y:i.y+r.y*a-s.quadrant.y*t},d={x:i.x+r.x*l-e.quadrant.x*t,y:i.y+r.y*l-e.quadrant.y*t},u=Math.hypot(r.x,r.y)||1;return{exit:{x:h.x+r.x/u*c,y:h.y+r.y/u*c},entry:{x:d.x-r.x/u*c,y:d.y-r.y/u*c}}}function pu(s,e=""){const t=rt("g",{class:`tb-motion ${e}`.trim()});return s.append(t),t}const g9=.7;async function ml(s,e,t,i,n,r={},o=!1){if(o)return;const a=pu(s,"tb-motion-slide"),[l,c]=Ba(i),[h,d]=Ba(n),u=r.hostile===!0?" tb-hostile":"";a.append(rt("line",{class:`tb-track${u}`,x1:l,y1:c,x2:h,y2:d}));const p=rt("line",{class:`tb-pulse tb-pulse-wide${u}`,x1:l,y1:c,x2:l,y2:c}),f=rt("line",{class:`tb-pulse tb-pulse-core${u}`,x1:l,y1:c,x2:l,y2:c}),_=r.heading??Hx(i,n),g=K_(t.kind,{cx:l,cy:c,size:g9},t.variant,_);g.classList.add(`tb-sector-${t.kind}`),a.append(p,f,g);const m=Math.max(1,Math.hypot(n.x-i.x,n.y-i.y));await e.tween(m*er.sector,w=>{const y=l+(h-l)*w,M=c+(d-c)*w,v=Math.max(0,w-.12),S=l+(h-l)*v,x=c+(d-c)*v;for(const b of[p,f])b.setAttribute("x1",String(S)),b.setAttribute("y1",String(x)),b.setAttribute("x2",String(y)),b.setAttribute("y2",String(M));Gx(g,y,M,_)}),a.remove()}async function vw(s,e,t,i,n,r=!1){if(r)return;const o=pu(s,"tb-motion-beam"),[a,l]=Ba(t),[c,h]=Ba(i),d=n?" tb-hostile":"";o.append(rt("line",{class:`tb-beam${d}`,x1:a,y1:l,x2:c,y2:h}),rt("line",{class:`tb-beam tb-beam-core${d}`,x1:a,y1:l,x2:c,y2:h})),await e.wait(er.beam),o.remove()}async function Mh(s,e,t,i,n=!1){if(n)return;const r=pu(s,`tb-motion-burst tb-burst tb-burst-${i}`),[o,a]=Ba(t),l=i==="misfire"?er.burst*.6:i==="supernova"?er.burst*1.6:er.burst;r.style.setProperty("--tb-ms",`${l}ms`),r.append(rt("circle",{class:"tb-burst-halo",cx:o,cy:a,r:.1}));const c=rt("g",{class:"tb-burst-spikes"}),h=i==="nova"||i==="supernova"?12:8,d=i==="misfire"?.6:i==="supernova"?1.8:i==="nova"?1.1:.95;for(let u=0;u<h;u++){const p=u/h*Math.PI*2+(h===8?Math.PI/8:0);c.append(rt("line",{class:"tb-burst-spike",x1:o+Math.cos(p)*.12,y1:a+Math.sin(p)*.12,x2:o+Math.cos(p)*d,y2:a+Math.sin(p)*d}))}r.append(c,rt("circle",{class:"tb-burst-core",cx:o,cy:a,r:.04})),await e.wait(l),r.remove()}async function _9(s,e,t=!1){if(t)return;const i=s.querySelector(".tb-ring");if(i===null)return;const n=rt("circle",{class:"tb-motion tb-ring-flare",cx:i.getAttribute("cx")??0,cy:i.getAttribute("cy")??0,r:.46});s.append(n),await e.wait(er.flare),n.remove()}class b9{layer;tail;photon;points=[];constructor(e,t){this.layer=pu(e,"tb-motion-torpedo"),this.tail=rt("g",{class:"tb-tail"}),this.photon=rt("g",{class:"tb-photon"}),this.photon.append(rt("circle",{class:"tb-photon-halo",cx:0,cy:0,r:.34}));const i=rt("g",{class:"tb-photon-pulses"});for(let o=0;o<10;o++){const a=rt("g",{transform:`rotate(${o*36})`});a.append(rt("rect",{x:.08,y:-.016,width:.2+o%3*.05,height:.032,rx:.006})),i.append(a)}this.photon.append(i,rt("circle",{class:"tb-photon-core",cx:0,cy:0,r:.12})),this.layer.append(this.tail,this.photon);const[n,r]=Ba(t);this.points.push([n,r]),this.photon.setAttribute("transform",`translate(${n} ${r})`)}async point_reach(e,t,i=!1){const[n,r]=[t.y,t.x];this.points.push([n,r]),this.photon.setAttribute("transform",`translate(${n} ${r})`),this.tail.replaceChildren();const o=this.points.slice(-4);for(let a=1;a<o.length;a++){const[l,c]=o[a-1],[h,d]=o[a];this.tail.append(rt("line",{class:"tb-tail-segment",x1:l,y1:c,x2:h,y2:d,"stroke-width":.03+.03*a,opacity:.25+.25*a}))}i||await e.wait(er.torpedoPoint)}async end(e,t=!1){this.photon.remove(),t||await e.wait(er.tail),this.layer.remove()}}function ww(s,e){s.classList.toggle("tb-rescan",e)}function M9(s,e){s.classList.remove("tb-bloom","tb-bloom-hostile"),s.offsetWidth,s.classList.add("tb-bloom"),e&&s.classList.add("tb-bloom-hostile"),s.addEventListener("animationend",()=>s.classList.remove("tb-bloom","tb-bloom-hostile"),{once:!0})}function wi(s,e){return s!==null&&e.includes(s.question)}function mu(s,e){const t=q("div","tb-station-head"),i=q("span","tb-station-step",""),n=ei("tb-grave tb-cancel","CANCEL",()=>{e.answer_send(n.dataset.line??"","CANCEL")});return n.hidden=!0,t.append(q("span","tb-station-name",s),i,q("span","tb-station-fill"),n),{root:t,step:i,cancel:n}}function gu(s,e,t,i){const n=t?.command??null,r=n!==null&&n.station===e&&t!==null&&t.question!=="command";s.step.textContent=r&&n!==null&&t!==null?`${n.label} · ${t.question.replace(/-/g," ").toUpperCase()}`:t?.question==="command"?"READY":"";const o=r?i?.cancel:void 0;s.cancel.hidden=o===void 0,s.cancel.dataset.line=o??"",s.cancel.textContent=n===null?"CANCEL":`CANCEL ${n.label}`}function Z_(s,e){const t=ei(`tb-command${s.grave===!0?" tb-grave":""}`,s.label,()=>{e.command_send(s)});return t.dataset.command=s.id,t}function Vx(s,e){const t=q("div","tb-pills tb-command-pills"),i=new Map;for(const n of fu.filter(r=>r.station===s)){const r=Z_(n,e);i.set(n.id,r),t.append(r)}return{root:t,pills:i}}function _u(s,e){for(const[t,i]of s)i.disabled=e?.question!=="command",i.classList.toggle("tb-pill-on",e?.command?.id===t)}function qx(s,e){const t=ei("tb-target","",e);return t.append(Y_("klingon",s.mark),document.createTextNode(`${s.x},${s.y}`)),t.title=`Klingon at ${s.x},${s.y}`,t}function jm(s,e){const t=q("span",s,e.supernova?"":e.code??"");return e.supernova&&t.append(Y_("supernova")),t}function Hm(s){return`quadrant ${s.x},${s.y}${s.supernova?" · supernova":s.code===null?" · unscanned":""}`}function Kx(s){const e=s.klingons.map(t=>({bearing:t.bearing,kind:"klingon",label:`Klingon at ${t.x},${t.y} · ${t.range.toFixed(1)} · ${Math.round(t.bearing)}°`,variant:t.mark}));for(const t of s.sectors)for(const i of t){if(i.kind!=="base")continue;const n=i.x-s.position.sector.x,r=i.y-s.position.sector.y;e.push({bearing:(Math.atan2(r,-n)*180/Math.PI+360)%360,kind:"base",label:`starbase at ${i.x},${i.y}`})}return e}class yw{root;wheel;distance;warp;rest;head;pills;readout=null;constructor(e,t,i){this.root=q("div","tb-station tb-station-helm"),this.head=mu("HELM",e);const n=Vx("helm",e);this.pills=n.pills;const r=q("div","tb-controls");this.wheel=new Px(t,"course wheel",a=>e.answer_send(String(a),"SET COURSE"));const o=q("div","tb-sliders");this.distance=new Lr(`${i}-distance`,"DISTANCE",1,a=>e.answer_send(a.toFixed(1),"SLIDER SET")),this.warp=new Lr(`${i}-warp`,"WARP FACTOR",1,a=>e.answer_send(a.toFixed(1),"SLIDER SET")),this.rest=new Lr(`${i}-rest`,"REST",1,a=>e.answer_send(a.toFixed(1),"SLIDER SET")),this.distance.input_listen(()=>this.arrival_note()),o.append(this.distance.root,this.warp.root,this.rest.root),r.append(this.wheel.root,o),this.root.append(this.head.root,n.root,r)}state_show(e){const t=this.readout===null;this.readout=e,this.wheel.marks_set(Kx(e)),this.warp.range_set(ks("warp-factor",e),e.ship.warp,"THE SHIP NOW · ABOVE 6 THE ENGINES MAY BURN",10),this.distance.range_set(ks("distance",e),t?1:this.distance.value_get(),"QUADRANTS · 0.1 IS ONE SECTOR",6),this.rest.range_set(ks("how-long",e),0,`STARDATES · ${e.mission.timeLeft.toFixed(1)} LEFT · REPAIRS RUN WHILE TIME PASSES`,2)}question_show(e){_u(this.pills,e);const t=e===null?null:ks(e.question,this.readout);gu(this.head,"helm",e,t),this.wheel.lit_set(wi(e,["course","direction"]),"SET COURSE"),this.distance.lit_set(wi(e,["distance"]),"ENGAGE"),this.warp.lit_set(wi(e,["warp-factor"]),"SET WARP"),this.rest.lit_set(wi(e,["how-long"]),"REST"),e?.question==="distance"&&this.arrival_note()}arrival_note(){if(this.readout===null)return;const e=this.distance.value_get(),t=n9(this.readout,this.wheel.degrees_get(),e),i=Ux(e,this.readout.ship.warp,this.readout.param.warptime);this.distance.note_set(`ARRIVES ${t.quadrant.x},${t.quadrant.y} / ${t.sector.x},${t.sector.y} · ${i.stardates.toFixed(2)} STARDATES AT WARP ${this.readout.ship.warp.toFixed(1)} · ${i.units} UNITS`)}}class Sw{constructor(e,t,i){this.host=e,this.root=q("div","tb-station tb-station-tactical"),this.head=mu("TACTICAL",e);const n=Vx("tactical",e);this.pills=n.pills;const r=q("div","tb-controls");this.wheel=new Px(t,"firing course wheel",l=>e.answer_send(String(l),"SET COURSE"));const o=q("div","tb-sliders");this.burst=new bh("BURST",ks("burst",null).choices??[],(l,c)=>e.answer_send(l,Dr(c,"choice"))),this.burstAngle=new bh("BURST ANGLE",ks("burst-angle",null).choices??[],(l,c)=>{this.wheel.wedge_set(Number(l)),e.answer_send(l,Dr(c,"choice"))}),this.manual=new bh("PHASERS",ks("manual-automatic",null).choices??[],(l,c)=>e.answer_send(l,Dr(c,"choice"))),this.units=new Lr(`${i}-units`,"UNITS",0,l=>e.answer_send(String(Math.round(l)),"SLIDER SET")),this.spread=new Lr(`${i}-spread`,"SPREAD",2,l=>e.answer_send(l.toFixed(2),"SLIDER SET")),this.upDown=new bh("SHIELDS",ks("up-down",null).choices??[],(l,c)=>e.answer_send(l,Dr(c,"choice")));const a=q("div","tb-fire-row");this.fire=ei("tb-fire","FIRE",()=>e.answer_send("0",null)),this.targets=q("div","tb-targets"),a.append(this.fire,this.targets),o.append(this.burst.root,this.burstAngle.root,this.manual.root,this.units.root,this.spread.root,this.upDown.root,a),r.append(this.wheel.root,o),this.root.append(this.head.root,n.root,r)}host;root;wheel;units;spread;head;pills;burst;burstAngle;manual;upDown;fire;targets;readout=null;state_show(e){this.readout=e,this.wheel.marks_set(Kx(e)),this.wheel.wedge_set(null),e.klingons[0]!==void 0&&this.wheel.degrees_set(e.klingons[0].bearing),this.units.range_set(ks("units",e),Math.min(e.ship.energy,Math.round(e.ship.energy/100)*10),`UP TO THE ${e.ship.energy} FREE`,6),this.spread.range_set(ks("spread",e),.5,"MANUAL PHASERS ONLY",3),this.burst.note_set(`${e.ship.torpedoes} TORPEDOES · A BURST FIRES 3`),this.upDown.note_set(`${e.ship.shieldsUp?"UP":"DOWN"} · ${e.ship.shield} OF ${e.ship.shieldMax} · REFILLS AT A STARBASE`);const t=this.pills.get("phasers");t!==void 0&&(t.classList.toggle("tb-barred",e.ship.shieldsUp),t.title=e.ship.shieldsUp?"Shields are up: phasers cannot fire through them. SHIELDS, then DOWN, first.":""),this.targets_draw(e)}question_show(e){_u(this.pills,e);const t=e===null?null:ks(e.question,this.readout);gu(this.head,"tactical",e,t),this.wheel.lit_set(wi(e,["torpedo-course","bank-course"]),"SET COURSE"),this.burst.lit_set(wi(e,["burst"])),this.burstAngle.lit_set(wi(e,["burst-angle"])),this.manual.lit_set(wi(e,["manual-automatic"])),this.units.lit_set(wi(e,["units","bank-units"]),e?.question==="units"?"FIRE":"SET BANK"),this.spread.lit_set(wi(e,["spread"])),this.upDown.lit_set(wi(e,["up-down"])),this.fire.disabled=!wi(e,["bank-units"]),this.fire.textContent="FIRE THE BANKS SET"}targets_draw(e){if(this.targets.replaceChildren(),e.klingons.length===0){this.targets.append(q("span","tb-note","NO KLINGONS IN THIS QUADRANT"));return}for(const t of["TARGET","RANGE","BEARING","PHASER HIT"])this.targets.append(q("span","tb-target-head",t));for(const t of e.klingons){const i=qx(t,()=>{this.host.voice.cue("scanner"),this.host.course_set(t.bearing,t.range/10)});this.targets.append(i,q("span","tb-target-cell",t.range.toFixed(1)),q("span","tb-target-cell",`${Math.round(t.bearing)}°`),q("span","tb-target-cell",`${$x(t.range/10)}%`))}}}class v9{root;rest;head;pills;damage;systems;since;inThatTime;readout=null;constructor(e){this.root=q("div","tb-view-body tb-view-engineering");const t=q("section","tb-panel tb-damage");t.append(q("span","tb-title","DAMAGE CONTROL"),q("span","tb-note","THE C'S REPORT · ALWAYS ON")),this.damage=q("div","tb-dc"),t.append(this.damage,q("span","tb-note","REPAIR TIMES IN STARDATES · REPAIRS RUN WHILE TIME PASSES · DOCKED, FASTER BY THE DOCK FACTOR"));const i=q("section","tb-panel tb-systems-section");i.append(q("span","tb-title","SHIP"),q("span","tb-note","ENERGY, SHIELDS, RESERVES")),this.systems=q("div","tb-systems"),i.append(this.systems,q("span","tb-title","SINCE THE LAST COMMAND")),this.since=q("div","tb-head-grid tb-since-grid"),i.append(this.since,q("span","tb-note","SHIELDS ARE UP OR DOWN IN TREK(6): THEIR ENERGY IS A READOUT, REFILLED AT A STARBASE"));const n=q("section","tb-panel tb-station tb-station-time");this.head=mu("REST",e);const r=q("div","tb-pills tb-command-pills");this.pills=new Map;for(const o of["rest","dock","undock"]){const a=fu.find(c=>c.id===o);if(a===void 0)continue;const l=Z_(a,e);this.pills.set(o,l),r.append(l)}this.rest=new Lr("tbe-rest","HOW LONG",1,o=>e.answer_send(o.toFixed(1),"SLIDER SET")),this.rest.input_listen(()=>this.inThatTime_note()),this.inThatTime=q("div","tb-in-that-time"),n.append(this.head.root,r,this.rest.root,q("span","tb-title","IN THAT TIME"),this.inThatTime),this.root.append(t,i,n)}state_show(e,t){this.readout=e,this.damage_draw(e),this.systems_draw(e),this.since.replaceChildren();const i=t===null?[]:jx(t,e);i.length===0&&this.since.append(q("span","tb-head-label","—"),q("span","tb-head-value","NOTHING MOVED"));for(const n of i)this.since.append(q("span","tb-head-label",n.label),q("span",`tb-head-value ${n.bad?"tb-bad":"tb-good"}`,n.change));this.rest.range_set(ks("how-long",e),this.rest.value_get(),`STARDATES · ${e.mission.timeLeft.toFixed(1)} LEFT`,4),this.inThatTime_note()}question_show(e){_u(this.pills,e);const t=e===null?null:ks(e.question,this.readout),i=e!==null&&(e.command===null||["rest","dock","undock"].includes(e.command.id))?e:null;gu(this.head,"helm",i,t),this.rest.lit_set(wi(e,["how-long"]),"REST")}damage_draw(e){this.damage.replaceChildren();for(const i of["DEVICE","","IN FLIGHT","DOCKED",""])this.damage.append(q("span","tb-dc-head",i));const t=Math.max(1,...e.damaged.map(i=>(i.repairAt??0)-e.mission.stardate));for(const i of e.devices){const n=bw(i,e),r=q("div","tb-bar-track"),o=q("div",`tb-bar-fill${n===null?" tb-bar-ok":" tb-bar-down"}`);o.style.width=n===null?"100%":`${Math.max(4,Math.min(100,Math.round(100*((i.repairAt??0)-e.mission.stardate)/t)))}%`,r.append(o),this.damage.append(q("span",`tb-dc-name${n===null?"":" tb-bad"}`,i.name.toUpperCase()),r,q("span","tb-dc-time",n===null?"—":n.inFlight.toFixed(2)),q("span","tb-dc-time",n===null?"—":n.docked.toFixed(2)),q("span",`tb-dc-state${n===null?" tb-good":" tb-bad"}`,n===null?"OK":"DOWN"))}}systems_draw(e){const{ship:t}=e;this.systems.replaceChildren();const i=(l,c,h,d,u)=>{const p=q("div","tb-bar-track"),f=q("div",`tb-bar-fill${u?" tb-bar-down":" tb-bar-ok"}`);f.style.width=`${Math.max(0,Math.min(100,Math.round(100*c/Math.max(1,h))))}%`,p.append(f),this.systems.append(q("span","tb-dc-name",l),p,q("span","tb-dc-time tb-sys-value",d))};i("ENERGY",t.energy,t.energyMax,`${t.energy} / ${t.energyMax}`,t.energy<t.energyMax/4),i("SHIELDS",t.shield,t.shieldMax,`${t.shieldsUp?"UP":"DOWN"} · ${t.shield} / ${t.shieldMax}`,t.shield<t.shieldMax/4),i("LIFE SUPPORT",t.reserves,t.reservesMax,`RESERVES ${t.reserves.toFixed(1)} / ${t.reservesMax.toFixed(1)}`,t.reserves<t.reservesMax/4);const n=q("div","tb-pips");for(let l=0;l<t.torpedoesMax;l++)n.append(q("span",`tb-pip${l<t.torpedoes?" tb-pip-on":""}`));this.systems.append(q("span","tb-dc-name","TORPEDOES"),n,q("span","tb-dc-time tb-sys-value",`${t.torpedoes} / ${t.torpedoesMax}`));const r=(l,c)=>{this.systems.append(q("span","tb-dc-name",l),q("span","tb-sys-text",c))};r("CREW",`${t.crew}${e.mission.captives>0?` · ${e.mission.captives} CAPTIVE`:" · BRIG EMPTY"}`);const o=e.damaged.some(l=>/warp/i.test(l.name));r("WARP",`${t.warp.toFixed(1)} · ENGINES ${o?"DOWN":"OK"}`);const a=e.damaged.some(l=>/cloak/i.test(l.name));r("CLOAK",`${t.cloaked?"ON":"OFF"} · DEVICE ${a?"DOWN":"OK"}`)}inThatTime_note(){if(this.readout===null)return;const e=this.rest.value_get();this.inThatTime.replaceChildren();const t=this.readout.damaged.filter(n=>(bw(n,this.readout)?.inFlight??1/0)<=e).map(n=>n.name.toUpperCase());this.inThatTime.append(q("span","tb-head-value tb-good",t.length===0?e>0?"NO REPAIR COMPLETES":"—":`${t.join(" · ")} REPAIRED`));const i=this.readout.klingons.length;i>0&&this.inThatTime.append(q("span","tb-head-value tb-bad",`${i} KLINGON${i===1?"":"S"} IN THE QUADRANT WILL FIRE · SPOCK MAY ASK TO CANCEL`))}}const zw=[{label:"CHART",line:"ch",asks:[]},{label:"TRAJECTORY",line:"t",asks:[]},{label:"COURSE",line:"c",asks:["quadrant","quadrant-y","sector","sector-y"]},{label:"MOVE",line:"m",asks:["quadrant","quadrant-y","sector","sector-y"]},{label:"SCORE",line:"s",asks:[]},{label:"PHASER EFFECT",line:"p",asks:["range"]},{label:"WARP COST",line:"w",asks:["computer-distance","computer-warp"]},{label:"IMPULSE COST",line:"i",asks:["computer-distance"]},{label:"DISTRESS LIST",line:"d",asks:[]}];class w9{constructor(e){this.host=e,this.root=q("div","tb-view-body tb-view-computer");const t=q("section","tb-panel tb-chart-section");t.append(q("span","tb-title","GALAXY · WHAT THE SHIP HAS SEEN"),q("span","tb-note","PRESS A QUADRANT: THE COURSE PANEL AIMS AT IT · HUNDREDS KLINGONS, TENS BASES, ONES STARS")),this.chart=q("div","tb-chart-big"),t.append(this.chart);const i=q("section","tb-station tb-station-computer");this.head=mu("COMPUTER",e);const n=q("div","tb-pills tb-command-pills");for(const d of zw){const u=ei("tb-command tb-request",d.label,()=>this.request_send(d));u.dataset.request=d.line,this.requestPills.push(u),n.append(u)}const r=q("div","tb-computer-panels"),o=q("div","tb-panel");o.append(q("span","tb-title","COURSE AND DISTANCE")),this.courseGrid=q("div","tb-head-grid");const a=q("div","tb-pills");a.append(ei("tb-commit tb-send-helm","SEND TO HELM",()=>this.helm_send()),ei("tb-commit tb-move-now","MOVE THERE NOW",()=>this.request_send(zw[3]))),o.append(this.courseGrid,a);const l=q("div","tb-panel");l.append(q("span","tb-title","WARP COST")),this.wcDistance=new Lr("tbc-distance","DISTANCE",2,()=>{}),this.wcWarp=new Lr("tbc-warp","WARP FACTOR",1,()=>{}),this.wcDistance.root.classList.add("tb-local"),this.wcWarp.root.classList.add("tb-local"),this.wcDistance.input_listen(()=>this.costs_note()),this.wcWarp.input_listen(()=>{this.warpTouched=!0,this.costs_note()}),this.wcResult=q("div","tb-head-grid"),l.append(this.wcDistance.root,this.wcWarp.root,this.wcResult);const c=q("div","tb-panel");c.append(q("span","tb-title","TRAJECTORY · KLINGONS HERE")),this.trajectory=q("div","tb-targets"),c.append(this.trajectory,q("span","tb-title","SCORE SO FAR")),this.score=q("div","tb-score"),c.append(this.score);const h=q("div","tb-panel tb-answer-panel");h.append(q("span","tb-title","THE COMPUTER ANSWERS")),this.answer=q("pre","tb-computer-answer","—"),h.append(this.answer),r.append(o,l,c,h),i.append(this.head.root,n,r),this.root.append(t,i)}host;root;head;chart;requestPills=[];courseGrid;wcDistance;wcWarp;wcResult;trajectory;score;answer;readout=null;target=null;open=null;warpTouched=!1;state_show(e){this.readout=e,this.target===null&&(this.target={quadrant:{...e.position.quadrant},sector:{...e.position.sector}}),this.chart_draw(e),this.wcWarp.range_set(ks("computer-warp",e),this.warpTouched?this.wcWarp.value_get():e.ship.warp,"THE SHIP'S NOW",4),this.wcDistance.range_set(ks("computer-distance",e),this.wcDistance.value_get(),"QUADRANTS · FILLED FROM THE COURSE",4),this.wcDistance.lit_set(!0,""),this.wcWarp.lit_set(!0,""),this.course_note(),this.trajectory_draw(e),this.score_draw(e)}question_show(e){this.open=e;const t=e===null?null:ks(e.question,this.readout);gu(this.head,"ship",e,t);const i=e?.question==="command"||e?.question==="request";for(const n of this.requestPills)n.disabled=!i}answer_take(e){if(e===null){this.answer.textContent="";return}this.answer.textContent=`${this.answer.textContent??""}${e}`.replace(/^\s*\n/,"")}sector_set(e){this.readout!==null&&(this.target={quadrant:this.target?.quadrant??{...this.readout.position.quadrant},sector:{x:e.x,y:e.y}},this.course_note())}request_send(e){const t=e.asks.map(n=>[n,this.plannedAnswer_derive(n)]);if(this.open?.question==="request"){this.host.plan_set(t),this.answer_take(null),this.host.answer_send(e.line,Dr(e.label,"computer")),this.host.voice.cue("thinking");return}const i=fu.find(n=>n.id==="computer");if(i===void 0||this.open?.question!=="command"){this.host.voice.cue("deny");return}this.host.plan_set([["request",e.line],...t]),this.answer_take(null),this.host.voice.pill(Dr(e.label,"computer")),this.host.command_send(i)}plannedAnswer_derive(e){const t=this.target,i=this.readout?.klingons[0];switch(e){case"quadrant":return String(t?.quadrant.x??0);case"quadrant-y":return String(t?.quadrant.y??0);case"sector":return String(t?.sector.x??0);case"sector-y":return String(t?.sector.y??0);case"range":return(i===void 0?this.wcDistance.value_get():i.range/10).toFixed(2);case"computer-distance":return this.wcDistance.value_get().toFixed(2);case"computer-warp":return this.wcWarp.value_get().toFixed(1);default:return""}}helm_send(){if(this.readout===null||this.target===null)return;const e=_w(this.readout,this.target);this.host.voice.pill("SEND TO HELM"),this.host.course_set(e.course,Math.round(e.distance*10)/10)}chart_draw(e){this.chart.replaceChildren(),this.chart.append(q("span","tb-srs-corner",""));for(let t=0;t<(e.chart[0]?.length??0);t++)this.chart.append(q("span","tb-srs-axis",String(t)));for(const t of e.chart){this.chart.append(q("span","tb-srs-axis",String(t[0]?.x??"")));for(const i of t)this.chart.append(this.quadrantButton_make(i))}}quadrantButton_make(e){const t=this.target?.quadrant.x===e.x&&this.target.quadrant.y===e.y,i=ei(`tb-cq${e.here?" tb-here":""}${e.klingons>0?" tb-hostile":""}${e.bases>0?" tb-based":""}${e.code===null?" tb-unscanned":""}${t?" tb-pressed":""}`,"",()=>{this.readout!==null&&(this.target={quadrant:{x:e.x,y:e.y},sector:this.target?.sector??{...this.readout.position.sector}},this.host.voice.cue("scanner"),this.chart_draw(this.readout),this.course_note())});return i.dataset.x=String(e.x),i.dataset.y=String(e.y),i.append(jm("tb-cq-code",e),q("span","tb-cq-at",`${e.x},${e.y}`)),i.title=Hm(e),i}course_note(){if(this.readout===null||this.target===null)return;const{position:e}=this.readout,t=_w(this.readout,this.target);this.courseGrid.replaceChildren(q("span","tb-head-label","FROM"),q("span","tb-head-value",`QUADRANT ${e.quadrant.x},${e.quadrant.y} · SECTOR ${e.sector.x},${e.sector.y}`),q("span","tb-head-label","TO"),q("span","tb-head-value",`QUADRANT ${this.target.quadrant.x},${this.target.quadrant.y} · SECTOR ${this.target.sector.x},${this.target.sector.y}`),q("span","tb-head-label","COURSE"),q("span","tb-head-value tb-course-value",`${t.course}°`),q("span","tb-head-label","DISTANCE"),q("span","tb-head-value tb-distance-value",t.distance.toFixed(2))),this.wcDistance.value_set(Math.round(t.distance*100)/100),this.costs_note()}costs_note(){if(this.readout===null)return;const e=this.wcDistance.value_get(),t=Ux(e,this.wcWarp.value_get(),this.readout.param.warptime),i=r9(e);this.wcResult.replaceChildren(q("span","tb-head-label","TIME"),q("span","tb-head-value",`${t.stardates.toFixed(2)} STARDATES`),q("span","tb-head-label","ENERGY"),q("span","tb-head-value",`${t.units} UNITS · ${t.unitsShielded} WITH SHIELDS UP`),q("span","tb-head-label","AT IMPULSE"),q("span","tb-head-value",`${i.stardates.toFixed(2)} STARDATES · ${i.units} UNITS`))}trajectory_draw(e){if(this.trajectory.replaceChildren(),e.klingons.length===0){this.trajectory.append(q("span","tb-note","NO KLINGONS IN THIS QUADRANT"));return}for(const t of["AT","COURSE","RANGE","PHASER HIT"])this.trajectory.append(q("span","tb-target-head",t));for(const t of e.klingons)this.trajectory.append(qx(t,()=>{this.host.voice.cue("scanner"),this.host.course_set(t.bearing,t.range/10)}),q("span","tb-target-cell",`${Math.round(t.bearing)}°`),q("span","tb-target-cell",t.range.toFixed(1)),q("span","tb-target-cell",`${$x(t.range/10)}%`))}score_draw(e){const t=Fx(e);this.score.replaceChildren();for(const i of t.items.filter(n=>n.points!==0||/killed|remaining/.test(n.label)))this.score.append(q("span","tb-score-label",i.label.toUpperCase()),q("span",`tb-score-points${i.points<0?" tb-bad":" tb-good"}`,`${i.points>0?"+":""}${i.points}`));this.score.append(q("span","tb-score-label tb-score-total","TOTAL"),q("span","tb-score-points tb-score-total",String(t.total)))}}const Ff=["bridge","helm","tactical","engineering","computer"],y9=400,S9="-0.6 -0.6 10.6 10.6",z9=.7,x9=/^S\.R\. scanners$/i,O9=/^L\.R\. scanners$/i,E9={ArrowUp:[-1,0],ArrowDown:[1,0],ArrowLeft:[0,-1],ArrowRight:[0,1]},A9=["length","skill","request","quadrant","quadrant-y","sector","sector-y","range","computer-distance","computer-warp","status-report","another","yes-no","unknown"];class T9{constructor(e,t){this.hooks=e,this.harness=new c9({question_changed:r=>{this.partial_flush(),this.question_show(r)},text_written:r=>this.text_take(r),state_shown:r=>this.state_show(r),ended:()=>{this.leaving||this.hooks.voice.cue("gameover")}}),this.frame=X_({id:"trek-bridge",className:"trek-bridge",brand:{name:"TREK",sub:"ARGUS · BSD TREK",mark:!1},banner:"TREK • THE BRIDGE",views:Ff.map(r=>({key:r,label:r.toUpperCase()})),leave:{label:"LEAVE BRIDGE",destroy:!0},stage:{title:"THE BRIDGE",note:"BRIDGE"},log:{title:"SHIP'S LOG",note:"READ ONLY"},labels:{views:"views",log:"ship's log"}},r=>{const o=Ff.find(a=>a===r);o!==void 0&&this.view_set(o)},()=>this.leave_ask()),this.frame.leave.classList.add("tb-leave"),this.root=this.frame.root,this.root.dataset.view="bridge",this.frame.view_mark("bridge"),this.root.setAttribute("aria-label","trek: the bridge");const i={},n=OH();n!==null&&this.root.append(n),this.gutter_build(i,t),this.frame.face.append(this.header_build(i)),this.frame.body.append(this.body_build(i)),this.strip_build(i),this.frame.aside.append(i.ask),this.frame.log.append(this.log_build(i)),this.leaveAsk_build(i),this.root.append(i.leaveAsk),this.parts=i,this.question_show(null)}hooks;root;frame;harness;readout=null;previous=null;view="bridge";nextDistance=null;plan=new Map;answering=!1;computerRunning=!1;leaving=!1;tracker=new $l;heading=0;pressedSector=null;scanDue=!1;fold=null;frames=new u9;shown=null;torpedo=null;trackPrinting=!1;partial="";lrsBloom=null;parts;stationHost_get(){return{answer_send:(e,t)=>this.answer_send(e,t),command_send:e=>this.command_send(e),plan_set:e=>{for(const[t,i]of e)this.plan.set(t,i)},course_set:(e,t)=>this.course_set(e,t),voice:this.hooks.voice}}gutter_build(e,t){e.seed=q("div","tb-seed",t===null?"RANDOM GALAXY":`SEED ${t}`),this.frame.seat.append(e.seed),e.views=new Map;for(const i of Ff){const n=this.frame.views.get(i);n!==void 0&&(n.classList.add("tb-view",`tb-view-${i}`),e.views.set(i,n))}}header_build(e){const t=q("header","tb-header"),i=q("section","tb-head-condition"),n=q("div","tb-condition");n.append(q("span","tb-condition-label","CONDITION")),e.condition=q("span","tb-condition-name","—"),n.append(e.condition),e.conditionWhy=q("div","tb-condition-why",""),i.append(n,e.conditionWhy);const r=p=>{const f=q("section","tb-head-section");f.append(q("span","tb-head-title",p));const _=q("div","tb-head-grid");return f.append(_),[f,_]},[o,a]=r("SHIP"),[l,c]=r("MISSION"),[h,d]=r("POSITION"),u=q("div","tb-head-grid tb-head-since");return l.append(q("span","tb-head-title","SINCE LAST COMMAND"),u),e.ship=a,e.mission=c,e.position=d,e.since=u,t.append(i,o,l,h),t}body_build(e){const t=this.stationHost_get(),i=q("main","tb-body");i.dataset.view="bridge",e.body=i;const n=q("section","tb-scans");n.append(q("span","tb-title","LONG RANGE")),e.lrs=q("div","tb-lrs"),n.append(e.lrs,q("span","tb-title","GALAXY · WHAT THE SHIP HAS SEEN")),e.chart=q("div","tb-chart"),n.append(e.chart);const r=q("section","tb-srs-section");e.srsTitle=q("span","tb-title","SHORT RANGE"),r.append(e.srsTitle),e.scan=rt("svg",{class:"tb-scan",viewBox:S9,role:"grid","aria-label":"short range scan"}),e.scan.addEventListener("keydown",l=>this.scan_key(l)),e.legend=this.legend_build(),r.append(e.scan,q("span","tb-note","PRESS A SECTOR: ITS COURSE AND DISTANCE FILL IN"),e.legend),e.shipPills=new Map;const o=q("div","tb-pills tb-ship-pills");o.append(q("span","tb-slider-label","SHIP"));for(const l of fu.filter(c=>c.station==="ship")){const c=Z_(l,t);e.shipPills.set(l.id,c),o.append(c)}r.append(o);const a=q("section","tb-stations");return e.helm=new yw(t,150,"tb"),e.tactical=new Sw(t,150,"tb"),a.append(e.helm.root,e.tactical.root),e.helmView=new yw(t,260,"tbh"),e.helmView.root.classList.add("tb-view-body","tb-view-helm"),e.tacticalView=new Sw(t,260,"tbt"),e.tacticalView.root.classList.add("tb-view-body","tb-view-tactical"),e.engineeringView=new v9(t),e.computerView=new w9(t),i.append(n,r,a,e.helmView.root,e.tacticalView.root,e.engineeringView.root,e.computerView.root),i}legend_build(){const e=q("div","tb-legend");for(const t of EH){const i=q("span",`tb-legend-item tb-legend-${t.kind}`),n=t.kind==="klingon"?Er:[null];for(const r of n)i.append(Y_(t.kind,r));i.append(q("span","tb-legend-glyph",_h[t.kind].trim()===""?"␠":_h[t.kind]),q("span","tb-legend-name",t.name)),e.append(i)}return e}strip_build(e){e.ask=q("div","tb-ask"),e.ask.hidden=!0,e.ask.setAttribute("role","dialog"),e.askText=q("span","tb-ask-text",""),e.askPills=q("div","tb-pills"),e.askInput=document.createElement("input"),e.askInput.type="text",e.askInput.className="tb-ask-input",e.askInput.setAttribute("aria-label","the answer");const t=e.askInput;e.askSend=ei("tb-commit","ANSWER",()=>this.answer_send(t.value,"ANSWER")),t.addEventListener("keydown",i=>{i.key==="Enter"&&this.answer_send(t.value,"ANSWER")}),e.ask.append(q("span","tb-ask-label","THE GAME ASKS"),e.askText,e.askPills,e.askInput,e.askSend)}log_build(e){const t=q("footer","tb-log-section");return e.log=q("div","tb-log"),e.log.setAttribute("aria-live","polite"),t.append(e.log),t}leaveAsk_build(e){e.leaveAsk=q("div","tb-leave-ask"),e.leaveAsk.hidden=!0,e.leaveAsk.setAttribute("role","dialog");const t=e.leaveAsk,i=ei("tb-grave","LEAVE · THE GAME ENDS",()=>{this.leaving=!0,this.hooks.voice.cue("close"),this.hooks.leave()}),n=ei("","STAY",()=>{t.hidden=!0});e.leaveAsk.append(q("span","tb-ask-label","LEAVE THE BRIDGE?"),q("span","tb-ask-text","The game ends where it stands; dump first to keep it."),i,n)}harness_get(){return this.harness}leave_ask(){this.frames.skip(),this.parts.leaveAsk.hidden&&this.hooks.voice.pill("LEAVE BRIDGE"),this.parts.leaveAsk.hidden=!1}frames_get(){return{played:{...this.frames.played},pending:this.frames.pending_count(),busy:this.frames.busy_is()}}frames_settle(){return this.frames.settle()}leaveAsk_isOpen(){return!this.parts.leaveAsk.hidden}leaveAsk_close(){this.parts.leaveAsk.hidden=!0}view_get(){return this.view}view_set(e){this.frames.skip(),this.view=e,this.root.dataset.view=e,this.parts.body.dataset.view=e,this.frame.view_mark(e);for(const[t,i]of this.parts.views)i.classList.toggle("tb-view-on",t===e);this.frame.stageNote.textContent=e.toUpperCase(),this.hooks.voice.pill(Dr(e.toUpperCase(),"view"))}readout_get(){return this.readout}command_send(e){if(this.frames.skip(),!this.harness.command_send(e))return this.hooks.voice.cue("deny"),!1;const t=GH(e.id);return t===null?this.hooks.voice.pill(Dr(e.label,"command")):this.hooks.voice.cue(t),this.nextDistance=null,this.computerRunning=e.id==="computer",this.computerRunning&&this.parts.computerView.answer_take(null),this.log_write(`Command: ${e.line}
|
|
4359
4359
|
`,!0),!0}answer_send(e,t){const i=this.harness.question_get();if(!this.harness.answer(e)){this.hooks.voice.cue("deny");return}const n=i===null?null:PH(i.question,i.command?.id??null);n!==null?this.hooks.voice.cue(n):t!==null&&this.hooks.voice.pill(t);const r=i===null?"":i.prompt.trim();this.log_write(`${r===""?"":`${r} `}${e}
|
|
4360
4360
|
`,!0),i?.question==="course"&&Number.isFinite(Number(e))&&(this.heading=(Number(e)%360+360)%360,this.shown!==null&&this.srs_draw(this.shown))}course_set(e,t){const{parts:i}=this;for(const n of[i.helm,i.helmView,i.tactical,i.tacticalView])n.wheel.degrees_set(e);t!==null&&(i.helm.distance.value_set(t),i.helmView.distance.value_set(t),this.nextDistance=t)}state_show(e){this.previous=this.readout;const t=s9(e);this.readout=t;const{parts:i}=this,n=this.previous===null||this.previous.position.quadrant.x!==t.position.quadrant.x||this.previous.position.quadrant.y!==t.position.quadrant.y;this.tracker.reconcile(t.klingons,{reset:n,byOrder:!this.device_isOk(t,x9)});for(const r of t.klingons)r.mark=this.tracker.mark_find(r);n&&(this.pressedSector=null),n&&this.device_isOk(t,O9)&&(this.scanDue=!0),i.condition.textContent=t.condition.name,i.condition.parentElement?.setAttribute("data-condition",t.condition.name.toLowerCase()),i.conditionWhy.textContent=t.condition.why.toUpperCase(),this.header_draw(t);for(const r of[i.helm,i.helmView,i.tactical,i.tacticalView,i.computerView])r.state_show(t);i.engineeringView.state_show(t,this.previous),this.partial_flush(),this.frames.push(this.stateFrame_make(t,this.previous)),this.question_show(this.harness.question_get())}stateFrame_make(e,t){return{kind:"state",run:async i=>{const n=this.parts.scan;await this.torpedo_end(!0);const r=this.shown,o=r!==null&&(r.position.quadrant.x!==e.position.quadrant.x||r.position.quadrant.y!==e.position.quadrant.y),a=r!==null&&(o||r.position.sector.x!==e.position.sector.x||r.position.sector.y!==e.position.sector.y);if(a&&r!==null){const c={x:r.position.quadrant.x*10+r.position.sector.x,y:r.position.quadrant.y*10+r.position.sector.y},h={x:e.position.quadrant.x*10+e.position.sector.x,y:e.position.quadrant.y*10+e.position.sector.y};this.heading=Math.round(Hx(c,h))}const l={kind:"ship",variant:null};if(a&&!i&&r!==null&&!o)this.srs_draw(r,!1),await ml(n,this.frames,l,r.position.sector,e.position.sector,{heading:this.heading});else if(a&&!i&&r!==null&&o){const{exit:c,entry:h}=m9(r.position,e.position);this.srs_draw(r,!1),await ml(n,this.frames,l,r.position.sector,c,{heading:this.heading}),ww(n,!0),this.shown=xw(e),this.srs_draw(this.shown,!1),this.lrs_draw(this.shown,!0),this.chart_draw(this.shown),await this.frames.wait(er.rescan),ww(n,!1),await ml(n,this.frames,l,h,e.position.sector,{heading:this.heading})}this.shown=xw(e),this.srs_draw(this.shown),this.lrs_draw(this.shown,o&&i),this.chart_draw(this.shown);for(const c of BH(t,e))this.hooks.voice.cue(c);this.standingOrder_try()}}}header_draw(e){const{parts:t}=this,i=(o,a)=>{o.replaceChildren();for(const[l,c,h]of a)o.append(q("span","tb-head-label",l),q("span",`tb-head-value${h===void 0?"":` ${h}`}`,c))},n=(o,a)=>`${Math.max(0,Math.min(100,Math.round(100*o/Math.max(1,a))))}`;i(t.ship,[["ENERGY",`${e.ship.energy} / ${e.ship.energyMax}`],["SHIELDS",`${e.ship.shieldsUp?"UP":"DOWN"} · ${e.ship.shield} (${n(e.ship.shield,e.ship.shieldMax)}%)`],["TORPEDOES",`${e.ship.torpedoes} / ${e.ship.torpedoesMax}`],["WARP",`${e.ship.warp.toFixed(1)}${e.ship.cloaked?" · CLOAKED":""}`]]),i(t.mission,[["STARDATE",e.mission.stardate.toFixed(2)],["TIME LEFT",e.mission.timeLeft.toFixed(2)],["KLINGONS",`${e.mission.klingonsLeft} LEFT · ${e.mission.killed} KILLED${e.mission.captives>0?` · ${e.mission.captives} CAPTIVE`:""}`],["STARBASES",e.nearestBase===null?`${e.mission.starbases}`:`${e.mission.starbases} · NEAREST ${e.nearestBase.at.x},${e.nearestBase.at.y}${e.nearestBase.here?" HERE":""}`]]),i(t.position,[["QUADRANT",`${e.position.quadrant.x},${e.position.quadrant.y}`],["SECTOR",`${e.position.sector.x},${e.position.sector.y}`],["CREW",`${e.ship.crew}`],["LIFE SUPPORT",`${e.ship.reserves.toFixed(1)} / ${e.ship.reservesMax.toFixed(1)}`],["SCORE",`${Fx(e).total}`]]);const r=this.previous===null?[]:jx(this.previous,e);i(t.since,r.length===0?[["—","NOTHING MOVED"]]:r.map(o=>[o.label,o.change,o.bad?"tb-bad":"tb-good"]))}srs_draw(e,t=!0){const{parts:i}=this;i.srsTitle.textContent=`SHORT RANGE · QUADRANT ${e.position.quadrant.x},${e.position.quadrant.y}`;const n=i.scan,r=[...n.querySelectorAll(":scope > .tb-motion")];n.replaceChildren();const o=e.sectors[0]?.length??0;for(let c=0;c<o;c++)n.append(this.axis_make(String(c),c+.5,-.3));for(const c of e.sectors)n.append(this.axis_make(String(c[0]?.x??""),-.3,(c[0]?.x??0)+.5));const a=e.position.sector,l=this.pressedSector??a;for(const c of e.sectors)for(const h of c)n.append(this.sector_make(h,e,a,l,t));if(t){const c=IH(e.ship.shield,e.ship.shieldMax,e.ship.shieldsUp,e.condition.name==="DOCKED"),h=rt("circle",{class:c.className,cx:a.y+.5,cy:a.x+.5,r:.46,"stroke-width":c.width});h.dataset.percent=String(Math.round(c.percent)),n.append(h)}n.append(...r)}axis_make(e,t,i){const n=rt("text",{class:"tb-scan-axis",x:t,y:i});return n.textContent=e,n}sector_make(e,t,i,n,r=!0){const o=Jh(i,e),a=Nd(i,e),l=this.pressedSector?.x===e.x&&this.pressedSector.y===e.y,c=rt("g",{class:`tb-sector tb-sector-${e.kind}${l?" tb-pressed":""}`,role:"button",tabindex:n.x===e.x&&n.y===e.y?0:-1});c.dataset.x=String(e.x),c.dataset.y=String(e.y);const h=rt("title",{}),d=e.kind==="empty"?"·":_h[e.kind];if(h.textContent=e.kind==="ship"?`the ship · ${e.x},${e.y}`:`${e.x},${e.y} ${d.trim()===""?"black hole":d} · course ${Math.round(o)}° · ${(a/10).toFixed(1)}`,c.append(h,rt("rect",{class:"tb-cell",x:e.y+.04,y:e.x+.04,width:.92,height:.92,rx:.16})),e.kind==="empty"||e.kind==="ship"&&!r)c.append(rt("circle",{class:"tb-cell-dot",cx:e.y+.5,cy:e.x+.5,r:.03}));else{const p=e.kind,f=p==="klingon"?t.klingons.find(m=>m.x===e.x&&m.y===e.y):void 0,_=p==="ship"?this.heading:p==="klingon"?Jh(e,i):0,g=K_(p,{cx:e.y+.5,cy:e.x+.5,size:z9},f?.mark??null,_);p==="star"&&g.style.setProperty("--tb-breathe",`-${(e.x*7+e.y*3)%11*.33}s`),c.append(g)}const u=()=>this.sector_press(e,o,a);return c.addEventListener("click",u),c.addEventListener("keydown",p=>{(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),u())}),c}scan_key(e){const t=E9[e.key],i=e.target?.closest(".tb-sector")??null;if(t===void 0||i===null)return;const n=Number(i.dataset.x)+t[0],r=Number(i.dataset.y)+t[1],o=this.parts.scan.querySelector(`.tb-sector[data-x="${n}"][data-y="${r}"]`);o!==null&&(e.preventDefault(),i.setAttribute("tabindex","-1"),o.setAttribute("tabindex","0"),o.focus())}sector_press(e,t,i){this.hooks.voice.cue("scanner"),this.course_set(t,Math.round(i)/10),this.parts.computerView.sector_set(e),this.pressedSector={x:e.x,y:e.y};for(const n of this.parts.scan.querySelectorAll(".tb-sector")){const r=n.dataset.x===String(e.x)&&n.dataset.y===String(e.y);n.classList.toggle("tb-pressed",r),n.setAttribute("tabindex",r?"0":"-1")}}device_isOk(e,t){const i=e.devices.find(n=>t.test(n.name));return i===void 0||i.repairAt===null}lrs_draw(e,t=!1){const{parts:i}=this;i.lrs.replaceChildren();const{quadrant:n}=e.position,r=this.lrsBloom;this.lrsBloom=null;for(let o=-1;o<=1;o++)for(let a=-1;a<=1;a++){const l=e.chart[n.x+o]?.[n.y+a];if(l===void 0){const h=q("div","tb-lrs-cell tb-lrs-edge");h.append(q("span","tb-lrs-code","—"),q("span","tb-lrs-at","EDGE")),h.title="outside the galaxy",i.lrs.append(h);continue}const c=q("div",`tb-lrs-cell${l.here?" tb-here":""}${l.klingons>0?" tb-hostile":""}${l.code===null?" tb-unscanned":""}${l.supernova?" tb-supernova":""}`);c.append(jm("tb-lrs-code",l),q("span","tb-lrs-at",`${l.x},${l.y}`)),c.title=Hm(l),c.dataset.x=String(l.x),c.dataset.y=String(l.y),i.lrs.append(c),(t&&l.here||r!==null&&r.at.x===l.x&&r.at.y===l.y)&&M9(c,r!==null&&!l.here&&r.hostile)}}chart_draw(e){const{parts:t}=this;t.chart.replaceChildren();for(const i of e.chart)for(const n of i){const r=jm(`tb-quadrant${n.here?" tb-here":""}${n.klingons>0?" tb-hostile":""}${n.bases>0?" tb-based":""}${n.code===null?" tb-unscanned":""}${n.supernova?" tb-supernova":""}`,n);r.title=Hm(n),t.chart.append(r)}}question_show(e){const{parts:t}=this;if(e?.question==="command"&&(this.plan.clear(),this.computerRunning=!1,this.fold_close(),this.standingOrder_try()))return;const i=e===null?void 0:this.plan.get(e.question);if(i!==void 0&&e!==null&&!this.answering){this.plan.delete(e.question),this.answering=!0;try{this.answer_send(i,null)}finally{this.answering=!1}return}_u(t.shipPills,e);for(const n of[t.helm,t.helmView,t.tactical,t.tacticalView,t.engineeringView,t.computerView])n.question_show(e);e?.question==="distance"&&this.nextDistance!==null&&(t.helm.distance.value_set(this.nextDistance),t.helmView.distance.value_set(this.nextDistance)),this.strip_show(e),this.lit_reveal()}lit_reveal(){const e=[...this.parts.body.querySelectorAll(".tb-lit")].find(t=>t.getClientRects().length>0);e!==void 0&&typeof e.scrollIntoView=="function"&&e.scrollIntoView({block:"nearest"})}strip_show(e){const{parts:t}=this,i=e?.question??null,n=i===null?null:ks(i,this.readout),r=n!==null&&i!==null&&i!=="command"&&(n.kind==="yesno"||n.kind==="text"||A9.includes(i));if(t.ask.hidden=!r,!r||n===null||e===null)return;t.askText.textContent=e.prompt.replace(/[:\s]+$/,"").trim(),t.askPills.replaceChildren();for(const a of n.choices??[])t.askPills.append(ei("tb-choice",a.label,()=>this.answer_send(a.line,a.label)));const o=n.kind==="text"||n.kind==="slider";t.askInput.hidden=!o,t.askSend.hidden=!o,o&&(t.askInput.value="",t.askInput.focus())}standingOrder_try(){if(!this.scanDue||this.answering||this.harness.question_get()?.question!=="command")return!1;this.scanDue=!1;const e=this.readout?.position.quadrant;return this.fold_open(`LONG RANGE SCAN · STANDING ORDER${e===void 0?"":` · QUADRANT ${e.x},${e.y}`}`),this.harness.answer("l")?(this.log_write(`Command: l
|
|
4361
4361
|
`,!0),!0):(this.fold_close(),!1)}fold_open(e){this.frames.push({kind:"fold",run:()=>{const t=q("details","tb-log-fold");t.append(q("summary","tb-log-fold-head",e)),this.parts.log.append(t),this.fold=t}})}fold_close(){this.frames.push({kind:"fold",run:()=>{this.fold=null}})}text_take(e){const t=e.replace(/\x1b\[[0-9;]*m/g,"").replace(/\x07/g,"");this.computerRunning&&this.parts.computerView.answer_take(t);const i=(this.partial+t).split(`
|
|
@@ -4372,7 +4372,7 @@ ${f instanceof Error?f.message:String(f)}`}}if(t!==null)return t.cluster_choose(
|
|
|
4372
4372
|
${c instanceof Error?c.message:String(c)}`}}if(e!==null)return e.open(o),`scripts: the screen is up${o===""?"":`, on ${o}`}`;i=document.title;const a=new i8({run:async l=>{t=!0;try{await s.client.line_execute(l,{operator:!0})}finally{t=!1}},ask:l=>s.client.line_execute(l,{silent:!0,observe:!1}),stop:()=>s.client.stop_send(),leave:n,manage_is:()=>s.manage_is(),elevate_ask:s.elevation_is()?l=>s.elevate_ask(l):null,voice:{pill:l=>Bs.pill_play(l),cue:l=>Bs.cue_play(l)}});return e=a,document.body.append(a.root),document.body.dataset.takeover="script",Bs.preload(),Bs.cue_play("open"),a.open(o),`scripts: the script screen takes the display${o===""?", on the library":` on ${o}`} (Esc or LEAVE gives it back)`},active_is:()=>e!==null,running_is:()=>e!==null&&t,ask:o=>e===null?Promise.resolve(null):e.ask_take(o.message,o.kind),output_take:o=>{e?.output_take(o)},task_ended:()=>{e?.taskEnded_take()},mode_refresh:()=>{e?.mode_refresh()}}}function r8(s){return`${s.date??"undated"} · ${s.entries.map(e=>`${e.package} ${e.version}`).join(" · ")}`}function o8(s,e){return s.releases.map(t=>{const i=t.merge??t.date??"undated",n=[];for(const r of t.entries)r.changes.forEach((o,a)=>{const l=`${i}:${r.package}:${a}`,c=o.body!=="";n.push({key:l,tag:r.package,text:o.headline,body:!1,more:c,internal:o.internal,of:l}),c&&e.has(l)&&n.push({key:`${l}:body`,tag:"",text:o.body,body:!0,more:!1,internal:o.internal,of:l})});return{key:i,title:r8(t),rows:n}})}class a8{constructor(e,t){this.hooks=t;const i=e.querySelector(".notes-panel");if(i===null)throw new Error("notes pane: no .notes-panel in its template");this.state=e.querySelector(".pane-state"),this.sincePill=e.querySelector(".notes-since"),this.internalPill=e.querySelector(".notes-internal"),this.listing=new sr({mount:i,traits:this.traits_declare(),key:n=>n.key,chrome:{root:e,prefix:"notes"},caps:"root",activatable:n=>n.more,activate:n=>this.unfold_toggle(n.of),row:{className:n=>`notes-row${n.body?" notes-row-body":""}${n.internal?" notes-row-internal":""}${n.more?" notes-row-more":""}`}}),this.sincePill?.addEventListener("click",()=>{this.since_cycle()}),this.internalPill?.addEventListener("click",()=>{this.internal_toggle()}),this.pills_paint()}hooks;listing;state;sincePill;internalPill;model=null;unfolded=new Set;ask={since:1,all:!1};traits_declare(){return[{key:"tag",label:"PACKAGE",className:"notes-tag",width:"minmax(5em, 7em)",cell:e=>e.tag},{key:"text",label:"CHANGE",className:"notes-text",width:"minmax(16em, 1fr)",cell:e=>e.more&&!e.body?`${e.text} ▸`:e.text}]}model_show(e){this.model=e,this.ask={since:e.releases.length>1?e.releases.length>=e.total?"all":e.releases.length:1,all:e.all},this.render()}releases_shown(){return this.model?.releases.length??0}unfolded_is(e){return this.unfolded.has(e)}unfold_toggle(e){this.unfolded.has(e)?this.unfolded.delete(e):this.unfolded.add(e),this.render()}async since_cycle(){const e=this.ask.since===1?5:this.ask.since===5?"all":1;await this.ask_again({...this.ask,since:e})}async internal_toggle(){await this.ask_again({...this.ask,all:!this.ask.all})}async ask_again(e){const t=e.since==="all"?"9999":String(e.since),i=await this.hooks.ask(`notes --since ${t}${e.all?" --all":""}`);i!==null&&(this.ask=e,this.model_show(i))}pills_paint(){this.sincePill!==null&&(this.sincePill.textContent=this.ask.since==="all"?"ALL RELEASES":this.ask.since===1?"LATEST RELEASE":`LAST ${this.ask.since} RELEASES`),this.internalPill!==null&&(this.internalPill.textContent=this.ask.all?"INTERNAL ON":"INTERNAL OFF",this.internalPill.classList.toggle("rail-off",!this.ask.all))}render(){const e=this.model;if(e===null)return;const t=n=>{const r=document.createElement("header");return r.className="files-path notes-block-head",r.textContent=n,r},i=o8(e,this.unfolded).map(n=>({key:n.key,header:t(n.title),rows:n.rows}));if(this.listing.rows_set(i,{field:"notes"}),this.state!==null){const n=Object.entries(e.installed).map(([r,o])=>`${r} ${o}`).join(" · ");this.state.textContent=`${e.source.toUpperCase()} · ${n}`}this.pills_paint()}}function l8(s){for(const e of s.envelopes){if(e.model?.kind!==xN)continue;const t=TN.safeParse(e.model.data);if(t.success)return t.data}return null}function c8(s,e){const{layout:t,panels:i,subjects:n}=s,r=async c=>l8(await e.ask(c)),o=c=>{const h=e.template_stamp("tpl-pane-notes");return i.set("notes",c,new a8(h,{ask:r})),{id:c,kind:"notes",mount:h,dispose:()=>{i.delete(c),n.pane_leave(c)}}},a=c=>{r("notes").then(h=>{h!==null&&i.get("notes",c)?.model_show(h)})};return{instance_build:o,open:()=>{const c=i.ids("notes").find(f=>t.panes_shown().includes(f));if(c!==void 0)return t.focus_set(c),a(c),"notes: on stage";const h=e.launcher_active();e.launcher_yield();const d=t.focused_get()??"files",u=e.instance_spawn("notes");return(h?t.leaf_replace("files",u.id):t.leaf_split(d,"col",u.id,!1))?(h?t.focus_set(u.id):e.birth_record(u.id,d,"col",!1),a(u.id),"notes: what the installed releases changed, as a pane (notes in the console prints it)"):(Ds(u.id),t.mount_remove(u.id),"notes: could not open a pane")},latest:()=>r("notes")}}function h8(s){if(s===null)return"REGION";const e=s.indexOf(":");return(e===-1?s:s.slice(e+1)).toUpperCase()}function Bw(s){return s===null?"—":String(s)}function d8(s){const e=new Map;for(const t of s.rows){const i=e.get(t.family)??[];i.push({key:`${t.family}:${t.limit}:${t.zone??"region"}`,family:t.family,limit:t.limit,zone:h8(t.zone),value:t.value,used:t.used,available:t.available}),e.set(t.family,i)}return[...e.entries()].map(([t,i])=>({key:t,title:`${t} · ${s.region}`,rows:i}))}class u8{constructor(e,t){this.hooks=t;const i=e.querySelector(".capacity-panel");if(i===null)throw new Error("capacity pane: no .capacity-panel in its template");this.state=e.querySelector(".pane-state"),this.listing=new sr({mount:i,traits:this.traits_declare(),key:n=>n.key,chrome:{root:e,prefix:"capacity"},caps:"root",activatable:()=>!1,row:{className:n=>`capacity-row${n.available===0?" capacity-row-full":""}`}})}hooks;listing;state;model=null;traits_declare(){return[{key:"family",label:"FAMILY",className:"capacity-family",width:"minmax(4em, 5em)",cell:e=>e.family},{key:"limit",label:"LIMIT",className:"capacity-limit",width:"minmax(10em, 16em)",cell:e=>e.limit},{key:"zone",label:"ZONE",className:"capacity-zone",width:"minmax(8em, 1fr)",cell:e=>e.zone},{key:"used",label:"USED",className:"capacity-num",width:"6em",cell:e=>Bw(e.used),compare:e=>e.used??-1},{key:"available",label:"FREE",className:"capacity-num",width:"6em",cell:e=>Bw(e.available),compare:e=>e.available??-1},{key:"value",label:"OF",className:"capacity-num",width:"6em",cell:e=>String(e.value),compare:e=>e.value}]}model_show(e){this.model=e,this.render()}families_shown(){return this.model===null?[]:[...new Set(this.model.rows.map(e=>e.family))]}async family_ask(e){const t=await this.hooks.ask(e===""?"capacity":`capacity ${e}`);t!==null&&this.model_show(t)}render(){const e=this.model;if(e===null)return;const t=n=>{const r=document.createElement("header");return r.className="files-path capacity-block-head",r.textContent=n,r},i=d8(e).map(n=>({key:n.key,header:t(n.title),rows:n.rows}));this.listing.rows_set(i,{field:"capacity"}),this.state!==null&&(this.state.textContent=`${e.region.toUpperCase()} · ${this.families_shown().join(" · ")||"NO FAMILY"}`)}}function f8(s){for(const e of s.envelopes){if(e.model?.kind!==fz)continue;const t=pz.safeParse(e.model.data);if(t.success)return t.data}return null}function p8(s,e){const{layout:t,panels:i,subjects:n}=s,r=async c=>f8(await e.ask(c)),o=c=>{const h=e.template_stamp("tpl-pane-capacity");return i.set("capacity",c,new u8(h,{ask:r})),{id:c,kind:"capacity",mount:h,dispose:()=>{i.delete(c),n.pane_leave(c)}}},a=(c,h)=>{i.get("capacity",c)?.family_ask(h)};return{instance_build:o,open:c=>{const h=c===""?"every family the region offers":c,d=i.ids("capacity").find(g=>t.panes_shown().includes(g));if(d!==void 0)return t.focus_set(d),a(d,c),`capacity: on stage, reading ${h}`;const u=e.launcher_active();e.launcher_yield();const p=t.focused_get()??"files",f=e.instance_spawn("capacity");return(u?t.leaf_replace("files",f.id):t.leaf_split(p,"col",f.id,!1))?(u?t.focus_set(f.id):e.birth_record(f.id,p,"col",!1),a(f.id,c),`capacity: what the region has free for ${h}, as a pane (capacity in the console prints it)`):(Ds(f.id),t.mount_remove(f.id),"capacity: could not open a pane")}}}function Gw(s){return[...s.querySelectorAll(".mode-frame button")].filter(e=>!e.disabled&&!e.hidden&&e.offsetParent!==null)}function m8(s){return[...s.querySelectorAll(".listing-row")].filter(e=>e.offsetParent!==null)}function g8(s,e,t){if(e===0)return null;switch(t){case"ArrowDown":return s<0?0:Math.min(e-1,s+1);case"ArrowUp":return s<0?e-1:Math.max(0,s-1);case"Home":return 0;case"End":return e-1;default:return null}}function _8(s,e){const{layout:t,panels:i,paneInstance_get:n}=s,r=[()=>e.palette_isOpen()?(e.palette_close(),"claimed"):"passed",()=>s.terminal.ask_abandon()?"claimed":"passed",()=>gx()?"claimed":"passed",()=>e.errand_abandon()?"claimed":"passed",()=>{const f=document.activeElement;return!(f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement)||f.closest(".workspace-pane")===null||f.closest("#terminal")!==null?"passed":(f.blur(),"claimed")},()=>i.values("image").some(f=>f.field_release())?"claimed":"passed",()=>i.values("edit").some(f=>f.field_release())?"claimed":"passed",()=>i.values("games").some(f=>f.field_release())?"claimed":"passed",()=>{if(s.terminal.ask_isOpen())return"passed";let f=!1;for(const _ of i.values("files"))_.select_isOn()&&(_.select_toggle(!1),f=!0);return f?"claimed":"passed"},()=>{const f=e.drawers_close(),_=e.modeFrames_close();return f||_?"claimed":"passed"},()=>document.body.dataset.zoom!==void 0?"yielded":"passed",()=>e.dive_leave()?"claimed":"passed",()=>e.overlay_escape()?"claimed":"passed",()=>{const f=i.entries("dag").find(([,_])=>_.inside_isHeld());return f===void 0?"passed":(f[1].flight_back(()=>{}),"claimed")},()=>{const f=t.focused_get(),_=i.entries("files").filter(([,g])=>g.content_isShown()).sort(([g],[m])=>g===f?-1:m===f?1:0)[0];return _===void 0?"passed":(_[1].listing_restore(),"claimed")},()=>i.values("dag").some(f=>f.nav_pop())?"claimed":"passed"],o=f=>{if(document.body.dataset.zoom!=="launcher")for(const _ of r){const g=_();if(g==="yielded")return;if(g==="claimed"){f.stopImmediatePropagation(),_!==r[0]&&s.sound("audio3");return}}},a=(f,_)=>{const g=()=>{f.preventDefault(),f.stopImmediatePropagation()},m=xG(f.key);if(f.ctrlKey&&!f.metaKey&&!f.altKey&&m!==null){const v=t.focused_get();return v!==null&&e.verbs.resize(v,m,.05),g(),!0}if(f.ctrlKey||f.metaKey||f.altKey)return!1;const w=v=>(e.drawers_close(),v(),g(),!0);if(m!==null)return w(()=>{l(),qz(e.host(),Fi[m].focusWord)!==null&&s.sound("audio3")});switch(f.key){case"o":case"O":{const v=t.panes_shown(),S=v.indexOf(t.focused_get()??""),x=v[(S+(f.key==="o"?1:v.length-1))%v.length];return w(()=>{l(),x!==void 0&&(t.focus_set(x),s.sound("audio3"))})}case"?":return w(()=>s.terminal.line_run("argus keys"));case";":return w(()=>{l(),t.focus_last()!==null&&s.sound("audio3")});case"q":return w(()=>{for(const v of t.panes_shown())e.verbs.bar_note(v,`@${v}`)});case" ":{const v=t.focused_get();return w(()=>{v!==null&&e.verbs.flip(v)})}case"!":{const v=t.focused_get();return w(()=>{v!==null&&t.panes_shown().length>1&&(e.stage_alone(v),e.verbs.bar_note(v,"ALONE ON STAGE"),s.sound("audio3"))})}case"w":return w(()=>e.element_require("gutter-panes").click());case"r":return w(()=>{l();const v=c();v!==null&&h(v)});case"&":return w(()=>s.terminal.line_run("pane close all"));case"[":return w(()=>{const v=document.querySelector(".argus-output");v!==null&&(v.tabIndex=-1,v.focus())})}const y=zn.find(v=>v.key===f.key&&v.selector!==null);if(y===void 0||y.selector===null)return!1;y.move===!0&&_.querySelector('.drawer-mode[data-mode="move"]')?.click();const M=_.querySelector(y.selector);return M===null||M.disabled?y.move===!0&&_.querySelector('.drawer-mode[data-mode="split"]')?.click():M.click(),g(),!0},l=()=>{const f=document.activeElement;f instanceof HTMLElement&&f.closest("#drawer")!==null&&f.blur(),e.console_release()},c=()=>{const f=document.body.dataset.zoom;if(f==="console"||f==="launcher")return null;const _=f!==void 0?f:t.focused_get();if(_===null)return null;const g=n(_)?.mount??null;return g?.closest(".workspace-pane")??g},h=f=>{f.classList.contains("workspace-pane")&&(f.dataset.modes="open");let _=0;const g=()=>{_+=1;const m=document.activeElement;!(m instanceof HTMLButtonElement&&m.closest(".mode-frame")!==null&&f.contains(m))&&(m===null||m===document.body)&&Gw(f)[0]?.focus(),_<30&&window.requestAnimationFrame(g)};return g(),s.sound("audio3"),!0},d=f=>{if(f.ctrlKey||f.metaKey||f.altKey||f.shiftKey)return!1;const _=c();if(_===null)return!1;const g=()=>(f.preventDefault(),f.stopImmediatePropagation(),!0),m=document.activeElement;if(m instanceof HTMLButtonElement&&m.closest(".mode-frame")!==null&&_.contains(m)){const x=Gw(_),b=x.indexOf(m);return f.key==="ArrowLeft"?(m.blur(),g()):f.key==="ArrowDown"||f.key==="ArrowUp"?(x[f.key==="ArrowDown"?Math.min(x.length-1,b+1):Math.max(0,b-1)]?.focus(),g()):!1}if(m!==null&&m!==document.body&&!m.classList.contains("listing-row"))return!1;const w=m8(_);if(w.length===0)return!1;const y=w.findIndex(x=>x.classList.contains("listing-cursor")),M=y>=0?y:w.findIndex(x=>x.classList.contains("listing-indicated"));if(f.key==="ArrowRight")return h(_)&&g();if(f.key==="Enter"){const x=w[M];if(x===void 0)return!1;if(x.classList.contains("listing-indicated")){const b=x.querySelector(".listing-control");b!==null?b.click():x.dispatchEvent(new MouseEvent("dblclick",{bubbles:!0,cancelable:!0}))}else x.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}));return g()}const v=g8(M,w.length,f.key);if(v===null)return!1;for(const x of w)x.classList.remove("listing-cursor");const S=w[v];return S?.classList.add("listing-cursor"),S?.scrollIntoView({block:"nearest"}),g()},u=f=>{const _=document.querySelector(".pane-drawer:not([hidden])")!==null;if(f.key===":"&&_){e.drawers_close(),e.palette_open(),f.preventDefault(),f.stopImmediatePropagation();return}if(!(f.key==="b"&&f.ctrlKey&&!f.altKey&&!f.metaKey))return;if(f.preventDefault(),_){e.drawers_close(),e.palette_open();return}const g=document.body.dataset.zoom,m=g==="console"||g===void 0&&e.consoleFocused(),w=g!==void 0&&g!=="console"?g:t.focused_get()??"files",y=m?e.element_require("console-drawer"):n(w)?.mount?.querySelector(".pane-drawer")??null;y!==null&&(y.hidden=!y.hidden,y.hidden||y.querySelector("button")?.focus(),s.sound("audio3"))},p=f=>{if(f.key==="Escape"){o(f);return}const _=document.querySelector(".pane-drawer:not([hidden])"),g=f.target instanceof HTMLInputElement||f.target instanceof HTMLTextAreaElement||f.target instanceof HTMLElement&&f.target.isContentEditable;_!==null&&!g&&a(f,_)||_===null&&!g&&!e.palette_isOpen()&&d(f)||u(f)};return window.addEventListener("keydown",p,{capture:!0}),()=>window.removeEventListener("keydown",p,{capture:!0})}function b8(s,e){const{layout:t,panels:i,subjects:n}=s,r=(l,c,h)=>{h.addEventListener("click",_=>{_.target instanceof Element&&_.target.closest("button")!==null||(c.hidden=!c.hidden,c.hidden||c.querySelector("button")?.focus(),s.sound("audio3"))});const d=c.querySelector(".drawer-zoom");d!==null&&(d.dataset.pane=l),h.addEventListener("dblclick",_=>{_.target instanceof Element&&_.target.closest("button")!==null||(window.getSelection()?.removeAllRanges(),d?.click())});for(const _ of c.querySelectorAll(".drawer-bind"))_.addEventListener("click",()=>{for(const g of c.querySelectorAll(".drawer-bind"))g.classList.remove("drawer-bind-selected");_.classList.add("drawer-bind-selected"),s.sound("audio3")});const u=[...c.querySelectorAll("[data-split]")],p=_=>SG(_.dataset.split,_.dataset.place)??"right",f=_=>{c.dataset.mode=_;for(const g of c.querySelectorAll(".drawer-mode"))g.classList.toggle("drawer-mode-selected",g.dataset.mode===_);for(const g of u){const m=p(g);g.disabled=_==="move"&&!t.move_possible(l,m);const w=Ri(m);g.title=_==="move"?`this pane moves ${m}${e.verbs.chordKeys_format(w,!0)}`:`new pane opens ${m}${e.verbs.chordKeys_format(w,!1)}`}};for(const _ of c.querySelectorAll(".drawer-mode"))_.addEventListener("click",()=>{const g=_.dataset.mode==="move"?"move":"split";f(g==="move"&&c.dataset.mode==="move"?"split":g),s.sound("audio3")});for(const _ of u)_.addEventListener("click",()=>{if(c.dataset.mode==="move"){e.verbs.move(l,p(_)),f("split"),c.hidden=!0;return}const g=_.dataset.split==="row"?"row":"col",m=_.dataset.place==="before",w=c.querySelector(".drawer-bind-selected")?.dataset.bind??"unlinked",y=w==="viewer"?"view":w==="fs"?"fs":"empty";e.pillPane_spawn(l,y,g,m)!==null&&(c.hidden=!0,s.sound("audio3"))});for(const _ of new Set(zn.filter(g=>g.selector!==null&&g.move!==!0).map(g=>g.selector??""))){const g=c.querySelector(_);g!==null&&!g.title.includes("[keys ")&&(g.title=`${g.title}${e.verbs.chordKeys_format(_,!1)}`)}c.querySelector(".drawer-close")?.addEventListener("click",()=>{if(l==="dag"){e.dag_dismiss(),e.home_apply();return}t.leaf_close(l)||e.home_apply(),e.orphans_dispose(),s.sound("audio3")})},o=(l,c,h)=>{const{browser:d}=e,u=c.querySelector(".drawer-binding");if(u!==null){const g=document.createElement("span");g.className="drawer-label drawer-label-cwd",g.textContent="CWD",u.appendChild(g);const m=(w,y,M)=>{const v=document.createElement("button");v.className="pacs-capsule drawer-cwdbind",v.dataset.follow=y?"on":"off",v.textContent=w,v.title=M,v.addEventListener("click",()=>{d.follows(l)!==y&&d.follow_set(l,y),s.sound("audio3")}),u.appendChild(v)};m("FOLLOW CWD",!0,"bind this browser to the session cwd (the console's browser)"),m("ROOT HERE",!1,"unbind from the cwd: this browser keeps its own place"),d.cwdBind_sync_register(l,()=>{const w=d.follows(l);for(const y of u.querySelectorAll(".drawer-cwdbind"))y.classList.toggle("drawer-bind-selected",y.dataset.follow==="on"===w)}),d.cwdBind_sync(l)}const p=()=>i.get("files",l);h.querySelector(".files-home")?.addEventListener("click",()=>{if(d.follows(l)){s.terminal.line_run("cd ~");return}const g=p();g!==void 0&&d.rooted_walk(l,g,"~")}),h.querySelector(".files-back")?.addEventListener("click",()=>{if(d.follows(l)){s.terminal.line_run("cd -");return}const g=p();g!==void 0&&d.rooted_back(l,g)});const f=()=>p()?.path_current()??null;h.querySelector(".files-mkdir")?.addEventListener("click",()=>{const g=f();g!==null&&d.directory_make(l,g)}),h.querySelector(".files-refresh")?.addEventListener("click",()=>{const g=f();g!==null&&d.listing_refresh(l,g)});const _=h.querySelector(".files-upload-input");h.querySelector(".files-upload")?.addEventListener("click",()=>{f()!==null&&_?.click()}),_?.addEventListener("change",()=>{const g=f(),m=_.files;g===null||m===null||m.length===0||(d.files_deliver(l,g,Array.from(m)),_.value="")})},a=(l,c)=>{const h=d=>d.modelKind==="fs.file"?d.address.replace(/\/[^/]*$/,"")||"/":d.address;c("ENTER NODE","move the session into the indicated node (its data directory)",()=>{const d=n.regard_get(l),u=i.get("dag",l)?.feed_get()??null,p=d===null?u===null?null:`/proc/jobs/feed_${u}`:h(d);p!==null&&s.terminal.line_run(`cd "${p}"`)}),c("PROCESS NODE","run an executable on the indicated node's output (a catalogue opens beside)",()=>{const d=n.regard_get(l),u=i.get("dag",l)?.feed_get()??null;if(d===null||u===null)return;const p=h(d),f=Fm(p)??(/_(\d+)\/?$/.exec(p)===null?null:parseInt(/_(\d+)\/?$/.exec(p)?.[1]??"",10));f!==null&&e.process_open(l,{input:p.replace(/\/data\/?$/,"")+"/data",feed:u,node:f})}),c("ENTER FEED","move the session into the feed on stage (or the one picked in the roster)",()=>{const d=i.get("dag",l)?.feed_get()??null;d!==null&&s.terminal.line_run(`cd "/proc/jobs/feed_${d}"`)}),c("BACK","return to the previous listing inside the node",()=>e.overlay_back(l)),c("CLEAR DETAIL","dismiss the node facts (a click on empty space does too)",()=>{i.get("dag",l)?.detail_clear()}),c("REFRESH","revisit the feed now (a watch keeps sampling it while it runs)",()=>{i.get("dag",l)?.refresh()})};return(l,c,h)=>{const d=h.querySelector(".pane-drawer"),u=h.querySelector(".pane-handle");if(d===null||u===null)return;r(l,d,u);const p=d.querySelector(".drawer-children");if(p===null)return;const f=(_,g,m)=>{const w=document.createElement("button");w.className="pacs-capsule drawer-child",w.textContent=_,w.title=g,w.addEventListener("click",()=>{m(),d.hidden=!0,s.sound("audio3")}),p.appendChild(w)};(c==="files"||c==="catalogue")&&o(l,d,h),c==="dag"&&a(l,f)}}async function M8(s,e){if(!Pa(window.location.search))return`${s}: this page did not come through a porter, so there is no other session to switch to`;const t=Hl(window.location.pathname,"switch");let i;try{i=await(await fetch(t,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(s==="stratus"?{to:s,cloud:"oci",spend:e}:{to:s})})).json()}catch(r){return`${s}: the porter did not answer (${r instanceof Error?r.message:String(r)})`}if(i.error!==void 0||i.key===void 0)return`${s}: ${i.error??"the porter refused"}`;const n=t.slice(0,-6);return window.location.assign(i.state==="starting"?`${n}greet/${i.key}`:`${n}s/${i.key}/?door`),s==="stratus"?`switching to your stratus session${e?" (to manage: build, tear down, spend)":" (to read)"}…`:"switching to your ChRIS session…"}function v8(s,e){const{layout:t,panels:i,paneInstance_get:n,subjects:r}=s,o=d=>n(d)?.kind??null,a=(d,u)=>{const p=new Set(t.panes_shown()),f=r.group_resolve(u),_=i.entries(d).filter(([g])=>p.has(g));return i.get(d,u)??_.find(([g])=>r.group_resolve(g)===f)?.[1]??(_.length===1?_[0]?.[1]:void 0)},l=async(d,u,p)=>{if(u==="state"){const f=d.state_get();if(f===null)return"image state: no image on the field";const _=(f.viewports??[]).map(g=>`${g.id.replace(/^.*-/,"")} scale=${g.scale.toFixed(3)} focus=${g.focus.map(m=>m.toFixed(2)).join(",")} voi=${g.voi===null?"-":`${g.voi.lower.toFixed(1)}..${g.voi.upper.toFixed(1)}`}`).join(" | ");return`image: layout=${f.layout} tool=${f.tool} primary=${f.primaryTool??"-"} slice=${f.slice}/${f.slices} refused=${f.refused} annotations=${f.annotations} filled=${f.filled}
|
|
4373
4373
|
viewports: ${_||"(none)"}`}if(u==="layout"){const f=p[0]??"";return n7.includes(f)?await d.layout_set(f)?`image layout ${f}`:d.state_get()?.waiting===f?`image layout ${f}: waiting for LOAD`:`image layout ${f}: not offered`:"image layout single|mpr|3d|slab"}if(u==="slice"){const f=Number(p[0]);return!Number.isInteger(f)||f<1?"image slice <n>":d.slice_set(f)?`image slice ${f}`:`image slice ${f}: not offered`}if(u==="series"){const f=Number(p[0]),_=d.siblings_get();if(_.length===0)return"image series: this pane holds one series, not a study";const g=_[f-1];if(g===void 0)return`image series <1..${_.length}>: ${_.map((w,y)=>`${y+1} ${w.label}`).join(" · ")}`;const m=await e.series_ask(g.path);return m===null?`image series ${f}: ${g.path}: not a readable DICOM series`:(d.series_show(m,{siblings:[..._]}),`image series ${f} ${g.label}`)}if(u==="wl"){if((p[0]??"").toLowerCase()==="preset"){const g=p[1]??"";return g===""?"image wl preset <brain|bone|lung|soft|liver>":d.wlPreset_set(g)?`image wl preset ${g}`:`image wl preset ${g}: none for this modality`}const f=Number(p[0]),_=Number(p[1]);return!Number.isFinite(f)||!Number.isFinite(_)||f>=_?"image wl <lower> <upper> | image wl preset <name>":d.wl_set(f,_)?`image wl ${f} ${_}`:"image wl: not offered"}if(u==="colormap"){const f=(p[0]??"").toLowerCase();return Ch.includes(f)?d.colormap_set(f)?`image colormap ${f}`:`image colormap ${f}: not offered`:"image colormap gray|hot|jet|cool"}if(u==="save")return await d.annotations_save()?"image save":"image save: nothing saved (the console says why)";if(u==="load")return await d.load_press()?"image load":"image load: nothing was waiting";if(u==="guard"){if((p[0]??"").toLowerCase()==="off")return d.guard_set(null),"image guard off";const _=Number(p[0]);return!Number.isFinite(_)||_<0?`image guard <bytes>|off (now ${d.guard_get()===null?"off":d.guard_get()})`:(d.guard_set(_),`image guard ${_}`)}if(u==="ghost"){const _=(p[0]??"").toLowerCase()==="off"?null:Number(p[0]);return _!==null&&(!Number.isFinite(_)||_<0||_>1)?"image ghost <0..1>|off (SLAB layout)":d.ghost_set(_)?`image ghost ${_===null?"off":_}`:"image ghost: SLAB layout only"}if(u==="tags"){const f=i.idOf("image",d);return f===null?"image tags: no image pane":e.tagsPane_open(f)}return"image <path> · layout single|mpr|3d · slice <n> · series <n> · wl <lo> <hi> | wl preset <name> · colormap <name> · save"},c=(d,u,p)=>{if(u==="redact"){const f=(p[0]??"").toLowerCase();return f!=="on"&&f!=="off"?"tags redact on|off":(d.redact_set(f==="on"),`tags redact ${f}`)}if(u==="filter"){const f=p.join(" ");return f===""||f.toLowerCase()==="off"?(d.filter_set(null),"tags filter off"):(d.filter_set(f),`tags filter ${f}`)}return"tags redact on|off · filter <text>|off"},h=()=>{const d=t.tree_get();if(d===null)return"# empty desktop";const u=[],p=v=>"pane"in v?v.pane:p(v.first),f=p(d),_=o(f);u.push(`view ${_==="dag"?"runs":_==="pacs"?"pacs":"files"}`);let g=1;const m=(v,S)=>{const x=o(v);x==="dag"&&v!==f&&u.push(`pane %${S} claim runs`),x==="files"&&v!==f&&r.group_resolve(v)===v&&u.push(`pane %${S} claim files`);const b=x==="files"?i.get("files",v)?.path_current()??null:null;b!==null&&u.push(`file %${S} open ${b}`);const z=x==="dag"?i.get("dag",v):void 0;if(z!==void 0&&z.graph_isShown())for(const T of z.view_lines())u.push(T.replace(/^dag /,`dag %${S} `));else if(x==="dag"){const T=n(v)?.mount,A=T?.querySelector(".dag-strategy")?.textContent?.toLowerCase()??"ranked",E=T?.querySelector(".dag-projection")?.textContent?.toLowerCase()??"3d",O=T?.querySelector(".dag-hue")?.textContent?.toLowerCase()??"status";A!=="ranked"&&u.push(`dag %${S} layout ${A}`),E!=="3d"&&u.push(`dag %${S} projection ${E}`),O!=="status"&&u.push(`dag %${S} hue ${O}`)}},w=(v,S)=>{if("pane"in v){m(v.pane,S);return}const x=p(v.second),b=o(x),z=b==="view"?"viewer":b==="files"&&r.group_resolve(x)!==x?"fs":"unlinked";u.push(`pane %${S} bind ${z}`),u.push(`pane %${S} split ${v.dir==="col"?"right":"below"}`);const T=++g;w(v.first,S),w(v.second,T)};w(d,g);const y=document.body.dataset.header;return y!==void 0&&u.push(`header ${y}`),document.getElementById("drawer")?.classList.contains("drawer-closed")&&u.push("console close"),u.join(`
|
|
4374
4374
|
`)};return{focused_get:()=>{const d=document.body.dataset.zoom;return d!==void 0&&d!=="console"?d:t.focused_get()??t.panes_shown()[0]??null},focus_set:d=>n(d)===void 0?!1:(t.focus_set(d),!0),panes_shown:()=>t.panes_shown(),pane_move:e.verbs.move,pane_flip:e.verbs.flip,pane_resize:e.verbs.resize,help_open:e.help_open,notes_open:e.notes_open,capacity_open:e.capacity_open,focus_last:()=>{const d=t.focus_last();return d!==null&&s.sound("audio3"),d===null?null:`focused ${d}`},paneRect_get:d=>document.querySelector(`.layout-leaf[data-leaf="${d}"]`)?.getBoundingClientRect()??null,paneMount_get:d=>n(d)?.mount??null,paneKind_get:o,paneLinked_get:d=>r.group_resolve(d)!==d,feed_enter:e.feed_enter,consoleZoom_toggle:e.consoleZoom_toggle,launcher_enter:e.launcher_enter,trek_open:e.trek_open,manage_is:e.manage_is,elevate_ask:e.elevate_ask,session_switch:M8,stage_keep:e.stage_keep,viewModes_hold:a5,identity_get:e.identity_get,dag_jump:(d,u,p=!1)=>{const f=i.get("dag",d)??i.values("dag")[0];return f===void 0?!1:(f.target_jumpTo(u,p),!0)},node_immerse:d=>{const p=r.regard_get(d)?.address.match(/_(\d+)(?:\/data)?\/?$/)??null;return p===null?!1:i.get("dag",d)?.node_flyTo(parseInt(p[1]??"",10))??!1},files_open:e.files_open,file_download:d=>{const u=r.regard_get(d);return u===null||u.modelKind!=="fs.file"?!1:(e.file_save(u.address),!0)},image_open:(d,u,p)=>e.image_open(d,u,p??{}),image_control:async(d,u,p)=>{const f=a("image",d);return f===void 0?`image ${u}: no image pane on stage for '${d}'`:l(f,u,p)},universe_control:(d,u,p)=>{const f=new Set(t.panes_shown()),_=(d!==null?i.get("universe",d):void 0)??i.entries("universe").find(([g])=>f.has(g))?.[1];return _===void 0?"universe: no universe pane on stage (press the dashboard tile)":_.control(u,p)},tags_control:(d,u,p)=>{const f=a("tags",d);return f===void 0?`tags ${u}: no tags pane on stage for '${d}'`:c(f,u,p)},file_delete:d=>{const u=r.regard_get(d);return u===null||u.modelKind!=="fs.file"?!1:(s.terminal.line_run(`rm "${u.address}"`),!0)},session_run:async d=>{try{return(await s.client.line_execute(d,{silent:!0,observe:!1})).envelopes.map(p=>p.renderedErr??p.rendered).join(`
|
|
4375
|
-
`)}catch(u){return u instanceof Error?u.message:String(u)}},desktop_serialize:h}}function w8(s,e,t){if(t===!0)return"daemon-older";if(e===void 0)return null;const i=e.surface;return t===!1?i!==void 0&&s.built<i.built?"argus-older":null:i===void 0?"daemon-older":i.git===s.git&&i.built===s.built?null:s.built>=i.built?"daemon-older":"argus-older"}const J_={"daemon-older":{readout:"CALYPSO DAEMON OUT OF DATE",before:"The calypso daemon has been updated and should be restarted; some controls may not work until then. ",cure:"Restart the calypso daemon",after:"."},"argus-older":{readout:"ARGUS OUT OF DATE",before:"ARGUS is older than the calypso daemon. ",cure:"Refresh",after:" to load the new ARGUS."}};function Jx(s){const e=J_[s];return`${e.before}${e.cure}${e.after}`}async function y8(s){try{const e=s??(typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0);if(e===void 0)return null;const t=await e("notes.json",{cache:"no-store"});if(!t.ok)return null;const i=await t.json(),r=i.releases?.[0]?.changes?.find(o=>o.internal!==!0)?.headline;return typeof r!="string"||typeof i.version!="string"?null:{version:i.version,headline:r}}catch{return null}}const Pw=96;function S8(s){const e=s.headline.length>Pw?`${s.headline.slice(0,Pw-1).trimEnd()}…`:s.headline;return`argus ${s.version} · ${e} — WHAT'S NEW after restart`}function z8(s,e,t,i,n=document.body,r){n.querySelector(".build-mismatch")?.remove();const o=t.surface!==void 0?`ARGUS ${t.surface.git} built ${t.surface.built}Z`:"an ARGUS too old to say its build";i(`argus: ${Jx(s)}`);const a=t.surface!==void 0&&t.surface.git===e.git&&t.surface.built===e.built;i(a?`argus: the calypso daemon's own code on disk has changed since it started (ARGUS ${e.git} built ${e.built}Z)`:`argus: ARGUS ${e.git} built ${e.built}Z · calypso daemon started with ${o}`);const l=J_[s],c=document.createElement("div");c.className="stale-page build-mismatch",c.dataset.mismatch=s,c.setAttribute("role","alert");const h=document.createElement("span");h.className="stale-page-words";let d=document.createTextNode(l.cure);if(s==="argus-older"){const p=document.createElement("button");p.type="button",p.className="stale-page-reload",p.textContent=l.cure,p.title="reload this tab to load the new ARGUS",p.addEventListener("click",()=>{window.location.reload()}),d=p}else if(r!==void 0){const p=document.createElement("button");p.type="button",p.className="stale-page-reload build-mismatch-restart",p.textContent=l.cure,p.title="restart the calypso daemon (asks first; you stay logged in)",p.addEventListener("click",r),d=p}h.append(document.createTextNode(l.before),d,document.createTextNode(l.after));const u=document.createElement("button");u.type="button",u.className="build-mismatch-dismiss",u.textContent="×",u.title="dismiss (the status strip keeps saying it)",u.addEventListener("click",()=>{c.remove()}),c.append(h,u),n.appendChild(c),s==="daemon-older"&&y8().then(p=>{if(p===null||!c.isConnected)return;const f=document.createElement("span");f.className="build-mismatch-news",f.textContent=S8(p),h.appendChild(f)})}function x8(s,e,t,i=document.body){const n={git:"
|
|
4375
|
+
`)}catch(u){return u instanceof Error?u.message:String(u)}},desktop_serialize:h}}function w8(s,e,t){if(t===!0)return"daemon-older";if(e===void 0)return null;const i=e.surface;return t===!1?i!==void 0&&s.built<i.built?"argus-older":null:i===void 0?"daemon-older":i.git===s.git&&i.built===s.built?null:s.built>=i.built?"daemon-older":"argus-older"}const J_={"daemon-older":{readout:"CALYPSO DAEMON OUT OF DATE",before:"The calypso daemon has been updated and should be restarted; some controls may not work until then. ",cure:"Restart the calypso daemon",after:"."},"argus-older":{readout:"ARGUS OUT OF DATE",before:"ARGUS is older than the calypso daemon. ",cure:"Refresh",after:" to load the new ARGUS."}};function Jx(s){const e=J_[s];return`${e.before}${e.cure}${e.after}`}async function y8(s){try{const e=s??(typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0);if(e===void 0)return null;const t=await e("notes.json",{cache:"no-store"});if(!t.ok)return null;const i=await t.json(),r=i.releases?.[0]?.changes?.find(o=>o.internal!==!0)?.headline;return typeof r!="string"||typeof i.version!="string"?null:{version:i.version,headline:r}}catch{return null}}const Pw=96;function S8(s){const e=s.headline.length>Pw?`${s.headline.slice(0,Pw-1).trimEnd()}…`:s.headline;return`argus ${s.version} · ${e} — WHAT'S NEW after restart`}function z8(s,e,t,i,n=document.body,r){n.querySelector(".build-mismatch")?.remove();const o=t.surface!==void 0?`ARGUS ${t.surface.git} built ${t.surface.built}Z`:"an ARGUS too old to say its build";i(`argus: ${Jx(s)}`);const a=t.surface!==void 0&&t.surface.git===e.git&&t.surface.built===e.built;i(a?`argus: the calypso daemon's own code on disk has changed since it started (ARGUS ${e.git} built ${e.built}Z)`:`argus: ARGUS ${e.git} built ${e.built}Z · calypso daemon started with ${o}`);const l=J_[s],c=document.createElement("div");c.className="stale-page build-mismatch",c.dataset.mismatch=s,c.setAttribute("role","alert");const h=document.createElement("span");h.className="stale-page-words";let d=document.createTextNode(l.cure);if(s==="argus-older"){const p=document.createElement("button");p.type="button",p.className="stale-page-reload",p.textContent=l.cure,p.title="reload this tab to load the new ARGUS",p.addEventListener("click",()=>{window.location.reload()}),d=p}else if(r!==void 0){const p=document.createElement("button");p.type="button",p.className="stale-page-reload build-mismatch-restart",p.textContent=l.cure,p.title="restart the calypso daemon (asks first; you stay logged in)",p.addEventListener("click",r),d=p}h.append(document.createTextNode(l.before),d,document.createTextNode(l.after));const u=document.createElement("button");u.type="button",u.className="build-mismatch-dismiss",u.textContent="×",u.title="dismiss (the status strip keeps saying it)",u.addEventListener("click",()=>{c.remove()}),c.append(h,u),n.appendChild(c),s==="daemon-older"&&y8().then(p=>{if(p===null||!c.isConnected)return;const f=document.createElement("span");f.className="build-mismatch-news",f.textContent=S8(p),h.appendChild(f)})}function x8(s,e,t,i=document.body){const n={git:"4fe3a4c7",built:"2026-11-02 21:52"};let r=[],o,a=null;const l=h=>{r!==null?r.push(h):e(h)},c=h=>{if(o===void 0)return;const d=w8(n,o,h);if(d!==a){if(a=d,d===null){s.build_show(null),i.querySelector(".build-mismatch")?.remove();return}s.build_show(J_[d].readout,Jx(d)),z8(d,n,o,l,i,Pa(window.location.search)?t:void 0)}};return{attach_take:h=>{o=h.stack,c(h.stale)},stale_take:h=>c(h),release:()=>{const h=r??[];r=null;for(const d of h)e(d)}}}function O8(s=document.getElementById("door-pill")){s===null||!Pa(window.location.search)||(s.hidden=!1,s.addEventListener("click",()=>{const e=Hl(window.location.pathname,"logout"),t=Hl(window.location.pathname,"login");fetch(e,{method:"POST",headers:{accept:"application/json"}}).catch(()=>{}).then(()=>{window.location.assign(t)})}))}const E8="Restart the calypso daemon? You'll stay logged in; the page reloads when the new daemon is up.";function A8(s){const e=[];s.running!==null&&e.push(`the running command: ${s.running}`);for(const r of s.joblets??[])e.push(`joblet %${r.number}: ${r.line} (ended; its log is kept)`);for(const r of s.unsaved)e.push(`an unsaved edit in ${r}`);const t=s.others.filter(r=>r.kind==="browser").length,i=s.others.length-t,n=[];return t>0&&n.push(t===1?"1 other browser":`${t} other browsers`),i>0&&n.push(i===1?"1 chell":`${i} chells`),n.length>0&&e.push(`${n.join(" and ")}, which will be disconnected`),e}function T8(s){return s==="restart"?"The calypso daemon is restarting (asked from another browser or surface). Following it…":s==="end"?"The calypso daemon was ended by an administrator.":"The calypso daemon stopped."}function D8(s,e){const t=document.createElement("div");t.className="stale-page restart-question",t.setAttribute("role","alertdialog");const i=document.createElement("div");i.className="stale-page-words";const n=document.createElement("div");if(n.textContent=E8,i.append(n),s.length>0){const h=document.createElement("ul");h.className="restart-cuts";const d=document.createElement("li");d.className="restart-cuts-lead",d.textContent="This will cut off:",h.append(d);for(const u of s){const p=document.createElement("li");p.textContent=u,h.append(p)}i.append(h)}const r=document.createElement("button");r.type="button",r.className="restart-yes",r.textContent="YES";const o=document.createElement("button");o.type="button",o.className="restart-no",o.textContent="NO";let a=!1;const l=h=>{a||(a=!0,t.remove(),e(h))};r.addEventListener("click",()=>l(!0)),o.addEventListener("click",()=>l(!1)),t.addEventListener("keydown",h=>{h.key!=="Enter"&&h.key!=="Escape"||(h.preventDefault(),h.stopPropagation(),l(h.key==="Enter"))});const c=document.createElement("div");return c.className="restart-answers",c.append(r,o),t.append(i,c),t}function I8(s,e=document.body){const t=Pa(window.location.search);let i=null,n=null,r=[],o=[],a=!1;const l=p=>{e.querySelector(".restart-said")?.remove();const f=document.createElement("div");f.className="stale-page restart-said",f.setAttribute("role","alert"),f.textContent=p,e.appendChild(f)},c=p=>{window.location.assign(`${Hl(window.location.pathname,"greet")}/${encodeURIComponent(p)}`)},h=async()=>{a=!0,l("Restarting the calypso daemon…");try{const p=await fetch(Hl(window.location.pathname,"restart"),{method:"POST",headers:{accept:"application/json"}}),f=await p.json();if(!p.ok||f.key===void 0)throw new Error(f.error??`the door answered ${p.status}`);c(f.key)}catch(p){a=!1,l(`The calypso daemon could not be restarted: ${p instanceof Error?p.message:String(p)}`)}},d=()=>{if(!t||e.querySelector(".restart-question")!==null)return;const p={running:n,unsaved:s.unsaved(),others:o.filter(_=>_.id!==i),joblets:r},f=D8(A8(p),_=>{_&&h()});e.querySelector(".build-mismatch")?.remove(),e.appendChild(f),f.querySelector(".restart-yes")?.focus()},u=document.getElementById("restart-pill");return u!==null&&t&&(u.hidden=!1,u.addEventListener("click",d)),{ask:d,attach_take:p=>{i=p.surface??null},telemetry_take:p=>{p?.lane!==void 0&&(n=p.lane.running?.line??null),p?.lane?.joblets!==void 0&&(r=p.lane.joblets),p?.surfaces!==void 0&&(o=p.surfaces)},closing_take:p=>{if(a||(l(T8(p)),p!=="restart"||!t))return;const f=window.location.pathname.split("/").filter(_=>_.length>0).at(-1);f!==void 0&&setTimeout(()=>c(f),1200)}}}function C8(s,e,t,i){s.line_execute(`motd ${t}`,{silent:!0,observe:!1}).then(n=>{const r=n.envelopes.filter(o=>o.status==="ok").map(o=>o.rendered).join("").trimEnd();r.length>0&&e.greeting_write(r.split(`
|
|
4376
4376
|
`))}).catch(()=>{}).finally(i)}var Qx=Object.defineProperty,R8=Object.getOwnPropertyDescriptor,k8=(s,e)=>{for(var t in e)Qx(s,t,{get:e[t],enumerable:!0})},as=(s,e,t,i)=>{for(var n=i>1?void 0:i?R8(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Qx(e,t,n),n},Ie=(s,e)=>(t,i)=>e(t,i,s),Lw="Terminal input",qm={get:()=>Lw,set:s=>Lw=s},Ww="Too much output to announce, navigate to rows manually to read",Km={get:()=>Ww,set:s=>Ww=s};function N8(s){return s.replace(/\r?\n/g,"\r")}function B8(s,e){return e?"\x1B[200~"+s+"\x1B[201~":s}function G8(s,e){s.clipboardData&&s.clipboardData.setData("text/plain",e.selectionText),s.preventDefault()}function P8(s,e,t,i){if(s.stopPropagation(),s.clipboardData){let n=s.clipboardData.getData("text/plain");eO(n,e,t,i)}}function eO(s,e,t,i){s=N8(s),s=B8(s,t.decPrivateModes.bracketedPasteMode&&i.rawOptions.ignoreBracketedPasteMode!==!0),t.triggerDataEvent(s,!0),e.value=""}function tO(s,e,t){let i=t.getBoundingClientRect(),n=s.clientX-i.left-10,r=s.clientY-i.top-10;e.style.width="20px",e.style.height="20px",e.style.left=`${n}px`,e.style.top=`${r}px`,e.style.zIndex="1000",e.focus()}function Fw(s,e,t,i,n){tO(s,e,t),n&&i.rightClickSelect(s),e.value=i.selectionText,e.select()}function xr(s){return s>65535?(s-=65536,String.fromCharCode((s>>10)+55296)+String.fromCharCode(s%1024+56320)):String.fromCharCode(s)}function bu(s,e=0,t=s.length){let i="";for(let n=e;n<t;++n){let r=s[n];r>65535?(r-=65536,i+=String.fromCharCode((r>>10)+55296)+String.fromCharCode(r%1024+56320)):i+=String.fromCharCode(r)}return i}var L8=class{constructor(){this._interim=0}clear(){this._interim=0}decode(s,e){let t=s.length;if(!t)return 0;let i=0,n=0;if(this._interim){let r=s.charCodeAt(n++);56320<=r&&r<=57343?e[i++]=(this._interim-55296)*1024+r-56320+65536:(e[i++]=this._interim,e[i++]=r),this._interim=0}for(let r=n;r<t;++r){let o=s.charCodeAt(r);if(55296<=o&&o<=56319){if(++r>=t)return this._interim=o,i;let a=s.charCodeAt(r);56320<=a&&a<=57343?e[i++]=(o-55296)*1024+a-56320+65536:(e[i++]=o,e[i++]=a);continue}o!==65279&&(e[i++]=o)}return i}},W8=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(s,e){let t=s.length;if(!t)return 0;let i=0,n,r,o,a,l=0,c=0;if(this.interim[0]){let u=!1,p=this.interim[0];p&=(p&224)===192?31:(p&240)===224?15:7;let f=0,_;for(;(_=this.interim[++f]&63)&&f<4;)p<<=6,p|=_;let g=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,m=g-f;for(;c<m;){if(c>=t)return 0;if(_=s[c++],(_&192)!==128){c--,u=!0;break}else this.interim[f++]=_,p<<=6,p|=_&63}u||(g===2?p<128?c--:e[i++]=p:g===3?p<2048||p>=55296&&p<=57343||p===65279||(e[i++]=p):p<65536||p>1114111||(e[i++]=p)),this.interim.fill(0)}let h=t-4,d=c;for(;d<t;){for(;d<h&&!((n=s[d])&128)&&!((r=s[d+1])&128)&&!((o=s[d+2])&128)&&!((a=s[d+3])&128);)e[i++]=n,e[i++]=r,e[i++]=o,e[i++]=a,d+=4;if(n=s[d++],n<128)e[i++]=n;else if((n&224)===192){if(d>=t)return this.interim[0]=n,i;if(r=s[d++],(r&192)!==128){d--;continue}if(l=(n&31)<<6|r&63,l<128){d--;continue}e[i++]=l}else if((n&240)===224){if(d>=t)return this.interim[0]=n,i;if(r=s[d++],(r&192)!==128){d--;continue}if(d>=t)return this.interim[0]=n,this.interim[1]=r,i;if(o=s[d++],(o&192)!==128){d--;continue}if(l=(n&15)<<12|(r&63)<<6|o&63,l<2048||l>=55296&&l<=57343||l===65279)continue;e[i++]=l}else if((n&248)===240){if(d>=t)return this.interim[0]=n,i;if(r=s[d++],(r&192)!==128){d--;continue}if(d>=t)return this.interim[0]=n,this.interim[1]=r,i;if(o=s[d++],(o&192)!==128){d--;continue}if(d>=t)return this.interim[0]=n,this.interim[1]=r,this.interim[2]=o,i;if(a=s[d++],(a&192)!==128){d--;continue}if(l=(n&7)<<18|(r&63)<<12|(o&63)<<6|a&63,l<65536||l>1114111)continue;e[i++]=l}}return i}},sO="",Ir=" ",dc=class iO{constructor(){this.fg=0,this.bg=0,this.extended=new Gd}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 iO;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}},Gd=class nO{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}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 nO(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Ui=class rO extends dc{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Gd,this.combinedData=""}static fromCharData(e){let t=new rO;return t.setFromCharData(e),t}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?xr(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 t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let i=e[1].charCodeAt(0);if(55296<=i&&i<=56319){let n=e[1].charCodeAt(1);56320<=n&&n<=57343?this.content=(i-55296)*1024+n-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Uw="di$target",Ym="di$dependencies",Vf=new Map;function F8(s){return s[Ym]||[]}function Is(s){if(Vf.has(s))return Vf.get(s);let e=function(t,i,n){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");U8(e,t,n)};return e._id=s,Vf.set(s,e),e}function U8(s,e,t){e[Uw]===e?e[Ym].push({id:s,index:t}):(e[Ym]=[{id:s,index:t}],e[Uw]=e)}var si=Is("BufferService"),oO=Is("CoreMouseService"),No=Is("CoreService"),$8=Is("CharsetService"),Q_=Is("InstantiationService"),aO=Is("LogService"),ii=Is("OptionsService"),lO=Is("OscLinkService"),j8=Is("UnicodeService"),uc=Is("DecorationService"),Xm=class{constructor(s,e,t){this._bufferService=s,this._optionsService=e,this._oscLinkService=t}provideLinks(s,e){let t=this._bufferService.buffer.lines.get(s-1);if(!t){e(void 0);return}let i=[],n=this._optionsService.rawOptions.linkHandler,r=new Ui,o=t.getTrimmedLength(),a=-1,l=-1,c=!1;for(let h=0;h<o;h++)if(!(l===-1&&!t.hasContent(h))){if(t.loadCell(h,r),r.hasExtendedAttrs()&&r.extended.urlId)if(l===-1){l=h,a=r.extended.urlId;continue}else c=r.extended.urlId!==a;else l!==-1&&(c=!0);if(c||l!==-1&&h===o-1){let d=this._oscLinkService.getLinkData(a)?.uri;if(d){let u={start:{x:l+1,y:s},end:{x:h+(!c&&h===o-1?1:0),y:s}},p=!1;if(!n?.allowNonHttpProtocols)try{let f=new URL(d);["http:","https:"].includes(f.protocol)||(p=!0)}catch{p=!0}p||i.push({text:d,range:u,activate:(f,_)=>n?n.activate(f,_,u):H8(f,_),hover:(f,_)=>n?.hover?.(f,_,u),leave:(f,_)=>n?.leave?.(f,_,u)})}c=!1,r.hasExtendedAttrs()&&r.extended.urlId?(l=h,a=r.extended.urlId):(l=-1,a=-1)}}e(i)}};Xm=as([Ie(0,si),Ie(1,ii),Ie(2,lO)],Xm);function H8(s,e){if(confirm(`Do you want to navigate to ${e}?
|
|
4377
4377
|
|
|
4378
4378
|
WARNING: This link could potentially be dangerous`)){let t=window.open();if(t){try{t.opener=null}catch{}t.location.href=e}else console.warn("Opening link blocked as opener could not be cleared")}}var Mu=Is("CharSizeService"),ar=Is("CoreBrowserService"),eb=Is("MouseService"),lr=Is("RenderService"),V8=Is("SelectionService"),cO=Is("CharacterJoinerService"),Fa=Is("ThemeService"),hO=Is("LinkProviderService"),q8=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(s){setTimeout(()=>{throw s.stack?$w.isErrorNoTelemetry(s)?new $w(s.message+`
|
|
@@ -4396,7 +4396,7 @@ WARNING: This link could potentially be dangerous`)){let t=window.open();if(t){t
|
|
|
4396
4396
|
`).slice(2).join(`
|
|
4397
4397
|
`))}},lY=class extends Error{constructor(s,e){super(s),this.name="ListenerLeakError",this.stack=e}},cY=class extends Error{constructor(s,e){super(s),this.name="ListenerRefusalError",this.stack=e}},hY=0,ap=class{constructor(s){this.value=s,this.id=hY++}},dY=2,uY,wr=class{constructor(s){this._size=0,this._options=s,this._leakageMon=this._options?.leakWarningThreshold?new oY(s?.onListenerError??op,this._options?.leakWarningThreshold??rY):void 0,this._perfMon=this._options?._profName?new nY(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(s,e,t)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let o=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(o);let a=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],l=new cY(`${o}. HINT: Stack shows most frequent listener (${a[1]}-times)`,a[0]);return(this._options?.onListenerError||op)(l),$d.None}if(this._disposed)return $d.None;e&&(s=s.bind(e));let i=new ap(s),n;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(i.stack=aY.create(),n=this._leakageMon.check(i.stack,this._size+1)),this._listeners?this._listeners instanceof ap?(this._deliveryQueue??=new fY,this._listeners=[this._listeners,i]):this._listeners.push(i):(this._options?.onWillAddFirstListener?.(this),this._listeners=i,this._options?.onDidAddFirstListener?.(this)),this._size++;let r=HO(()=>{n?.(),this._removeListener(i)});return t instanceof cb?t.add(r):Array.isArray(t)&&t.push(r),r},this._event}_removeListener(s){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let e=this._listeners,t=e.indexOf(s);if(t===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,e[t]=void 0;let i=this._deliveryQueue.current===this;if(this._size*dY<=e.length){let n=0;for(let r=0;r<e.length;r++)e[r]?e[n++]=e[r]:i&&(this._deliveryQueue.end--,n<this._deliveryQueue.i&&this._deliveryQueue.i--);e.length=n}}_deliver(s,e){if(!s)return;let t=this._options?.onListenerError||op;if(!t){s.value(e);return}try{s.value(e)}catch(i){t(i)}}_deliverQueue(s){let e=s.current._listeners;for(;s.i<s.end;)this._deliver(e[s.i++],s.value);s.reset()}fire(s){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof ap)this._deliver(this._listeners,s);else{let e=this._deliveryQueue;e.enqueue(this,s,this._listeners.length),this._deliverQueue(e)}this._perfMon?.stop()}hasListeners(){return this._size>0}},fY=class{constructor(){this.i=-1,this.end=0}enqueue(s,e,t){this.i=0,this.end=t,this.current=s,this.value=e}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},jd=class ad{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new wr,this.onChange=this._onChange.event;let e=new qK;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return(e&1)!==0}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,i=!1){return(e&16777215)<<3|(t&3)<<1|(i?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw new Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(e){let t=0,i=0,n=e.length;for(let r=0;r<n;++r){let o=e.charCodeAt(r);if(55296<=o&&o<=56319){if(++r>=n)return t+this.wcwidth(o);let c=e.charCodeAt(r);56320<=c&&c<=57343?o=(o-55296)*1024+c-56320+65536:t+=this.wcwidth(c)}let a=this.charProperties(o,i),l=ad.extractWidth(a);ad.extractShouldJoin(a)&&(l-=ad.extractWidth(i)),t+=l,i=a}return t}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},lp=[[768,879],[1155,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1541],[1552,1562],[1564,1564],[1611,1631],[1648,1648],[1750,1757],[1759,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2045,2045],[2070,2073],[2075,2083],[2085,2087],[2089,2093],[2137,2139],[2259,2306],[2362,2362],[2364,2364],[2369,2376],[2381,2381],[2385,2391],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2558,2558],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2641,2641],[2672,2673],[2677,2677],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2810,2815],[2817,2817],[2876,2876],[2879,2879],[2881,2884],[2893,2893],[2902,2902],[2914,2915],[2946,2946],[3008,3008],[3021,3021],[3072,3072],[3076,3076],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3170,3171],[3201,3201],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3328,3329],[3387,3388],[3393,3396],[3405,3405],[3426,3427],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3981,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4151],[4153,4154],[4157,4158],[4184,4185],[4190,4192],[4209,4212],[4226,4226],[4229,4230],[4237,4237],[4253,4253],[4448,4607],[4957,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6158],[6277,6278],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6683,6683],[6742,6742],[6744,6750],[6752,6752],[6754,6754],[6757,6764],[6771,6780],[6783,6783],[6832,6846],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7040,7041],[7074,7077],[7080,7081],[7083,7085],[7142,7142],[7144,7145],[7149,7149],[7151,7153],[7212,7219],[7222,7223],[7376,7378],[7380,7392],[7394,7400],[7405,7405],[7412,7412],[7416,7417],[7616,7673],[7675,7679],[8203,8207],[8234,8238],[8288,8292],[8294,8303],[8400,8432],[11503,11505],[11647,11647],[11744,11775],[12330,12333],[12441,12442],[42607,42610],[42612,42621],[42654,42655],[42736,42737],[43010,43010],[43014,43014],[43019,43019],[43045,43046],[43204,43205],[43232,43249],[43263,43263],[43302,43309],[43335,43345],[43392,43394],[43443,43443],[43446,43449],[43452,43453],[43493,43493],[43561,43566],[43569,43570],[43573,43574],[43587,43587],[43596,43596],[43644,43644],[43696,43696],[43698,43700],[43703,43704],[43710,43711],[43713,43713],[43756,43757],[43766,43766],[44005,44005],[44008,44008],[44013,44013],[64286,64286],[65024,65039],[65056,65071],[65279,65279],[65529,65531]],pY=[[66045,66045],[66272,66272],[66422,66426],[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[68325,68326],[68900,68903],[69446,69456],[69633,69633],[69688,69702],[69759,69761],[69811,69814],[69817,69818],[69821,69821],[69837,69837],[69888,69890],[69927,69931],[69933,69940],[70003,70003],[70016,70017],[70070,70078],[70089,70092],[70191,70193],[70196,70196],[70198,70199],[70206,70206],[70367,70367],[70371,70378],[70400,70401],[70459,70460],[70464,70464],[70502,70508],[70512,70516],[70712,70719],[70722,70724],[70726,70726],[70750,70750],[70835,70840],[70842,70842],[70847,70848],[70850,70851],[71090,71093],[71100,71101],[71103,71104],[71132,71133],[71219,71226],[71229,71229],[71231,71232],[71339,71339],[71341,71341],[71344,71349],[71351,71351],[71453,71455],[71458,71461],[71463,71467],[71727,71735],[71737,71738],[72148,72151],[72154,72155],[72160,72160],[72193,72202],[72243,72248],[72251,72254],[72263,72263],[72273,72278],[72281,72283],[72330,72342],[72344,72345],[72752,72758],[72760,72765],[72767,72767],[72850,72871],[72874,72880],[72882,72883],[72885,72886],[73009,73014],[73018,73018],[73020,73021],[73023,73029],[73031,73031],[73104,73105],[73109,73109],[73111,73111],[73459,73460],[78896,78904],[92912,92916],[92976,92982],[94031,94031],[94095,94098],[113821,113822],[113824,113827],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[121344,121398],[121403,121452],[121461,121461],[121476,121476],[121499,121503],[121505,121519],[122880,122886],[122888,122904],[122907,122913],[122915,122916],[122918,122922],[123184,123190],[123628,123631],[125136,125142],[125252,125258],[917505,917505],[917536,917631],[917760,917999]],cp=[[4352,4447],[8986,8987],[9001,9002],[9193,9196],[9200,9200],[9203,9203],[9725,9726],[9748,9749],[9800,9811],[9855,9855],[9875,9875],[9889,9889],[9898,9899],[9917,9918],[9924,9925],[9934,9934],[9940,9940],[9962,9962],[9970,9971],[9973,9973],[9978,9978],[9981,9981],[9989,9989],[9994,9995],[10024,10024],[10060,10060],[10062,10062],[10067,10069],[10071,10071],[10133,10135],[10160,10160],[10175,10175],[11035,11036],[11088,11088],[11093,11093],[11904,11929],[11931,12019],[12032,12245],[12272,12283],[12288,12329],[12334,12350],[12353,12438],[12443,12543],[12549,12591],[12593,12686],[12688,12730],[12736,12771],[12784,12830],[12832,12871],[12880,19903],[19968,42124],[42128,42182],[43360,43388],[44032,55203],[63744,64255],[65040,65049],[65072,65106],[65108,65126],[65128,65131],[65281,65376],[65504,65510]],mY=[[94176,94179],[94208,100343],[100352,101106],[110592,110878],[110928,110930],[110948,110951],[110960,111355],[126980,126980],[127183,127183],[127374,127374],[127377,127386],[127488,127490],[127504,127547],[127552,127560],[127568,127569],[127584,127589],[127744,127776],[127789,127797],[127799,127868],[127870,127891],[127904,127946],[127951,127955],[127968,127984],[127988,127988],[127992,128062],[128064,128064],[128066,128252],[128255,128317],[128331,128334],[128336,128359],[128378,128378],[128405,128406],[128420,128420],[128507,128591],[128640,128709],[128716,128716],[128720,128722],[128725,128725],[128747,128748],[128756,128762],[128992,129003],[129293,129393],[129395,129398],[129402,129442],[129445,129450],[129454,129482],[129485,129535],[129648,129651],[129656,129658],[129664,129666],[129680,129685],[131072,196605],[196608,262141]],Ln;function ky(s,e){let t=0,i=e.length-1,n;if(s<e[0][0]||s>e[i][1])return!1;for(;i>=t;)if(n=t+i>>1,s>e[n][1])t=n+1;else if(s<e[n][0])i=n-1;else return!0;return!1}var gY=class{constructor(){if(this.version="11",!Ln){Ln=new Uint8Array(65536),Ln.fill(1),Ln[0]=0,Ln.fill(0,1,32),Ln.fill(0,127,160);for(let s=0;s<lp.length;++s)Ln.fill(0,lp[s][0],lp[s][1]+1);for(let s=0;s<cp.length;++s)Ln.fill(2,cp[s][0],cp[s][1]+1)}}wcwidth(s){return s<32?0:s<127?1:s<65536?Ln[s]:ky(s,pY)?0:ky(s,mY)?2:1}charProperties(s,e){let t=this.wcwidth(s),i=t===0&&e!==0;if(i){let n=jd.extractWidth(e);n===0?i=!1:n>t&&(t=n)}return jd.createPropertyValue(0,t,i)}},_Y=class{activate(s){s.unicode.register(new gY)}dispose(){}};var bY=class{constructor(s,e,t,i={}){this._terminal=s,this._regex=e,this._handler=t,this._options=i}provideLinks(s,e){let t=vY.computeLink(s,this._regex,this._terminal,this._handler);e(this._addCallbacks(t))}_addCallbacks(s){return s.map(e=>(e.leave=this._options.leave,e.hover=(t,i)=>{if(this._options.hover){let{range:n}=e;this._options.hover(t,i,n)}},e))}};function MY(s){try{let e=new URL(s),t=e.password&&e.username?`${e.protocol}//${e.username}:${e.password}@${e.host}`:e.username?`${e.protocol}//${e.username}@${e.host}`:`${e.protocol}//${e.host}`;return s.toLocaleLowerCase().startsWith(t.toLocaleLowerCase())}catch{return!1}}var vY=class ld{static computeLink(e,t,i,n){let r=new RegExp(t.source,(t.flags||"")+"g"),[o,a]=ld._getWindowedLineStrings(e-1,i),l=o.join(""),c,h=[];for(;c=r.exec(l);){let d=c[0];if(!MY(d))continue;let[u,p]=ld._mapStrIdx(i,a,0,c.index),[f,_]=ld._mapStrIdx(i,u,p,d.length);if(u===-1||p===-1||f===-1||_===-1)continue;let g={start:{x:p+1,y:u+1},end:{x:_,y:f+1}};h.push({range:g,text:d,activate:n})}return h}static _getWindowedLineStrings(e,t){let i,n=e,r=e,o=0,a="",l=[];if(i=t.buffer.active.getLine(e)){let c=i.translateToString(!0);if(i.isWrapped&&c[0]!==" "){for(o=0;(i=t.buffer.active.getLine(--n))&&o<2048&&(a=i.translateToString(!0),o+=a.length,l.push(a),!(!i.isWrapped||a.indexOf(" ")!==-1)););l.reverse()}for(l.push(c),o=0;(i=t.buffer.active.getLine(++r))&&i.isWrapped&&o<2048&&(a=i.translateToString(!0),o+=a.length,l.push(a),a.indexOf(" ")===-1););}return[l,n]}static _mapStrIdx(e,t,i,n){let r=e.buffer.active,o=r.getNullCell(),a=i;for(;n;){let l=r.getLine(t);if(!l)return[-1,-1];for(let c=a;c<l.length;++c){l.getCell(c,o);let h=o.getChars();if(o.getWidth()&&(n-=h.length||1,c===l.length-1&&h==="")){let d=r.getLine(t+1);d&&d.isWrapped&&(d.getCell(0,o),o.getWidth()===2&&(n+=1))}if(n<0)return[t,c]}t++,a=0}return[t,a]}},wY=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function yY(s,e){let t=window.open();if(t){try{t.opener=null}catch{}t.location.href=e}else console.warn("Opening link blocked as opener could not be cleared")}var SY=class{constructor(s=yY,e={}){this._handler=s,this._options=e}activate(s){this._terminal=s;let e=this._options,t=e.urlRegex||wY;this._linkProvider=this._terminal.registerLinkProvider(new bY(this._terminal,t,this._handler,e))}dispose(){this._linkProvider?.dispose()}};const zY=6677;function xY(s){const e=/^state=(idle|busy|asking|playing)$/.exec(s.trim());return e===null?null:e[1]}const kg="argus.terminalId",OY="'JetBrainsMono NF Mono', 'MesloLGS NF', monospace",EY=[{label:"ESC",data:"\x1B"},{label:"TAB",data:" "},{label:"CTRL",data:"ctrl"},{label:"←",data:"\x1B[D"},{label:"↑",data:"\x1B[A"},{label:"↓",data:"\x1B[B"},{label:"→",data:"\x1B[C"}];function AY(s){const[e,t,i,n,r,o,a,l,c,h,d,u,p,f,_,g]=u2;return{background:"#000000",foreground:s,cursor:s,cursorAccent:"#000000",selectionBackground:"#44556680",black:e,red:t,green:i,yellow:n,blue:r,magenta:o,cyan:a,white:l,brightBlack:c,brightRed:h,brightGreen:d,brightYellow:u,brightBlue:p,brightMagenta:f,brightCyan:_,brightWhite:g}}function TY(s){if(s.length!==1)return s;const e=s.toUpperCase().charCodeAt(0);return e>=64&&e<=95?String.fromCharCode(e-64):s}function DY(){try{return sessionStorage.getItem(kg)??void 0}catch{return}}function Ny(s){try{s===null?sessionStorage.removeItem(kg):sessionStorage.setItem(kg,s)}catch{}}class IY{constructor(e,t,i,n=()=>{}){this.mount=e,this.wire=t,this.refused=i,this.state=n;const r=getComputedStyle(e).color||"#ffaa44";this.term=new FK({fontFamily:OY,fontSize:Math.max(10,Math.floor(parseFloat(getComputedStyle(e).fontSize)||13)),theme:AY(r),cursorBlink:!0,scrollback:5e3,allowProposedApi:!0}),this.term.loadAddon(this.fit),this.term.loadAddon(new SY),this.term.loadAddon(new _Y),this.term.unicode.activeVersion="11";const o=document.createElement("div");o.className="argus-xterm",e.appendChild(o),this.term.open(o),this.keyRow_build(),this.term.onData(a=>this.keys_send(a)),this.term.onLineFeed(()=>{this.feeds++}),this.term.parser.registerOscHandler(zY,a=>{const l=xY(a);return l!==null&&this.state(l),!0}),this.term.onResize(({cols:a,rows:l})=>{this.terminalId!==null&&this.wire.resize(this.terminalId,a,l)}),this.observer=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>this.size_fit()),this.observer?.observe(e),this.size_fit(),this.wire.open(this.term.cols,this.term.rows,DY())}mount;wire;refused;state;term;fit=new jK;terminalId=null;ended=!1;ctrlHeld=!1;resizeFrame=null;feeds=0;observer;size_fit(){this.resizeFrame===null&&(this.resizeFrame=requestAnimationFrame(()=>{if(this.resizeFrame=null,this.mount.offsetParent!==null)try{this.fit.fit()}catch{}}))}terminalId_get(){return this.terminalId}focus(){this.term.focus()}opened(e,t,i){if(i!==void 0){this.refused(i);return}this.terminalId=e,this.ended=!1,Ny(e),t!==""&&this.term.write(t),this.wire.resize(e,this.term.cols,this.term.rows)}data(e,t){e===this.terminalId&&this.term.write(t)}exited(e,t){e===this.terminalId&&(this.ended=!0,this.terminalId=null,Ny(null),this.term.write(`\r
|
|
4398
4398
|
\x1B[90m[the console's shell exited${t===0?"":` (${t})`}; press a key for a new one]\x1B[0m\r
|
|
4399
|
-
`))}offer(e){this.terminalId!==null&&this.wire.input(this.terminalId,`${e}`),this.focus()}buffer_lines(){const e=this.term.buffer.active,t=[];for(let i=0;i<e.length;i++){const n=e.getLine(i),r=n?.translateToString(!0)??"";n?.isWrapped===!0&&t.length>0?t[t.length-1]+=r:t.push(r)}for(;t.length>0&&t[t.length-1]==="";)t.pop();return t}mark(){return this.feeds}lines_since(e){const t=this.buffer_lines(),i=Math.max(0,this.feeds-e)+1;return t.slice(Math.max(0,t.length-i))}type(e){this.keys_send(e)}dispose(){this.observer?.disconnect(),this.term.dispose()}keys_send(e){if(this.ended){this.ended=!1,this.term.reset(),this.wire.open(this.term.cols,this.term.rows);return}if(this.terminalId===null)return;let t=e;this.ctrlHeld&&(t=TY(e),this.ctrlHeld=!1,this.mount.querySelector(".argus-xterm-key.held")?.classList.remove("held")),this.wire.input(this.terminalId,t)}keyRow_build(){const e=document.createElement("div");e.className="argus-xterm-keys";for(const t of EY){const i=document.createElement("button");i.type="button",i.className="argus-xterm-key",i.textContent=t.label,i.addEventListener("pointerdown",n=>{n.preventDefault(),t.data==="ctrl"?(this.ctrlHeld=!this.ctrlHeld,i.classList.toggle("held",this.ctrlHeld)):this.keys_send(t.data),this.focus()}),e.appendChild(i)}this.mount.appendChild(e)}}const CY="argus.consoleMode",RY="console: the transcript, deprecated: this host offers no pseudo-terminal (node-pty did not build). Install python, make and g++ and reinstall for the terminal console.";function kY(){try{localStorage.removeItem(CY)}catch{}}function NY(s){const{client:e,terminal:t,offered:i}=s,n=document.getElementById("terminal");let r=null,o="transcript";const a=l=>{if(n!==null)if(l==="terminal"&&i){if(n.classList.add("console-terminal"),r===null){const h=document.createElement("div");h.className="argus-terminal-mount",n.appendChild(h),r=new IY(h,{open:(d,u,p)=>e.terminal_open(d,u,p),input:(d,u)=>e.terminal_input(d,u),resize:(d,u,p)=>e.terminal_resize(d,u,p)},d=>{a("transcript"),t.line_note(`console: ${d}`)},d=>{n.dataset.terminalState=d}),n.dataset.terminalState="busy",s.screen_set(r)}const c=r;e.mirror_set(!0),t.delegate_set({note:h=>e.note_send(h),offer:h=>c.offer(h),focus:()=>c.focus(),fit:()=>c.size_fit()}),c.size_fit(),o="terminal"}else n.classList.remove("console-terminal"),e.mirror_set(!1),t.delegate_set(null),o="transcript"};return kY(),a(i?"terminal":"transcript"),i||t.line_note(RY),Object.assign(globalThis,{__argusConsole:{mode:()=>o,state:()=>n?.dataset.terminalState??"busy",type:l=>r?.type(l),lines:()=>r?.buffer_lines()??[],mark:()=>r?.mark()??0,since:l=>r?.lines_since(l)??[]}}),{terminal_is:()=>o==="terminal",question_sheet:async l=>{document.querySelector(".question-sheet")?.remove();const c=document.createElement("div");c.className="share-sheet question-sheet",c.setAttribute("role","dialog");const h=document.createElement("div");h.className="share-head",h.textContent="THE SESSION ASKS",c.appendChild(h),document.body.appendChild(c);try{return await V_(t,c,l)}finally{c.remove()}}}}const BY=new Set(["busy","asking","playing"]);function GY(s,e=()=>null){const t=document.querySelector(".console-stop"),i=document.getElementById("terminal");if(t===null||i===null)return;const n=()=>{const o=i.classList.contains("console-terminal")?BY.has(i.dataset.terminalState??""):i.dataset.busy==="true";t.hidden=!o};new MutationObserver(n).observe(i,{attributes:!0,attributeFilter:["data-busy","data-terminal-state","class"]}),n(),t.addEventListener("click",()=>{const r=i.classList.contains("console-terminal")?e():null;r!==null&&s.terminal_input(r,""),s.stop_send()})}let ao=()=>{};function By(){ao(document.body.dataset.zoom==="console"?null:"console")}const PY=ME(),LY=wE(),WY=new URL("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNDAgMjkwIj4KPGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJnIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjQwIiB5MT0iMCIgeDI9IjIwMCIgeTI9IjIyNCI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjMmE2M2JmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjN2FkM2YxIi8+PC9saW5lYXJHcmFkaWVudD4KPHJhZGlhbEdyYWRpZW50IGlkPSJoIj48c3RvcCBvZmZzZXQ9IjAiIHN0b3AtY29sb3I9IiM3YWQzZjEiIHN0b3Atb3BhY2l0eT0iMC40NSIvPjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzdhZDNmMSIgc3RvcC1vcGFjaXR5PSIwIi8+PC9yYWRpYWxHcmFkaWVudD48L2RlZnM+CjxjaXJjbGUgY3g9IjEyMCIgY3k9IjExMiIgcj0iMTA0IiBmaWxsPSJ1cmwoI2gpIi8+PHJlY3QgeD0iMjIuMCIgeT0iNDguMCIgd2lkdGg9IjE5NiIgaGVpZ2h0PSIxMjgiIHJ4PSI2NC4wIiBmaWxsPSJub25lIiBzdHJva2U9IiNjNzQ2MzQiIHN0cm9rZS13aWR0aD0iMTYiLz48bGluZSB4MT0iMTIwIiB5MT0iMTEyIiB4Mj0iMjE0IiB5Mj0iMjIiIHN0cm9rZT0iIzdhZDNmMSIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtZGFzaGFycmF5PSIyIDUiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgb3BhY2l0eT0iMC44Ii8+PGxpbmUgeDE9IjEyMCIgeTE9IjExMiIgeDI9IjI2IiB5Mj0iMjAyIiBzdHJva2U9IiM3YWQzZjEiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWRhc2hhcnJheT0iMiA1IiBzdHJva2UtbGluZWNhcD0icm91bmQiIG9wYWNpdHk9IjAuOCIvPjxwYXRoIGQ9Ik0yMTQsMC4wIEwyMTguNSwxNy41IEwyMzAuMCwyMiBMMjE4LjUsMjYuNSBMMjE0LDQ0LjAgTDIwOS41LDI2LjUgTDE5OC4wLDIyIEwyMDkuNSwxNy41WiIgZmlsbD0idXJsKCNnKSIvPjxwYXRoIGQ9Ik0yNiwxODguOCBMMjguNywxOTkuMyBMMzUuNiwyMDIgTDI4LjcsMjA0LjcgTDI2LDIxNS4yIEwyMy4zLDIwNC43IEwxNi40LDIwMiBMMjMuMywxOTkuM1oiIGZpbGw9InVybCgjZykiLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDEwOC42LDg0LjYgMTIwLjAsMi4wIiBmaWxsPSJ1cmwoI2cpIi8+PHBvbHlnb24gcG9pbnRzPSIxMjAuMCwxMTIuMCAxMjAuMCwyLjAgMTMxLjQsODQuNiIgZmlsbD0idXJsKCNnKSIgZmlsbC1vcGFjaXR5PSIwLjciLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDEzMS40LDg0LjYgMTUxLjEsODAuOSIgZmlsbD0idXJsKCNnKSIvPjxwb2x5Z29uIHBvaW50cz0iMTIwLjAsMTEyLjAgMTUxLjEsODAuOSAxNDcuNCwxMDAuNiIgZmlsbD0idXJsKCNnKSIgZmlsbC1vcGFjaXR5PSIwLjciLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDE0Ny40LDEwMC42IDE5Mi4wLDExMi4wIiBmaWxsPSJ1cmwoI2cpIi8+PHBvbHlnb24gcG9pbnRzPSIxMjAuMCwxMTIuMCAxOTIuMCwxMTIuMCAxNDcuNCwxMjMuNCIgZmlsbD0idXJsKCNnKSIgZmlsbC1vcGFjaXR5PSIwLjciLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDE0Ny40LDEyMy40IDE1MS4xLDE0My4xIiBmaWxsPSJ1cmwoI2cpIi8+PHBvbHlnb24gcG9pbnRzPSIxMjAuMCwxMTIuMCAxNTEuMSwxNDMuMSAxMzEuNCwxMzkuNCIgZmlsbD0idXJsKCNnKSIgZmlsbC1vcGFjaXR5PSIwLjciLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDEzMS40LDEzOS40IDEyMC4wLDIyMi4wIiBmaWxsPSJ1cmwoI2cpIi8+PHBvbHlnb24gcG9pbnRzPSIxMjAuMCwxMTIuMCAxMjAuMCwyMjIuMCAxMDguNiwxMzkuNCIgZmlsbD0idXJsKCNnKSIgZmlsbC1vcGFjaXR5PSIwLjciLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDEwOC42LDEzOS40IDg4LjksMTQzLjEiIGZpbGw9InVybCgjZykiLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDg4LjksMTQzLjEgOTIuNiwxMjMuNCIgZmlsbD0idXJsKCNnKSIgZmlsbC1vcGFjaXR5PSIwLjciLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDkyLjYsMTIzLjQgNDguMCwxMTIuMCIgZmlsbD0idXJsKCNnKSIvPjxwb2x5Z29uIHBvaW50cz0iMTIwLjAsMTEyLjAgNDguMCwxMTIuMCA5Mi42LDEwMC42IiBmaWxsPSJ1cmwoI2cpIiBmaWxsLW9wYWNpdHk9IjAuNyIvPjxwb2x5Z29uIHBvaW50cz0iMTIwLjAsMTEyLjAgOTIuNiwxMDAuNiA4OC45LDgwLjkiIGZpbGw9InVybCgjZykiLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDg4LjksODAuOSAxMDguNiw4NC42IiBmaWxsPSJ1cmwoI2cpIiBmaWxsLW9wYWNpdHk9IjAuNyIvPgo8ZyBzdHJva2U9IiNmZmYiIHN0cm9rZS13aWR0aD0iMyIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBmaWxsPSJub25lIj48bGluZSB4MT0iMTIwIiB5MT0iMTEyIiB4Mj0iMTIwLjAiIHkyPSIxNy40Ii8+PGxpbmUgeDE9IjEyMCIgeTE9IjExMiIgeDI9IjE4MS45IiB5Mj0iMTEyLjAiLz48bGluZSB4MT0iMTIwIiB5MT0iMTEyIiB4Mj0iMTIwLjAiIHkyPSIyMDYuNiIvPjxsaW5lIHgxPSIxMjAiIHkxPSIxMTIiIHgyPSI1OC4xIiB5Mj0iMTEyLjAiLz48cG9seWdvbiBwb2ludHM9IjEzMS40LDg0LjYgMTQ3LjQsMTAwLjYgMTQ3LjQsMTIzLjQgMTMxLjQsMTM5LjQgMTA4LjYsMTM5LjQgOTIuNiwxMjMuNCA5Mi42LDEwMC42IDEwOC42LDg0LjYiLz48L2c+CjxnIGZpbGw9IiNmZmYiPjxjaXJjbGUgY3g9IjEyMCIgY3k9IjExMiIgcj0iMTAiLz48Y2lyY2xlIGN4PSIxMjAuMCIgY3k9IjUxLjUiIHI9IjQuNSIvPjxjaXJjbGUgY3g9IjE1OS42IiBjeT0iMTEyLjAiIHI9IjQuNSIvPjxjaXJjbGUgY3g9IjEyMC4wIiBjeT0iMTcyLjUiIHI9IjQuNSIvPjxjaXJjbGUgY3g9IjgwLjQiIGN5PSIxMTIuMCIgcj0iNC41Ii8+PGNpcmNsZSBjeD0iMTMxLjQiIGN5PSI4NC42IiByPSIzLjUiLz48Y2lyY2xlIGN4PSIxNDcuNCIgY3k9IjEwMC42IiByPSIzLjUiLz48Y2lyY2xlIGN4PSIxNDcuNCIgY3k9IjEyMy40IiByPSIzLjUiLz48Y2lyY2xlIGN4PSIxMzEuNCIgY3k9IjEzOS40IiByPSIzLjUiLz48Y2lyY2xlIGN4PSIxMDguNiIgY3k9IjEzOS40IiByPSIzLjUiLz48Y2lyY2xlIGN4PSI5Mi42IiBjeT0iMTIzLjQiIHI9IjMuNSIvPjxjaXJjbGUgY3g9IjkyLjYiIGN5PSIxMDAuNiIgcj0iMy41Ii8+PGNpcmNsZSBjeD0iMTA4LjYiIGN5PSI4NC42IiByPSIzLjUiLz48L2c+Cjx0ZXh0IHg9IjEyMCIgeT0iMjY4IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmb250LWZhbWlseT0iTW9udHNlcnJhdCxIZWx2ZXRpY2EsQXJpYWwsc2Fucy1zZXJpZiIgZm9udC13ZWlnaHQ9IjcwMCIgZm9udC1zaXplPSIzOCIgZmlsbD0iIzJhNjNiZiIgbGV0dGVyLXNwYWNpbmc9IjQiPk9DSSBURDwvdGV4dD4KPC9zdmc+",import.meta.url).href,FY=`data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" fill="#000"/><rect x="6" y="14" width="52" height="36" rx="18" fill="#20bdef"/><rect x="34" y="14" width="24" height="36" fill="#20bdef"/></svg>')}`;function Gy(s){for(const e of document.querySelectorAll('link[rel="icon"], link[rel="apple-touch-icon"]'))e.href=s}const UY="ARGUS",Py="argus-audio",$Y=.4;let yr=!1;const jY={audio1:{file:"press",cue:"press"},audio2:{file:"arrive",cue:"ack"},audio3:{file:"retreat",cue:"close"},audio4:{file:"refuse",cue:"deny"}},JO=new Set;function HY(){fetch("sounds/index.json").then(s=>s.ok?s.json():Promise.resolve(null)).then(s=>{const e=typeof s=="object"&&s!==null?s.files:void 0;if(Array.isArray(e))for(const t of e)typeof t=="string"&&JO.add(t.replace(/\.[a-z0-9]+$/,""))}).catch(()=>{})}function Pi(s){if(yr)return;const e=jY[s];if(e!==void 0&&!JO.has(e.file)){Bs.cue_play(e.cue);return}const t=document.getElementById(s);t instanceof HTMLAudioElement&&(t.currentTime=0,t.volume=$Y,t.play().catch(()=>{}))}function VY(){const s=et("head-menu-pill"),e=t=>{t?document.body.dataset.headMenu="open":delete document.body.dataset.headMenu,s.setAttribute("aria-expanded",String(t))};s.addEventListener("click",t=>{t.stopPropagation(),e(document.body.dataset.headMenu!=="open")}),document.addEventListener("click",t=>{if(document.body.dataset.headMenu!=="open")return;t.target instanceof Element&&t.target.closest("#header-dag-info")!==null||e(!1)})}function qY(){const s=et("audio-pill");try{yr=window.localStorage.getItem(Py)==="off"}catch{yr=!1}const e=()=>{s.classList.toggle("audio-off",yr),Bs.muted_set(yr)};e(),HY(),s.addEventListener("click",()=>{yr=!yr;try{window.localStorage.setItem(Py,yr?"off":"on")}catch{}e(),Pi("audio2")})}function KY(){return yE(window.location)}let hp=null,Hd=0;function hb(s,e){const t=()=>{e.dataset.zoom!==void 0||e.dataset.header==="away"||(Hd=Math.ceil(s.offsetTop+s.offsetHeight),e.style.setProperty("--zoom-header-height",`${Hd}px`))};t(),hp===null&&(hp=new ResizeObserver(t),hp.observe(s))}const Ly=120,YY=96;function XY(s,e,t,i){let n="";const r=h=>{h?(n=s.style.height,s.style.height=""):n!==""&&(s.style.height=n),s.classList.toggle("drawer-closed",h),Pi("audio3"),h||(i.size_fit(),i.focus_take())};t.addEventListener("click",()=>r(!s.classList.contains("drawer-closed")));let o=0,a=0,l=!1;e.addEventListener("pointerdown",h=>{l=!0,o=h.clientY,a=s.getBoundingClientRect().height,s.classList.add("drawer-dragging"),e.setPointerCapture(h.pointerId),h.preventDefault()}),e.addEventListener("pointermove",h=>{if(!l)return;const d=Math.max(Ly,window.innerHeight-YY),u=a+(h.clientY-o),p=Math.min(Math.max(Ly,u),d);s.style.height=`${p}px`,i.size_fit()});const c=()=>{l=!1,s.classList.remove("drawer-dragging")};return e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c),r}function ZY(s){const e=document.body,t=document.querySelector(".wrap:not(#gap)");let i;const n=r=>{for(const o of document.querySelectorAll(".pane-zoomed, .pane-zoomed-path"))o.classList.remove("pane-zoomed","pane-zoomed-path");if(r===null)delete e.dataset.zoom,i!==void 0&&(e.dataset.header=i,i=void 0);else{window.scrollTo(0,0),e.dataset.header==="away"?(i="away",delete e.dataset.header,Hd>0&&e.style.setProperty("--zoom-header-height",`${Hd}px`)):t!==null&&hb(t,e),e.dataset.zoom=r;const a=jh(r)?.mount?.parentElement??null;a?.classList.add("pane-zoomed");let l=a?.parentElement??null;for(;l!==null&&l.id!=="layout-root";)l.classList.add("pane-zoomed-path"),l=l.parentElement}for(const o of document.querySelectorAll(".drawer-zoom"))o.textContent=r!==null&&o.dataset.pane===r?"RESTORE":"ZOOM";Pi("audio3")};return et("header-restore").addEventListener("click",()=>{e.dataset.zoom!==void 0&&n(null)}),document.addEventListener("click",r=>{const o=r.target;if(!(o instanceof Element))return;const a=o.closest("[data-pane]");if(a===null)return;const l=a.dataset.pane??"";l!==""&&n(e.dataset.zoom===l?null:l)}),window.addEventListener("keydown",r=>{r.key==="Escape"&&e.dataset.zoom!==void 0&&(n(null),r.stopImmediatePropagation())}),et("drawer").addEventListener("transitionend",r=>{r.propertyName==="height"&&s.size_fit()}),n}function JY(){const s=new A6(document.getElementById("data-cascade")),e=document.getElementById("header-telemetry");return e!==null&&s.telemetryPanel_bind(e),s}const dp=96,QY=220,Wy="argus.headerBand.height",eX=52;function tX(){const s=document.documentElement,e=document.getElementById("header-strip"),t=document.querySelector(".wrap:not(#gap)");if(e===null||t===null)return;const i=h=>{const d=Math.max(dp,window.innerHeight-QY),u=Math.min(Math.max(dp,h),d);s.style.setProperty("--header-band-h",`${u}px`);try{window.localStorage.setItem(Wy,String(u))}catch{}},n=(()=>{try{return window.localStorage.getItem(Wy)}catch{return null}})();n!==null&&Number.isFinite(Number(n))&&i(Number(n));const r=()=>{const h=t.getBoundingClientRect();e.style.top=`${Math.max(0,h.bottom-eX)}px`};r(),window.addEventListener("resize",r),new MutationObserver(r).observe(document.body,{attributes:!0,attributeFilter:["data-header"]}),window.setInterval(r,500);let o=!1,a=0,l=0;e.addEventListener("pointerdown",h=>{const d=document.querySelector(".header-face");o=!0,a=h.clientY,l=d===null?dp:d.getBoundingClientRect().height,e.setPointerCapture(h.pointerId),h.preventDefault()}),e.addEventListener("pointermove",h=>{o&&(i(l+(h.clientY-a)),r())});const c=()=>{o=!1,r()};e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c)}let db=null;function sX(s){const e=s.querySelector(".gather-rows");if(e===null)return;const t=ai(e,{rows:".listing-row",label:i=>`+${i} MORE · ON STAGE`,press:()=>{db?.()},className:"strategy-pill gather-more",mount:s});t.title="the whole cohort as a pane on the main panel"}function Fy(s){ai(s,{rows:".strategy-pill, .listing-action, .holder-mark",className:"frame-more"})}function iX(){const s=e=>{for(const t of e.querySelectorAll(".mode-frame:not([data-more])"))Fy(t)};new MutationObserver(e=>{for(const t of e)for(const i of t.addedNodes)i instanceof HTMLElement&&(i.matches(".mode-frame")&&i.dataset.more===void 0&&Fy(i),s(i))}).observe(document.body,{childList:!0,subtree:!0}),s(document)}function Uy(s){const e=s?.text;if(typeof e!="string"||e.length===0||typeof window.speechSynthesis>"u")return;const t=new SpeechSynthesisUtterance(e);t.rate=1,window.speechSynthesis.speak(t)}function nX(){const s=document.body,e=document.querySelector(".wrap:not(#gap)"),t=r=>{s.dataset.header===r?(e!==null&&hb(e,s),s.dataset.header="away"):s.dataset.header=r};document.querySelector(".panel-1")?.addEventListener("click",()=>t("stats")),document.querySelector(".panel-2")?.addEventListener("click",()=>t("dag")),document.querySelector(".panel-gather")?.addEventListener("click",()=>t("gather"));const i=document.querySelector(".header-gather-field");i?.querySelector(".gather-stage")?.addEventListener("click",r=>{r.stopPropagation(),db?.()}),i!==null&&sX(i),iX();const n=()=>{s.dataset.zoom===void 0&&(delete s.dataset.header,Pi("audio3"))};et("header-restore").addEventListener("click",n),window.addEventListener("keydown",r=>{r.key==="Escape"&&s.dataset.header==="away"&&s.dataset.zoom===void 0&&s.dataset.gutter!=="away"&&n()})}const ha=[{key:"lower-decks",label:"LOWER DECKS"},{key:"gold",label:"CERRITOS GOLD"},{key:"medical",label:"MEDICAL"},{key:"nemesis",label:"NEMESIS"},{key:"pharos",label:"PHAROS"}],QO="argus-landing",rX=15e3;function $y(){try{return(window.localStorage.getItem(QO)??"launcher")==="launcher"}catch{return!0}}function oX(s){try{window.localStorage.setItem(QO,s?"launcher":"last")}catch{}}const jy="argus-theme",aX="argus-lcars",lX="medical",cX={sickbay:"medical"};function hX(){const s=et("theme-pill"),e=Math.max(ha.findIndex(r=>r.key===lX),0);let t=e;try{const r=window.localStorage.getItem(jy)??window.localStorage.getItem(aX),o=r===null?null:cX[r]??r,a=ha.findIndex(l=>l.key===o);t=a>=0?a:e}catch{t=e}const i=document.documentElement,n=()=>{const r=ha[t]??ha[0];r.key==="lower-decks"?delete i.dataset.theme:i.dataset.theme=r.key,s.textContent=r.label};n(),s.addEventListener("click",()=>{t=(t+1)%ha.length,n();try{window.localStorage.setItem(jy,ha[t]?.key??"lower-decks")}catch{}Pi("audio2")})}function dX(s){const e=document.getElementById("about-rows");if(e===null)return;e.replaceChildren();const i={...c2(s)==="chris"?{cumin:s.stack?.cumin,salsa:s.stack?.salsa,chili:s.stack?.chili}:{},brasa:s.stack?.brasa,calypso:s.stack?.calypso,chell:s.stack?.chell},n=[];for(const[r,o]of Object.entries(i))o!==void 0&&n.push([r.toUpperCase(),o]);n.push(["MENU","0.34.0"],["ARGUS","d3fc2fe9 · 2026-11-02 21:08Z"],["WIRE",`V${s.protocolVersion}`]),s.stack?.build!==void 0&&n.push(["BUILD",s.stack.build]);for(const[r,o]of n){const a=document.createElement("div");a.className="telemetry-row";const l=document.createElement("span");l.className="telemetry-label",l.textContent=r;const c=document.createElement("span");c.className="telemetry-value",c.textContent=o,c.title=o,a.append(l,c),e.appendChild(a)}}function uX(){for(const s of document.querySelectorAll(".left-frame button, .left-frame-top button"))s.addEventListener("click",()=>Pi("audio2"))}let da=null;async function fX(s){let e=null;const t=await zE(s),i=t==="chris";document.body.dataset.composition=t;const n=new w6(document),r=i?f6(et("index-instrument"),{dag_primary:()=>Et,dag_instances:()=>a.values("dag"),universes:()=>a.values("universe"),pacs:()=>ne,runs_show:I=>ze(I)}):{promptContext_take:()=>{},telemetry_take:()=>{},progress_take:()=>{}},o=new S6(et("lane-instrument"),void 0,I=>{Re.line_run(I)});window.setInterval(()=>o.tick(),500);const a=new wj;i&&nM(N6(()=>Ce)),t==="stratus"&&nM(h6(()=>({...Ce,controller_open:I=>Vi.open(I),script_open:I=>qi.open(I)})));const l=new m6;l.writeObserver_set((I,U)=>{st.regard_send({address:I.address,...I.modelKind!==void 0?{modelKind:I.modelKind}:{},groupId:U,paneId:I.paneId}),be()});let c=null,h=!1;const d=async I=>{if(c===!0)return!0;if(!h)return Re.line_note(`${I}: entered as READ, and this session cannot be raised: it was started without a door to ask`),!1;const U=await eE(I);if(U===null)return!1;const ge=await st.elevate(U);return ge.granted?(c=!0,n.mode_show(!0),Vi.mode_refresh(),qi.mode_refresh(),Re.line_note("MODE MANAGE: this session may build, tear down and spend, each after its own question, until you leave it"),!0):(Re.line_note(`MANAGE refused: ${ge.reason??"the door said no"}`),!1)},u={get layout(){return le},panels:a,paneInstance_get:jh,subjects:l,get dormant(){return Le},sound:Pi,get terminal(){return Re},get client(){return st},manage_is:()=>c,elevation_is:()=>h,elevate_ask:d},p=V6(u,{catalogue_find:I=>O.get(I),run_press:(I,U,ge)=>{De(I,U,ge)}}),f=p.entry_show,_=I=>Bg(I,s),g=pj(u,{vfsUrl_build:_,downloadUrl_build:I=>xE(I,s),image_open:(I,U)=>W(I,U),process_open:(I,U)=>ee(I,U),run_press:(I,U,ge)=>{De(I,U,ge)},cohort_gather:I=>qe(I),verbLine_run:(I,U)=>K(I,U),askOnPane_await:(I,U)=>te(I,U),binEntry_show:f,catalogue_find:I=>O.get(I),promptUser:()=>A,template_stamp:sn,pane_find:Js}),{previewProvider:m,fileText_fetch:w,file_save:y,rootedListing_show:M,listing_refresh:v,directory_make:S,files_deliver:x,filesBody_stamp:b,rowVerbs_build:z}=g,T=g.instance_build;let A=null,E=null;const O=new Map,{imageInstance_build:R,tagsInstance_build:C,tagsPane_follow:k,tagsPane_open:G,series_ask:L,image_open:W}=Lj({client:()=>st,terminal:()=>Re,panels:()=>a,subjects:()=>l,layout:()=>le,desktop:()=>_e,instance_spawn:(I,U)=>rs(I,U),errandHost_find:()=>P(),launcher_yield:()=>xe(),birth_record:(I,U,ge,ke,$e)=>ve(I,U,ge,ke,$e),vfsUrl_build:I=>_(I)}),ee=(I,U)=>{xe();const ge=new Set(le.panes_shown());for(const[ut,ui]of O)if(ge.has(ut)&&ui.input===U.input){le.focus_set(ut);return}const ke=ge.has(I)?I:P()??I,$e=rs("catalogue",I);if(!le.leaf_split(ke,_e.replayPlace_get()?.dir??"col",$e.id,_e.replayPlace_get()?.before??!1)){Ds($e.id),le.mount_remove($e.id);return}ve($e.id,ke,_e.replayPlace_get()?.dir??"col",_e.replayPlace_get()?.before??!1),O.set($e.id,U);const yt=a.get("files",$e.id);yt!==void 0&&(yt.binding_set({input:U.input,place:U.feed===null?"new feed":`feed ${U.feed}${U.node===null?"":` · node ${U.node}`}`}),yt.feedOpen_declare(ut=>Pe($e.id,ut)),M($e.id,yt,"/bin"),Ae(yt),le.focus_set($e.id))},X=5,he=40,Ae=I=>{st.line_execute(`plugininstance list --limit ${he} --fields id,plugin_name,plugin_version,owner_username`,{silent:!0,observe:!1}).then(ge=>{const ke=[];for(const $e of ge.envelopes)if(!($e.model?.kind!=="plugininstance.list"||!Array.isArray($e.model.data)))for(const yt of $e.model.data){if(typeof yt.pluginName!="string"||typeof yt.pluginVersion!="string"||A!==null&&typeof yt.owner=="string"&&yt.owner!==A||yt.pluginName==="pl-dircopy")continue;const ut=`${yt.pluginName}-v${yt.pluginVersion}`;if(ke.includes(ut)||ke.push(ut),ke.length>=X)break}I.recent_set(ke.length===0?null:ke)}).catch(()=>{})},Pe=(I,U)=>{xe();const ge=new Set(le.panes_shown());for(const[yt,ut]of a.entries("dag"))if(yt!=="dag"&&ge.has(yt)&&ut.feed_get()===U){le.focus_set(yt);return}const ke=ge.has(I)?I:P()??I,$e=rs("dag",I);if(!le.leaf_split(ke,_e.replayPlace_get()?.dir??"col",$e.id,_e.replayPlace_get()?.before??!1)){Ds($e.id),le.mount_remove($e.id);return}ve($e.id,ke,_e.replayPlace_get()?.dir??"col",_e.replayPlace_get()?.before??!1),a.get("dag",$e.id)?.feed_enter(U)},De=async(I,U,ge)=>{const ke=O.get(I),$e=a.get("files",I);if(ke===void 0||$e===void 0)return;const yt=qs=>{Re.output_write("err",`\x1B[31m${qs}\x1B[0m
|
|
4399
|
+
`))}offer(e){this.terminalId!==null&&this.wire.input(this.terminalId,`${e}`),this.focus()}buffer_lines(){const e=this.term.buffer.active,t=[];for(let i=0;i<e.length;i++){const n=e.getLine(i),r=n?.translateToString(!0)??"";n?.isWrapped===!0&&t.length>0?t[t.length-1]+=r:t.push(r)}for(;t.length>0&&t[t.length-1]==="";)t.pop();return t}mark(){return this.feeds}lines_since(e){const t=this.buffer_lines(),i=Math.max(0,this.feeds-e)+1;return t.slice(Math.max(0,t.length-i))}type(e){this.keys_send(e)}dispose(){this.observer?.disconnect(),this.term.dispose()}keys_send(e){if(this.ended){this.ended=!1,this.term.reset(),this.wire.open(this.term.cols,this.term.rows);return}if(this.terminalId===null)return;let t=e;this.ctrlHeld&&(t=TY(e),this.ctrlHeld=!1,this.mount.querySelector(".argus-xterm-key.held")?.classList.remove("held")),this.wire.input(this.terminalId,t)}keyRow_build(){const e=document.createElement("div");e.className="argus-xterm-keys";for(const t of EY){const i=document.createElement("button");i.type="button",i.className="argus-xterm-key",i.textContent=t.label,i.addEventListener("pointerdown",n=>{n.preventDefault(),t.data==="ctrl"?(this.ctrlHeld=!this.ctrlHeld,i.classList.toggle("held",this.ctrlHeld)):this.keys_send(t.data),this.focus()}),e.appendChild(i)}this.mount.appendChild(e)}}const CY="argus.consoleMode",RY="console: the transcript, deprecated: this host offers no pseudo-terminal (node-pty did not build). Install python, make and g++ and reinstall for the terminal console.";function kY(){try{localStorage.removeItem(CY)}catch{}}function NY(s){const{client:e,terminal:t,offered:i}=s,n=document.getElementById("terminal");let r=null,o="transcript";const a=l=>{if(n!==null)if(l==="terminal"&&i){if(n.classList.add("console-terminal"),r===null){const h=document.createElement("div");h.className="argus-terminal-mount",n.appendChild(h),r=new IY(h,{open:(d,u,p)=>e.terminal_open(d,u,p),input:(d,u)=>e.terminal_input(d,u),resize:(d,u,p)=>e.terminal_resize(d,u,p)},d=>{a("transcript"),t.line_note(`console: ${d}`)},d=>{n.dataset.terminalState=d}),n.dataset.terminalState="busy",s.screen_set(r)}const c=r;e.mirror_set(!0),t.delegate_set({note:h=>e.note_send(h),offer:h=>c.offer(h),focus:()=>c.focus(),fit:()=>c.size_fit()}),c.size_fit(),o="terminal"}else n.classList.remove("console-terminal"),e.mirror_set(!1),t.delegate_set(null),o="transcript"};return kY(),a(i?"terminal":"transcript"),i||t.line_note(RY),Object.assign(globalThis,{__argusConsole:{mode:()=>o,state:()=>n?.dataset.terminalState??"busy",type:l=>r?.type(l),lines:()=>r?.buffer_lines()??[],mark:()=>r?.mark()??0,since:l=>r?.lines_since(l)??[]}}),{terminal_is:()=>o==="terminal",question_sheet:async l=>{document.querySelector(".question-sheet")?.remove();const c=document.createElement("div");c.className="share-sheet question-sheet",c.setAttribute("role","dialog");const h=document.createElement("div");h.className="share-head",h.textContent="THE SESSION ASKS",c.appendChild(h),document.body.appendChild(c);try{return await V_(t,c,l)}finally{c.remove()}}}}const BY=new Set(["busy","asking","playing"]);function GY(s,e=()=>null){const t=document.querySelector(".console-stop"),i=document.getElementById("terminal");if(t===null||i===null)return;const n=()=>{const o=i.classList.contains("console-terminal")?BY.has(i.dataset.terminalState??""):i.dataset.busy==="true";t.hidden=!o};new MutationObserver(n).observe(i,{attributes:!0,attributeFilter:["data-busy","data-terminal-state","class"]}),n(),t.addEventListener("click",()=>{const r=i.classList.contains("console-terminal")?e():null;r!==null&&s.terminal_input(r,""),s.stop_send()})}let ao=()=>{};function By(){ao(document.body.dataset.zoom==="console"?null:"console")}const PY=ME(),LY=wE(),WY=new URL("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNDAgMjkwIj4KPGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJnIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjQwIiB5MT0iMCIgeDI9IjIwMCIgeTI9IjIyNCI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjMmE2M2JmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjN2FkM2YxIi8+PC9saW5lYXJHcmFkaWVudD4KPHJhZGlhbEdyYWRpZW50IGlkPSJoIj48c3RvcCBvZmZzZXQ9IjAiIHN0b3AtY29sb3I9IiM3YWQzZjEiIHN0b3Atb3BhY2l0eT0iMC40NSIvPjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzdhZDNmMSIgc3RvcC1vcGFjaXR5PSIwIi8+PC9yYWRpYWxHcmFkaWVudD48L2RlZnM+CjxjaXJjbGUgY3g9IjEyMCIgY3k9IjExMiIgcj0iMTA0IiBmaWxsPSJ1cmwoI2gpIi8+PHJlY3QgeD0iMjIuMCIgeT0iNDguMCIgd2lkdGg9IjE5NiIgaGVpZ2h0PSIxMjgiIHJ4PSI2NC4wIiBmaWxsPSJub25lIiBzdHJva2U9IiNjNzQ2MzQiIHN0cm9rZS13aWR0aD0iMTYiLz48bGluZSB4MT0iMTIwIiB5MT0iMTEyIiB4Mj0iMjE0IiB5Mj0iMjIiIHN0cm9rZT0iIzdhZDNmMSIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtZGFzaGFycmF5PSIyIDUiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgb3BhY2l0eT0iMC44Ii8+PGxpbmUgeDE9IjEyMCIgeTE9IjExMiIgeDI9IjI2IiB5Mj0iMjAyIiBzdHJva2U9IiM3YWQzZjEiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWRhc2hhcnJheT0iMiA1IiBzdHJva2UtbGluZWNhcD0icm91bmQiIG9wYWNpdHk9IjAuOCIvPjxwYXRoIGQ9Ik0yMTQsMC4wIEwyMTguNSwxNy41IEwyMzAuMCwyMiBMMjE4LjUsMjYuNSBMMjE0LDQ0LjAgTDIwOS41LDI2LjUgTDE5OC4wLDIyIEwyMDkuNSwxNy41WiIgZmlsbD0idXJsKCNnKSIvPjxwYXRoIGQ9Ik0yNiwxODguOCBMMjguNywxOTkuMyBMMzUuNiwyMDIgTDI4LjcsMjA0LjcgTDI2LDIxNS4yIEwyMy4zLDIwNC43IEwxNi40LDIwMiBMMjMuMywxOTkuM1oiIGZpbGw9InVybCgjZykiLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDEwOC42LDg0LjYgMTIwLjAsMi4wIiBmaWxsPSJ1cmwoI2cpIi8+PHBvbHlnb24gcG9pbnRzPSIxMjAuMCwxMTIuMCAxMjAuMCwyLjAgMTMxLjQsODQuNiIgZmlsbD0idXJsKCNnKSIgZmlsbC1vcGFjaXR5PSIwLjciLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDEzMS40LDg0LjYgMTUxLjEsODAuOSIgZmlsbD0idXJsKCNnKSIvPjxwb2x5Z29uIHBvaW50cz0iMTIwLjAsMTEyLjAgMTUxLjEsODAuOSAxNDcuNCwxMDAuNiIgZmlsbD0idXJsKCNnKSIgZmlsbC1vcGFjaXR5PSIwLjciLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDE0Ny40LDEwMC42IDE5Mi4wLDExMi4wIiBmaWxsPSJ1cmwoI2cpIi8+PHBvbHlnb24gcG9pbnRzPSIxMjAuMCwxMTIuMCAxOTIuMCwxMTIuMCAxNDcuNCwxMjMuNCIgZmlsbD0idXJsKCNnKSIgZmlsbC1vcGFjaXR5PSIwLjciLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDE0Ny40LDEyMy40IDE1MS4xLDE0My4xIiBmaWxsPSJ1cmwoI2cpIi8+PHBvbHlnb24gcG9pbnRzPSIxMjAuMCwxMTIuMCAxNTEuMSwxNDMuMSAxMzEuNCwxMzkuNCIgZmlsbD0idXJsKCNnKSIgZmlsbC1vcGFjaXR5PSIwLjciLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDEzMS40LDEzOS40IDEyMC4wLDIyMi4wIiBmaWxsPSJ1cmwoI2cpIi8+PHBvbHlnb24gcG9pbnRzPSIxMjAuMCwxMTIuMCAxMjAuMCwyMjIuMCAxMDguNiwxMzkuNCIgZmlsbD0idXJsKCNnKSIgZmlsbC1vcGFjaXR5PSIwLjciLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDEwOC42LDEzOS40IDg4LjksMTQzLjEiIGZpbGw9InVybCgjZykiLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDg4LjksMTQzLjEgOTIuNiwxMjMuNCIgZmlsbD0idXJsKCNnKSIgZmlsbC1vcGFjaXR5PSIwLjciLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDkyLjYsMTIzLjQgNDguMCwxMTIuMCIgZmlsbD0idXJsKCNnKSIvPjxwb2x5Z29uIHBvaW50cz0iMTIwLjAsMTEyLjAgNDguMCwxMTIuMCA5Mi42LDEwMC42IiBmaWxsPSJ1cmwoI2cpIiBmaWxsLW9wYWNpdHk9IjAuNyIvPjxwb2x5Z29uIHBvaW50cz0iMTIwLjAsMTEyLjAgOTIuNiwxMDAuNiA4OC45LDgwLjkiIGZpbGw9InVybCgjZykiLz48cG9seWdvbiBwb2ludHM9IjEyMC4wLDExMi4wIDg4LjksODAuOSAxMDguNiw4NC42IiBmaWxsPSJ1cmwoI2cpIiBmaWxsLW9wYWNpdHk9IjAuNyIvPgo8ZyBzdHJva2U9IiNmZmYiIHN0cm9rZS13aWR0aD0iMyIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBmaWxsPSJub25lIj48bGluZSB4MT0iMTIwIiB5MT0iMTEyIiB4Mj0iMTIwLjAiIHkyPSIxNy40Ii8+PGxpbmUgeDE9IjEyMCIgeTE9IjExMiIgeDI9IjE4MS45IiB5Mj0iMTEyLjAiLz48bGluZSB4MT0iMTIwIiB5MT0iMTEyIiB4Mj0iMTIwLjAiIHkyPSIyMDYuNiIvPjxsaW5lIHgxPSIxMjAiIHkxPSIxMTIiIHgyPSI1OC4xIiB5Mj0iMTEyLjAiLz48cG9seWdvbiBwb2ludHM9IjEzMS40LDg0LjYgMTQ3LjQsMTAwLjYgMTQ3LjQsMTIzLjQgMTMxLjQsMTM5LjQgMTA4LjYsMTM5LjQgOTIuNiwxMjMuNCA5Mi42LDEwMC42IDEwOC42LDg0LjYiLz48L2c+CjxnIGZpbGw9IiNmZmYiPjxjaXJjbGUgY3g9IjEyMCIgY3k9IjExMiIgcj0iMTAiLz48Y2lyY2xlIGN4PSIxMjAuMCIgY3k9IjUxLjUiIHI9IjQuNSIvPjxjaXJjbGUgY3g9IjE1OS42IiBjeT0iMTEyLjAiIHI9IjQuNSIvPjxjaXJjbGUgY3g9IjEyMC4wIiBjeT0iMTcyLjUiIHI9IjQuNSIvPjxjaXJjbGUgY3g9IjgwLjQiIGN5PSIxMTIuMCIgcj0iNC41Ii8+PGNpcmNsZSBjeD0iMTMxLjQiIGN5PSI4NC42IiByPSIzLjUiLz48Y2lyY2xlIGN4PSIxNDcuNCIgY3k9IjEwMC42IiByPSIzLjUiLz48Y2lyY2xlIGN4PSIxNDcuNCIgY3k9IjEyMy40IiByPSIzLjUiLz48Y2lyY2xlIGN4PSIxMzEuNCIgY3k9IjEzOS40IiByPSIzLjUiLz48Y2lyY2xlIGN4PSIxMDguNiIgY3k9IjEzOS40IiByPSIzLjUiLz48Y2lyY2xlIGN4PSI5Mi42IiBjeT0iMTIzLjQiIHI9IjMuNSIvPjxjaXJjbGUgY3g9IjkyLjYiIGN5PSIxMDAuNiIgcj0iMy41Ii8+PGNpcmNsZSBjeD0iMTA4LjYiIGN5PSI4NC42IiByPSIzLjUiLz48L2c+Cjx0ZXh0IHg9IjEyMCIgeT0iMjY4IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmb250LWZhbWlseT0iTW9udHNlcnJhdCxIZWx2ZXRpY2EsQXJpYWwsc2Fucy1zZXJpZiIgZm9udC13ZWlnaHQ9IjcwMCIgZm9udC1zaXplPSIzOCIgZmlsbD0iIzJhNjNiZiIgbGV0dGVyLXNwYWNpbmc9IjQiPk9DSSBURDwvdGV4dD4KPC9zdmc+",import.meta.url).href,FY=`data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" fill="#000"/><rect x="6" y="14" width="52" height="36" rx="18" fill="#20bdef"/><rect x="34" y="14" width="24" height="36" fill="#20bdef"/></svg>')}`;function Gy(s){for(const e of document.querySelectorAll('link[rel="icon"], link[rel="apple-touch-icon"]'))e.href=s}const UY="ARGUS",Py="argus-audio",$Y=.4;let yr=!1;const jY={audio1:{file:"press",cue:"press"},audio2:{file:"arrive",cue:"ack"},audio3:{file:"retreat",cue:"close"},audio4:{file:"refuse",cue:"deny"}},JO=new Set;function HY(){fetch("sounds/index.json").then(s=>s.ok?s.json():Promise.resolve(null)).then(s=>{const e=typeof s=="object"&&s!==null?s.files:void 0;if(Array.isArray(e))for(const t of e)typeof t=="string"&&JO.add(t.replace(/\.[a-z0-9]+$/,""))}).catch(()=>{})}function Pi(s){if(yr)return;const e=jY[s];if(e!==void 0&&!JO.has(e.file)){Bs.cue_play(e.cue);return}const t=document.getElementById(s);t instanceof HTMLAudioElement&&(t.currentTime=0,t.volume=$Y,t.play().catch(()=>{}))}function VY(){const s=et("head-menu-pill"),e=t=>{t?document.body.dataset.headMenu="open":delete document.body.dataset.headMenu,s.setAttribute("aria-expanded",String(t))};s.addEventListener("click",t=>{t.stopPropagation(),e(document.body.dataset.headMenu!=="open")}),document.addEventListener("click",t=>{if(document.body.dataset.headMenu!=="open")return;t.target instanceof Element&&t.target.closest("#header-dag-info")!==null||e(!1)})}function qY(){const s=et("audio-pill");try{yr=window.localStorage.getItem(Py)==="off"}catch{yr=!1}const e=()=>{s.classList.toggle("audio-off",yr),Bs.muted_set(yr)};e(),HY(),s.addEventListener("click",()=>{yr=!yr;try{window.localStorage.setItem(Py,yr?"off":"on")}catch{}e(),Pi("audio2")})}function KY(){return yE(window.location)}let hp=null,Hd=0;function hb(s,e){const t=()=>{e.dataset.zoom!==void 0||e.dataset.header==="away"||(Hd=Math.ceil(s.offsetTop+s.offsetHeight),e.style.setProperty("--zoom-header-height",`${Hd}px`))};t(),hp===null&&(hp=new ResizeObserver(t),hp.observe(s))}const Ly=120,YY=96;function XY(s,e,t,i){let n="";const r=h=>{h?(n=s.style.height,s.style.height=""):n!==""&&(s.style.height=n),s.classList.toggle("drawer-closed",h),Pi("audio3"),h||(i.size_fit(),i.focus_take())};t.addEventListener("click",()=>r(!s.classList.contains("drawer-closed")));let o=0,a=0,l=!1;e.addEventListener("pointerdown",h=>{l=!0,o=h.clientY,a=s.getBoundingClientRect().height,s.classList.add("drawer-dragging"),e.setPointerCapture(h.pointerId),h.preventDefault()}),e.addEventListener("pointermove",h=>{if(!l)return;const d=Math.max(Ly,window.innerHeight-YY),u=a+(h.clientY-o),p=Math.min(Math.max(Ly,u),d);s.style.height=`${p}px`,i.size_fit()});const c=()=>{l=!1,s.classList.remove("drawer-dragging")};return e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c),r}function ZY(s){const e=document.body,t=document.querySelector(".wrap:not(#gap)");let i;const n=r=>{for(const o of document.querySelectorAll(".pane-zoomed, .pane-zoomed-path"))o.classList.remove("pane-zoomed","pane-zoomed-path");if(r===null)delete e.dataset.zoom,i!==void 0&&(e.dataset.header=i,i=void 0);else{window.scrollTo(0,0),e.dataset.header==="away"?(i="away",delete e.dataset.header,Hd>0&&e.style.setProperty("--zoom-header-height",`${Hd}px`)):t!==null&&hb(t,e),e.dataset.zoom=r;const a=jh(r)?.mount?.parentElement??null;a?.classList.add("pane-zoomed");let l=a?.parentElement??null;for(;l!==null&&l.id!=="layout-root";)l.classList.add("pane-zoomed-path"),l=l.parentElement}for(const o of document.querySelectorAll(".drawer-zoom"))o.textContent=r!==null&&o.dataset.pane===r?"RESTORE":"ZOOM";Pi("audio3")};return et("header-restore").addEventListener("click",()=>{e.dataset.zoom!==void 0&&n(null)}),document.addEventListener("click",r=>{const o=r.target;if(!(o instanceof Element))return;const a=o.closest("[data-pane]");if(a===null)return;const l=a.dataset.pane??"";l!==""&&n(e.dataset.zoom===l?null:l)}),window.addEventListener("keydown",r=>{r.key==="Escape"&&e.dataset.zoom!==void 0&&(n(null),r.stopImmediatePropagation())}),et("drawer").addEventListener("transitionend",r=>{r.propertyName==="height"&&s.size_fit()}),n}function JY(){const s=new A6(document.getElementById("data-cascade")),e=document.getElementById("header-telemetry");return e!==null&&s.telemetryPanel_bind(e),s}const dp=96,QY=220,Wy="argus.headerBand.height",eX=52;function tX(){const s=document.documentElement,e=document.getElementById("header-strip"),t=document.querySelector(".wrap:not(#gap)");if(e===null||t===null)return;const i=h=>{const d=Math.max(dp,window.innerHeight-QY),u=Math.min(Math.max(dp,h),d);s.style.setProperty("--header-band-h",`${u}px`);try{window.localStorage.setItem(Wy,String(u))}catch{}},n=(()=>{try{return window.localStorage.getItem(Wy)}catch{return null}})();n!==null&&Number.isFinite(Number(n))&&i(Number(n));const r=()=>{const h=t.getBoundingClientRect();e.style.top=`${Math.max(0,h.bottom-eX)}px`};r(),window.addEventListener("resize",r),new MutationObserver(r).observe(document.body,{attributes:!0,attributeFilter:["data-header"]}),window.setInterval(r,500);let o=!1,a=0,l=0;e.addEventListener("pointerdown",h=>{const d=document.querySelector(".header-face");o=!0,a=h.clientY,l=d===null?dp:d.getBoundingClientRect().height,e.setPointerCapture(h.pointerId),h.preventDefault()}),e.addEventListener("pointermove",h=>{o&&(i(l+(h.clientY-a)),r())});const c=()=>{o=!1,r()};e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c)}let db=null;function sX(s){const e=s.querySelector(".gather-rows");if(e===null)return;const t=ai(e,{rows:".listing-row",label:i=>`+${i} MORE · ON STAGE`,press:()=>{db?.()},className:"strategy-pill gather-more",mount:s});t.title="the whole cohort as a pane on the main panel"}function Fy(s){ai(s,{rows:".strategy-pill, .listing-action, .holder-mark",className:"frame-more"})}function iX(){const s=e=>{for(const t of e.querySelectorAll(".mode-frame:not([data-more])"))Fy(t)};new MutationObserver(e=>{for(const t of e)for(const i of t.addedNodes)i instanceof HTMLElement&&(i.matches(".mode-frame")&&i.dataset.more===void 0&&Fy(i),s(i))}).observe(document.body,{childList:!0,subtree:!0}),s(document)}function Uy(s){const e=s?.text;if(typeof e!="string"||e.length===0||typeof window.speechSynthesis>"u")return;const t=new SpeechSynthesisUtterance(e);t.rate=1,window.speechSynthesis.speak(t)}function nX(){const s=document.body,e=document.querySelector(".wrap:not(#gap)"),t=r=>{s.dataset.header===r?(e!==null&&hb(e,s),s.dataset.header="away"):s.dataset.header=r};document.querySelector(".panel-1")?.addEventListener("click",()=>t("stats")),document.querySelector(".panel-2")?.addEventListener("click",()=>t("dag")),document.querySelector(".panel-gather")?.addEventListener("click",()=>t("gather"));const i=document.querySelector(".header-gather-field");i?.querySelector(".gather-stage")?.addEventListener("click",r=>{r.stopPropagation(),db?.()}),i!==null&&sX(i),iX();const n=()=>{s.dataset.zoom===void 0&&(delete s.dataset.header,Pi("audio3"))};et("header-restore").addEventListener("click",n),window.addEventListener("keydown",r=>{r.key==="Escape"&&s.dataset.header==="away"&&s.dataset.zoom===void 0&&s.dataset.gutter!=="away"&&n()})}const ha=[{key:"lower-decks",label:"LOWER DECKS"},{key:"gold",label:"CERRITOS GOLD"},{key:"medical",label:"MEDICAL"},{key:"nemesis",label:"NEMESIS"},{key:"pharos",label:"PHAROS"}],QO="argus-landing",rX=15e3;function $y(){try{return(window.localStorage.getItem(QO)??"launcher")==="launcher"}catch{return!0}}function oX(s){try{window.localStorage.setItem(QO,s?"launcher":"last")}catch{}}const jy="argus-theme",aX="argus-lcars",lX="medical",cX={sickbay:"medical"};function hX(){const s=et("theme-pill"),e=Math.max(ha.findIndex(r=>r.key===lX),0);let t=e;try{const r=window.localStorage.getItem(jy)??window.localStorage.getItem(aX),o=r===null?null:cX[r]??r,a=ha.findIndex(l=>l.key===o);t=a>=0?a:e}catch{t=e}const i=document.documentElement,n=()=>{const r=ha[t]??ha[0];r.key==="lower-decks"?delete i.dataset.theme:i.dataset.theme=r.key,s.textContent=r.label};n(),s.addEventListener("click",()=>{t=(t+1)%ha.length,n();try{window.localStorage.setItem(jy,ha[t]?.key??"lower-decks")}catch{}Pi("audio2")})}function dX(s){const e=document.getElementById("about-rows");if(e===null)return;e.replaceChildren();const i={...c2(s)==="chris"?{cumin:s.stack?.cumin,salsa:s.stack?.salsa,chili:s.stack?.chili}:{},brasa:s.stack?.brasa,calypso:s.stack?.calypso,chell:s.stack?.chell},n=[];for(const[r,o]of Object.entries(i))o!==void 0&&n.push([r.toUpperCase(),o]);n.push(["MENU","0.34.0"],["ARGUS","4fe3a4c7 · 2026-11-02 21:52Z"],["WIRE",`V${s.protocolVersion}`]),s.stack?.build!==void 0&&n.push(["BUILD",s.stack.build]);for(const[r,o]of n){const a=document.createElement("div");a.className="telemetry-row";const l=document.createElement("span");l.className="telemetry-label",l.textContent=r;const c=document.createElement("span");c.className="telemetry-value",c.textContent=o,c.title=o,a.append(l,c),e.appendChild(a)}}function uX(){for(const s of document.querySelectorAll(".left-frame button, .left-frame-top button"))s.addEventListener("click",()=>Pi("audio2"))}let da=null;async function fX(s){let e=null;const t=await zE(s),i=t==="chris";document.body.dataset.composition=t;const n=new w6(document),r=i?f6(et("index-instrument"),{dag_primary:()=>Et,dag_instances:()=>a.values("dag"),universes:()=>a.values("universe"),pacs:()=>ne,runs_show:I=>ze(I)}):{promptContext_take:()=>{},telemetry_take:()=>{},progress_take:()=>{}},o=new S6(et("lane-instrument"),void 0,I=>{Re.line_run(I)});window.setInterval(()=>o.tick(),500);const a=new wj;i&&nM(N6(()=>Ce)),t==="stratus"&&nM(h6(()=>({...Ce,controller_open:I=>Vi.open(I),script_open:I=>qi.open(I)})));const l=new m6;l.writeObserver_set((I,U)=>{st.regard_send({address:I.address,...I.modelKind!==void 0?{modelKind:I.modelKind}:{},groupId:U,paneId:I.paneId}),be()});let c=null,h=!1;const d=async I=>{if(c===!0)return!0;if(!h)return Re.line_note(`${I}: entered as READ, and this session cannot be raised: it was started without a door to ask`),!1;const U=await eE(I);if(U===null)return!1;const ge=await st.elevate(U);return ge.granted?(c=!0,n.mode_show(!0),Vi.mode_refresh(),qi.mode_refresh(),Re.line_note("MODE MANAGE: this session may build, tear down and spend, each after its own question, until you leave it"),!0):(Re.line_note(`MANAGE refused: ${ge.reason??"the door said no"}`),!1)},u={get layout(){return le},panels:a,paneInstance_get:jh,subjects:l,get dormant(){return Le},sound:Pi,get terminal(){return Re},get client(){return st},manage_is:()=>c,elevation_is:()=>h,elevate_ask:d},p=V6(u,{catalogue_find:I=>O.get(I),run_press:(I,U,ge)=>{De(I,U,ge)}}),f=p.entry_show,_=I=>Bg(I,s),g=pj(u,{vfsUrl_build:_,downloadUrl_build:I=>xE(I,s),image_open:(I,U)=>W(I,U),process_open:(I,U)=>ee(I,U),run_press:(I,U,ge)=>{De(I,U,ge)},cohort_gather:I=>qe(I),verbLine_run:(I,U)=>K(I,U),askOnPane_await:(I,U)=>te(I,U),binEntry_show:f,catalogue_find:I=>O.get(I),promptUser:()=>A,template_stamp:sn,pane_find:Js}),{previewProvider:m,fileText_fetch:w,file_save:y,rootedListing_show:M,listing_refresh:v,directory_make:S,files_deliver:x,filesBody_stamp:b,rowVerbs_build:z}=g,T=g.instance_build;let A=null,E=null;const O=new Map,{imageInstance_build:R,tagsInstance_build:C,tagsPane_follow:k,tagsPane_open:G,series_ask:L,image_open:W}=Lj({client:()=>st,terminal:()=>Re,panels:()=>a,subjects:()=>l,layout:()=>le,desktop:()=>_e,instance_spawn:(I,U)=>rs(I,U),errandHost_find:()=>P(),launcher_yield:()=>xe(),birth_record:(I,U,ge,ke,$e)=>ve(I,U,ge,ke,$e),vfsUrl_build:I=>_(I)}),ee=(I,U)=>{xe();const ge=new Set(le.panes_shown());for(const[ut,ui]of O)if(ge.has(ut)&&ui.input===U.input){le.focus_set(ut);return}const ke=ge.has(I)?I:P()??I,$e=rs("catalogue",I);if(!le.leaf_split(ke,_e.replayPlace_get()?.dir??"col",$e.id,_e.replayPlace_get()?.before??!1)){Ds($e.id),le.mount_remove($e.id);return}ve($e.id,ke,_e.replayPlace_get()?.dir??"col",_e.replayPlace_get()?.before??!1),O.set($e.id,U);const yt=a.get("files",$e.id);yt!==void 0&&(yt.binding_set({input:U.input,place:U.feed===null?"new feed":`feed ${U.feed}${U.node===null?"":` · node ${U.node}`}`}),yt.feedOpen_declare(ut=>Pe($e.id,ut)),M($e.id,yt,"/bin"),Ae(yt),le.focus_set($e.id))},X=5,he=40,Ae=I=>{st.line_execute(`plugininstance list --limit ${he} --fields id,plugin_name,plugin_version,owner_username`,{silent:!0,observe:!1}).then(ge=>{const ke=[];for(const $e of ge.envelopes)if(!($e.model?.kind!=="plugininstance.list"||!Array.isArray($e.model.data)))for(const yt of $e.model.data){if(typeof yt.pluginName!="string"||typeof yt.pluginVersion!="string"||A!==null&&typeof yt.owner=="string"&&yt.owner!==A||yt.pluginName==="pl-dircopy")continue;const ut=`${yt.pluginName}-v${yt.pluginVersion}`;if(ke.includes(ut)||ke.push(ut),ke.length>=X)break}I.recent_set(ke.length===0?null:ke)}).catch(()=>{})},Pe=(I,U)=>{xe();const ge=new Set(le.panes_shown());for(const[yt,ut]of a.entries("dag"))if(yt!=="dag"&&ge.has(yt)&&ut.feed_get()===U){le.focus_set(yt);return}const ke=ge.has(I)?I:P()??I,$e=rs("dag",I);if(!le.leaf_split(ke,_e.replayPlace_get()?.dir??"col",$e.id,_e.replayPlace_get()?.before??!1)){Ds($e.id),le.mount_remove($e.id);return}ve($e.id,ke,_e.replayPlace_get()?.dir??"col",_e.replayPlace_get()?.before??!1),a.get("dag",$e.id)?.feed_enter(U)},De=async(I,U,ge)=>{const ke=O.get(I),$e=a.get("files",I);if(ke===void 0||$e===void 0)return;const yt=qs=>{Re.output_write("err",`\x1B[31m${qs}\x1B[0m
|
|
4400
4400
|
`);const Su=$e.indicated_get();Su!==null&&$e.rowReadout_show(Su,qs.toUpperCase().slice(0,80))};if(ge==="pipeline"&&ke.node===null){yt(`${U}: a pipeline runs on a node — PROCESS a node of a feed`);return}let ut=$e.commandLine_get();if((ut===""||t1(ut)!==U)&&(ut=Jz(ke.input,U)),ke.feed===null&&!$G(ut)){const qs=ke.input.split("/").filter(Boolean).pop()??"feed",Mb=(await te(I,{message:"Feed title: ",kind:"text",suggest:qs,commit:"RUN"})??"").trim();if(Mb==="")return;ut=jG(ut,Mb)}$e.commandLine_set(ut),Re.line_echo(ut);let ui;try{ui=await st.line_execute(ut,{silent:!0})}catch(qs){yt(qs instanceof Error?qs.message:String(qs));return}Re.outcome_write(ui),ui.envelopes.some(qs=>qs.model?.kind==="fs.cwd")&&st.line_execute("ls",{silent:!0});const bc=ui.envelopes.find(qs=>qs.model?.kind==="run.scheduled"||qs.model?.kind==="pipeline.scheduled")?.model?.data;if(typeof bc?.feedId=="number"){$e.run_show(bc.feedId);return}const _b=ui.envelopes.map(qs=>qs.renderedErr??"").join(" ").replace(/\x1b\[[0-9;]*m/g,"").trim().split(`
|
|
4401
4401
|
`)[0]??"",bb=$e.indicated_get();bb!==null&&$e.rowReadout_show(bb,_b===""?"NOT SCHEDULED":_b.toUpperCase().slice(0,80))},ie=I=>{xe();const U=new Set(le.panes_shown());for(const[ut]of a.entries("files"))if(U.has(ut)&&l.regard_get(ut)?.address===I){le.focus_set(ut);return}let ge;for(const[ut,ui]of a.entries("image"))if(U.has(ut)&&(l.regard_get(ut)?.address===I||ui.state_get()?.path===I)){ge=ut;break}const ke=P();if(ke===null)return;const $e=rs("files",ge);if(!le.leaf_split(ke,_e.replayPlace_get()?.dir??"col",$e.id,_e.replayPlace_get()?.before??!1)){Ds($e.id),le.mount_remove($e.id);return}ve($e.id,ke,_e.replayPlace_get()?.dir??"col",_e.replayPlace_get()?.before??!1),ge===void 0&&l.regard_write($e.id,{address:I,modelKind:"dicom.series"});const yt=a.get("files",$e.id);yt!==void 0&&M($e.id,yt,I)},oe=Q6(u,{image_open:(I,U)=>W(I,U),process_open:(I,U)=>ee(I,U),feed_open:(I,U)=>Pe(I,U),askOnPane_await:(I,U)=>te(I,U),errandHost_find:()=>P(),instance_spawn:(I,U)=>rs(I,U),birth_record:(I,U,ge,ke)=>ve(I,U,ge,ke),replayPlace_get:()=>_e.replayPlace_get(),stage_relight:()=>be(),home_apply:()=>Me(),orphans_dispose:()=>Xe(),template_stamp:sn,pane_find:Js,element_require:et}),pe=oe.instance_build,qe=oe.gather,Qe=oe.open,Ke=I=>{const U=sn("tpl-pane-view");ai(Js(U,".view-body"));const ge=new p6(Js(U,".view-body"),Js(U,".view-title"),{content_fetch:async ke=>(await w(ke)).text,imageUrl_build:_,path_isImage:tu});return a.set("view",I,ge),{id:I,kind:"view",mount:U,dispose:()=>{a.delete(I),l.pane_leave(I)}}},gt=q6(u,{filesBody_stamp:b,rootedListing_show:M,rowVerbs_build:z,image_open:(I,U)=>W(I,U),imagery_is:zx,tableFile_is:I=>Sx.test(I),vfsUrl_build:_,fileText_fetch:w,previewProvider:m}),Ne=gt.open;gt.close;const St=ej(u,{askOnPane_await:(I,U)=>te(I,U),promptUser:()=>A,changed:()=>{for(const I of a.values("dag"))I.roster_ask(),I.marks_refresh(),I.indicated_refresh()}}),zt=_j({client:()=>st,terminal:()=>Re,panels:()=>a,subjects:()=>l,context:()=>u,feedVerbs:()=>St,nodeOverlay:()=>gt,nodeOverlay_open:(I,U)=>Ne(I,U),process_open:(I,U)=>ee(I,U),promptUser:()=>A,runs_show:()=>ze(),dag_primary:()=>Et,binEntry_show:(I,U,ge,ke)=>f(I,U,ge,ke),dag_summon:()=>Nt()}),ft=T("files",!0);uh(ft);const ns=Wj({panes:zt,dicom:{imageInstance_build:R,tagsInstance_build:C},gather_build:pe,pacsMount:et("pacs-workspace")}),Ft=i?ns:{primaries:[],domains:[],presets:[],factories:[]};for(const I of Ft.primaries)uh(I);for(const I of Ft.domains)bj(I);const Vt=sn("tpl-pane-launcher");uh({id:"launcher",kind:"launcher",mount:Vt});const Zt=sn("tpl-pane-panes");uh({id:"panes",kind:"panes",mount:Zt});const qt=a.get("files","files"),Et=a.get("dag","dag"),H=new I6(et("pipeline-cycler"),et("pipeline-cycler-name"),I=>{st.line_execute(I,{silent:!0})});let ms=null;const xt=K6(u,{instance_spawn:(I,U)=>rs(I,U),birth_record:(I,U,ge,ke)=>ve(I,U,ge,ke),replayPlace_get:()=>_e.replayPlace_get(),rootedListing_show:M,console_expose:()=>ms?.(!1),questionSheet_ask:I=>e!==null&&e.terminal_is()?e.question_sheet(I):null}),{errandHost_find:P,errand_open:D,verbLine_run:K,askOnPane_await:te}=xt;ai(et("pacs-workspace"),{rows:".listing-row"});const ne=new tP(et("pacs-workspace"),{command_run:I=>{const U=/^(pacs query|pull )/.test(I);U&&Re.line_echo(I),st.line_execute(I,{silent:!0,operator:U}).then(ge=>{for(const ke of ge.envelopes)ne.envelope_observe(ke)})},command_show:I=>{Re.line_run(I)},note:I=>Re.line_note(I),image_open:I=>{W(null,I).then(U=>Re.line_note(U))},dir_open:I=>ie(I),process_open:I=>ee("pacs",{input:I,feed:null,node:null}),gather_add:I=>qe([I]),gathered_is:I=>oe.has(I),workspace_close:()=>Me()}),be=()=>{const I=new Set(le.panes_shown()),U=new Map;for(const ge of Hh()){if(!I.has(ge.id))continue;const ke=l.regard_get(ge.id)?.address;if(ke===void 0)continue;const $e=Oe(ge.id);if($e!=="image"&&$e!=="files")continue;const yt=ke.replace(/\/$/,""),ut=U.get(yt)??{viewer:!1,browser:!1};$e==="image"?ut.viewer=!0:ut.browser=!0,U.set(yt,ut)}ne.stage_lit(U)},le=new B6(et("layout-root"),new Map([...Ft.primaries.map(I=>[I.id,I.mount]),["files",ft.mount],["launcher",Vt],["panes",Zt]]));let re=!1;const ue=()=>re?{dir:"col",ratio:.45,first:{pane:"files"},second:{pane:"dag"}}:{pane:"files"};le.preset_register("files",ue);for(const[I,U]of Ft.presets)le.preset_register(I,U);le.preset_register("panes",()=>({pane:"panes"})),le.preset_register("launcher",()=>({pane:"launcher"})),le.renderObserver_set(()=>{document.body.dataset.zoom==="launcher"&&!le.panes_shown().includes("launcher")&&ao(null),window.requestAnimationFrame(()=>{for(const I of a.values("dag"))I.size_fit()})});const ye=(I,U,ge,ke)=>{const $e=U==="view"?rs("view",I):U==="fs"?rs("files",I):rs("empty");if(!le.leaf_split(I,ge,$e.id,ke))return Ds($e.id),le.mount_remove($e.id),null;if(ve($e.id,I,ge,ke,U),U==="fs"){const yt=ui=>{const yu=a.get("files",$e.id);if(yu===void 0)return;const bc=ui.modelKind==="fs.file"?ui.address.replace(/\/[^/]*$/,"")||"/":ui.address;M($e.id,yu,bc)};l.regard_subscribe($e.id,yt);const ut=l.regard_get(I);ut!==null&&yt(ut)}return $e.id},Le=new oE(Hy,Vy());Object.assign(globalThis,{__argusDormant:{list:()=>Le.list(),get:I=>Le.get(I),dismiss:I=>Le.dismiss(I)}});const _e=W6(u,{image_open:W,dir_open:ie,process_open:ee,gather_open:Qe,feed_open:Pe,edit_open:I=>se.edit_open(I),pillPane_spawn:ye,pacsQuery_get:()=>ne.query_get(),catalogue_find:I=>O.get(I),catalogueIds:()=>[...O.keys()],stage_relight:()=>be()}),{birth_record:ve,domain_enter:Fe,orphans_dispose:Xe}=_e,ot=_e.capture,$=_e.restore,Me=()=>{Fe("files"),Et.size_fit()},de=()=>{Fe("launcher"),Ge.render(),le.focus_set("launcher"),ao("launcher")},Se=(I=!1)=>{if(document.body.dataset.zoom!=="launcher"||(ao(null),!I))return;const U=document.querySelector(".wrap:not(#gap)");U!==null&&hb(U,document.body),document.body.dataset.header="away",ms?.(!0)},xe=()=>{Se(),le.activePreset_get()==="launcher"&&(re=!1,Me())};let me=!1;const je=LG({ask:I=>st.line_execute(I,{silent:!0,observe:!1}),home_open:()=>{re=!1,Me(),le.focus_set("files")},home_cd:I=>{re=!1,Me(),Re.line_run(`cd "${I}"`)},desktops:()=>Le.list(),desktop_restore:I=>{$(I)},panes_open:()=>{Fe("panes"),$t.render(),le.focus_set("panes")},keys_open:()=>{Va()},notes_open:()=>{N.open()},notes_latest:()=>N.latest(),daemon_stale:()=>me,console_open:()=>et("gutter-console").click(),...i?{contribution:Fj({ask:I=>st.line_execute(I,{silent:!0,observe:!1}),universe_show:()=>Be(),runs_show:I=>ze(I),feed_enter:I=>{ze(),a.get("dag","dag")?.feed_enter(I)},line_offer:I=>Re.line_offer(I),pacs_query:()=>ne.query_get()??"",pacs_open:()=>{Fe("pacs"),le.focus_set("pacs")},cloud_enter:Pa(window.location.search)?()=>{et("gutter-console").click(),Re.line_run("stratus oci")}:null})}:{},...t!=="stratus"?{}:{contribution:a6({ask:I=>st.line_execute(I,{silent:!0,observe:!1}),cluster_open:I=>{Vi.open(I)},script_open:I=>{qi.open(I)},home_open:()=>{re=!1,Me(),le.focus_set("files")},line_run:I=>{et("gutter-console").click(),Re.line_run(I)},capacity_open:I=>{V.open(I)},names_seen:I=>_c(I),repaint:()=>Ge.render()})}}),Ge=new vG(Vt,{tiles:je,leave:()=>Se(!0),startHere_get:$y,startHere_set:oX});setInterval(()=>{le.activePreset_get()==="launcher"&&(!Vt.isConnected||document.visibilityState!=="visible"||Ge.render())},rX),ai(Js(Zt,".panes-body"),{rows:".panes-card"});const $t=new pE(Zt,{list:()=>Le.list(),restore:I=>{$(I)},dismiss:I=>{Le.dismiss(I)}}),Nt=()=>{const I=le.activePreset_get();if(I==="pacs"||I==="dag"||I==="launcher"){re=!0;return}re&&I==="files"||(re=!0,Me())},rs=(I,U)=>{const ge=vj(I);return l.pane_join(ge.id,U!==void 0?l.group_resolve(U):ge.id),I==="tags"&&l.regard_subscribe(ge.id,ke=>{ke.modelKind==="dicom.instance"&&k(ge.id,ke.address)}),I==="view"&&(l.viewer_mark(ge.id),l.regard_subscribe(ge.id,ke=>{ke.modelKind!=="dicom.instance"&&a.get("view",ge.id)?.regard_show(ke)})),le.mount_register(ge.id,ge.mount),Yr(ge.id,I,ge.mount),ge},{bar_note:xi,move:mc,flip:gc,resize:$a,chordKeys_format:ja}=P6(u),Yr=b8(u,{verbs:{move:mc,chordKeys_format:ja},browser:g,pillPane_spawn:ye,process_open:(I,U)=>ee(I,U),overlay_back:I=>gt.back(I),home_apply:()=>Me(),orphans_dispose:()=>Xe(),dag_dismiss:()=>{re=!1}});Yr("files","files",ft.mount);for(const I of Ft.primaries)Yr(I.id,I.kind,I.mount);Yr("launcher","launcher",Vt),Yr("panes","panes",Zt);let Xr=!1;const cn=I=>{Xr=I};for(const I of["click","focusin"])document.addEventListener(I,U=>{U.target instanceof Element&&(U.target.closest("#drawer")!==null?Xr=!0:U.target.closest("#layout-root")!==null&&(Xr=!1))});const hn=()=>{let I=!1;for(const U of document.querySelectorAll(".pane-drawer:not([hidden])"))U.hidden=!0,I=!0;return I},Bo=()=>{let I=!1;for(const U of document.querySelectorAll('.workspace-pane[data-modes="open"], [data-frame-host][data-modes="open"]'))delete U.dataset.modes,I=!0;return ne.serverStrip_isOpen()&&(ne.serverStrip_close(),I=!0),I};document.addEventListener("click",I=>{if(!(I.target instanceof Element)||I.target.closest(".mode-frame")!==null&&I.target.closest(".mode-fill")===null||I.target.closest("#pacs-server-strip")!==null||I.target.closest("#pacs-f-server")!==null||I.target.closest(".listing-framed .listing-row, .ask-bar")!==null)return;const U=I.target.closest(".mode-strip"),ge=U?.closest(".workspace-pane, [data-frame-host]")??null,ke=ge?.dataset.modes==="open",$e=Bo();if(U!==null&&ge!==null&&!ke){ge.dataset.modes="open",Pi("audio3");return}$e&&Pi("audio3")}),_8(u,{palette_isOpen:()=>!Ue.hidden,palette_open:()=>Dt(),palette_close:()=>Bt(),errand_abandon:()=>xt.errand_abandon(),dive_leave:()=>p.dive_leave(),overlay_escape:()=>gt.escape(),drawers_close:hn,modeFrames_close:Bo,consoleFocused:()=>Xr,console_release:()=>cn(!1),verbs:{bar_note:xi,flip:gc,resize:$a},host:()=>Ce,stage_alone:I=>{ot(),le.tree_set({pane:I}),Xe()},element_require:et});const Hi=new oP,Ha=(I,U)=>{const ge=rs(U);return le.leaf_replace(I,ge.id),Ds(I),le.mount_remove(I),ge};Hi.claim_add("fs.listing","files"),i&&aP(Hi,{dag_target:()=>{const I=le.focused_get();return I!==null&&a.has("dag",I)?a.get("dag",I):Et},dags:()=>[Et,...a.values("dag")],universes:()=>a.values("universe"),pacs:()=>ne,pacs_present:()=>{le.preset_apply("pacs"),Xe()},image_open:(I,U)=>{W(le.focused_get(),I,U?{force:!0}:{}).then(ge=>Re.line_note(ge))},pane_replace:(I,U)=>Ha(I,U).id,cohort_adopt:I=>oe.envelope_observe(I),dag_get:I=>a.get("dag",I),image_get:I=>a.get("image",I),tags_get:I=>a.get("tags",I)});const Go=(I,U,ge)=>{const ke=Hi.claimer_get(U);if(ke!==void 0){ke(I,ge);return}const $e=Ha(I,U),yt=a.get("files",$e.id);for(const ut of ge)yt?.envelope_observe(ut)},cr={instance_spawn:rs,birth_record:ve,launcher_yield:xe,launcher_active:()=>le.activePreset_get()==="launcher",template_stamp:sn},Zr=iH(u,cr),Va=Zr.open,qa=zH(u,cr),Oi=G9(u);function _c(I){c6(I)&&u.client.claims_send(iM())}const Vi=Q9(u,I=>_c(I)),qi=n8(u),N=c8(u,{...cr,ask:I=>st.line_execute(I,{silent:!0})}),V=p8(u,{...cr,ask:I=>st.line_execute(I,{silent:!0})}),se=tH(u,{...cr,replayPlace_get:_e.replayPlace_get,errandHost_find:P,saved:()=>{for(const I of a.values("dag"))I.marks_refresh()}});fn("files",I=>T(I,!1)),fn("catalogue",I=>T(I,!1,!0)),fn("view",Ke),fn("help",Zr.instance_build),fn("games",qa.instance_build),fn("notes",N.instance_build),fn("capacity",V.instance_build),fn("edit",se.instance_build);for(const[I,U]of Ft.factories)fn(I,U);fn("empty",I=>{const U=sn("tpl-pane-empty");return new nP(U,{execute:ge=>st.line_execute(ge,{silent:!0,observe:!1}),claim:(ge,ke)=>Go(I,ge,ke),claimKind_find:ge=>Hi.claimKind_find(ge)}),{id:I,kind:"empty",mount:U}});const J=I=>{I?document.body.dataset.gutter="away":delete document.body.dataset.gutter,Pi("audio3")},Z=(I,U)=>{if(le.activePreset_get()===I&&le.panes_shown().includes(I)){J(!0);return}document.body.dataset.gutter==="away"&&delete document.body.dataset.gutter,U()};et("gutter-restore").addEventListener("click",()=>J(!1)),window.addEventListener("keydown",I=>{I.key==="Escape"&&document.body.dataset.gutter==="away"&&document.body.dataset.zoom===void 0&&J(!1)}),et("gutter-files").addEventListener("click",()=>{Z("files",()=>{re=!1,Me(),le.focus_set("files"),cn(!1)})});const ze=(I="")=>{Fe("dag"),Et.stage_returned(),Et.list_reset(),Et.roster_filter(I),Et.feedsChooser_request(),le.focus_set("dag"),cn(!1)},Be=()=>{Fe("universe");const I=a.get("universe","universe");I!==void 0&&!I.shown_get()&&I.request(),I?.stage_returned(),le.focus_set("universe"),cn(!1)};et("gutter-runs").addEventListener("click",()=>Z("dag",()=>ze())),et("gutter-console").addEventListener("click",()=>{et("drawer").classList.contains("drawer-closed")&&et("drawer-toggle").click(),Re.focus_take(),cn(!0)}),et("gutter-tools").addEventListener("click",()=>{Z("pacs",()=>{Fe("pacs"),le.focus_set("pacs"),cn(!1)})}),et("gutter-dashboard").addEventListener("click",()=>{Z("launcher",de)}),et("gutter-panes").addEventListener("click",()=>{Z("panes",()=>{Fe("panes"),$t.render(),le.focus_set("panes"),cn(!1)})});const Oe=I=>jh(I)?.kind??null,Ce=v8(u,{verbs:{move:mc,flip:gc,resize:$a},help_open:Va,notes_open:N.open,capacity_open:V.open,launcher_enter:de,manage_is:()=>c,elevate_ask:d,trek_open:I=>Oi.active_is()?"trek: the bridge is already up":(Oi.open(I),"trek: the bridge takes the screen (Esc or LEAVE BRIDGE gives it back)"),identity_get:()=>E,consoleZoom_toggle:By,feed_enter:I=>Et.feed_enter(I),file_save:y,stage_keep:()=>ot(),files_open:(I,U)=>{const ge=a.get("files",I);return ge===void 0?!1:(g.follow_set(I,!1),M(I,ge,U),!0)},image_open:(I,U,ge)=>W(I,U,ge),series_ask:L,tagsPane_open:G}),Ue=et("lang-palette"),Je=et("lang-input"),lt=et("lang-result"),He=et("lang-pill"),Dt=()=>{hn(),Ue.hidden=!1,He.classList.add("lang-live"),lt.textContent="",Je.value="",Je.focus(),Pi("audio3")},Bt=()=>{Ue.hidden=!0,He.classList.remove("lang-live"),lt.textContent=""};He.addEventListener("click",()=>{Ue.hidden?Dt():Bt()});const Kt=["pane","view","runs","node","dag","file","pacs","header","console","back","desktop","argus","help","notes","capacity"],Ct={pane:["split","zoom","close","bind","claim","focus","flip","resize"],resize:["left","right","up","down"],help:["keys","verbs"],notes:["pane"],capacity:["pane"],focus:["left","right","up","down","last"],view:["files","runs","pacs"],runs:["enter","sort","filter"],node:["enter","immerse","back","clear"],dag:["layout","projection","scale","hue","draw","pulse","census","gravity","select","enter","physics","refresh"],draw:["spheres","stars"],pulse:["on","off"],census:["on","off"],gravity:["on","off"],physics:["charge","link","collide","gravity","reset"],file:["home","back","download","delete","sort","filter","follow","root","list","cards","preview"],pacs:["sort","filter","connect","disconnect","list","query","pull","status"],header:["stats","dag","away","restore"],console:["open","close","toggle","zoom","height"],desktop:["save","load","show","list","delete","clear","share"],split:["left","right","above","below"],bind:["unlinked","fs","viewer"],claim:["files","runs","pacs"],layout:["ranked","molecule"],projection:["2d","3d"],scale:["time","size"],hue:["status","compute"],argus:["verbs"]};if(Je.addEventListener("keydown",I=>{if(I.key==="Escape"){I.stopPropagation(),Bt();return}if(I.key==="Tab"){I.preventDefault();const U=Je.value.split(/\s+/),ge=U[U.length-1]??"",ke=U.length<=1?"":U[U.length-2]??"",yt=(U.length<=1?Kt:Ct[ke]??Ct[U[0]??""]??[]).find(ut=>ut.startsWith(ge.toLowerCase()));yt!==void 0&&(U[U.length-1]=yt,Je.value=`${U.join(" ")} `);return}if(I.key==="Enter"){const U=Je.value.trim();if(U.length===0){Bt();return}Nh(Ce,U).then(ge=>{ge!==null&&(Oi.active_is()||Vi.active_is()||qi.active_is())?(Re.output_write("data",`: ${U}
|
|
4402
4402
|
${ge}
|