var y=typeof window<"u"&&window.__MARKON_I18N__?.t||(o=>o),U={t(o,...t){let e=typeof window<"u"&&window.__MARKON_I18N__?.t||null;return e?e(o,...t):o}},h={BREAKPOINTS:{WIDE_SCREEN:1400},DIMENSIONS:{NOTE_CARD_WIDTH:280,NOTE_CARD_RIGHT_MARGIN:40,HEADING_TOP_MARGIN:64,HEADING_TOP_MARGIN_TIGHT:5,POPOVER_OFFSET:10},THRESHOLDS:{NOTE_CLUSTER:50,NOTE_MIN_SPACING:32,HEADING_SCROLL_THRESHOLD:40},WEBSOCKET:{INITIAL_RECONNECT_DELAY:1e3,MAX_RECONNECT_DELAY:3e4,STABLE_CONNECTION_THRESHOLD:5e3},ANIMATION:{RESIZE_DEBOUNCE:150,PANEL_TRANSITION:200},UNDO:{MAX_STACK_SIZE:50},SHORTCUTS:{HELP:{key:"?",ctrl:!1,shift:!1,desc:y("web.kbd.help"),cat:"global"},THEME_PANEL:{key:"t",ctrl:!1,shift:!1,desc:y("web.kbd.theme"),cat:"global"},UNDO:{key:"z",ctrl:!0,shift:!1,desc:y("web.kbd.undo"),cat:"core"},REDO:{key:"z",ctrl:!0,shift:!0,desc:y("web.kbd.redo"),cat:"core"},REDO_ALT:{key:"y",ctrl:!0,shift:!1,desc:y("web.kbd.redo.alt"),cat:"core"},ESCAPE:{key:"Escape",ctrl:!1,shift:!1,desc:y("web.kbd.escape"),cat:"core"},TOGGLE_TOC:{key:"\\",ctrl:!0,shift:!1,desc:y("web.kbd.toc"),cat:"core"},SEARCH:{key:"/",ctrl:!1,shift:!1,desc:y("web.kbd.search"),cat:"search",feature:"workspace_spotlight"},EXPORT_NOTES:{key:"x",ctrl:!1,shift:!1,desc:y("web.kbd.exportnotes"),cat:"core"},WORKSPACE_NAVIGATOR:{key:"g",ctrl:!1,shift:!1,desc:y("web.kbd.workspace_nav"),cat:"search",feature:"workspace_spotlight"},PREV_HEADING:{key:"k",ctrl:!1,shift:!1,desc:y("web.kbd.prevheading"),cat:"nav"},NEXT_HEADING:{key:"j",ctrl:!1,shift:!1,desc:y("web.kbd.nextheading"),cat:"nav"},PREV_ANNOTATION:{key:"k",ctrl:!0,shift:!1,desc:y("web.kbd.prevanno"),cat:"nav"},NEXT_ANNOTATION:{key:"j",ctrl:!0,shift:!1,desc:y("web.kbd.nextanno"),cat:"nav"},SCROLL_HALF_PAGE_DOWN:{key:" ",ctrl:!1,shift:!1,desc:y("web.kbd.scroll"),cat:"nav"},TOGGLE_SECTION_COLLAPSE:{key:"o",ctrl:!1,shift:!1,desc:y("web.kbd.collapse"),cat:"viewed"},TOGGLE_VIEWED:{key:"v",ctrl:!1,shift:!1,desc:y("web.kbd.viewed"),cat:"viewed"},EDIT:{key:"e",ctrl:!1,shift:!1,desc:y("web.kbd.edit"),cat:"edit"},TOGGLE_LIVE_ACTIVE:{key:"l",ctrl:!1,shift:!1,desc:y("web.kbd.live.active"),cat:"live"},TOGGLE_LIVE_OFF:{key:"l",ctrl:!1,shift:!0,desc:y("web.kbd.live.off"),cat:"live"},TOGGLE_CHAT:{key:"c",ctrl:!1,shift:!1,desc:y("web.kbd.chat"),cat:"chat"},TOGGLE_CHAT_ALT:{key:"c",ctrl:!1,shift:!0,desc:y("web.kbd.chat.alt"),cat:"chat"},DIFF_TOGGLE_VIEW:{key:"m",ctrl:!1,shift:!1,desc:y("web.kbd.diff.view"),cat:"diff"},DIFF_NEXT_FILE:{key:"n",ctrl:!1,shift:!1,desc:y("web.kbd.diff.nextfile"),cat:"diff"},DIFF_PREV_FILE:{key:"p",ctrl:!1,shift:!1,desc:y("web.kbd.diff.prevfile"),cat:"diff"},VISUAL_ZOOM_IN:{key:"+",ctrl:!1,shift:!1,desc:y("web.kbd.visual.zoom_in"),cat:"visual",feature:"visual_zoom_in"},VISUAL_ZOOM_IN_ALT:{key:"=",ctrl:!1,shift:!1,desc:y("web.kbd.visual.zoom_in"),cat:"visual",feature:"visual_zoom_in"},VISUAL_ZOOM_OUT:{key:"-",ctrl:!1,shift:!1,desc:y("web.kbd.visual.zoom_out"),cat:"visual"},VISUAL_ZOOM_RESET:{key:"0",ctrl:!1,shift:!1,desc:y("web.kbd.visual.reset"),cat:"visual",feature:"visual_reset"},VISUAL_ZOOM_RESET_ALT:{key:"r",ctrl:!1,shift:!1,desc:y("web.kbd.visual.reset"),cat:"visual",feature:"visual_reset"},VISUAL_ZOOM_FIT:{key:"f",ctrl:!1,shift:!1,desc:y("web.kbd.visual.fit"),cat:"visual",feature:"visual_fit"},VISUAL_ZOOM_FIT_CMD:{key:"0",ctrl:!0,shift:!1,desc:y("web.kbd.visual.fit"),cat:"visual",feature:"visual_fit"},VISUAL_ZOOM_TOOL:{key:"z",ctrl:!1,shift:!1,desc:y("web.kbd.visual.tool"),cat:"visual"},VISUAL_ZOOM_TOOL_OUT:{key:"z",ctrl:!1,shift:!0,desc:y("web.kbd.visual.tool_out"),cat:"visual"},VISUAL_ZOOM_CLOSE:{key:"Escape",ctrl:!1,shift:!1,desc:y("web.kbd.visual.close"),cat:"visual",feature:"ESCAPE"}},STORAGE_KEYS:{ANNOTATIONS:o=>`markon-annotations-${o}`,VIEWED:o=>`markon-viewed-${o}`,LIVE_POS:"markon-live-pos",LIVE_COLOR:"markon-user-color",IDENTITY_NAME:"markon-user-name",LIVE_MODE:"markon-live-mode",CLIENT_ID:"markon-client-id",CHAT_POS:"markon-chat-pos",CHAT_SIZE:"markon-chat-size",NOTE_INPUT_OFFSET:"markon-note-input-offset",NOTE_INPUT_SIZE:"markon-note-input-size",POPOVER_OFFSET:"markon-popover-offset",SHORTCUTS_HELP_POS:"markon-shortcuts-help-pos",WORKSPACE_SPOTLIGHT_POS:"markon-workspace-spotlight-pos"},SELECTORS:{MARKDOWN_BODY:".markdown-body",HEADINGS:"h1, h2, h3, h4, h5, h6",TOC_CONTAINER:"#toc-container",TOC_ICON:"#toc-icon",HIGHLIGHT_CLASSES:".highlight-orange, .highlight-green, .highlight-yellow, .strikethrough"},SKIP_ELEMENTS:{IDS:new Set(["toc"]),CLASSES:new Set(["back-link","toc","selection-popover","note-card-margin","note-popup"])},META_TAGS:{FILE_PATH:"file-path",WORKSPACE_ID:"workspace-id",SHARED_ANNOTATION:"shared-annotation",ENABLE_SEARCH:"enable-search",ENABLE_VIEWED:"enable-viewed",ENABLE_EDIT:"enable-edit",ENABLE_LIVE:"enable-live",ENABLE_CHAT:"enable-chat",DEFAULT_CHAT_MODE:"default-chat-mode",CHAT_ONLY:"chat-only"},WS_MESSAGE_TYPES:{ALL_ANNOTATIONS:"all_annotations",NEW_ANNOTATION:"new_annotation",DELETE_ANNOTATION:"delete_annotation",CLEAR_ANNOTATIONS:"clear_annotations",VIEWED_STATE:"viewed_state",UPDATE_VIEWED_STATE:"update_viewed_state",LIVE_ACTION:"live_action",FILE_CHANGED:"file_changed"},COLLABORATION:{COLORS:["#3451B2","#E64560","#27AE60","#F39C12","#8E44AD","#0EA5E9","#EC4899","#14B8A6"],SYNC_DEBOUNCE:100},ANNOTATION_TYPES:{STRIKETHROUGH:"strikethrough",HAS_NOTE:"has-note"},HTML_TAGS:{HIGHLIGHT:"span",STRIKETHROUGH:"s"},BLOCK_TAGS:["P","DIV","LI","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","TD","TH"]};if(typeof window<"u"&&window.__MARKON_SHORTCUTS__){let o=Object.entries(window.__MARKON_SHORTCUTS__);for(let[t,e]of o)h.SHORTCUTS[t]&&Object.assign(h.SHORTCUTS[t],e)}Object.freeze(h);Object.freeze(h.BREAKPOINTS);Object.freeze(h.DIMENSIONS);Object.freeze(h.THRESHOLDS);Object.freeze(h.WEBSOCKET);Object.freeze(h.ANIMATION);Object.freeze(h.UNDO);Object.freeze(h.SHORTCUTS);Object.freeze(h.SELECTORS);Object.freeze(h.SKIP_ELEMENTS);Object.freeze(h.META_TAGS);Object.freeze(h.WS_MESSAGE_TYPES);Object.freeze(h.COLLABORATION);Object.freeze(h.ANNOTATION_TYPES);Object.freeze(h.HTML_TAGS);var D=class{static isMac(){return navigator.platform.toUpperCase().includes("MAC")}static isNarrowScreen(){return window.innerWidth<=h.BREAKPOINTS.WIDE_SCREEN}static isWideScreen(){return window.innerWidth>h.BREAKPOINTS.WIDE_SCREEN}};function nt(o,t){let e,n=((...i)=>{e!==void 0&&clearTimeout(e),e=setTimeout(()=>{e=void 0,o(...i)},t)});return n.cancel=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},n}var q={uuid(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`},short(){return Math.random().toString(36).slice(2,11)}},u=class o{static#t=!0;static enable(){o.#t=!0}static disable(){o.#t=!1}static log(t,e,...n){o.#t&&console.log(`[${t}]`,e,...n)}static warn(t,e,...n){o.#t&&console.warn(`[${t}]`,e,...n)}static error(t,e,...n){console.error(`[${t}]`,e,...n)}};function Yt(o){return o.split("/").filter((t,e,n)=>t!==""||e>0&&e<n.length-1).map(encodeURIComponent).join("/")}function it(o){return encodeURIComponent(o.trim().replace(/^\/+|\/+$/g,""))}function mt(o){return o.trim().replace(/^\/+/,"")}function zt(o){let t=it(o);return t?`/${t}/`:"/"}function gt(o,t=""){let e=t.trim().replace(/^\/+/,""),n=zt(o);return e?`${n}${Yt(e)}`:n}function vt(o,t){let e=it(o),n=mt(t);return e?`/_/${e}/${n}`:`/_/${n}`}function yt(o){return vt(o,"chat")}function bt(o){return vt(o,"ws")}function A(o,t=""){let e=it(o),n=mt(t);return e?n?`/api/chat/${e}/${n}`:`/api/chat/${e}`:n?`/api/chat/${n}`:"/api/chat"}var ot={getBlockParent(o,t){let e=o.nodeType===3?o.parentElement:o;for(;e&&e!==t;){if(h.BLOCK_TAGS.includes(e.tagName))return e;e=e.parentElement}return null},findLastTextNode(o){let t=null,e=n=>{if(n.nodeType===3&&(n.textContent??"").trim())t=n;else if(n.nodeType===1)for(let i of n.childNodes)e(i)};return e(o),t},shouldSkip(o){if(o.nodeType!==1)return!1;let t=o;return t.id&&h.SKIP_ELEMENTS.IDS.has(t.id)?!0:t.className&&typeof t.className=="string"?t.className.split(" ").some(e=>h.SKIP_ELEMENTS.CLASSES.has(e)):!1},getHeight(o,t=80){let e=o.offsetHeight;return e>0?e:t},onOutsideClick(o,t,{ignore:e}={}){let n=s=>{o.contains(s.target)||e?.(s.target)||t(s)},i=()=>document.removeEventListener("click",n,!0);return document.addEventListener("click",n,!0),i}},S={get(o){return document.querySelector(`meta[name="${o}"]`)?.getAttribute("content")??null},flag(o){return this.get(o)==="true"}};var Et=(o,t,e,n)=>({left:o,top:t,right:o+e,bottom:t+n,width:e,height:n});function Xt(o){return o.sort((t,e)=>t.rolePriority-e.rolePriority||(t.id<e.id?-1:t.id>e.id?1:0))}function N(o,t){if(o.shape==="circle")return Et(t.x,t.y,40,40);let{width:e,height:n}=o.box,i=o.panelAnchor,s=i==="TL"||i==="BL"?t.x:t.x+40-e,r=i==="TL"||i==="TR"?t.y:t.y+40-n;return Et(s,r,e,n)}function G(o,t,e){let n=e.viewport.width,i=e.viewport.height,s=e.margins.minVisible,r=Math.max(s-40,Math.min(Number(t.x)||0,n-s)),a=Math.max(s-40,Math.min(Number(t.y)||0,i-s));if(o.active&&o.shape==="rect"){let l=e.margins.panelInset,c=N(o,{x:r,y:a});c.right>n-l&&(r-=c.right-(n-l)),c.bottom>i-l&&(a-=c.bottom-(i-l));let p=N(o,{x:r,y:a});p.left<l&&(r+=l-p.left),p.top<l&&(a+=l-p.top)}return{x:r,y:a}}function Zt(o,t,e,n,i){if(t==="circle"&&n==="circle"){let r=Math.min(e.width,e.height)/2,a=o.left+20,l=o.top+20,c=e.left+e.width/2,p=e.top+e.height/2;return Math.hypot(a-c,l-p)<20+r+i}if(t==="circle"){let r=o.left+20,a=o.top+20,l=Math.max(e.left,Math.min(r,e.right)),c=Math.max(e.top,Math.min(a,e.bottom));return Math.hypot(r-l,a-c)<20+i}if(n==="circle"){let s=Math.min(e.width,e.height)/2,r=e.left+e.width/2,a=e.top+e.height/2,l=Math.max(o.left,Math.min(r,o.right)),c=Math.max(o.top,Math.min(a,o.bottom));return Math.hypot(r-l,a-c)<s+i}return!(o.right+i<=e.left||e.right+i<=o.left||o.bottom+i<=e.top||e.bottom+i<=o.top)}function Tt(o,t,e){let n=N(o,t);for(let i of e)if(Zt(n,o.shape,i.rect,i.shape,o.gap))return!0;return!1}function wt(o,t,e){let n=N(o,t),i=o.gap,s=0;for(let r of e){let a=Math.min(n.right+i,r.rect.right)-Math.max(n.left-i,r.rect.left),l=Math.min(n.bottom+i,r.rect.bottom)-Math.max(n.top-i,r.rect.top);a>0&&l>0&&(s+=a*l)}return s}function Jt(o,t,e,n,i,s,r){let a=Math.max(n.left,Math.min(o,n.right)),l=Math.max(n.top,Math.min(t,n.bottom)),c=o-a,p=t-l,d=Math.hypot(c,p),f=e+i;if(d===0){let w=s.width,g=s.height,m=(k,C)=>k-e>=0&&k+e<=w&&C-e>=0&&C+e<=g,R=[{newCx:n.left-f,newCy:t,mag:o-n.left},{newCx:n.right+f,newCy:t,mag:n.right-o},{newCx:o,newCy:n.top-f,mag:t-n.top},{newCx:o,newCy:n.bottom+f,mag:n.bottom-t}];R.sort((k,C)=>{let K=m(k.newCx,k.newCy),P=m(C.newCx,C.newCy);return K!==P?K?-1:1:k.mag-C.mag});let x=R[0];return x?r(x.newCx,x.newCy):r(o,t)}if(d>=f)return r(o,t);let b=c/d,E=p/d;return r(a+b*f,l+E*f)}function Qt(o,t,e,n,i){let s=Math.max(o.left,Math.min(e,o.right)),r=Math.max(o.top,Math.min(n,o.bottom)),a=e-s,l=n-r;if(Math.hypot(a,l)>=i)return t;let p=[{axis:"x",delta:e-i-o.right},{axis:"x",delta:e+i-o.left},{axis:"y",delta:n-i-o.bottom},{axis:"y",delta:n+i-o.top}];p.sort((f,b)=>Math.abs(f.delta)-Math.abs(b.delta));let d=p[0];return d?{x:t.x+(d.axis==="x"?d.delta:0),y:t.y+(d.axis==="y"?d.delta:0)}:t}function te(o,t,e,n){let i=N(o,t),s=o.shape,r=e.rect,a=e.shape,l=o.gap;if(s==="circle"&&a==="circle"){let g=Math.min(r.width,r.height)/2,m=i.left+20,R=i.top+20,x=r.left+r.width/2,k=r.top+r.height/2,C=m-x,K=R-k,P=Math.hypot(C,K),et=20+g+l;if(P>=et)return t;let Vt=P===0?0:C/P,Ut=P===0?1:K/P,qt=x+Vt*et,jt=k+Ut*et;return{x:qt-20,y:jt-20}}if(s==="circle"&&a==="rect"){let g=i.left+20,m=i.top+20;return Jt(g,m,20,r,l,n,(R,x)=>({x:R-20,y:x-20}))}if(s==="rect"&&a==="circle"){let w=Math.min(r.width,r.height)/2,g=r.left+r.width/2,m=r.top+r.height/2;return Qt(i,t,g,m,w+l)}let c=Math.min(i.right,r.right)-Math.max(i.left,r.left),p=Math.min(i.bottom,r.bottom)-Math.max(i.top,r.top);if(c<=-l||p<=-l)return t;let d=c+l,f=p+l;if(d<f){let w=(i.left+i.right)/2,g=(r.left+r.right)/2;return{x:t.x+(w<g?-d:d),y:t.y}}let b=(i.top+i.bottom)/2,E=(r.top+r.bottom)/2;return{x:t.x,y:t.y+(b<E?-f:f)}}function ee(o,t,e,n){let i=[40,60,90,130,180,240,320,420,560],s=[{dx:0,dy:-1},{dx:1,dy:0},{dx:-1,dy:0},{dx:0,dy:1},{dx:1,dy:-1},{dx:-1,dy:-1},{dx:1,dy:1},{dx:-1,dy:1}],r=null,a=1/0;for(let p of i)for(let d of s){let f=G(o,{x:t.x+d.dx*p,y:t.y+d.dy*p},n);if(!Tt(o,f,e))return f;let b=wt(o,f,e)+Math.hypot(f.x-t.x,f.y-t.y)*.001;b<a&&(a=b,r=f)}let l=G(o,t,n);return(wt(o,l,e)<a||r===null)&&(r=l),r}function st(o,t,e){let n={...o.home};for(let i=0;i<8;i++){let s=!1;for(let r of t){let a=te(o,n,r,e.viewport);(a.x!==n.x||a.y!==n.y)&&(n=a,s=!0)}if(!s)break}return n=G(o,n,e),Tt(o,n,t)&&(n=ee(o,o.home,t,e)),n}function _t(o,t){return{id:o.id,rolePriority:o.rolePriority,rect:N(o,t),shape:o.shape}}function kt(o){let t=[...o.items].sort((r,a)=>r.rolePriority-a.rolePriority||(r.id<a.id?-1:r.id>a.id?1:0)),e=[],n=[];for(let r of t)r.passive?e.push(_t(r,r.home)):n.push(r);let i=[],s=[];for(let r of n){let a=Xt(e.concat(s.filter(c=>c.rolePriority<=r.rolePriority)).filter(c=>c.id!==r.id)),l=st(r,a,o);i.push({id:r.id,pos:l}),s.push(_t(r,l))}return i}function St(o,t,e,n){if(o>40){let i=n,s=Math.max(i,t-n-o);return{lo:i,hi:s}}return{lo:e-o,hi:t-e}}function Lt(o,t,e,n,i,s){let{width:r,height:a}=o,l=St(r,i.width,s.minVisible,s.panelInset),c=St(a,i.height,s.minVisible,s.panelInset),p=(g,m)=>g<m.bottom&&g+a>m.top,d=(g,m)=>g<m.right&&g+r>m.left,f=t.x,b=Math.min(Math.max(e.x,l.lo),l.hi);if(b>f){let g=b;for(let m of n)p(t.y,m)&&m.left-r>=f&&m.left-r<g&&(g=m.left-r);f=g}else if(b<f){let g=b;for(let m of n)p(t.y,m)&&m.right<=f&&m.right>g&&(g=m.right);f=g}let E=t.y,w=Math.min(Math.max(e.y,c.lo),c.hi);if(w>E){let g=w;for(let m of n)d(f,m)&&m.top-a>=E&&m.top-a<g&&(g=m.top-a);E=g}else if(w<E){let g=w;for(let m of n)d(f,m)&&m.bottom<=E&&m.bottom>g&&(g=m.bottom);E=g}return{x:f,y:E}}var $={getAbsolute(o){let t=o.getBoundingClientRect(),e=window.scrollY||window.pageYOffset,n=window.scrollX||window.pageXOffset;return{left:t.left+n,top:t.top+e,right:t.right+n,bottom:t.bottom+e}},constrainToViewport(o,t,e,n,i={}){let s=i.margin??10,r=i.fixed?0:window.scrollX||window.pageXOffset,a=i.fixed?0:window.scrollY||window.pageYOffset,l=o,c=t;return l<r+s&&(l=r+s),l+e>window.innerWidth+r-s&&(l=window.innerWidth+r-e-s),c<a+s&&(c=a+s),c+n>window.innerHeight+a-s&&(c=window.innerHeight+a-n-s),{left:l,top:c}},smartScrollToHeading(o){let t=o.closest(".heading-section")??o;if(!(t instanceof HTMLElement))return;let e=t.offsetHeight,n=window.innerHeight;if(e<=n){let i=n-e,s=i>=h.DIMENSIONS.HEADING_TOP_MARGIN?h.DIMENSIONS.HEADING_TOP_MARGIN:i/2,r=t.getBoundingClientRect().top+window.scrollY-s;window.scrollTo({top:r,behavior:"smooth"})}else{let i=t.getBoundingClientRect().top+window.scrollY-h.DIMENSIONS.HEADING_TOP_MARGIN_TIGHT;window.scrollTo({top:i,behavior:"smooth"})}}};var B=["button","input","textarea","select","option","a[href]",'[contenteditable="true"]',"[data-no-drag]"].join(", "),rt=(o,t=B)=>!t||!(o instanceof Node)?!1:!!(o instanceof Element?o:o.parentElement)?.closest(t),j=class{#t;#o=[];#e;#l=!1;#v=0;#a=0;#d=0;#c=0;#n={};#h="";#s=!1;constructor(t,e={}){this.#t=t,this.#e={storageKey:null,handle:null,onDragEnd:null,saveOffset:!1,restoreOffset:!1,savePosition:!1,restorePosition:!1,fixed:!1,margin:10,nonDragSelector:B,handleClassName:null,...e},this.#y()}#y(){if(typeof this.#e.handle=="string"?this.#o=Array.from(this.#t.querySelectorAll(this.#e.handle)):this.#o=[this.#e.handle??this.#t],this.#o.length===0){u.warn("Draggable","Handle element not found");return}if(this.#e.handleClassName)for(let t of this.#o)t.classList.add(this.#e.handleClassName);this.#e.restorePosition?this.#S():this.#e.restoreOffset&&this.#x(),this.#n.mousedown=t=>this.#r(t),this.#n.mousemove=t=>this.#b(t),this.#n.mouseup=()=>this.#N(),this.#n.touchstart=t=>this.#r(t),this.#n.touchmove=t=>this.#b(t),this.#n.touchend=()=>this.#N();for(let t of this.#o)t.addEventListener("mousedown",this.#n.mousedown),t.addEventListener("touchstart",this.#n.touchstart,{passive:!1})}#r(t){if(t instanceof MouseEvent&&t.button!==0||rt(t.target,this.#e.nonDragSelector))return;this.#l=!0;let e=this.#H(t);this.#v=e.x,this.#a=e.y;let n=this.#O();this.#d=n.left,this.#c=n.top,this.#t.style.cursor="grabbing";for(let i of this.#o)i.classList.add("is-dragging");this.#h=document.body.style.userSelect,this.#s=!0,document.body.style.userSelect="none",this.#n.mousemove&&document.addEventListener("mousemove",this.#n.mousemove),this.#n.mouseup&&document.addEventListener("mouseup",this.#n.mouseup),this.#n.touchmove&&document.addEventListener("touchmove",this.#n.touchmove,{passive:!1}),this.#n.touchend&&document.addEventListener("touchend",this.#n.touchend),t.preventDefault()}#b(t){if(!this.#l)return;let e=this.#H(t),n=e.x-this.#v,i=e.y-this.#a,s=this.#d+n,r=this.#c+i;({left:s,top:r}=$.constrainToViewport(s,r,this.#t.offsetWidth,this.#t.offsetHeight,{fixed:this.#e.fixed,margin:this.#e.margin})),this.#T(s,r)}#N(){if(this.#l){this.#l=!1,this.#t.style.cursor="";for(let t of this.#o)t.classList.remove("is-dragging");if(this.#s&&(document.body.style.userSelect=this.#h,this.#s=!1),this.#n.mousemove&&document.removeEventListener("mousemove",this.#n.mousemove),this.#n.mouseup&&document.removeEventListener("mouseup",this.#n.mouseup),this.#n.touchmove&&document.removeEventListener("touchmove",this.#n.touchmove),this.#n.touchend&&document.removeEventListener("touchend",this.#n.touchend),this.#e.saveOffset&&this.#e.storageKey&&this.#I(),this.#e.savePosition&&this.#e.storageKey&&this.#_(),this.#e.onDragEnd){let t=parseFloat(this.#t.style.left)||0,e=parseFloat(this.#t.style.top)||0;this.#e.onDragEnd(t,e)}}}#I(){let t=parseFloat(this.#t.style.left)||0,e=parseFloat(this.#t.style.top)||0,n=parseFloat(this.#t.dataset.originalLeft??""),i=parseFloat(this.#t.dataset.originalTop??"");if(!isNaN(n)&&!isNaN(i)&&this.#e.storageKey){let s={dx:t-n,dy:e-i};localStorage.setItem(this.#e.storageKey,JSON.stringify(s)),u.log("Draggable",`Saved offset to ${this.#e.storageKey}:`,s)}}#x(){if(!this.#e.storageKey)return;let t=parseFloat(this.#t.dataset.originalLeft??""),e=parseFloat(this.#t.dataset.originalTop??"");if(!(!Number.isFinite(t)||!Number.isFinite(e)))try{let n=JSON.parse(localStorage.getItem(this.#e.storageKey)||"null");if(!n||typeof n!="object")return;let i=n,s=typeof i.dx=="number"?i.dx:0,r=typeof i.dy=="number"?i.dy:0;if(!Number.isFinite(s)||!Number.isFinite(r))return;let a=$.constrainToViewport(t+s,e+r,this.#t.offsetWidth,this.#t.offsetHeight,{fixed:this.#e.fixed,margin:this.#e.margin});this.#T(a.left,a.top)}catch{}}#_(){if(!this.#e.storageKey)return;let t=parseFloat(this.#t.style.left),e=parseFloat(this.#t.style.top);!Number.isFinite(t)||!Number.isFinite(e)||(localStorage.setItem(this.#e.storageKey,JSON.stringify({left:t,top:e})),u.log("Draggable",`Saved position to ${this.#e.storageKey}`))}#S(){if(this.#e.storageKey)try{let t=JSON.parse(localStorage.getItem(this.#e.storageKey)||"null");if(!t||typeof t!="object")return;let e=t,n=typeof e.left=="number"?e.left:e.x,i=typeof e.top=="number"?e.top:e.y;if(typeof n!="number"||typeof i!="number")return;let s=$.constrainToViewport(n,i,this.#t.offsetWidth,this.#t.offsetHeight,{fixed:this.#e.fixed,margin:this.#e.margin});this.#T(s.left,s.top)}catch{}}#O(){let t=this.#t.getBoundingClientRect(),e=this.#e.fixed?0:window.scrollX||window.pageXOffset,n=this.#e.fixed?0:window.scrollY||window.pageYOffset,i=parseFloat(this.#t.style.left),s=parseFloat(this.#t.style.top),r=Number.isFinite(i)?i:t.left+e,a=Number.isFinite(s)?s:t.top+n;return this.#T(r,a),{left:r,top:a}}#T(t,e){this.#t.style.position=this.#e.fixed?"fixed":"absolute",this.#t.style.left=`${t}px`,this.#t.style.top=`${e}px`,this.#t.style.right="auto",this.#t.style.bottom="auto",this.#t.style.margin="0",this.#t.style.transform="none"}#H(t){if(t.type==="touchstart"||t.type==="touchmove"){let n=t,i=n.touches[0]??n.changedTouches[0];if(!i){let s=this.#O();return{x:s.left,y:s.top}}return this.#e.fixed?{x:i.clientX,y:i.clientY}:{x:i.pageX,y:i.pageY}}let e=t;return this.#e.fixed?{x:e.clientX,y:e.clientY}:{x:e.pageX,y:e.pageY}}destroy(){for(let t of this.#o)this.#n.mousedown&&t.removeEventListener("mousedown",this.#n.mousedown),this.#n.touchstart&&t.removeEventListener("touchstart",this.#n.touchstart),this.#e.handleClassName&&t.classList.remove(this.#e.handleClassName),t.classList.remove("is-dragging");this.#l&&(this.#n.mousemove&&document.removeEventListener("mousemove",this.#n.mousemove),this.#n.mouseup&&document.removeEventListener("mouseup",this.#n.mouseup),this.#n.touchmove&&document.removeEventListener("touchmove",this.#n.touchmove),this.#n.touchend&&document.removeEventListener("touchend",this.#n.touchend)),this.#t.style.cursor="",this.#s&&(document.body.style.userSelect=this.#h,this.#s=!1),u.log("Draggable","Destroyed")}};var O=new Map,xt=20,Ot=8,ne=10,ie=5,Y=60,Mt=4,Ct="20px",oe={toc:0,chat:1,live:2},se=2,F=class o{static get(t){return O.get(t)}static all(){return O.values()}name;_opts;_passive;_draggable;_expandable;_expandedClass;_homeAnchor;_panelAnchor;_gap;_rolePriority;_home=null;_intentionalHome=null;_isDragging=!1;_morphAnim=null;_classObserver=null;_resizeRaf=null;_docClickHandler=null;_resizeHandler=null;constructor(t){if(!t?.name)throw new Error("FloatingLayer: name required");if(!t.container)throw new Error("FloatingLayer: container required");if(O.has(t.name))throw new Error(`FloatingLayer: duplicate name "${t.name}"`);this.name=t.name,this._opts=t,this._passive=!!t.passive,this._draggable=!this._passive&&t.draggable!==!1,this._expandable=!this._passive&&t.expandable!==!1,this._expandedClass=t.expandedClass||"expanded",this._homeAnchor=t.homeAnchor||"BR",this._panelAnchor=t.panelAnchor||this._homeAnchor,this._gap=t.gap??ne,this._rolePriority=t.rolePriority??oe[t.name]??se,O.set(this.name,this)}init(){if(this._passive){this._observeObstacleClass(),o._relayout();return}this._home=this._loadHome(),this._intentionalHome={...this._home},this._applyDisplayed(),this._bindEvents(),o._relayout()}destroy(){O.delete(this.name),this._classObserver&&this._classObserver.disconnect(),this._morphAnim&&(this._morphAnim.cancel(),this._morphAnim=null),this._docClickHandler&&(document.removeEventListener("click",this._docClickHandler),this._docClickHandler=null),this._resizeHandler&&(window.removeEventListener("resize",this._resizeHandler),this._resizeHandler=null),this._resizeRaf!==null&&(cancelAnimationFrame(this._resizeRaf),this._resizeRaf=null)}get isExpanded(){return this._opts.container.classList.contains(this._expandedClass)}toggle(){this.isExpanded?this.collapse():this.expand()}expand(){if(this._passive||this.isExpanded)return;for(let p of O.values())p!==this&&(p._passive?p.isExpanded&&p._opts.collapseExpanded&&p._opts.collapseExpanded():(p.isExpanded||p._morphAnim)&&p._snapToSphere());this._applyDisplayed();let t=this._opts.container.getBoundingClientRect(),e={x:t.left,y:t.top},n=this._placeSelf(!0,this._intentionalHome);this._home=n;let i=Math.hypot(n.x-e.x,n.y-e.y),s=this._opts.container;this._morphAnim&&(this._morphAnim.cancel(),this._morphAnim=null),this._applyDisplayed();let r=e.x-n.x,a=e.y-n.y,l=i<Mt?null:s.animate([{transform:`translate(${r}px, ${a}px)`},{transform:"translate(0, 0)"}],{duration:Y,easing:"ease",fill:"none"}),c=()=>{this._morphAnim&&(this._morphAnim.cancel(),this._morphAnim=null),this._beginExpandPhase2()};l?(this._morphAnim=l,l.onfinish=c):c(),o._relayout()}_beginExpandPhase2(){let t=this._opts.container;t.classList.add(this._expandedClass),this._applyDisplayed(),this._opts.onExpand&&this._opts.onExpand();let e=window.getComputedStyle(t),n=e.width,i=e.height,s=e.borderRadius;this._morphAnim=t.animate([{width:`${40}px`,height:`${40}px`,borderRadius:Ct},{width:n,height:i,borderRadius:s}],{duration:Y,easing:"ease",fill:"none"}),this._morphAnim.onfinish=()=>{this._morphAnim&&(this._morphAnim.cancel(),this._morphAnim=null),o._relayout()}}collapse(){if(this._passive||!this.isExpanded&&!this._morphAnim)return;let t=this._opts.container;if(this._morphAnim){try{this._morphAnim.commitStyles()}catch{}this._morphAnim.cancel(),this._morphAnim=null}let e=window.getComputedStyle(t),n={width:e.width,height:e.height,borderRadius:e.borderRadius};this._morphAnim=t.animate([n,{width:`${40}px`,height:`${40}px`,borderRadius:Ct}],{duration:Y,easing:"ease",fill:"forwards"}),this._morphAnim.onfinish=()=>{if(this._morphAnim){try{this._morphAnim.commitStyles()}catch{}this._morphAnim.cancel(),this._morphAnim=null,this._beginCollapsePhase2()}}}_beginCollapsePhase2(){let t=this._opts.container,e=t.getBoundingClientRect(),n={x:e.left,y:e.top},i=this._clampSelf(!1,this._intentionalHome);this._home=i,t.classList.remove(this._expandedClass),t.style.width="",t.style.height="",t.style.borderRadius="",t.style.transform="",this._applyDisplayed();let s=this._placeSelf(!1,i),r=n.x-s.x,a=n.y-s.y;if(Math.hypot(r,a)<Mt){this._opts.onCollapse&&this._opts.onCollapse(),o._relayout();return}t.style.transform=`translate(${r}px, ${a}px)`,this._morphAnim=t.animate([{transform:`translate(${r}px, ${a}px)`},{transform:"translate(0, 0)"}],{duration:Y,easing:"ease",fill:"forwards"}),this._morphAnim.onfinish=()=>{if(this._morphAnim){try{this._morphAnim.commitStyles()}catch{}this._morphAnim.cancel(),this._morphAnim=null,t.style.transform="",this._opts.onCollapse&&this._opts.onCollapse(),o._relayout()}}}_snapToSphere(){if(this._passive||!this.isExpanded&&!this._morphAnim)return;this._morphAnim&&(this._morphAnim.cancel(),this._morphAnim=null),this._home=this._clampSelf(!1,this._intentionalHome);let t=this._opts.container;t.classList.remove(this._expandedClass),t.style.width="",t.style.height="",t.style.borderRadius="",t.style.transform="",this._applyDisplayed(),this._opts.onCollapse&&this._opts.onCollapse(),o._relayout()}getObstacleRect(){if(this._opts.getObstacleRect)return this._opts.getObstacleRect();if((this.isExpanded||this._morphAnim)&&this._opts.panelSize&&this._home){let e=this._opts.container.getBoundingClientRect();return this.isExpanded&&!this._morphAnim&&e.width>0&&e.height>0?e:N(this._toLayoutItem(!0),this._home)}let t=this._opts.container.getBoundingClientRect();return t.width===0||t.height===0?null:t}getObstacleShape(){if(this._opts.getObstacleShape)return this._opts.getObstacleShape();if((this.isExpanded||this._morphAnim)&&this._opts.panelSize)return"rect";let t=this.getObstacleRect();return t&&Math.abs(t.width-40)<4&&Math.abs(t.height-40)<4?"circle":"rect"}_bindEvents(){let t=this._opts.handle||this._opts.container;if(this._expandable&&(t.addEventListener("click",e=>{this._isDragging||(e.stopPropagation(),this.toggle())}),this._docClickHandler=e=>{if(!this.isExpanded)return;let n=e.target;n instanceof Node&&this._opts.container.contains(n)||this.collapse()},document.addEventListener("click",this._docClickHandler)),this._draggable){t.addEventListener("mousedown",n=>{this.isExpanded||n.button===0&&this._beginDrag(n)});let e=this._resolveExpandedDragHandles();for(let n of e)n.addEventListener("mousedown",i=>{this.isExpanded&&i.button===0&&(rt(i.target,this._opts.nonDragSelector??null)||this._beginDrag(i))})}this._resizeHandler=()=>{this._passive||this._resizeRaf===null&&(this._resizeRaf=requestAnimationFrame(()=>{this._resizeRaf=null,this._home&&(this._home=this._clampSelf(this.isExpanded,this._home)),o._relayout()}))},window.addEventListener("resize",this._resizeHandler)}_resolveExpandedDragHandles(){let t=this._opts.expandedDragHandle;return t?typeof t=="string"?Array.from(this._opts.container.querySelectorAll(t)):[t]:this._opts.body?[this._opts.body]:[]}_observeObstacleClass(){this._classObserver=new MutationObserver(()=>o._relayout()),this._classObserver.observe(this._opts.container,{attributes:!0,attributeFilter:["class"]})}relayout(){o._relayout()}_beginDrag(t){t.preventDefault();let e={x:t.clientX,y:t.clientY},n={...this._home},i={...n},s=!1,r=l=>{let c=l.clientX-e.x,p=l.clientY-e.y;if(!s&&Math.hypot(c,p)<ie)return;s=!0,this._isDragging=!0;let d=this._toLayoutItem(this.isExpanded),f=d.box,b=N(d,i),E=b.left-i.x,w=b.top-i.y,g=this._clampSelf(this.isExpanded,{x:n.x+c,y:n.y+p}),m={x:g.x+E,y:g.y+w},R={x:i.x+E,y:i.y+w},x=this._collectAllPeerRects(),k=Lt(f,R,m,x,o._sceneFrame().viewport,{minVisible:xt,panelInset:Ot});i={x:k.x-E,y:k.y-w},this._home=i,this._intentionalHome={...i},this._writeDisplayed(i)},a=()=>{if(document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",a),this._isDragging=!1,!s)return;this._persistHome();let l=c=>{c.stopImmediatePropagation(),c.preventDefault(),window.removeEventListener("click",l,!0)};window.addEventListener("click",l,!0),setTimeout(()=>window.removeEventListener("click",l,!0),0)};document.addEventListener("mousemove",r),document.addEventListener("mouseup",a)}_loadHome(){let t=this._opts;if(t.storageKey)try{let e=JSON.parse(localStorage.getItem(t.storageKey)||"null");if(e&&typeof e=="object"){let n=e;if(typeof n.x=="number"&&typeof n.y=="number")return this._clampSelf(!1,{x:n.x,y:n.y});if(typeof n.right=="number"||typeof n.bottom=="number")return this._clampSelf(!1,this._offsetToScreen(n))}}catch{}return this._clampSelf(!1,this._offsetToScreen(t.initialOffset||{right:20,bottom:20}))}_persistHome(){!this._opts.storageKey||!this._intentionalHome||localStorage.setItem(this._opts.storageKey,JSON.stringify(this._intentionalHome))}_offsetToScreen(t){let e=window.innerWidth,n=window.innerHeight,i=0,s=0;return typeof t.left=="number"?i=t.left:typeof t.right=="number"&&(i=e-t.right-40),typeof t.top=="number"?s=t.top:typeof t.bottom=="number"&&(s=n-t.bottom-40),{x:i,y:s}}_measurePanelBox(){if(this._opts.panelSize){let t=this._opts.container.getBoundingClientRect();return this.isExpanded&&!this._morphAnim&&t.width>0&&t.height>0?{width:t.width,height:t.height}:{...this._opts.panelSize}}return{width:40,height:40}}_toLayoutItem(t){let e=t??(this.isExpanded||!!this._morphAnim||this._isDragging),n=e&&this._opts.panelSize?this._measurePanelBox():{width:40,height:40},i=n.width===40&&n.height===40;return{id:this.name,rolePriority:this._rolePriority,active:e,passive:this._passive,home:this._home??this._intentionalHome??{x:0,y:0},homeAnchor:this._homeAnchor,panelAnchor:this._panelAnchor,box:n,shape:i?"circle":"rect",gap:this._gap}}_placeSelf(t,e){let n=this._toLayoutItem(t);n.home=e;let i=this._collectPeerObstacles(n.rolePriority);return st(n,i,o._sceneFrame())}_clampSelf(t,e){let n=this._toLayoutItem(t);return n.home=e,G(n,e,o._sceneFrame())}_collectPeerObstacles(t){let e=[];for(let n of O.values()){if(n===this||n._rolePriority>t)continue;let i=n.getObstacleRect();i&&e.push({id:n.name,rolePriority:n._rolePriority,rect:at(i),shape:n.getObstacleShape()})}return e}_collectAllPeerRects(){let t=[];for(let e of O.values()){if(e===this)continue;let n=e.getObstacleRect();n&&t.push(at(n))}return t}_applyDisplayed(){if(this._passive)return;let t=this._home;t&&this._writeDisplayed(this._placeSelf(this.isExpanded,t))}_writeDisplayed(t){if(this._passive)return;let e=this._opts.container;e.style.position="fixed",e.style.top=e.style.right=e.style.bottom=e.style.left="";let n=this.isExpanded?this._panelAnchor:this._homeAnchor,i=n==="TL"||n==="TR",s=n==="TL"||n==="BL",r=window.innerWidth,a=window.innerHeight,l=40;i?e.style.top=`${t.y}px`:e.style.bottom=`${a-t.y-l}px`,s?e.style.left=`${t.x}px`:e.style.right=`${r-t.x-l}px`}static _sceneFrame(){return{viewport:{width:window.innerWidth,height:window.innerHeight},margins:{minVisible:xt,panelInset:Ot}}}static _buildScene(){let t=[];for(let n of O.values()){if(!n._passive&&!n._home)continue;let i=n._toLayoutItem();if(n._passive){let s=n.getObstacleRect();if(!s)continue;let r=at(s);i.home={x:r.left,y:r.top},i.box={width:r.width,height:r.height},i.shape=n.getObstacleShape(),i.panelAnchor="TL"}t.push(i)}let e=o._sceneFrame();return{viewport:e.viewport,items:t,margins:e.margins}}static _relayout(){let t=kt(o._buildScene());for(let e of t){let n=O.get(e.id);!n||n._passive||n._morphAnim||n._writeDisplayed(e.pos)}}};function at(o){return{left:o.left,top:o.top,right:o.right,bottom:o.bottom,width:o.width,height:o.height}}var rn=window.__MARKON_I18N__?.t||(o=>o),re="markon-modal-drag-handle",At=".markon-modal-frame-drag-region",an=`${B}, .markon-modal-frame > *`,Nt=()=>`
<span class="markon-modal-frame-drag-region markon-modal-frame-drag-top" aria-hidden="true"></span>
<span class="markon-modal-frame-drag-region markon-modal-frame-drag-right" aria-hidden="true"></span>
<span class="markon-modal-frame-drag-region markon-modal-frame-drag-bottom" aria-hidden="true"></span>
<span class="markon-modal-frame-drag-region markon-modal-frame-drag-left" aria-hidden="true"></span>
`,It=(o,t)=>new j(o,{handle:t.handle,storageKey:t.storageKey??null,saveOffset:t.storageMode==="offset"&&!!t.storageKey,restoreOffset:t.storageMode==="offset"&&!!t.storageKey,savePosition:(t.storageMode??"position")==="position"&&!!t.storageKey,restorePosition:(t.storageMode??"position")==="position"&&!!t.storageKey,fixed:!0,margin:t.margin??10,nonDragSelector:t.nonDragSelector??B,handleClassName:re});async function ae(o){let t=`HTTP ${o.status}${o.statusText?` ${o.statusText}`:""}`,e="";try{let n=(await o.text()).trim();n&&(e=le(n))}catch{e=""}return e?`${t}: ${e}`:t}function le(o){try{let t=JSON.parse(o);if(t&&typeof t=="object"){let e=t;for(let n of["error","message","detail"]){let i=e[n];if(typeof i=="string"&&i.trim())return Ht(i)}}}catch{}return Ht(o)}function Ht(o){let t=o.replace(/\s+/g," ").trim();return t.length>500?`${t.slice(0,497)}...`:t}var ce={"&":"&","<":"<",">":">",'"':""","'":"'"};function v(o){return String(o).replace(/[&<>"']/g,t=>ce[t]??t)}function he(o){let t=o.trim();return t?/^[./?#]/.test(t)?!0:/^(https?:|mailto:)/i.test(t):!1}function lt(o){let t=v(o),e=[];return t=t.replace(/`([^`]+)`/g,(n,i)=>(e.push(i),` CODE${e.length-1} `)),t=t.replace(/\*\*([^*\n]+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/(^|[^*])\*([^*\n]+?)\*(?!\*)/g,"$1<em>$2</em>"),t=t.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(n,i,s)=>he(s)?`<a href="${s}" target="_blank" rel="noopener noreferrer">${i}</a>`:i),t=t.replace(/ CODE(\d+) /g,(n,i)=>`<code>${v(e[Number(i)])}</code>`),t}function de(o){if(!o)return"";let t=(typeof o=="string"?o:JSON.stringify(o)??"").split(`
`),e=[],n=0;for(;n<t.length;){let i=t[n]??"";if(/^```(\S*)\s*$/.exec(i)){let a=[];for(n++;n<t.length&&!/^```\s*$/.test(t[n]??"");)a.push(t[n]??""),n++;n<t.length&&n++,e.push(`<pre><code>${v(a.join(`
`))}</code></pre>`);continue}if(/^\s*[-*+]\s+/.test(i)){let a=[];for(;n<t.length&&/^\s*[-*+]\s+/.test(t[n]??"");)a.push(lt((t[n]??"").replace(/^\s*[-*+]\s+/,""))),n++;e.push(`<ul>${a.map(l=>`<li>${l}</li>`).join("")}</ul>`);continue}if(/^\s*\d+\.\s+/.test(i)){let a=[];for(;n<t.length&&/^\s*\d+\.\s+/.test(t[n]??"");)a.push(lt((t[n]??"").replace(/^\s*\d+\.\s+/,""))),n++;e.push(`<ol>${a.map(l=>`<li>${l}</li>`).join("")}</ol>`);continue}if(!i.trim()){n++;continue}let r=[i];for(n++;n<t.length&&(t[n]??"").trim()&&!(t[n]??"").startsWith("```")&&!/^\s*[-*+]\s+/.test(t[n]??"")&&!/^\s*\d+\.\s+/.test(t[n]??"");)r.push(t[n]??""),n++;e.push(`<p>${lt(r.join(`
`))}</p>`)}return e.join("")}function ue(o){let t=Array.isArray(o.content)?o.content:[{type:"text",text:String(o.content??"")}],e=Array.isArray(o.mentions)?o.mentions.map(n=>typeof n=="string"?n:n?.path??"").filter(n=>!!n):[];return{id:`m${o.seq??q.short()}`,role:o.role,blocks:t,seq:o.seq??null,error:null,mentions:e}}function pe(o,t){let e=t-1,n="";for(;e>=0;){let i=o[e]??"";if(i==="@")return e===0||/\s/.test(o[e-1]??"")?{token:n,anchor:e}:null;if(/\s/.test(i))return null;n=i+n,e--}return null}function fe(o){let t=/\.(md|markdown|mdx|rs|py|js|mjs|cjs|ts|tsx|jsx|vue|svelte|go|java|kt|kts|c|cc|cpp|cxx|h|hpp|hh|m|mm|swift|rb|php|cs|scala|toml|yaml|yml|json|jsonc|html|htm|css|scss|sass|less|txt|sh|bash|zsh|fish|sql|xml|ini|conf|cfg|env|lua|r|dart)$/i,e=i=>{let s=i.lastIndexOf(".");return s>=0&&t.test(i.slice(s))},n=/^([^\s:#]+):(\d+)(?:-(\d+))?$/.exec(o);if(n){let i=n[1]??"";return e(i)?{path:i,line:Number(n[2]),lineEnd:n[3]?Number(n[3]):null,anchor:null}:null}if(n=/^([^\s:#]+)#([A-Za-z0-9_\-:.]+)$/.exec(o),n){let i=n[1]??"";return e(i)?{path:i,line:null,lineEnd:null,anchor:n[2]??null}:null}return null}var me=`
<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M4 4.5 H20 A2 2 0 0 1 22 6.5 V17.5 A2 2 0 0 1 20 19.5 H10 L7 22.5 V19.5 H4 A2 2 0 0 1 2 17.5 V6.5 A2 2 0 0 1 4 4.5 Z"/>
<path d="M7 10.5 H17 M7 13.5 H13"/>
</svg>`,ct=`
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M7 7 L17 17 M17 7 L7 17" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/>
</svg>`,I={POPOUT_READY:"markon-chat-popout-ready",SELECTION:"markon-chat-selection",DRAFT:"markon-chat-draft",DOCK_BACK:"markon-chat-dock-back"},ge=`
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M12 5 V19 M5 12 H19" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>`,ve=`
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M12 18 V6 M6 12 L12 6 L18 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>`,ye=`
<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<rect x="6" y="6" width="12" height="12" rx="2"/>
</svg>`,ht=`
<svg viewBox="0 0 24 24" width="12" height="12" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M9 6 L15 12 L9 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>`,be=`
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M4 20h4L18 10l-4-4L4 16v4Z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/>
<path d="M14 6l4 4" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/>
</svg>`,Ee=`
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M14 4h6v6"/>
<path d="M10 14 20 4"/>
<path d="M19 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h5"/>
</svg>`,we=`
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M19 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h5"/>
<path d="M20 4 14 10"/>
<path d="M14 4v6h6"/>
</svg>`,_e=`
<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M18 7h-3l-2 4v6h6v-6h-3zm-8 0H7l-2 4v6h6v-6H8z"/>
</svg>`,z=class{#t;#o;#e;#l=null;#v=null;#a=null;#d=null;#c=null;#n=null;#h=null;#s=null;#y=null;#r=null;#b=null;#N=null;#I=null;#x=null;#_=null;#S=null;#O=null;#T=null;#H=null;#et=null;#nt=null;#mt=null;#M=[];#u=null;#E=null;#R=!1;#Y="in_page";#P=null;#gt=null;#p=[];#f=null;#m=new Map;#W=null;#it=!1;#vt=!1;#K=!0;#ot=null;#yt=0;#D=null;#$=new Set;#g=null;#k=[];#w=0;#z=-1;#st=nt(t=>{this.#le(t)},120);#L=null;#G=null;#X=null;#B=null;constructor(t){this.#t=t,this.#o=S.get(h.META_TAGS.WORKSPACE_ID)||"";let e=typeof window<"u"&&window.__MARKON_I18N__?.t;this.#e=e||(n=>n),this.#t}init(){if(S.flag(h.META_TAGS.ENABLE_CHAT)){if(!this.#o){u.warn("Chat","enable-chat is on but workspace-id is missing; skipping init");return}this.#Y=this.#Dt(),this.#_t(),this.#qt(),this.#Kt(),this.#Bt(),this.#Wt(),u.log("Chat",`Initialized (workspace=${this.#o}, defaultMode=${this.#Y})`)}}destroy(){this.#X&&(document.removeEventListener("click",this.#X),this.#X=null),this.#B&&(window.removeEventListener("message",this.#B),this.#B=null),this.#G&&(document.removeEventListener("mousedown",this.#G,!0),this.#G=null),this.#E&&(clearInterval(this.#E),this.#E=null),this.#st.cancel(),this.#L&&(this.#L.abort(),this.#L=null),this.#d&&(this.#d.destroy(),this.#d=null)}#Dt(){return(S.get(h.META_TAGS.DEFAULT_CHAT_MODE)||"")==="popout"?"popout":"in_page"}#$t(t){let e=this.#Y==="in_page"?"popout":"in_page";return t?e:this.#Y}#Bt(){this.#R||(this.#P||(this.#P=document.createElement("style"),this.#P.dataset.markon="chat-size-override",document.head.appendChild(this.#P)),this.#bt(this.#Ft()))}#bt(t){this.#P&&(this.#P.textContent=t?`.markon-chat-container.expanded { width: ${t.w}px; height: ${t.h}px; }`:"")}#Ft(){try{let t=localStorage.getItem(`${h.STORAGE_KEYS.CHAT_SIZE}:${this.#o}`);if(!t)return null;let e=JSON.parse(t),n=typeof e.w=="number"?e.w:NaN,i=typeof e.h=="number"?e.h:NaN;return!Number.isFinite(n)||!Number.isFinite(i)||n<200||i<200?null:{w:n,h:i}}catch{return null}}#Wt(){if(!this.#l||this.#R)return;let t=nt((e,n)=>{try{localStorage.setItem(`${h.STORAGE_KEYS.CHAT_SIZE}:${this.#o}`,JSON.stringify({w:e,h:n}))}catch{}this.#bt({w:e,h:n})},200);this.#gt=new ResizeObserver(()=>{let e=this.#l;if(!e?.classList.contains("expanded"))return;let n=e.offsetWidth,i=e.offsetHeight;n<240||i<320||(t(n,i),this.#d?.relayout())}),this.#gt.observe(this.#l)}#Kt(){let t=e=>{if(e.origin!==location.origin||!this.#u||e.source!==this.#u)return;let n=e.data;n&&(n.type===I.POPOUT_READY?this.#Gt():n.type===I.DOCK_BACK&&(this.#u=null,this.#E&&clearInterval(this.#E),this.#E=null,setTimeout(()=>this.#rt(),0)))};this.#B=t,window.addEventListener("message",t)}#Gt(){if(!this.#u||this.#u.closed)return;let t=(this.#r?.value??"").trim(),e=this.#D;e&&this.#u.postMessage({type:I.SELECTION,text:e,currentDoc:null},location.origin),t&&this.#u.postMessage({type:I.DRAFT,text:t},location.origin),(e||t)&&(this.#D=null,this.#At(),this.#r&&(this.#r.value="",this.#F()))}#Vt(){try{let t=window.opener;t&&!t.closed&&t.postMessage({type:I.DOCK_BACK},location.origin)}catch{}window.close()}open(){this.#rt()}close(){this.#d?.collapse()}toggle(){this.#d?.isExpanded?this.close():this.open()}openInDefault({invert:t=!1}={}){this.#wt({invert:t})}openWithSelection({text:t,currentDoc:e=null,shift:n=!1}={}){let i={invert:n,currentDoc:e};t!==void 0&&(i.text=t),this.#wt(i)}#Et({invert:t,hasSelection:e}){return this.#u&&!this.#u.closed?{kind:"focus-popout"}:this.#R?e?{kind:"prefill-popout"}:{kind:"noop"}:this.#$t(t)==="popout"?{kind:"spawn-popout"}:{kind:"expand-in-page"}}#wt({invert:t,text:e,currentDoc:n=null}){switch(this.#Et({invert:t,hasSelection:!!e}).kind){case"noop":return;case"focus-popout":this.#u?.focus(),e&&this.#u?.postMessage({type:I.SELECTION,text:e,currentDoc:n},location.origin);return;case"prefill-popout":this.#ut(e);return;case"spawn-popout":this.#ut(e),this.#at();return;case"expand-in-page":setTimeout(()=>this.#rt(),0),this.#ut(e);return}}#rt(){if(this.#d?.isExpanded){this.#j();return}this.#d?.expand()}initPopout(){if(!this.#o){u.warn("Chat","enable-chat is on but workspace-id is missing; skipping popout init");return}if(this.#R=!0,document.body.classList.add("markon-chat-popout-mode"),this.#_t(),this.#l&&this.#l.classList.add("expanded","popout-mode"),this.#O){let e=this.#i("web.chat.dock","Back to in-page chat");this.#O.innerHTML=we,this.#O.title=e,this.#O.setAttribute("aria-label",e)}this.#St(),this.#B=e=>{if(e.origin!==location.origin)return;let n=e.data;n&&(n.type===I.SELECTION&&typeof n.text=="string"?this.openWithSelection({text:n.text,currentDoc:n.currentDoc??null}):n.type===I.DRAFT&&typeof n.text=="string"&&this.#r&&(this.#r.value=n.text,this.#F(),this.#j()))},window.addEventListener("message",this.#B);let t=()=>{try{window.opener?.postMessage({type:I.POPOUT_READY},location.origin)}catch{}};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0})}#at(){if(this.#u&&!this.#u.closed){this.#u.focus();return}let t=yt(this.#o),n=window.open(t,"markon-chat-popout","popup=yes,width=440,height=640,menubar=no,toolbar=no,location=no,status=no,resizable=yes");if(!n){u.warn("Chat","popup blocked \u2014 could not open chat window");return}this.#u=n,this.close(),this.#Ut()}#Ut(){this.#E&&clearInterval(this.#E),this.#E=setInterval(()=>{(!this.#u||this.#u.closed)&&(this.#u=null,this.#E&&clearInterval(this.#E),this.#E=null)},1e3)}prefillInput(t){this.#r&&(this.#r.value=t||"",this.#F(),this.#j())}#_t(){let t=this.#i("web.chat.tooltip","AI Chat"),e=this.#i("web.chat.new","New thread"),n=this.#i("web.chat.switch","Switch thread"),i=this.#i("web.chat.send","Send"),s=this.#i("web.chat.placeholder","Ask anything\u2026"),r=this.#i("web.chat.title.placeholder","New chat"),a=document.createElement("div");a.innerHTML=`
<div id="markon-chat-container" class="markon-chat-container" role="dialog" aria-label="AI Chat">
${Nt()}
<div class="markon-chat-face" title="${v(t)}" aria-label="${v(t)}">
<span class="markon-chat-face-icon icon-chat">${me}</span>
<span class="markon-chat-face-icon icon-close">${ct}</span>
</div>
<div class="markon-chat-body">
<header class="markon-chat-header">
<div class="markon-chat-header-left-actions">
<button type="button" class="markon-chat-icon-btn markon-chat-popout" title="${v(this.#i("web.chat.popout","Open in new window"))}" aria-label="${v(this.#i("web.chat.popout","Open in new window"))}">${Ee}</button>
</div>
<div class="markon-chat-header-titlebar">
<span class="markon-chat-thread-title" data-placeholder="${v(r)}"></span>
<button type="button" class="markon-chat-icon-btn markon-chat-rename" title="${v(this.#i("web.chat.rename","Rename"))}" aria-label="${v(this.#i("web.chat.rename","Rename"))}">${be}</button>
</div>
<div class="markon-chat-header-actions">
<button type="button" class="markon-chat-icon-btn markon-chat-thread-switcher" aria-haspopup="listbox" title="${v(n)}" aria-label="${v(n)}">${ht}</button>
<button type="button" class="markon-chat-icon-btn markon-chat-new" title="${v(e)}" aria-label="${v(e)}">${ge}</button>
</div>
<div class="markon-chat-thread-menu" role="listbox" hidden></div>
</header>
<div class="markon-chat-messages-wrap">
<div class="markon-chat-messages" role="log" aria-live="polite"></div>
<button type="button" class="markon-chat-scroll-pill" hidden>${this.#i("web.chat.scroll.pill","\u2193 new messages")}</button>
</div>
<footer class="markon-chat-footer">
<div class="markon-chat-input-group">
<div class="markon-chat-quote-chip" hidden>
<span class="markon-chat-quote-icon" aria-hidden="true">${_e}</span>
<span class="markon-chat-quote-text"></span>
<button type="button" class="markon-chat-quote-dismiss" title="${v(this.#i("web.chat.quote.dismiss","Remove quote"))}" aria-label="${v(this.#i("web.chat.quote.dismiss","Remove quote"))}">${ct}</button>
</div>
<textarea
class="markon-chat-input"
rows="1"
placeholder="${v(s)}"
spellcheck="true"
autocomplete="off"></textarea>
<button type="button" class="markon-chat-send" title="${v(i)}" aria-label="${v(i)}">
<span class="markon-chat-send-icon">${ve}</span>
<span class="markon-chat-stop-icon" hidden>${ye}</span>
</button>
</div>
<div class="markon-chat-edit-bar" hidden role="group" aria-label="${v(this.#i("web.chat.edit.bar","Pending edit confirmation"))}">
<span class="markon-chat-edit-bar-label"></span>
<div class="markon-chat-edit-bar-buttons">
<button type="button" class="markon-chat-edit-bar-reject" title="${v(this.#i("web.chat.edit.reject.tip","Reject (Esc)"))}">${v(this.#i("web.chat.edit.reject","Reject"))}</button>
<button type="button" class="markon-chat-edit-bar-apply" title="${v(this.#i("web.chat.edit.apply.tip","Apply (Enter)"))}">${v(this.#i("web.chat.edit.apply","Apply"))}</button>
</div>
</div>
</footer>
</div>
</div>
`.trim(),this.#l=a.firstElementChild,document.body.appendChild(this.#l),this.#v=this.#l.querySelector(".markon-chat-face"),this.#a=this.#l.querySelector(".markon-chat-body"),this.#a&&(this.#c=this.#a.querySelector(".markon-chat-thread-title"),this.#n=this.#a.querySelector(".markon-chat-thread-switcher"),this.#h=this.#a.querySelector(".markon-chat-thread-menu"),this.#s=this.#a.querySelector(".markon-chat-messages"),this.#y=this.#a.querySelector(".markon-chat-scroll-pill"),this.#r=this.#a.querySelector(".markon-chat-input"),this.#b=this.#a.querySelector(".markon-chat-send"),this.#N=this.#b?.querySelector(".markon-chat-send-icon")??null,this.#I=this.#b?.querySelector(".markon-chat-stop-icon")??null,this.#x=this.#a.querySelector(".markon-chat-quote-chip"),this.#_=this.#a.querySelector(".markon-chat-quote-text"),this.#S=this.#a.querySelector(".markon-chat-quote-dismiss"),this.#O=this.#a.querySelector(".markon-chat-popout"),this.#T=this.#a.querySelector(".markon-chat-input-group"),this.#H=this.#a.querySelector(".markon-chat-edit-bar"),this.#et=this.#a.querySelector(".markon-chat-edit-bar-label"),this.#nt=this.#a.querySelector(".markon-chat-edit-bar-apply"),this.#mt=this.#a.querySelector(".markon-chat-edit-bar-reject")),this.#jt()}#qt(){!this.#l||!this.#v||!this.#a||(this.#d=new F({name:"chat",container:this.#l,handle:this.#v,body:this.#a,rolePriority:1,panelSize:{width:420,height:600},homeAnchor:"BR",panelAnchor:"TL",initialOffset:{right:20,bottom:70},storageKey:h.STORAGE_KEYS.CHAT_POS,expandedDragHandle:`.markon-chat-header, ${At}`,nonDragSelector:'[contenteditable="true"], input, textarea, [role="listbox"], [role="listbox"] *',onExpand:()=>{this.#St()},onCollapse:()=>{}}),this.#d.init())}#jt(){if(!this.#a)return;this.#a.querySelector(".markon-chat-new")?.addEventListener("click",()=>{this.#Xt()}),this.#a.querySelector(".markon-chat-rename")?.addEventListener("click",e=>{e.stopPropagation(),this.#Jt()}),this.#n?.addEventListener("click",()=>this.#zt()),this.#S?.addEventListener("click",e=>{e.preventDefault(),this.#At(),this.#r?.focus()}),this.#O?.addEventListener("click",e=>{e.preventDefault(),this.#R?this.#Vt():this.#at()}),this.#v?.addEventListener("click",e=>{let n=this.#Et({invert:e.shiftKey,hasSelection:!1});if(n.kind==="focus-popout"){e.stopImmediatePropagation(),e.preventDefault(),this.#u?.focus();return}n.kind==="spawn-popout"&&!this.#d?.isExpanded&&(e.stopImmediatePropagation(),e.preventDefault(),this.#at())},{capture:!0}),this.#c?.addEventListener("keydown",e=>{e.key==="Enter"&&(e.preventDefault(),this.#c?.blur()),e.key==="Escape"&&(e.preventDefault(),this.#Tt(!0))}),this.#c?.addEventListener("blur",()=>{this.#Tt(!1)}),this.#r&&(this.#r.addEventListener("input",()=>{this.#F(),this.#Rt(),this.#pt()}),this.#r.addEventListener("keydown",e=>{if(this.#g&&!this.#g.hidden){if(e.key==="ArrowDown"){e.preventDefault(),this.#It(1);return}if(e.key==="ArrowUp"){e.preventDefault(),this.#It(-1);return}if((e.key==="Enter"||e.key==="Tab")&&this.#k.length>0){e.preventDefault(),this.#Ht(this.#w);return}if(e.key==="Escape"){e.preventDefault(),this.#A();return}}e.key==="Enter"&&!e.shiftKey&&!e.isComposing&&(e.preventDefault(),this.#dt())}),this.#r.addEventListener("blur",()=>{setTimeout(()=>this.#A(),120)}),this.#r.addEventListener("click",()=>this.#pt()),this.#r.addEventListener("keyup",e=>{["ArrowLeft","ArrowRight","Home","End"].includes(e.key)&&this.#pt()})),this.#b?.addEventListener("click",()=>{this.#it?this.#re():this.#dt()}),this.#nt?.addEventListener("click",()=>{this.#q("apply")}),this.#mt?.addEventListener("click",()=>{this.#q("reject")}),this.#a?.addEventListener("keydown",e=>{if(this.#M.length===0)return;let n=e.target;n?.tagName==="TEXTAREA"||n?.tagName==="INPUT"||(e.key==="Enter"&&(e.preventDefault(),this.#q("apply")),e.key==="Escape"&&(e.preventDefault(),this.#q("reject")))}),this.#s?.addEventListener("scroll",()=>{let e=this.#oe();this.#K=e,e&&this.#y&&(this.#y.hidden=!0)},{passive:!0}),this.#y?.addEventListener("click",()=>{this.#K=!0,this.#y&&(this.#y.hidden=!0),this.#tt()});let t=e=>{if(!this.#h||this.#h.hidden)return;let n=e.target;n?.closest(".markon-chat-thread-menu")||n?.closest(".markon-chat-thread-switcher")||(this.#h.hidden=!0)};this.#X=t,document.addEventListener("click",t)}async#St(){if(this.#a&&(this.#j(),!this.#vt)){this.#vt=!0;try{await this.#Yt();let t=localStorage.getItem(this.#ft()),e=t&&this.#p.find(n=>n.id===t)?.id||this.#p[0]?.id||null;e?await this.#Z(e):this.#J()}catch(t){u.error("Chat","Failed to load threads",t),this.#J(this.#i("web.chat.error.threads","Failed to load threads"))}}}async#Yt(){let t=await fetch(A(this.#o,"threads"));if(!t.ok)throw new Error(`threads HTTP ${t.status}`);this.#p=await t.json(),this.#V()}#V(){if(!this.#h)return;if(this.#p.length===0){let n=this.#i("web.chat.threads.empty","No threads yet");this.#h.innerHTML=`<div class="markon-chat-thread-empty">${v(n)}</div>`;return}let t=this.#i("web.chat.thread.delete","Delete thread"),e=this.#p.length<=1;this.#h.innerHTML=this.#p.map(n=>{let i=n.id===this.#f?" active":"",s=v(n.title||this.#i("web.chat.thread.untitled","Untitled")),r=e?"":`<button type="button" class="markon-chat-thread-row-delete" title="${v(t)}" aria-label="${v(t)}">${ct}</button>`;return`
<div class="markon-chat-thread-row${i}" role="option" data-id="${v(n.id)}" tabindex="0">
<span class="markon-chat-thread-row-title">${s}</span>
${r}
</div>
`}).join(""),this.#h.querySelectorAll(".markon-chat-thread-row").forEach(n=>{n.addEventListener("click",i=>{if(i.target?.closest(".markon-chat-thread-row-delete"))return;let r=n.dataset.id;this.#h&&(this.#h.hidden=!0),r&&this.#Z(r)})}),this.#h.querySelectorAll(".markon-chat-thread-row-delete").forEach(n=>{n.addEventListener("click",i=>{i.stopPropagation();let r=n.closest(".markon-chat-thread-row")?.dataset.id;r&&this.#Zt(r)})})}#zt(){this.#h&&(this.#h.hidden&&this.#V(),this.#h.hidden=!this.#h.hidden)}async#Xt(){try{let t=await fetch(A(this.#o,"threads"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});if(!t.ok)throw new Error(`HTTP ${t.status}`);let e=await t.json();this.#p.unshift(e),await this.#Z(e.id)}catch(t){u.error("Chat","Failed to create thread",t)}}async#Zt(t){if(!(this.#p.length<=1)){try{let e=await fetch(A(this.#o,`threads/${encodeURIComponent(t)}`),{method:"DELETE"});if(!e.ok&&e.status!==204)throw new Error(`HTTP ${e.status}`)}catch(e){u.error("Chat","Failed to delete thread",e);return}if(this.#p=this.#p.filter(e=>e.id!==t),this.#m.delete(t),this.#f===t){let e=this.#p[0]?.id;e?await this.#Z(e):(this.#f=null,this.#J(),this.#lt(""))}this.#V()}}async#Z(t){if(!t)return;this.#f=t,localStorage.setItem(this.#ft(),t);let e=this.#p.find(n=>n.id===t);if(this.#lt(e?.title||""),this.#m.has(t)){this.#ct();return}this.#s&&(this.#s.innerHTML=`<div class="markon-chat-empty">${v(this.#i("web.chat.loading","Loading\u2026"))}</div>`);try{let n=await fetch(A(this.#o,`threads/${encodeURIComponent(t)}`));if(!n.ok)throw new Error(`HTTP ${n.status}`);let s=((await n.json()).messages||[]).map(r=>ue(r));this.#m.set(t,s),this.#ct()}catch(n){u.error("Chat",`Failed to load thread ${t}`,n),this.#s&&(this.#s.innerHTML=`<div class="markon-chat-empty">${v(this.#i("web.chat.error.thread","Failed to load thread"))}</div>`)}}#lt(t){this.#c&&(this.#c.textContent=t||"")}#Jt(){if(!this.#c)return;this.#c.setAttribute("contenteditable","true"),this.#c.focus();let t=document.createRange();t.selectNodeContents(this.#c);let e=window.getSelection();e?.removeAllRanges(),e?.addRange(t)}async#Tt(t){if(!this.#c||this.#c.getAttribute("contenteditable")!=="true")return;this.#c.setAttribute("contenteditable","false");let e=this.#p.find(i=>i.id===this.#f);if(t){this.#c.textContent=e?.title||"";return}let n=(this.#c.textContent||"").trim();!e||n===e.title||(e.title=n,this.#V())}#J(t){if(!this.#s)return;let e=t||this.#i("web.chat.empty","Start a new conversation by typing below.");this.#s.innerHTML=`<div class="markon-chat-empty">${v(e)}</div>`}#ct(){if(!this.#s||!this.#f)return;let t=this.#m.get(this.#f)||[];if(t.length===0){this.#J();return}this.#s.innerHTML="";for(let e of t)this.#s.appendChild(this.#U(e));this.#K=!0,this.#tt()}#U(t){let e=document.createElement("div");return e.className=`markon-chat-message markon-chat-message-${t.role}`,e.dataset.id=t.id,e.appendChild(this.#Qt(t)),e}#Qt(t){let e=document.createElement("div");e.className="markon-chat-message-body";for(let n of t.blocks)if(n.type==="text"){let i=document.createElement("div");i.className="markon-chat-text",i.innerHTML=de(n.text||""),t.role==="assistant"?this.#pe(i):t.role==="user"&&Array.isArray(t.mentions)&&t.mentions.length>0&&this.#ue(i,t.mentions),e.appendChild(i)}else n.type==="tool_use"?e.appendChild(this.#te(n)):n.type==="tool_result"?e.appendChild(this.#ee(n)):n.type==="edit_pending"&&e.appendChild(this.#ne(n));if(t.error){let n=document.createElement("div");n.className="markon-chat-error";let i=document.createElement("span");i.className="markon-chat-error-text",i.textContent=t.error;let s=document.createElement("button");s.type="button",s.className="markon-chat-retry",s.textContent=this.#i("web.chat.retry","Retry"),s.addEventListener("click",()=>this.#Ct()),n.appendChild(i),n.appendChild(s),e.appendChild(n)}if(t.stopped){let n=document.createElement("div");n.className="markon-chat-stopped",n.textContent=this.#i("web.chat.stopped","(stopped)"),e.appendChild(n)}return e}#te(t){let e=document.createElement("details");e.className="markon-chat-tool-call";let n=document.createElement("summary");n.innerHTML=`
<span class="markon-chat-tool-pill-icon">${ht}</span>
<span class="markon-chat-tool-name">${v(t.name||"tool")}</span>
`,e.appendChild(n);let i=document.createElement("pre");i.className="markon-chat-tool-args";let s="";try{s=JSON.stringify(t.input??{},null,2)}catch{s=typeof t.input=="string"?t.input:""}return i.textContent=s,e.appendChild(i),e}#ee(t){let e=t.content??t.output??"",n=typeof e=="string"?e:JSON.stringify(e)??"",i=n.split(`
`).length,s=document.createElement("details");s.className="markon-chat-tool-result",t.is_error&&s.classList.add("markon-chat-tool-result-error"),i<=10&&(s.open=!0);let r=i>10?this.#i("web.chat.tool.result.collapsed",`Result (${i} lines)`).replace("{lines}",String(i)):this.#i("web.chat.tool.result","Result"),a=document.createElement("summary");a.innerHTML=`<span class="markon-chat-tool-pill-icon">${ht}</span> ${v(r)}`,s.appendChild(a);let l=document.createElement("pre");return l.className="markon-chat-tool-output",l.textContent=n,s.appendChild(l),s}#ne(t){let e=document.createElement("div");e.className="markon-chat-edit-pending",e.dataset.editId=t.edit_id;let n=t.status??"pending";e.dataset.status=n;let i=document.createElement("div");i.className="markon-chat-edit-pending-head";let s=document.createElement("span");s.className="markon-chat-edit-pending-path",s.textContent=`\u{1F4DD} ${t.path} \xB7 L${t.line}`;let r=document.createElement("span");r.className="markon-chat-edit-pending-head-right";let a=document.createElement("span");if(a.className="markon-chat-edit-pending-status",a.textContent=this.#ie(n),r.appendChild(a),n==="applied"){let d=document.createElement("button");d.type="button",d.className="markon-chat-edit-pending-undo",d.textContent=this.#i("web.chat.edit.undo","Undo"),d.title=this.#i("web.chat.edit.undo.tip","Revert this edit"),d.addEventListener("click",f=>{f.preventDefault(),this.#kt(t.edit_id)}),r.appendChild(d)}i.appendChild(s),i.appendChild(r),e.appendChild(i);let l=document.createElement("div");l.className="markon-chat-edit-pending-diff";let c=document.createElement("div");c.className="markon-chat-edit-pending-old",c.textContent=t.old_string;let p=document.createElement("div");return p.className="markon-chat-edit-pending-new",p.textContent=t.new_string,l.appendChild(c),l.appendChild(p),e.appendChild(l),e}#ie(t){switch(t){case"applied":return this.#i("web.chat.edit.status.applied","Applied");case"rejected":return this.#i("web.chat.edit.status.rejected","Rejected");case"drifted":return this.#i("web.chat.edit.status.drifted","Source drifted");case"reverted":return this.#i("web.chat.edit.status.reverted","Reverted");default:return this.#i("web.chat.edit.status.pending","Awaiting confirmation")}}async#kt(t){let e=this.#ht(t);if(!e)return;let{msg:n,block:i}=e;if(i.status==="applied"){try{let s=await fetch(A(this.#o,"edits/undo"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:i.path,find:i.new_string,replace_with:i.old_string})});if(!s.ok){u.warn("Chat",`undo edit failed: HTTP ${s.status}`);return}let r=await s.json().catch(()=>({}));i.status=r.status==="reverted"?"reverted":"drifted"}catch(s){u.warn("Chat","undo edit threw",s);return}this.#C(n)}}#ht(t){for(let e of this.#m.values())for(let n of e)for(let i of n.blocks)if(i.type==="edit_pending"&&i.edit_id===t)return{msg:n,block:i};return null}#Q(){if(!this.#H||!this.#T)return;let t=this.#M[0];if(!t){this.#H.hidden=!0,this.#T.hidden=!1;return}let e=this.#ht(t);if(!e){this.#M.shift(),this.#Q();return}let{block:n}=e,i=this.#M.length,s=i>1?` \xB7 1 / ${i}`:"";this.#et&&(this.#et.textContent=`${n.path} \xB7 L${n.line}${s}`),this.#T.hidden=!0,this.#H.hidden=!1,(this.#nt??this.#H).focus()}async#q(t){let e=this.#M[0];if(!e)return;let n=this.#ht(e);if(!n){this.#M.shift(),this.#Q();return}try{let i=await fetch(A(this.#o,`edits/${encodeURIComponent(e)}/${t}`),{method:"POST"});if(!i.ok){u.warn("Chat",`${t} edit failed: HTTP ${i.status}`);return}let s=await i.json().catch(()=>({})),r=s.status==="applied"?"applied":s.status==="drifted"?"drifted":"rejected";n.block.status=r}catch(i){u.warn("Chat",`${t} edit threw`,i);return}this.#M.shift(),this.#C(n.msg),this.#Q()}#C(t){if(!this.#s)return;let e=this.#s.querySelector(`.markon-chat-message[data-id="${CSS.escape(t.id)}"]`);e?e.replaceWith(this.#U(t)):this.#s.appendChild(this.#U(t)),this.#K?this.#tt():this.#y&&(this.#y.hidden=!1)}#Lt(t){this.#ot||(this.#ot=requestAnimationFrame(e=>{if(this.#ot=null,e-this.#yt<50){this.#Lt(t);return}this.#yt=e,this.#C(t)}))}#oe(){let t=this.#s;return t?t.scrollHeight-t.scrollTop-t.clientHeight<60:!0}#tt(){this.#s&&(this.#s.scrollTop=this.#s.scrollHeight)}#F(){let t=this.#r;if(!t)return;t.style.height="auto";let e=136;t.style.height=`${Math.min(t.scrollHeight,e)}px`}async#dt(){if(!this.#r||!this.#s)return;let t=(this.#r.value||"").trim();if(!t||this.#it)return;this.#Rt();let e=[...this.#$].filter(a=>t.includes(`@${a}`)),n={id:`local-u-${Date.now()}`,role:"user",blocks:[{type:"text",text:t}],mentions:e},i={id:`local-a-${Date.now()}`,role:"assistant",blocks:[{type:"text",text:""}],streaming:!0},s=this.#f&&this.#m.get(this.#f)||[];s.push(n,i),this.#f?this.#m.set(this.#f,s):this.#m.set("__pending__",s),this.#s.querySelector(".markon-chat-empty")&&(this.#s.innerHTML=""),this.#s.appendChild(this.#U(n)),this.#s.appendChild(this.#U(i)),this.#K=!0,this.#tt(),this.#r.value="",this.#F(),this.#A(),this.#Nt(),await this.#se(t,i,e),this.#$.clear()}async#se(t,e,n=[]){this.#Mt(!0),this.#W=new AbortController;let i=document.querySelector(".heading-focused"),s=S.get(h.META_TAGS.FILE_PATH)||null,r=(this.#D||"").trim()||null;this.#D=null;let a={thread_id:this.#f,user_message:t,selection:r,current_doc:s,mentions:n.map(l=>({path:l})),heading:i?.id||null};try{let l=await fetch(A(this.#o),{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(a),signal:this.#W.signal});if(!l.ok)throw new Error(await ae(l));if(!l.body)throw new Error(`HTTP ${l.status}: empty chat stream`);await this.#xt(l.body,e)}catch(l){let c=l;c?.name==="AbortError"?e.stopped=!0:(u.error("Chat","stream failed",l),e.error=c?.message||String(l)),this.#C(e)}finally{e.streaming=!1,this.#Mt(!1),this.#W=null}}async#xt(t,e){let n=t.getReader(),i=new TextDecoder,s="";for(;;){let{value:r,done:a}=await n.read();if(a)break;s+=i.decode(r,{stream:!0});let l;for(;(l=s.indexOf(`
`))!==-1;){let c=s.slice(0,l);s=s.slice(l+2);let p=c.split(`
`).filter(f=>f.startsWith("data:")).map(f=>f.slice(5).trimStart());if(p.length===0)continue;let d=p.join(`
`);try{let f=JSON.parse(d);this.#Ot(f,e)}catch{u.warn("Chat","malformed SSE frame",d)}}}}#Ot(t,e){switch(t.type){case"thread_assigned":{let n=!this.#f;if(this.#f=t.thread_id,localStorage.setItem(this.#ft(),t.thread_id),n&&this.#m.has("__pending__")){let i=this.#m.get("__pending__");i&&this.#m.set(t.thread_id,i),this.#m.delete("__pending__")}this.#p.find(i=>i.id===t.thread_id)||this.#p.unshift({id:t.thread_id,title:t.title||"",created_at:Date.now(),updated_at:Date.now(),message_count:0}),this.#lt(t.title||""),this.#V();break}case"text":{let n=e.blocks[e.blocks.length-1];n&&n.type==="text"?n.text+=t.delta||"":e.blocks.push({type:"text",text:t.delta||""}),this.#Lt(e);break}case"tool_start":{let n={type:"tool_use",name:t.name,input:t.input||{}};t.id!==void 0&&(n.id=t.id),e.blocks.push(n),this.#C(e);break}case"tool_end":{let n={type:"tool_result",content:t.output??"",is_error:!!t.is_error};t.id!==void 0&&(n.tool_use_id=t.id),e.blocks.push(n),this.#C(e);break}case"edit_pending":{let n={type:"edit_pending",edit_id:t.id,path:t.path,line:t.line,old_string:t.old_string,new_string:t.new_string,status:"pending"};t.tool_use_id!==void 0&&(n.tool_use_id=t.tool_use_id),e.blocks.push(n),this.#M.push(t.id),this.#C(e),this.#Q();break}case"turn_end":break;case"done":e.streaming=!1,this.#C(e);break;case"error":e.error=t.message||"unknown error",this.#C(e);break;default:u.warn("Chat","unknown SSE event",t)}}#re(){this.#W&&this.#W.abort()}#Mt(t){this.#it=t,this.#b&&(this.#N&&(this.#N.hidden=t),this.#I&&(this.#I.hidden=!t),this.#b.classList.toggle("streaming",t),this.#b.title=t?this.#i("web.chat.stop","Stop"):this.#i("web.chat.send","Send"))}#Ct(){if(!this.#r)return;let t=this.#f??"__pending__",e=this.#m.get(t)||[];for(let n=e.length-1;n>=0;n--){let i=e[n];if(i&&i.role==="user"){let r=(i.blocks.find(a=>a.type==="text")?.text||"").trim();r&&(e.length=n+1,this.#m.set(t,e),this.#ct(),this.#r.value=r,this.#dt());return}}}#ut(t){t&&(this.#D=t,this.#ae(t),this.#j())}#j(){setTimeout(()=>{let t=this.#r;if(!t||this.#T?.hidden||!this.#R&&!this.#l?.classList.contains("expanded"))return;t.focus({preventScroll:!0});let e=t.value.length;t.setSelectionRange(e,e)},0)}#ae(t){!this.#x||!this.#_||(this.#_.textContent=t.replace(/\s+/g," ").trim(),this.#x.hidden=!1)}#At(){this.#D=null,this.#Nt()}#Nt(){this.#x&&(this.#x.hidden=!0),this.#_&&(this.#_.textContent="")}#pt(){let t=this.#r;if(!t)return;let e=t.selectionStart??0,n=t.value||"",i=pe(n,e);if(i){this.#z=i.anchor,this.#st(i.token);return}this.#A()}async#le(t){this.#L&&this.#L.abort(),this.#L=new AbortController;try{let e=A(this.#o,"files")+`?q=${encodeURIComponent(t)}&limit=8`,n=await fetch(e,{signal:this.#L.signal});if(!n.ok){this.#A();return}let i=await n.json();this.#he(Array.isArray(i)?i:[])}catch(e){if(e?.name==="AbortError")return;u.warn("Chat","mention query failed",e),this.#A()}}#ce(){if(this.#g)return this.#g;let t=document.createElement("div");return t.className="markon-chat-mention-popup markon-modal-frame",t.setAttribute("role","listbox"),t.hidden=!0,document.body.appendChild(t),this.#g=t,this.#G=e=>{if(!this.#g||this.#g.hidden)return;let n=e.target;n!==this.#r&&(n&&this.#g.contains(n)||this.#A())},document.addEventListener("mousedown",this.#G,!0),t}#he(t){let e=this.#ce();if(this.#k=t.slice(0,8),this.#k.length===0){this.#A();return}this.#w>=this.#k.length&&(this.#w=0),this.#w<0&&(this.#w=0),e.innerHTML=this.#k.map((n,i)=>{let s=String(n.path||""),r=s.lastIndexOf("/"),a=r>=0?s.slice(r+1):s,l=r>=0?s.slice(0,r+1):"";return`
<div class="markon-chat-mention-row${i===this.#w?" is-active":""}" role="option" data-idx="${i}">
<span class="markon-chat-mention-name">${v(a)}</span>
<span class="markon-chat-mention-dir">${v(l)}</span>
</div>
`}).join(""),e.querySelectorAll(".markon-chat-mention-row").forEach(n=>{n.addEventListener("mousedown",i=>{i.preventDefault();let s=Number(n.dataset.idx);this.#Ht(s)})}),this.#de(),e.hidden=!1}#de(){if(!this.#g||!this.#r)return;let e=(this.#r.closest(".markon-chat-input-group")??this.#r).getBoundingClientRect(),n=this.#g;n.style.width=`${e.width}px`,n.style.left="-9999px",n.style.top="-9999px",n.style.visibility="hidden",n.hidden=!1;let i=n.offsetHeight||200;n.style.visibility="";let s=Math.max(8,e.top-i-6);n.style.left=`${e.left}px`,n.style.top=`${s}px`}#It(t){if(!this.#k||this.#k.length===0)return;let e=this.#k.length;if(this.#w=((this.#w+t)%e+e)%e,!this.#g)return;let n=this.#g.querySelectorAll(".markon-chat-mention-row");n.forEach((s,r)=>s.classList.toggle("is-active",r===this.#w));let i=n[this.#w];i&&i.scrollIntoView({block:"nearest"})}#Ht(t){let e=this.#k[t];if(!e)return;let n=String(e.path||"");if(!n)return;let i=this.#r;if(!i||this.#z<0)return;let s=i.value||"",r=i.selectionStart??s.length,a=s.slice(0,this.#z),l=s.slice(r),c=`@${n} `;i.value=a+c+l;let p=a.length+c.length;i.setSelectionRange(p,p),this.#$.add(n),this.#A(),this.#F(),i.focus()}#A(){this.#g&&(this.#g.hidden=!0),this.#k=[],this.#w=0,this.#z=-1,this.#L&&(this.#L.abort(),this.#L=null),this.#st.cancel()}#Rt(){if(this.#$.size===0)return;let t=this.#r?.value||"";for(let e of[...this.#$])t.includes(`@${e}`)||this.#$.delete(e)}#ue(t,e){if(!t||!e||e.length===0)return;let n=[...e].sort((c,p)=>p.length-c.length),i=c=>c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`@(${n.map(i).join("|")})`,"g"),r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),a=[],l;for(;l=r.nextNode();){let c=l.parentElement;c&&c.closest("code, pre")||s.test(l.nodeValue??"")&&(s.lastIndex=0,a.push(l))}for(let c of a){let p=c.nodeValue??"",d=document.createDocumentFragment(),f=0;s.lastIndex=0;let b;for(;(b=s.exec(p))!==null;){b.index>f&&d.appendChild(document.createTextNode(p.slice(f,b.index)));let E=b[1]??"",w=E.lastIndexOf("/"),g=w>=0?E.slice(w+1):E,m=document.createElement("span");m.className="markon-chat-mention-pill",m.setAttribute("data-path",E),m.title=E,m.textContent=`@${g}`,d.appendChild(m),f=b.index+b[0].length}f<p.length&&d.appendChild(document.createTextNode(p.slice(f))),c.parentNode?.replaceChild(d,c)}}#pe(t){if(!t)return;let e=t.querySelectorAll("code");for(let n of e){if(n.parentElement&&n.parentElement.tagName==="PRE")continue;let i=(n.textContent||"").trim();if(!i)continue;let s=fe(i);if(!s)continue;let r=document.createElement("a");r.className="markon-chat-citation",r.setAttribute("data-path",s.path),s.line&&r.setAttribute("data-line",String(s.line)),s.lineEnd&&r.setAttribute("data-line-end",String(s.lineEnd)),s.anchor&&r.setAttribute("data-anchor",s.anchor),r.href=this.#Pt(s),r.textContent=i,r.title=i,r.addEventListener("click",a=>this.#fe(a,s)),n.replaceWith(r)}}#Pt(t){let e=gt(this.#o,t.path);return t.anchor?e+=`#${t.anchor}`:t.line&&(e+=`#L${t.line}`),e}#fe(t,e){t.preventDefault();let n=this.#Pt(e);t.metaKey||t.ctrlKey?window.open(n,"_blank","noopener,noreferrer"):window.location.href=n}#ft(){return`markon-chat-last-thread-${this.#o}`}#i(t,e){let n=this.#e(t);return!n||n===t?e:n}_testHandleEvent(t,e){this.#Ot(t,e)}_testConsumeSSE(t,e){return this.#xt(t,e)}get _testMessagesByThread(){return this.#m}get _testCurrentThreadId(){return this.#f}get _testThreads(){return this.#p}get _testPendingEditQueue(){return this.#M}_testResolveHeadEdit(t){return this.#q(t)}_testUndoAppliedEdit(t){return this.#kt(t)}_testRetryLast(){this.#Ct()}};var dt=h.STORAGE_KEYS.LIVE_COLOR,ut=h.STORAGE_KEYS.IDENTITY_NAME;function Se(){let o=h.COLLABORATION.COLORS,t=Math.floor(Math.random()*o.length);return o[t]??o[0]??"#3451B2"}var W={color(){let o=localStorage.getItem(dt);return o||(o=Se(),localStorage.setItem(dt,o)),o},setColor(o){localStorage.setItem(dt,o)},name(){return localStorage.getItem(ut)??""},setName(o){let t=o.trim();t?localStorage.setItem(ut,t):localStorage.removeItem(ut)},author(){let o={color:this.color()},t=this.name();return t&&(o.name=t),o}};var L={create(o){let t=[],e=o;for(;e&&e.nodeName!=="ARTICLE";){let n=1;for(let i=e.previousSibling;i;i=i.previousSibling)i.nodeName===e.nodeName&&!ot.shouldSkip(i)&&n++;t.unshift(`${e.nodeName}[${n}]`),e=e.parentNode}return t.length===0?"//article[1]":`//article[1]/${t.join("/")}`},resolve(o){let t=/^\/\/article\[1\](?:\/(.+))?$/.exec(o);if(!t)return null;let e=document.querySelector("article.markdown-body");if(!e||!t[1])return e;for(let n of t[1].split("/")){let i=/^([A-Z0-9]+)\[(\d+)\]$/.exec(n);if(!i)return null;let s=i[1],r=i[2];if(!s||!r)return null;let a=0,l=null;for(let c of Array.from(e.childNodes))if(c.nodeName===s&&!ot.shouldSkip(c)&&++a===parseInt(r)){l=c;break}if(!l)return null;e=l}return e},getAbsoluteOffset(o,t){let e=o.nodeType===3?o.parentNode:o,n=0;if(o.nodeType===3){let i=e.firstChild;for(;i;){if(i===o){n+=t;break}n+=i.nodeType===3?i.length:(i.textContent??"").length,i=i.nextSibling}}else for(let i=0;i<t&&i<o.childNodes.length;i++){let s=o.childNodes[i];s&&(n+=(s.textContent??"").length)}return n},findNode(o,t){let e=0,n=null,i=0,s=null,r=a=>{if(!n){if(a.nodeType===3){let l=a;s=l,e+l.length>=t?(n=l,i=t-e):e+=l.length}else if(a.nodeType===1)for(let l=a.firstChild;l&&(r(l),!n);l=l.nextSibling);}};return r(o),!n&&s&&e===t&&(n=s,i=s.length),{node:n,offset:i}}};var M=(o,...t)=>U.t(o,...t),_=Object.freeze({OFF:"off",BROADCAST:"broadcast",FOLLOW:"follow"}),Rt=[_.BROADCAST,_.FOLLOW],pt=[_.OFF,...Rt],Te=`
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="12" cy="8" r="3.2"/>
<path d="M5.5 19a6.6 6.6 0 0 1 13 0"/>
</svg>`,ke=`
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="12" cy="12" r="1.7" fill="currentColor" stroke="none"/>
<path d="M8.5 15.5a5 5 0 0 1 0-7"/>
<path d="M15.5 8.5a5 5 0 0 1 0 7"/>
<path d="M5.5 18.5a9.2 9.2 0 0 1 0-13"/>
<path d="M18.5 5.5a9.2 9.2 0 0 1 0 13"/>
</svg>`,X=class{app;clientId;userColor;workspaceId;liveEnabled=!1;mode;activeLeader;leaderTimer;container;sphere;panel;layer;_lastActiveMode;_applyingRemote;_lastFocusXPath;_lastSelectionKey;_lastViewportKey;_focusObserver;constructor(t){this.app=t,this.clientId=this._getOrCreateClientId(),this.workspaceId=S.get(h.META_TAGS.WORKSPACE_ID)||"",this.userColor=W.color(),this.mode=this._loadSavedMode(),this.activeLeader=null,this.leaderTimer=null,this.container=null,this.sphere=null,this.panel=null,this.layer=null}get isBroadcasting(){return this.mode===_.BROADCAST}get isFollowing(){return this.mode===_.FOLLOW}init(){this.liveEnabled=this.app.enableLive??S.flag(h.META_TAGS.ENABLE_LIVE);let t=S.flag(h.META_TAGS.SHARED_ANNOTATION);if(!(!this.liveEnabled&&!t)){if(!this.app.ws){u.warn("Collab","shared/live is on but WebSocket is unavailable");return}this._createUI(),this._setupFloatingLayer(),this._setupEventListeners(),this._updateUIState(),this.app.ws.on("live_action",e=>{this.handleLiveAction(e.data)}),this.isBroadcasting&&(this._broadcastNavigation(),this._broadcastViewport()),u.log("Live",`Initialized (clientId=${this.clientId}, mode=${this.mode})`)}}toggleActiveMode(){this.mode===_.FOLLOW?this.setMode(_.BROADCAST):this.setMode(_.FOLLOW)}toggleOff(){this.mode===_.OFF?this.setMode(this._lastActiveMode||_.FOLLOW):(this._lastActiveMode=this.mode,this.setMode(_.OFF))}setMode(t){!pt.includes(t)||t===this.mode||(Rt.includes(t)&&(this._lastActiveMode=t),this.mode=t,localStorage.setItem(h.STORAGE_KEYS.LIVE_MODE,t),this._updateUIState(),t===_.BROADCAST&&(this._broadcastNavigation(),this._broadcastViewport()))}_loadSavedMode(){let t=localStorage.getItem(h.STORAGE_KEYS.LIVE_MODE);return pt.includes(t??"")?t:_.OFF}handleLiveAction(t){if(t.clientId!==this.clientId&&this.isFollowing&&this._sameWorkspace(t.workspaceId)){if(t.action==="navigate"){this._applyNavigation(t);return}if(t.route&&!this._isCurrentRoute(t.route)){let e={action:"navigate",clientId:t.clientId,color:t.color,route:t.route};t.workspaceId&&(e.workspaceId=t.workspaceId),this._applyNavigation(e);return}t.action!=="viewport"&&(this.activeLeader=t,this._updateUIState(),this.leaderTimer&&clearTimeout(this.leaderTimer),this.leaderTimer=setTimeout(()=>{this.activeLeader=null,this._updateUIState()},3e3)),t.action==="focus_section"?this._applyFocusSection(t.xpath,t.color):t.action==="selection"?t.cleared?window.getSelection()?.removeAllRanges():this._applySelection(t):t.action==="viewed"?this._applyViewed(t):t.action==="viewport"&&this._applyViewport(t)}}_sameWorkspace(t){return!t||!this.workspaceId||t===this.workspaceId}_currentRoute(){return`${window.location.pathname}${window.location.search}${window.location.hash}`}_resolveWorkspaceRoute(t){let e;try{e=new URL(t,window.location.origin)}catch{return null}if(e.origin!==window.location.origin)return null;if(!this.workspaceId)return e;let n=`/${this.workspaceId}`,i=`/_/${this.workspaceId}`,s=e.pathname;return s!==n&&!s.startsWith(`${n}/`)&&s!==i&&!s.startsWith(`${i}/`)?null:e}_isCurrentRoute(t){let e=this._resolveWorkspaceRoute(t);return e?`${e.pathname}${e.search}${e.hash}`===this._currentRoute():!0}_applyNavigation(t){let e=this._resolveWorkspaceRoute(t.route);if(!e)return;let n=`${e.pathname}${e.search}${e.hash}`;n!==this._currentRoute()&&window.location.assign(n)}_currentScrollTarget(){return document.querySelector("[data-diff-view-panel]:not([hidden])[data-diff-scroller], [data-diff-view-panel]:not([hidden]) [data-diff-scroller]")||window}_readViewport(){let t=this._currentScrollTarget();if(t===window)return{scrollX:window.scrollX,scrollY:window.scrollY};let e=t;return{scrollX:e.scrollLeft,scrollY:e.scrollTop}}_applyViewport(t){let e=this._currentScrollTarget();this._applyingRemote=!0;try{e===window?window.scrollTo({left:t.scrollX,top:t.scrollY,behavior:"smooth"}):e.scrollTo({left:t.scrollX,top:t.scrollY,behavior:"smooth"})}finally{setTimeout(()=>{this._applyingRemote=!1},250)}}_applyViewed(t){if(!t.headingId)return;let e=document.querySelector(`.viewed-checkbox[data-heading-id="${CSS.escape(t.headingId)}"]`);if(!e)return;let n=!!t.checked;if(e.checked!==n){this._applyingRemote=!0;try{e.checked=n,e.dispatchEvent(new Event("change",{bubbles:!0}))}finally{setTimeout(()=>{this._applyingRemote=!1},250)}}}_applyFocusSection(t,e){let n=L.resolve(t);if(n){this._applyingRemote=!0;try{document.querySelectorAll(".heading-focused").forEach(s=>s.classList.remove("heading-focused")),n.classList.add("heading-focused"),$.smartScrollToHeading(n),n.id&&window.__markonTocSetSelected&&window.__markonTocSetSelected(n.id);let i=n.closest(".heading-section")??n;e&&i.style.setProperty("--live-pulse-color",e),i.classList.remove("markon-live-focus-pulse"),i.offsetWidth,i.classList.add("markon-live-focus-pulse"),setTimeout(()=>{i.classList.remove("markon-live-focus-pulse"),i.style.removeProperty("--live-pulse-color")},1500)}finally{setTimeout(()=>{this._applyingRemote=!1},250)}}}_applySelection(t){if(t.startPath===void 0||t.endPath===void 0||t.startOffset===void 0||t.endOffset===void 0)return;let e=L.resolve(t.startPath),n=L.resolve(t.endPath);if(!e||!n)return;let i=L.findNode(e,t.startOffset),s=L.findNode(n,t.endOffset);if(!i.node||!s.node)return;let r=document.createRange();try{r.setStart(i.node,i.offset),r.setEnd(s.node,s.offset)}catch{return}this._applyingRemote=!0;try{let a=window.getSelection();a&&(a.removeAllRanges(),a.addRange(r)),document.body.dataset.markonLiveRemote="1";let l=r.getBoundingClientRect(),c=window.innerHeight,p=window.innerWidth;if(!(l.bottom>0&&l.top<c&&l.right>0&&l.left<p)&&l.width+l.height>0){let f=window.scrollY+l.top-c*.3;window.scrollTo({top:f,behavior:"smooth"})}}finally{setTimeout(()=>{this._applyingRemote=!1},250)}}broadcastAction(t,e={}){!this.isBroadcasting||!this.app.ws||this.app.ws.send({type:"live_action",data:{clientId:this.clientId,color:this.userColor,workspaceId:this.workspaceId,route:this._currentRoute(),action:t,...e}})}_broadcastNavigation(){this.broadcastAction("navigate",{route:this._currentRoute()})}_broadcastViewport(){let{scrollX:t,scrollY:e}=this._readViewport(),n=`${this._currentRoute()}|${Math.round(t)}|${Math.round(e)}`;n!==this._lastViewportKey&&(this._lastViewportKey=n,this.broadcastAction("viewport",{scrollX:t,scrollY:e}))}_observeFocusedSection(){let t=document.querySelector("article.markdown-body");t&&(this._focusObserver?.disconnect(),this._focusObserver=new MutationObserver(()=>{if(this._applyingRemote)return;let e=t.querySelector(".heading-focused");if(!e)return;let n=L.create(e);n!==this._lastFocusXPath&&(this._lastFocusXPath=n,this.broadcastAction("focus_section",{xpath:n}))}),this._focusObserver.observe(t,{subtree:!0,attributes:!0,attributeFilter:["class"]}))}_observeSelection(){let t=document.querySelector("article.markdown-body");if(!t)return;let e;document.addEventListener("selectionchange",()=>{e&&clearTimeout(e),e=setTimeout(()=>this._broadcastSelection(t),120)})}_observeViewed(){document.addEventListener("change",t=>{if(this._applyingRemote)return;let e=t.target;if(!e?.classList?.contains("viewed-checkbox"))return;let n=e.dataset?.headingId;n&&this.broadcastAction("viewed",{headingId:n,checked:e.checked})})}_observeViewport(){let t,e=()=>{this._applyingRemote||(t&&clearTimeout(t),t=setTimeout(()=>this._broadcastViewport(),140))};window.addEventListener("scroll",e,{passive:!0}),document.querySelectorAll("[data-diff-scroller]").forEach(n=>{n.addEventListener("scroll",e,{passive:!0})}),window.addEventListener("hashchange",()=>{this.isBroadcasting&&this._broadcastNavigation()})}_broadcastSelection(t){if(this._applyingRemote||!this.isBroadcasting||!this.app.ws)return;let e=window.getSelection();if(!e||e.rangeCount===0||e.isCollapsed){this._lastSelectionKey&&(this._lastSelectionKey=null,this.broadcastAction("selection",{cleared:!0}));return}let n=e.getRangeAt(0);if(!t.contains(n.commonAncestorContainer))return;let i=n.startContainer.nodeType===3?n.startContainer.parentElement:n.startContainer,s=n.endContainer.nodeType===3?n.endContainer.parentElement:n.endContainer;if(!i||!s)return;let r={startPath:L.create(i),startOffset:L.getAbsoluteOffset(n.startContainer,n.startOffset),endPath:L.create(s),endOffset:L.getAbsoluteOffset(n.endContainer,n.endOffset)},a=`${r.startPath}|${r.startOffset}|${r.endPath}|${r.endOffset}`;a!==this._lastSelectionKey&&(this._lastSelectionKey=a,this.broadcastAction("selection",r))}_createUI(){let t=l=>({[_.OFF]:M("web.live.off"),[_.BROADCAST]:M("web.live.broadcast"),[_.FOLLOW]:M("web.live.follow")})[l],e=h.COLLABORATION.COLORS.map((l,c)=>`<div class="color-dot ${l===this.userColor?"active":""}" style="background-color: ${l}; --dot-color: ${l}" data-color="${l}" title="${c+1}">${c+1}</div>`).join(""),n=pt.map(l=>`<button type="button" class="mode-btn ${l===this.mode?"active":""}" data-mode="${l}">${t(l)}</button>`).join(""),i=this.liveEnabled?`
<div class="panel-section-label" role="img" aria-label="${M("web.collab.live")}" title="${M("web.collab.live")}">${ke}</div>
<div class="panel-row panel-row-mode">
<div class="mode-group">${n}</div>
</div>`:"",s=`
<div id="markon-live-container" class="markon-live-container">
<div class="markon-live-face" title="${M("web.collab.title")}">
<svg class="icon-collab" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="6" cy="9.2" r="1.9"/>
<path d="M2.6 16.6v-.3a3.4 3.4 0 0 1 5-3"/>
<circle cx="18" cy="9.2" r="1.9"/>
<path d="M21.4 16.6v-.3a3.4 3.4 0 0 0-5-3"/>
<circle cx="12" cy="8.2" r="2.5"/>
<path d="M7.4 17.2v-.8a4.6 4.6 0 0 1 9.2 0v.8"/>
</svg>
<svg class="icon-off" viewBox="0 0 24 24" width="40" height="40" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<line x1="3.5" y1="3.5" x2="20.5" y2="20.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
</svg>
<svg class="icon-close" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" aria-hidden="true">
<path d="M7 7 L17 17 M17 7 L7 17"/>
</svg>
<div class="leader-info"></div>
</div>
<div class="markon-live-body">
<div class="panel-header">${M("web.collab.title")}</div>
<div class="panel-section-label" role="img" aria-label="${M("web.collab.you")}" title="${M("web.collab.you")}">${Te}</div>
<div class="panel-row-color">
<div class="color-picker">${e}</div>
<input type="text" class="identity-name" maxlength="24" placeholder="${M("web.collab.nickname")}">
</div>${i}
</div>
</div>
`,r=document.createElement("div");r.innerHTML=s,this.container=r.firstElementChild;let a=document.getElementById("toc-container");document.body.insertBefore(this.container,a||document.body.firstChild),this.sphere=this.container,this.panel=this.container.querySelector(".markon-live-body")}_setupFloatingLayer(){!this.container||!this.panel||(this.layer=new F({name:"live",container:this.container,handle:this.container.querySelector(".markon-live-face"),body:this.panel,rolePriority:2,panelSize:{width:260,height:210},homeAnchor:"BR",panelAnchor:"TL",initialOffset:{right:20,bottom:20},storageKey:h.STORAGE_KEYS.LIVE_POS,nonDragSelector:".panel-row.clickable, .color-dot, .mode-btn, .identity-name"}),this.layer.init())}_setupEventListeners(){if(!this.panel)return;this.panel.querySelectorAll(".mode-btn").forEach(n=>{n.addEventListener("click",()=>{let i=n.dataset.mode;i&&this.setMode(i)})}),this.panel.querySelectorAll(".color-dot").forEach(n=>{n.addEventListener("click",()=>{let i=n.dataset.color;i&&(this.userColor=i,W.setColor(i),this._updateUIState())})});let t=this.panel.querySelector(".identity-name");t&&(t.value=W.name(),t.addEventListener("change",()=>{W.setName(t.value),t.value=W.name()})),this._observeFocusedSection(),this._observeSelection(),this._observeViewed(),this._observeViewport();let e=()=>{this._applyingRemote||delete document.body.dataset.markonLiveRemote};document.addEventListener("mousedown",e,!0),document.addEventListener("touchstart",e,!0),document.addEventListener("keydown",e,!0)}collapse(){this.layer?.collapse()}_updateUIState(){if(!this.sphere||!this.container||!this.panel)return;this.sphere.classList.toggle("broadcasting",this.liveEnabled&&this.isBroadcasting),this.sphere.classList.toggle("live-off",this.liveEnabled&&this.mode===_.OFF),this.container.style.setProperty("--markon-live-user",this.userColor),this.panel.querySelectorAll(".mode-btn").forEach(e=>{e.classList.toggle("active",e.dataset.mode===this.mode)}),this.panel.querySelectorAll(".color-dot").forEach(e=>{e.classList.toggle("active",e.dataset.color===this.userColor)});let t=this.sphere.querySelector(".leader-info");t&&(this.activeLeader&&this.isFollowing?(t.style.setProperty("--leader-color",this.activeLeader.color||"currentColor"),t.classList.add("show")):t.classList.remove("show"))}_getOrCreateClientId(){let t=sessionStorage.getItem(h.STORAGE_KEYS.CLIENT_ID);return t||(t=q.short(),sessionStorage.setItem(h.STORAGE_KEYS.CLIENT_ID,t)),t}};var ft=(o,...t)=>U.t(o,...t),Pt=["global","core","nav","diff","search","visual","edit","viewed","live","chat"],Le=10,xe=720,V=o=>o.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t),Oe=o=>{let t=D.isMac()?"\u2318":"Ctrl",e=[];o.ctrl&&e.push(t),o.shift&&e.push("Shift");let n=o.key;return o.key===" "?n="Space":o.key==="Escape"?n="Esc":o.key.length===1&&/[a-z]/i.exec(o.key)&&(n=o.key.toLowerCase()),e.push(n),e},Me=o=>{let t=new Map;for(let n of Object.keys(h.SHORTCUTS)){if(!o.has(n))continue;let i=h.SHORTCUTS[n],s=i.cat,r=i.feature||n,a=t.get(s);a||(a=new Map,t.set(s,a));let l=a.get(r)??{names:[]};l.names.push(n),a.set(r,l)}let e=n=>{let i=Pt.indexOf(n);return i===-1?Pt.length:i};return[...t.entries()].sort((n,i)=>e(n[0])-e(i[0])).map(([n,i])=>({cat:n,entries:[...i.values()]}))},Dt=o=>o.reduce((t,e)=>t+e.entries.length,0),Ce=o=>{let t=Math.ceil(Dt(o)/2),e=[],n=[],i=0;for(let s of o)e.length>0&&i>=t?n.push(s):(e.push(s),i+=s.entries.length);return n.length===0&&e.length>1&&n.unshift(e.pop()),[e,n]},Ae=o=>{let t=o.names[0];if(!t)return"";let e=h.SHORTCUTS[t],n=new Set,i=o.names.map(s=>{let r=Oe(h.SHORTCUTS[s]).map(a=>`<kbd>${V(a)}</kbd>`).join("");return n.has(r)?"":(n.add(r),`<span class="shortcut-key-combo">${r}</span>`)}).filter(Boolean).join('<span class="shortcut-key-separator">or</span>');return[`<div class="shortcut-item" data-shortcut-name="${t}">`,`<div class="shortcut-key">${i}</div>`,'<div class="shortcut-desc">',`<button type="button" class="shortcut-action" data-shortcut-name="${t}">${V(e.desc)}</button>`,"</div>","</div>"].join("")},Ne=({cat:o,entries:t})=>['<div class="shortcuts-category">',`<h3>${V(ft(`web.kbd.cat.${o}`))}</h3>`,'<div class="shortcuts-list">',t.map(Ae).join(""),"</div></div>"].join(""),Z=(o,t=!1)=>{if(o.__markonShortcutCleanup?.(),delete o.__markonShortcutCleanup,t){o.remove();return}o.classList.remove("visible"),setTimeout(()=>o.remove(),h.ANIMATION.PANEL_TRANSITION)},J=(o=!1)=>{let t=document.querySelector(".shortcuts-help-panel");return t?(Z(t,o),!0):!1};function $t(o,t){if(document.querySelector(".shortcuts-help-panel")){J(!0);return}let e=Me(new Set(o)),n=Dt(e)>Le&&window.innerWidth>=xe,i=n?Ce(e):[e],s=document.createElement("div");s.className="shortcuts-help-panel markon-modal-layer";let r='<div class="shortcuts-help-overlay markon-modal-backdrop"></div>';r+=`<div class="shortcuts-help-modal markon-modal-frame${n?" is-two-column":""}">`,r+=`<div class="shortcuts-help-header"><h2>${V(ft("web.kbd.title"))}</h2></div>`,r+='<div class="shortcuts-help-content">';for(let d of i)r+=`<div class="shortcuts-column">${d.map(Ne).join("")}</div>`;r+="</div>",r+=`<div class="shortcuts-help-footer">${V(ft("web.kbd.footer"))}</div>`,r+="</div>",s.innerHTML=r,document.body.appendChild(s);let a=null;s.classList.add("visible");let l=s.querySelector(".shortcuts-help-modal");l&&(a=It(l,{handle:l,storageKey:h.STORAGE_KEYS.SHORTCUTS_HELP_POS,nonDragSelector:`${B}, .shortcuts-help-content, .shortcuts-help-footer`})),s.querySelector(".shortcuts-help-overlay")?.addEventListener("click",()=>Z(s));let c=d=>{if(!(!d||!t)){if(d==="HELP"){t(d);return}Z(s,!0),t(d)}};s.querySelectorAll(".shortcut-item").forEach(d=>{d.addEventListener("click",f=>{f.target?.closest(".shortcut-action")||c(d.dataset.shortcutName)})}),s.querySelectorAll(".shortcut-action").forEach(d=>{d.addEventListener("click",()=>{c(d.dataset.shortcutName)})});let p=d=>{(d.key==="Escape"||d.key==="?")&&(d.preventDefault(),Z(s))};s.__markonShortcutCleanup=()=>{a?.destroy(),a=null,document.removeEventListener("keydown",p)},document.addEventListener("keydown",p)}var Q=class{#t=new Map;#o=!0;#e(t){let e=h.SHORTCUTS[t];return[e.ctrl?"ctrl":"",e.shift?"shift":"",e.key.length===1?e.key.toLowerCase():e.key].filter(Boolean).join("+")}#l(t){return h.SHORTCUTS[t].feature||t}register(t,e){let n=this.#e(t),i=this.#l(t);for(let s of this.#t.keys())if(this.#e(s)===n&&this.#l(s)!==i){u.warn("KeyboardShortcuts",`Skipped ${t}; shortcut conflicts with registered ${s}`);return}this.#t.set(t,e),u.log("KeyboardShortcuts",`Registered handler: ${t}`)}unregister(t){this.#t.delete(t),u.log("KeyboardShortcuts",`Unregistered handler: ${t}`)}matches(t,e){let n=h.SHORTCUTS[e];if(!n)return!1;let s=D.isMac()?t.metaKey:t.ctrlKey;return!n.ctrl&&n.key.length===1&&!/[a-z]/i.exec(n.key)?t.key===n.key&&!s&&!t.altKey:t.key.toLowerCase()===n.key.toLowerCase()&&s===n.ctrl&&t.shiftKey===n.shift&&!t.altKey}handle(t){if(!this.#o)return!1;if(document.querySelector(".shortcuts-help-panel")&&t.key==="Escape")return t.preventDefault(),J(!0),!0;let e=t.target,n=!!e&&!!e.classList&&e.classList.contains("viewed-checkbox"),i=e?.tagName,s=!!e?.isContentEditable;if((i==="INPUT"||i==="TEXTAREA"||s)&&!n||(n&&(t.key==="j"||t.key==="k")&&e.blur(),window.tocNavigator?.active&&(t.key==="j"||t.key==="k"||t.key==="ArrowUp"||t.key==="ArrowDown")))return!1;for(let[a,l]of this.#t.entries())if(this.matches(t,a))return u.log("KeyboardShortcuts",`Matched: ${a}`),t.preventDefault(),document.querySelector(".shortcuts-help-panel")&&a!=="HELP"&&J(!0),l(t),!0;return!1}showHelp(){$t(this.#t.keys(),t=>this.run(t)),u.log("KeyboardShortcuts","Help panel shown")}run(t){let e=this.#t.get(t);if(!e)return!1;let n=h.SHORTCUTS[t],i=D.isMac(),s=new KeyboardEvent("keydown",{key:n.key,ctrlKey:n.ctrl&&!i,metaKey:n.ctrl&&i,shiftKey:n.shift,bubbles:!0,cancelable:!0});return u.log("KeyboardShortcuts",`Run: ${t}`),e(s),!0}enable(){this.#o=!0,u.log("KeyboardShortcuts","Enabled")}disable(){this.#o=!1,u.log("KeyboardShortcuts","Disabled")}isEnabled(){return this.#o}};var H={DISCONNECTED:"disconnected",CONNECTING:"connecting",CONNECTED:"connected",RECONNECTING:"reconnecting"};function Ie(){let o=Math.random()*4294967296>>>0,t=Math.random()*4294967296>>>0;return o.toString(16).padStart(8,"0")+t.toString(16).padStart(8,"0")}var He=256,Re=3e4,Pe=16,tt=class{#t=null;#o=H.DISCONNECTED;#e;#l;#v=0;#a=null;#d=null;#c=new Map;#n=new Map;#h=null;#s=new Map;constructor(t,e){this.#e=t,this.#l=e}getWebSocket(){return this.#t}async connect(){if(this.#o===H.CONNECTED||this.#o===H.CONNECTING){u.warn("WebSocket","Already connected or connecting");return}return this.#S(H.CONNECTING),new Promise((t,e)=>{try{let i=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}${bt(this.#e)}`;u.log("WebSocket",`Connecting to ${i}...`),this.#t=new WebSocket(i),this.#t.onopen=()=>{u.log("WebSocket","Connected successfully"),this.#S(H.CONNECTED),this.#t&&(this.#t.send(JSON.stringify({type:"hello",target:this.#l})),u.log("WebSocket",`Sent ${this.#l.kind} hello`)),this.#N(),t()},this.#t.onmessage=s=>{this.#r(s)},this.#t.onclose=s=>{this.#b(s)},this.#t.onerror=s=>{u.error("WebSocket","Error occurred:",s),e(new Error("WebSocket connection error"))}}catch(n){u.error("WebSocket","Failed to create connection:",n),this.#S(H.DISCONNECTED),e(n instanceof Error?n:new Error(String(n)))}})}disconnect(){this.#I(),this.#t&&(this.#t.onclose=null,this.#t.onerror=null,this.#t.onmessage=null,this.#t.close(),this.#t=null),this.#S(H.DISCONNECTED),u.log("WebSocket","Disconnected")}async send(t){if(!this.isConnected()||!this.#t){u.warn("WebSocket","Cannot send message: not connected");return}try{let e=JSON.stringify(t);this.#t.send(e),u.log("WebSocket","Sent message:",t.type)}catch(e){u.error("WebSocket","Failed to send message:",e)}}async sendWithOpId(t){let e=Ie();return this.recordOutgoing(e),await this.send({...t,op_id:e}),e}recordOutgoing(t){this.#y(),this.#s.set(t,Date.now()+Re)}isOwnEcho(t){if(!t)return!1;let e=this.#s.get(t);return e===void 0?!1:(this.#s.delete(t),e>Date.now())}#y(){let t=Date.now();for(let[e,n]of this.#s)n<=t&&this.#s.delete(e);for(;this.#s.size>=He;){let e=this.#s.keys().next().value;if(e===void 0)break;this.#s.delete(e)}}on(t,e){let n=this.#c.get(t)??[];n.push(e),this.#c.set(t,n),u.log("WebSocket",`Registered handler for message type: ${t}`);let i=this.#n.get(t);if(i?.length){this.#n.delete(t);for(let s of i)try{e(s)}catch(r){u.error("WebSocket",`Replay handler error for ${t}:`,r)}}}off(t,e){let n=this.#c.get(t);if(!n)return;let i=n.indexOf(e);i>=0&&n.splice(i,1)}onStateChange(t){this.#h=t}isConnected(){return this.#o===H.CONNECTED&&!!this.#t&&this.#t.readyState===WebSocket.OPEN}getState(){return this.#o}#r(t){try{let e=JSON.parse(t.data);if(!e||typeof e!="object"||!("type"in e))return;let n=e,i=this.#c.get(n.type);if(!i||i.length===0){let s=this.#n.get(n.type)??[];s.push(n),s.length>Pe&&s.shift(),this.#n.set(n.type,s);return}i.forEach(s=>{try{s(n)}catch(r){u.error("WebSocket",`Handler error for ${n.type}:`,r)}})}catch(e){u.error("WebSocket","Failed to parse message:",e)}}#b(t){this.#I(),u.log("WebSocket",`Connection closed (code: ${t.code}, reason: ${t.reason||"none"})`),this.#S(H.RECONNECTING),this.#v++;let e=Math.min(h.WEBSOCKET.INITIAL_RECONNECT_DELAY*Math.pow(2,this.#v-1),h.WEBSOCKET.MAX_RECONNECT_DELAY);u.log("WebSocket",`Reconnecting in ${e/1e3}s (attempt ${this.#v})...`),this.#a=setTimeout(()=>{this.connect().catch(n=>{u.error("WebSocket","Reconnect failed:",n)})},e)}#N(){this.#_(),this.#d=setTimeout(()=>{this.#v=0,u.log("WebSocket","Connection stable, reset reconnect counter")},h.WEBSOCKET.STABLE_CONNECTION_THRESHOLD)}#I(){this.#x(),this.#_()}#x(){this.#a&&(clearTimeout(this.#a),this.#a=null)}#_(){this.#d&&(clearTimeout(this.#d),this.#d=null)}#S(t){let e=this.#o;this.#o=t,this.#h&&e!==t&&this.#h(t,e)}};var Wt=o=>o.getAttribute("data-current-diff-view")==="rendered"?"rendered":"raw",De=o=>{let t=Wt(o)==="rendered"?"raw":"rendered";document.querySelector(`[data-diff-view-seg] [data-view="${t}"]`)?.click()},Kt=".diff-change-block.is-modified, .diff-change-block.is-added, .diff-change-block.is-deleted",$e=()=>`${window.location.pathname}${window.location.search}`,Be=async()=>{let o=S.flag(h.META_TAGS.ENABLE_LIVE),t=null;if(o){let e=S.get(h.META_TAGS.WORKSPACE_ID);if(!e)return u.warn("DiffShortcuts","Collaboration enabled without workspace-id; skipping"),null;let n=new tt(e,{kind:"surface",key:$e()});try{await n.connect();let i=n.getWebSocket();i&&(window.ws=i),t=new X({enableLive:o,ws:n}),t.init()}catch(i){u.warn("DiffShortcuts","Workspace live socket unavailable:",i)}}if(S.flag(h.META_TAGS.ENABLE_CHAT)){let e=new z(null);e.init(),window.chatManager=e}return t},Gt=o=>{let t=Wt(o),e=document.querySelector(`[data-diff-view-panel="${t}"]`);if(!e||e.hidden)return null;let n=e.matches("[data-diff-scroller]")?e:e.querySelector("[data-diff-scroller]")||e;return{panel:e,scroller:n}},Bt=(o,t)=>{let e=Gt(o);if(!e)return;let{panel:n,scroller:i}=e,s=[...n.querySelectorAll(Kt)].filter(d=>d.offsetParent!==null);if(!s.length)return;let r=s.findIndex(d=>d.classList.contains("is-focused")),a;if(r>=0)a=s[r+t];else{let d=i.getBoundingClientRect().top+56;if(t>0)a=s.find(f=>f.getBoundingClientRect().top>d+4)||s[0];else{let f=s.filter(b=>b.getBoundingClientRect().top<d-4);a=f[f.length-1]||s[s.length-1]}}if(!a){i.scrollBy({top:t*i.clientHeight*.85,behavior:"smooth"});return}s.forEach(d=>d.classList.remove("is-focused")),a.classList.add("is-focused");let c=(a.closest(".md-diff-file-section")?.querySelector(".md-diff-file-header")?.offsetHeight||44)+10,p=a.getBoundingClientRect().top-i.getBoundingClientRect().top-c+i.scrollTop;i.scrollTo({top:Math.max(0,p),behavior:"smooth"})},Ft=async()=>{let o=document.querySelector("[data-diff-shell]");if(!o)return;let t=await Be(),e=new Q,n=()=>document.querySelectorAll(".diff-change-block.is-focused").forEach(i=>i.classList.remove("is-focused"));e.register("HELP",()=>e.showHelp()),e.register("THEME_PANEL",()=>window.MarkonTheme?.togglePanel()),e.register("ESCAPE",()=>{let i=document.querySelector(".shortcuts-help-panel");if(i){i.classList.remove("visible"),setTimeout(()=>i.remove(),200);return}n()}),e.register("DIFF_TOGGLE_VIEW",()=>De(o)),e.register("DIFF_NEXT_FILE",()=>Bt(o,1)),e.register("DIFF_PREV_FILE",()=>Bt(o,-1)),S.flag(h.META_TAGS.ENABLE_LIVE)&&t&&(e.register("TOGGLE_LIVE_ACTIVE",()=>t.toggleActiveMode()),e.register("TOGGLE_LIVE_OFF",()=>t.toggleOff())),S.flag(h.META_TAGS.ENABLE_CHAT)&&(e.register("TOGGLE_CHAT",()=>window.chatManager?.openInDefault()),e.register("TOGGLE_CHAT_ALT",()=>window.chatManager?.openInDefault({invert:!0}))),document.addEventListener("keydown",i=>e.handle(i)),document.addEventListener("click",i=>{let s=i.target;if(!s)return;if(s.closest("[data-diff-scroll-path]")){n();return}let r=s.closest(Kt);if(!r)return;let a=Gt(o);a?.panel.contains(r)&&(a.panel.querySelectorAll(".diff-change-block.is-focused").forEach(l=>l.classList.remove("is-focused")),r.classList.add("is-focused"))}),window.shortcutsManager=e};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{Ft()},{once:!0}):Ft();