texlite 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/client/assets/{AdminUsers-3CHb5012.js → AdminUsers-Dazar9cj.js} +1 -1
  2. package/dist/client/assets/{CitationLibraryDialog-zPpsUhWJ.js → CitationLibraryDialog-VSUiSPgG.js} +1 -1
  3. package/dist/client/assets/{Dashboard-CWfSLzD3.js → Dashboard-CoE5ESfb.js} +2 -2
  4. package/dist/client/assets/GitDialog-C9Loz4Al.js +3 -0
  5. package/dist/client/assets/HistoryDialog-3UNN_jhU.js +7 -0
  6. package/dist/client/assets/{LatexEditor-CM445Tk0.js → LatexEditor-Bq76v8sO.js} +2 -2
  7. package/dist/client/assets/{PdfPreview-BFVNczSk.js → PdfPreview-BKhcS-2c.js} +1 -1
  8. package/dist/client/assets/{ProjectIconPickerDialog-Cf0zBf8u.js → ProjectIconPickerDialog-BoWMjQVm.js} +1 -1
  9. package/dist/client/assets/{ProjectNavigationDialogs-TPbe11iR.js → ProjectNavigationDialogs-CZKTnxrl.js} +1 -1
  10. package/dist/client/assets/{ProjectSettings-CDQvIlQ4.js → ProjectSettings-DiOQVJ40.js} +1 -1
  11. package/dist/client/assets/ProjectWorkspace-DqLwkGpT.js +27 -0
  12. package/dist/client/assets/SelectionHistoryDialog-D3dO83lg.js +3 -0
  13. package/dist/client/assets/{SystemMetricsDialog-CuqHPUnn.js → SystemMetricsDialog-0zCwLtH_.js} +1 -1
  14. package/dist/client/assets/{TagManagementDialog-gRLM3lLx.js → TagManagementDialog-C6KDwtvd.js} +1 -1
  15. package/dist/client/assets/{WordCountDialog-B4PI0vEk.js → WordCountDialog-TwpyAP3m.js} +1 -1
  16. package/dist/client/assets/check-sZxOOKtS.js +1 -0
  17. package/dist/client/assets/chevron-left-32SrOwa5.js +1 -0
  18. package/dist/client/assets/{hard-drive-6uYFyezl.js → hard-drive-XHSiS_A7.js} +1 -1
  19. package/dist/client/assets/index-BRr3Kuxh.css +1 -0
  20. package/dist/client/assets/{index-C0t11tlT.js → index-BjzELSQ-.js} +3 -5
  21. package/dist/client/assets/{index-BRT5O-Hg.js → index-Cd6-F29b.js} +1 -1
  22. package/dist/client/assets/{key-round-DOAxDSfz.js → key-round-C-CXCWnz.js} +1 -1
  23. package/dist/client/assets/minimize-2-BMDPVaF-.js +1 -0
  24. package/dist/client/assets/{minus-9eVJnugf.js → minus-BIa7-KuM.js} +1 -1
  25. package/dist/client/assets/{plus-BGXipRoG.js → plus-BKDWy4Ui.js} +1 -1
  26. package/dist/client/assets/{refresh-cw-Dvp3O90f.js → refresh-cw-Bo7-a7-I.js} +1 -1
  27. package/dist/client/assets/{search-b1ORp1k8.js → search-Bz9Ob5mT.js} +1 -1
  28. package/dist/client/assets/{sigma-Bk0_MzWi.js → sigma-DxlHf9gv.js} +1 -1
  29. package/dist/client/assets/spellCheck-BfZEnpwY.js +1 -0
  30. package/dist/client/assets/{tags-JAkbmWns.js → tags-IMZehjzE.js} +1 -1
  31. package/dist/client/assets/{type-CE2DYkPH.js → type-DTWpFQNQ.js} +1 -1
  32. package/dist/client/assets/{user-plus-CKalKSsw.js → user-plus--aVpd8K6.js} +1 -1
  33. package/dist/client/assets/{x-Bq29njHL.js → x-Tbo3aA0J.js} +1 -1
  34. package/dist/client/index.html +2 -2
  35. package/dist/server/harper.js +205 -8
  36. package/dist/server/history.js +53 -3
  37. package/dist/server/i18n.js +8 -0
  38. package/dist/server/latexSpellMask.js +197 -43
  39. package/dist/server/routes/comments.js +13 -1
  40. package/dist/server/routes/projectHistory.js +13 -1
  41. package/dist/server/routes/projects.js +36 -4
  42. package/package.json +1 -1
  43. package/dist/client/assets/GitDialog-BUU2U_LV.js +0 -3
  44. package/dist/client/assets/HistoryDialog-B6aopsrw.js +0 -7
  45. package/dist/client/assets/ProjectWorkspace-C6GrvKN6.js +0 -27
  46. package/dist/client/assets/SelectionHistoryDialog-CyE0_YDs.js +0 -3
  47. package/dist/client/assets/check-BXvzrdoz.js +0 -1
  48. package/dist/client/assets/chevron-left-BB5MYb7g.js +0 -1
  49. package/dist/client/assets/index-DXWp2bzM.css +0 -1
  50. package/dist/client/assets/minimize-2-BWtbag2I.js +0 -1
  51. package/dist/client/assets/spellCheck-BJjWgnef.js +0 -1
@@ -1,27 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/spellCheck-BJjWgnef.js","assets/index-C0t11tlT.js","assets/react-BVUjbTTn.js","assets/index-DXWp2bzM.css","assets/LatexEditor-CM445Tk0.js","assets/editor-CiK7TK0p.js","assets/check-BXvzrdoz.js","assets/x-Bq29njHL.js","assets/search-b1ORp1k8.js","assets/user-plus-CKalKSsw.js","assets/refresh-cw-Dvp3O90f.js","assets/CitationLibraryDialog-zPpsUhWJ.js","assets/citationLibrary-ZeQPCv5O.js","assets/plus-BGXipRoG.js","assets/chevron-left-BB5MYb7g.js","assets/tags-JAkbmWns.js","assets/GitDialog-BUU2U_LV.js","assets/key-round-DOAxDSfz.js","assets/minimize-2-BWtbag2I.js","assets/minus-9eVJnugf.js","assets/HistoryDialog-B6aopsrw.js","assets/index-BRT5O-Hg.js","assets/hard-drive-6uYFyezl.js","assets/SelectionHistoryDialog-CyE0_YDs.js","assets/ProjectNavigationDialogs-TPbe11iR.js","assets/ProjectSettings-CDQvIlQ4.js","assets/type-CE2DYkPH.js","assets/sigma-Bk0_MzWi.js","assets/WordCountDialog-B4PI0vEk.js"])))=>i.map(i=>d[i]);
2
- import{c as Le,f as ie,g as le,A as Si,n as Id,l as Pd,r as Ud,_ as kt,S as zd,b as it,i as cs,h as ua,C as hs,M as Wt,d as da,j as Bd}from"./index-C0t11tlT.js";import{r as h,u as Ke,j as o,P as fr,d as Bi,e as qd}from"./react-BVUjbTTn.js";import{C as Wd}from"./check-BXvzrdoz.js";import{e as Vd,U as ki,B as Hd,M as Kd,G as Jd,X as fs,F as Gd,f as hl,g as Yd,a as Xd,C as Qd,b as Zd,T as Jt,c as ha,d as Un,L as eh,i as Ft,S as Ci,D as Gs,A as Ys,P as fl,h as pl}from"./x-Bq29njHL.js";import{S as th}from"./search-b1ORp1k8.js";import{U as nh}from"./user-plus-CKalKSsw.js";import{R as sh}from"./refresh-cw-Dvp3O90f.js";const rh=Le("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);const fa=Le("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const ih=Le("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const qi=Le("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);const ml=Le("Columns2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]);const ji=Le("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]);const oh=Le("FileClock",[["path",{d:"M16 22h2a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"37hlfg"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"8",cy:"16",r:"6",key:"10v15b"}],["path",{d:"M9.5 17.5 8 16.25V14",key:"1o80t2"}]]);const lh=Le("FilePlus2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 15h6",key:"4e2qda"}],["path",{d:"M6 12v6",key:"1u72j0"}]]);const pa=Le("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);const gl=Le("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);const ah=Le("Keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]);const wl=Le("Move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);const ma=Le("PackageOpen",[["path",{d:"M12 22v-9",key:"x3hkom"}],["path",{d:"M15.17 2.21a1.67 1.67 0 0 1 1.63 0L21 4.57a1.93 1.93 0 0 1 0 3.36L8.82 14.79a1.655 1.655 0 0 1-1.64 0L3 12.43a1.93 1.93 0 0 1 0-3.36z",key:"2ntwy6"}],["path",{d:"M20 13v3.87a2.06 2.06 0 0 1-1.11 1.83l-6 3.08a1.93 1.93 0 0 1-1.78 0l-6-3.08A2.06 2.06 0 0 1 4 16.87V13",key:"1pmm1c"}],["path",{d:"M21 12.43a1.93 1.93 0 0 0 0-3.36L8.83 2.2a1.64 1.64 0 0 0-1.63 0L3 4.57a1.93 1.93 0 0 0 0 3.36l12.18 6.86a1.636 1.636 0 0 0 1.63 0z",key:"12ttoo"}]]);const ga=Le("PanelLeftClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);const ch=Le("PanelLeftOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]);const uh=Le("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);const dh=Le("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);const hh=Le("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);const fh=Le("Reply",[["polyline",{points:"9 17 4 12 9 7",key:"hvgpf2"}],["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}]]);const ph=Le("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);const yl=Le("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);const mh=Le("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);const gh=Le("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),vi=[{id:"jetbrains",labelKey:"projectSettings.fontJetBrains",stack:'"JetBrains Mono", ui-monospace, monospace'},{id:"source-code",labelKey:"projectSettings.fontSourceCode",stack:'"Source Code Pro", ui-monospace, monospace'},{id:"ibm-plex",labelKey:"projectSettings.fontIbmPlex",stack:'"IBM Plex Mono", ui-monospace, monospace'},{id:"fira-code",labelKey:"projectSettings.fontFiraCode",stack:'"Fira Code", ui-monospace, monospace'},{id:"iosevka",labelKey:"projectSettings.fontIosevka",stack:'"Iosevka", ui-monospace, monospace'}],wt={font:"jetbrains",fontSize:14,lineHeight:1.65,lineWrapping:!0,spellCheck:!0,mathPreviewOnHover:!1,vimMode:!1,formatOnCompile:!1,texFmtConfig:"",openFilesInTabs:!1},wh="texlite-editor-preferences";function wa(t,e){return`${wh}:${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function Qw(t){return vi.find(e=>e.id===t)?.stack??vi[0].stack}function bl(t,e){try{const n=JSON.parse(localStorage.getItem(wa(t,e))??"{}");return{font:vi.some(s=>s.id===n.font)?n.font:wt.font,fontSize:[12,13,14,15,16,18,20].includes(Number(n.fontSize))?Number(n.fontSize):wt.fontSize,lineHeight:[1.45,1.65,1.85].includes(Number(n.lineHeight))?Number(n.lineHeight):wt.lineHeight,lineWrapping:typeof n.lineWrapping=="boolean"?n.lineWrapping:wt.lineWrapping,spellCheck:typeof n.spellCheck=="boolean"?n.spellCheck:wt.spellCheck,mathPreviewOnHover:typeof n.mathPreviewOnHover=="boolean"?n.mathPreviewOnHover:wt.mathPreviewOnHover,vimMode:typeof n.vimMode=="boolean"?n.vimMode:wt.vimMode,formatOnCompile:typeof n.formatOnCompile=="boolean"?n.formatOnCompile:wt.formatOnCompile,texFmtConfig:typeof n.texFmtConfig=="string"&&n.texFmtConfig.length<=16*1024?n.texFmtConfig:wt.texFmtConfig,openFilesInTabs:typeof n.openFilesInTabs=="boolean"?n.openFilesInTabs:wt.openFilesInTabs}}catch{return wt}}function yh(t,e,n){localStorage.setItem(wa(t,e),JSON.stringify(n))}function bh(){let t={status:"loading",error:""};const e=new Set,n=(s,r="")=>{if(!(t.status===s&&t.error===r)){t={status:s,error:r};for(const i of e)i()}};return{getSnapshot:()=>t,subscribe:s=>(e.add(s),()=>e.delete(s)),loading:()=>n("loading"),working:()=>n("working"),failed:s=>n("error",s instanceof Error?s.message:String(s))}}const Vt=bh(),xh=/\.(?:tex|bib|cls|sty)$/i,ya=3e4;let yt=null,Xs=!1,cn=null,Sh=1;const hn=new Map,Qs=[];let Rn=null,os=null;class at extends Error{constructor(e,n){super(n),this.kind=e,this.name="TexFmtError"}kind}function ti(t){return t instanceof at}function Ot(t){yt?.terminate(),yt=null,Xs=!1,cn!==null&&window.clearTimeout(cn),cn=null,Rn=null,Qs.length=0,os=null,Vt.failed(t);for(const e of hn.values())e.timeout!==null&&window.clearTimeout(e.timeout),e.reject(t);hn.clear()}function us(){if(Rn!==null||Qs.length===0)return;let t;try{t=kh()}catch(s){Ot(s instanceof at?s:new at("load","The bundled tex-fmt formatter could not be loaded."));return}if(!Xs)return;const e=Qs.shift();if(e===void 0)return;const n=hn.get(e);if(!n){us();return}Rn=e,n.timeout=window.setTimeout(()=>{Rn===e&&Ot(new at("result","The formatter did not respond within 30 seconds."))},ya);try{t.postMessage({...n.request,id:e})}catch{Ot(new at("load","The formatter worker could not receive the source."))}}function kh(){if(yt)return yt;if(typeof Worker>"u"){const t=new at("load","This browser does not support formatter workers.");throw Vt.failed(t),t}Vt.loading();try{yt=new Worker(new URL("/assets/latexFormatterWorker-DYkYtcFy.js",import.meta.url),{type:"module",name:"texlite-latex-formatter"}),cn=window.setTimeout(()=>{Xs||Ot(new at("load","The formatter did not finish loading within 30 seconds."))},ya)}catch{const t=new at("load","The bundled tex-fmt formatter could not be loaded.");throw Vt.failed(t),t}return yt.onmessage=t=>{const e=t.data;if(e&&"type"in e){e.type==="ready"&&(Xs=!0,cn!==null&&window.clearTimeout(cn),cn=null,us());return}if(!e||typeof e.id!="number"){Ot(new at("result","The formatter worker returned an invalid response."));return}const n=hn.get(e.id);if(n)if(hn.delete(e.id),n.timeout!==null&&window.clearTimeout(n.timeout),Rn===e.id&&(Rn=null),e.ok)Vt.working(),n.resolve(e.result),us();else{const s=new at(e.kind,e.message);e.kind==="format"?(Vt.working(),n.reject(s),us()):(n.reject(s),Ot(s))}},yt.onerror=()=>{Ot(new at("load","The bundled tex-fmt formatter could not be loaded."))},yt.onmessageerror=()=>{Ot(new at("result","The formatter worker returned an unreadable response."))},yt}function Wi(t){const e=Sh++;return new Promise((n,s)=>{hn.set(e,{request:t,resolve:n,reject:s,timeout:null}),Qs.push(e),us()})}function Ch(t,e=""){return Wi({action:"format",source:t,config:e})}async function jh(){yt&&Vt.getSnapshot().status==="working"||(os||(os=Wi({action:"probe"}).then(()=>{}).finally(()=>{os=null})),await os)}async function Zw(){(yt||hn.size)&&Ot(new at("load","The formatter runtime was reloaded.")),Vt.loading(),await jh()}function Ps(t){return xh.test(t)}function vh(t){return t.match(/(?:\r?\n)+$/)?.[0]??""}function Eh(t,e){const n=vh(t),l=(n?t.slice(0,-n.length):t).split(/\r?\n/).find(u=>u.trim())?.match(/^[\t ]*/)?.[0]??"",a=e.replace(/(?:\r?\n)+$/,"");return`${l?a.split(`
3
- `).map(u=>u&&`${l}${u}`).join(`
4
- `):a}${n}`}async function ni(t,e,n=0){return Wi({action:"diff",source:t,formatted:e,baseOffset:n})}function Dh(t,e=null){const n=xl(t),r=e==="succeeded"||e===null&&Th(t)?[]:Sl(n.filter(kl)),i=xl(_h(t));return{warnings:Sl(i.filter(a=>!kl(a)&&Lh(a))),errors:r}}function xl(t){return t.split(`
5
- `).map(e=>e.trim()).filter(Boolean)}function Sl(t){return[...new Set(t)]}function _h(t){const e=/^Running ['"][^\n]*(?:pdf|xe|lua)latex(?:\s|['"])[^\n]*$/gim;let n=-1;for(const s of t.matchAll(e))n=s.index;return n>=0?t.slice(n):t}function Th(t){return/Latexmk: All targets .* are up-to-date/i.test(t)&&/Output written on .*\.pdf/i.test(t)}function kl(t){return/^!\s/.test(t)||/(?:^|:\s)(?:LaTeX|Package|Class|pdfTeX|XeTeX|LuaTeX)?\s*Error:/i.test(t)||/^Latexmk:.*(?:\bErrors?,|did not complete making targets|failure)/i.test(t)||/^Collected error summary/i.test(t)||/\b(?:fatal error|emergency stop|undefined control sequence|no output pdf|no pages of output)\b/i.test(t)||/\b(?:bibtex|biber) errors?:/i.test(t)||/^error, and then rerun latexmk/i.test(t)}function Lh(t){return/\bwarnings?\b|overfull|underfull|badness/i.test(t)}function Rh(t){return t instanceof Error&&t.name==="AbortError"}function Ah({projectId:t,activeFile:e,permission:n,revision:s,selection:r,save:i,onError:l,onAdded:a,onChanged:c}){const[u,f]=h.useState([]),[d,p]=h.useState(null),[w,g]=h.useState(!1),[b,x]=h.useState(""),E=h.useRef(null),R=h.useRef(e),S=h.useRef(i),z=h.useRef(l),J=h.useRef(a),C=h.useRef(c);R.current=e,S.current=i,z.current=l,J.current=a,C.current=c;const k=async O=>{E.current?.abort();const q=new AbortController;E.current=q;try{const W=await ie(`/api/projects/${t}/comments?path=${encodeURIComponent(O)}`,{signal:q.signal});R.current===O&&f(W.comments)}catch(W){!Rh(W)&&R.current===O&&f([])}finally{E.current===q&&(E.current=null)}};return h.useEffect(()=>{p(null)},[t,e]),h.useEffect(()=>(e?k(e):f([]),()=>{E.current?.abort(),E.current=null}),[t,e,s]),{comments:u,focusComment:d,setFocusComment:p,commentOpen:w,setCommentOpen:g,commentText:b,setCommentText:x,addComment:async()=>{if(!(!b.trim()||!e))try{if(n!=="read"&&!await S.current())return;await ie(`/api/projects/${t}/comments`,{method:"POST",body:JSON.stringify({path:e,content:b,...r})}),await k(e),g(!1),x(""),J.current(),C.current?.()}catch(O){z.current(le(O))}},toggleComment:async O=>{try{await ie(`/api/projects/${t}/comments/${O.id}`,{method:"PATCH",body:JSON.stringify({resolved:!O.resolved})}),await k(e),C.current?.()}catch(q){z.current(le(q))}},replyToComment:async(O,q)=>{try{return await ie(`/api/projects/${t}/comments/${O.id}/replies`,{method:"POST",body:JSON.stringify({content:q})}),await k(e),C.current?.(),!0}catch(W){return z.current(le(W)),!1}},editComment:async(O,q)=>{try{return await ie(`/api/projects/${t}/comments/${O.id}`,{method:"PATCH",body:JSON.stringify({content:q})}),await k(e),C.current?.(),!0}catch(W){return z.current(le(W)),!1}},deleteComment:async O=>{try{return await ie(`/api/projects/${t}/comments/${O.id}`,{method:"DELETE"}),await k(e),p(q=>q?.id===O.id?null:q),C.current?.(),!0}catch(q){return z.current(le(q)),!1}},editCommentReply:async(O,q,W)=>{try{return await ie(`/api/projects/${t}/comments/${O.id}/replies/${q}`,{method:"PATCH",body:JSON.stringify({content:W})}),await k(e),C.current?.(),!0}catch(G){return z.current(le(G)),!1}},deleteCommentReply:async(O,q)=>{try{return await ie(`/api/projects/${t}/comments/${O.id}/replies/${q}`,{method:"DELETE"}),await k(e),C.current?.(),!0}catch(W){return z.current(le(W)),!1}}}}function Nh(t){return t instanceof Error&&t.name==="AbortError"}function Oh(t,e,n){const[s,r]=h.useState([]),i=h.useRef(null),l=h.useRef(n);l.current=n;const a=h.useCallback(async(f=!1)=>{i.current?.abort();const d=new AbortController;i.current=d;try{const p=await ie(`/api/projects/${t}/mentions?unread=1&limit=100`,{signal:d.signal});i.current===d&&r(p.mentions)}catch(p){i.current===d&&!Nh(p)&&(r([]),f&&l.current(le(p)))}finally{i.current===d&&(i.current=null)}},[t]);return h.useEffect(()=>(a(),()=>{i.current?.abort(),i.current=null}),[a,e]),{unreadMentions:s,refresh:a,markMentionRead:async f=>{try{return await ie(`/api/projects/${t}/mentions/${encodeURIComponent(f)}/read`,{method:"POST"}),r(d=>d.filter(p=>p.id!==f)),!0}catch(d){return l.current(le(d)),!1}},markAllMentionsRead:async()=>{if(!s.length)return!0;try{return await ie(`/api/projects/${t}/mentions/read-all`,{method:"POST"}),r([]),!0}catch(f){return l.current(le(f)),!1}}}}const rt=()=>new Map,Ei=t=>{const e=rt();return t.forEach((n,s)=>{e.set(s,n)}),e},Dt=(t,e,n)=>{let s=t.get(e);return s===void 0&&t.set(e,s=n()),s},Fh=(t,e)=>{const n=[];for(const[s,r]of t)n.push(e(r,s));return n},Mh=(t,e)=>{for(const[n,s]of t)if(e(s,n))return!0;return!1},Gt=()=>new Set,si=t=>t[t.length-1],$h=(t,e)=>{for(let n=0;n<e.length;n++)t.push(e[n])},$t=Array.from,Vi=(t,e)=>{for(let n=0;n<t.length;n++)if(!e(t[n],n,t))return!1;return!0},Hi=(t,e)=>{for(let n=0;n<t.length;n++)if(e(t[n],n,t))return!0;return!1},Ih=(t,e)=>{const n=new Array(t);for(let s=0;s<t;s++)n[s]=e(s,n);return n},zn=Array.isArray;class Ki{constructor(){this._observers=rt()}on(e,n){return Dt(this._observers,e,Gt).add(n),n}once(e,n){const s=(...r)=>{this.off(e,s),n(...r)};this.on(e,s)}off(e,n){const s=this._observers.get(e);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(e))}emit(e,n){return $t((this._observers.get(e)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}class ba{constructor(){this._observers=rt()}on(e,n){Dt(this._observers,e,Gt).add(n)}once(e,n){const s=(...r)=>{this.off(e,s),n(...r)};this.on(e,s)}off(e,n){const s=this._observers.get(e);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(e))}emit(e,n){return $t((this._observers.get(e)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}const xt=Math.floor,Ws=Math.abs,Ji=(t,e)=>t<e?t:e,gn=(t,e)=>t>e?t:e,Ph=Math.pow,xa=t=>t!==0?t<0:1/t<0,Cl=1,jl=2,ri=4,ii=8,ps=32,Mt=64,ct=128,ey=1<<29,pr=31,Di=63,dn=127,Uh=2147483647,Zs=Number.MAX_SAFE_INTEGER,vl=Number.MIN_SAFE_INTEGER,zh=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&xt(t)===t),Sa=String.fromCharCode,Bh=t=>t.toLowerCase(),qh=/^\s*/g,Wh=t=>t.replace(qh,""),Vh=/([A-Z])/g,El=(t,e)=>Wh(t.replace(Vh,n=>`${e}${Bh(n)}`)),Hh=t=>{const e=unescape(encodeURIComponent(t)),n=e.length,s=new Uint8Array(n);for(let r=0;r<n;r++)s[r]=e.codePointAt(r);return s},ms=typeof TextEncoder<"u"?new TextEncoder:null,Kh=t=>ms.encode(t),Jh=ms?Kh:Hh;let ds=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ds&&ds.decode(new Uint8Array).length===1&&(ds=null);const Gh=(t,e)=>Ih(e,()=>t).join("");class js{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Ne=()=>new js,Gi=t=>{let e=t.cpos;for(let n=0;n<t.bufs.length;n++)e+=t.bufs[n].length;return e},xe=t=>{const e=new Uint8Array(Gi(t));let n=0;for(let s=0;s<t.bufs.length;s++){const r=t.bufs[s];e.set(r,n),n+=r.length}return e.set(new Uint8Array(t.cbuf.buffer,0,t.cpos),n),e},Yh=(t,e)=>{const n=t.cbuf.length;n-t.cpos<e&&(t.bufs.push(new Uint8Array(t.cbuf.buffer,0,t.cpos)),t.cbuf=new Uint8Array(gn(n,e)*2),t.cpos=0)},Ve=(t,e)=>{const n=t.cbuf.length;t.cpos===n&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(n*2),t.cpos=0),t.cbuf[t.cpos++]=e},_i=Ve,V=(t,e)=>{for(;e>dn;)Ve(t,ct|dn&e),e=xt(e/128);Ve(t,dn&e)},Yi=(t,e)=>{const n=xa(e);for(n&&(e=-e),Ve(t,(e>Di?ct:0)|(n?Mt:0)|Di&e),e=xt(e/64);e>0;)Ve(t,(e>dn?ct:0)|dn&e),e=xt(e/128)},Ti=new Uint8Array(3e4),Xh=Ti.length/3,Qh=(t,e)=>{if(e.length<Xh){const n=ms.encodeInto(e,Ti).written||0;V(t,n);for(let s=0;s<n;s++)Ve(t,Ti[s])}else Ae(t,Jh(e))},Zh=(t,e)=>{const n=unescape(encodeURIComponent(e)),s=n.length;V(t,s);for(let r=0;r<s;r++)Ve(t,n.codePointAt(r))},Xe=ms&&ms.encodeInto?Qh:Zh,mr=(t,e)=>{const n=t.cbuf.length,s=t.cpos,r=Ji(n-s,e.length),i=e.length-r;t.cbuf.set(e.subarray(0,r),s),t.cpos+=r,i>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(gn(n*2,i)),t.cbuf.set(e.subarray(r)),t.cpos=i)},Ae=(t,e)=>{V(t,e.byteLength),mr(t,e)},Xi=(t,e)=>{Yh(t,e);const n=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,n},ef=(t,e)=>Xi(t,4).setFloat32(0,e,!1),tf=(t,e)=>Xi(t,8).setFloat64(0,e,!1),nf=(t,e)=>Xi(t,8).setBigInt64(0,e,!1),Dl=new DataView(new ArrayBuffer(4)),sf=t=>(Dl.setFloat32(0,t),Dl.getFloat32(0)===t),gs=(t,e)=>{switch(typeof e){case"string":Ve(t,119),Xe(t,e);break;case"number":zh(e)&&Ws(e)<=Uh?(Ve(t,125),Yi(t,e)):sf(e)?(Ve(t,124),ef(t,e)):(Ve(t,123),tf(t,e));break;case"bigint":Ve(t,122),nf(t,e);break;case"object":if(e===null)Ve(t,126);else if(zn(e)){Ve(t,117),V(t,e.length);for(let n=0;n<e.length;n++)gs(t,e[n])}else if(e instanceof Uint8Array)Ve(t,116),Ae(t,e);else{Ve(t,118);const n=Object.keys(e);V(t,n.length);for(let s=0;s<n.length;s++){const r=n[s];Xe(t,r),gs(t,e[r])}}break;case"boolean":Ve(t,e?120:121);break;default:Ve(t,127)}};class _l extends js{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&V(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const Tl=t=>{t.count>0&&(Yi(t.encoder,t.count===1?t.s:-t.s),t.count>1&&V(t.encoder,t.count-2))};class Vs{constructor(){this.encoder=new js,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Tl(this),this.count=1,this.s=e)}toUint8Array(){return Tl(this),xe(this.encoder)}}const Ll=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);Yi(t.encoder,e),t.count>1&&V(t.encoder,t.count-2)}};class oi{constructor(){this.encoder=new js,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Ll(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Ll(this),xe(this.encoder)}}class rf{constructor(){this.sarr=[],this.s="",this.lensE=new Vs}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new js;return this.sarr.push(this.s),this.s="",Xe(e,this.sarr.join("")),mr(e,this.lensE.toUint8Array()),xe(e)}}const St=t=>new Error(t),bt=()=>{throw St("Method unimplemented")},ut=()=>{throw St("Unexpected case")},ka=St("Unexpected end of array"),Ca=St("Integer out of Range");class gr{constructor(e){this.arr=e,this.pos=0}}const Qt=t=>new gr(t),Li=t=>t.pos!==t.arr.length,of=(t,e)=>{const n=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,n},Qe=t=>of(t,se(t)),Bn=t=>t.arr[t.pos++],se=t=>{let e=0,n=1;const s=t.arr.length;for(;t.pos<s;){const r=t.arr[t.pos++];if(e=e+(r&dn)*n,n*=128,r<ct)return e;if(e>Zs)throw Ca}throw ka},Qi=t=>{let e=t.arr[t.pos++],n=e&Di,s=64;const r=(e&Mt)>0?-1:1;if((e&ct)===0)return r*n;const i=t.arr.length;for(;t.pos<i;){if(e=t.arr[t.pos++],n=n+(e&dn)*s,s*=128,e<ct)return r*n;if(n>Zs)throw Ca}throw ka},lf=t=>{let e=se(t);if(e===0)return"";{let n=String.fromCodePoint(Bn(t));if(--e<100)for(;e--;)n+=String.fromCodePoint(Bn(t));else for(;e>0;){const s=e<1e4?e:1e4,r=t.arr.subarray(t.pos,t.pos+s);t.pos+=s,n+=String.fromCodePoint.apply(null,r),e-=s}return decodeURIComponent(escape(n))}},af=t=>ds.decode(Qe(t)),_e=ds?af:lf,Zi=(t,e)=>{const n=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,n},cf=t=>Zi(t,4).getFloat32(0,!1),uf=t=>Zi(t,8).getFloat64(0,!1),df=t=>Zi(t,8).getBigInt64(0,!1),hf=[t=>{},t=>null,Qi,cf,uf,df,t=>!1,t=>!0,_e,t=>{const e=se(t),n={};for(let s=0;s<e;s++){const r=_e(t);n[r]=ws(t)}return n},t=>{const e=se(t),n=[];for(let s=0;s<e;s++)n.push(ws(t));return n},Qe],ws=t=>hf[127-Bn(t)](t);class Rl extends gr{constructor(e,n){super(e),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Li(this)?this.count=se(this)+1:this.count=-1),this.count--,this.s}}class Hs extends gr{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Qi(this);const e=xa(this.s);this.count=1,e&&(this.s=-this.s,this.count=se(this)+2)}return this.count--,this.s}}class li extends gr{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=Qi(this),n=e&1;this.diff=xt(e/2),this.count=1,n&&(this.count=se(this)+2)}return this.s+=this.diff,this.count--,this.s}}class ff{constructor(e){this.decoder=new Hs(e),this.str=_e(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),n=this.str.slice(this.spos,e);return this.spos=e,n}}const pf=crypto.getRandomValues.bind(crypto),ja=()=>pf(new Uint32Array(1))[0],mf="10000000-1000-4000-8000"+-1e11,gf=()=>mf.replace(/[018]/g,t=>(t^ja()&15>>t/4).toString(16)),Yt=Date.now,qn=t=>new Promise(t);Promise.all.bind(Promise);const Al=t=>t===void 0?null:t;class wf{constructor(){this.map=new Map}setItem(e,n){this.map.set(e,n)}getItem(e){return this.map.get(e)}}let va=new wf,eo=!0;try{typeof localStorage<"u"&&localStorage&&(va=localStorage,eo=!1)}catch{}const Ea=va,yf=t=>eo||addEventListener("storage",t),bf=t=>eo||removeEventListener("storage",t),ys=Symbol("Equality"),Da=(t,e)=>t===e||!!t?.[ys]?.(e)||!1,xf=t=>typeof t=="object",Sf=Object.assign,kf=Object.keys,Cf=(t,e)=>{for(const n in t)e(t[n],n)},jf=(t,e)=>{const n=[];for(const s in t)n.push(e(t[s],s));return n},er=t=>kf(t).length,vf=t=>{for(const e in t)return!1;return!0},vs=(t,e)=>{for(const n in t)if(!e(t[n],n))return!1;return!0},to=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Ef=(t,e)=>t===e||er(t)===er(e)&&vs(t,(n,s)=>(n!==void 0||to(e,s))&&Da(e[s],n)),Df=Object.freeze,_a=t=>{for(const e in t){const n=t[e];(typeof n=="object"||typeof n=="function")&&_a(t[e])}return Df(t)},no=(t,e,n=0)=>{try{for(;n<t.length;n++)t[n](...e)}finally{n<t.length&&no(t,e,n+1)}},_f=t=>t,An=(t,e)=>{if(t===e)return!0;if(t==null||e==null||t.constructor!==e.constructor&&(t.constructor||Object)!==(e.constructor||Object))return!1;if(t[ys]!=null)return t[ys](e);switch(t.constructor){case ArrayBuffer:t=new Uint8Array(t),e=new Uint8Array(e);case Uint8Array:{if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;break}case Set:{if(t.size!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;break}case Map:{if(t.size!==e.size)return!1;for(const n of t.keys())if(!e.has(n)||!An(t.get(n),e.get(n)))return!1;break}case void 0:case Object:if(er(t)!==er(e))return!1;for(const n in t)if(!to(t,n)||!An(t[n],e[n]))return!1;break;case Array:if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!An(t[n],e[n]))return!1;break;default:return!1}return!0},Tf=(t,e)=>e.includes(t);var Ta={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",La=typeof window<"u"&&typeof document<"u"&&!Xt;let jt;const Lf=()=>{if(jt===void 0)if(Xt){jt=rt();const t=process.argv;let e=null;for(let n=0;n<t.length;n++){const s=t[n];s[0]==="-"?(e!==null&&jt.set(e,""),e=s):e!==null&&(jt.set(e,s),e=null)}e!==null&&jt.set(e,"")}else typeof location=="object"?(jt=rt(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){const[e,n]=t.split("=");jt.set(`--${El(e,"-")}`,n),jt.set(`-${El(e,"-")}`,n)}})):jt=rt();return jt},Ri=t=>Lf().has(t),tr=t=>Al(Xt?Ta[t.toUpperCase().replaceAll("-","_")]:Ea.getItem(t)),Ra=t=>Ri("--"+t)||tr(t)!==null,Rf=Ra("production"),Af=Xt&&Tf(Ta.FORCE_COLOR,["true","1","2"]),Nf=Af||!Ri("--no-colors")&&!Ra("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Ri("--color")||tr("COLORTERM")!==null||(tr("TERM")||"").includes("color")),Aa=t=>new Uint8Array(t),Of=(t,e,n)=>new Uint8Array(t,e,n),Ff=t=>new Uint8Array(t),Mf=t=>{let e="";for(let n=0;n<t.byteLength;n++)e+=Sa(t[n]);return btoa(e)},$f=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),If=t=>{const e=atob(t),n=Aa(e.length);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return n},Pf=t=>{const e=Buffer.from(t,"base64");return Of(e.buffer,e.byteOffset,e.byteLength)},Uf=La?Mf:$f,zf=La?If:Pf,Bf=t=>{const e=Aa(t.byteLength);return e.set(t),e};class qf{constructor(e,n){this.left=e,this.right=n}}const Nt=(t,e)=>new qf(t,e),Wf=(t,e)=>t.forEach(n=>e(n.left,n.right)),Nl=t=>t.next()>=.5,ai=(t,e,n)=>xt(t.next()*(n+1-e)+e),Na=(t,e,n)=>xt(t.next()*(n+1-e)+e),so=(t,e,n)=>Na(t,e,n),Vf=t=>Sa(so(t,97,122)),Hf=(t,e=0,n=20)=>{const s=so(t,e,n);let r="";for(let i=0;i<s;i++)r+=Vf(t);return r},ci=(t,e)=>e[so(t,0,e.length-1)],Kf=Symbol("0schema");class Jf{constructor(){this._rerrs=[]}extend(e,n,s,r=null){this._rerrs.push({path:e,expected:n,has:s,message:r})}toString(){const e=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];e.push(Gh(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return e.join(`
6
- `)}}const Ai=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[ys]?Da(t,e):zn(t)?Vi(t,n=>Hi(e,s=>Ai(n,s))):xf(t)?vs(t,(n,s)=>Ai(n,e[s])):!1;class nt{static _dilutes=!1;extends(e){let[n,s]=[this.shape,e.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Ai(n,s)}equals(e){return this.constructor===e.constructor&&An(this.shape,e.shape)}[Kf](){return!0}[ys](e){return this.equals(e)}validate(e){return this.check(e)}check(e,n){bt()}get nullable(){return Yn(this,Sr)}get optional(){return new Ma(this)}cast(e){return Ol(e,this),e}expect(e){return Ol(e,this),e}}class ro extends nt{constructor(e,n){super(),this.shape=e,this._c=n}check(e,n=void 0){const s=e?.constructor===this.shape&&(this._c==null||this._c(e));return!s&&n?.extend(null,this.shape.name,e?.constructor.name,e?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const ze=(t,e=null)=>new ro(t,e);ze(ro);class io extends nt{constructor(e){super(),this.shape=e}check(e,n){const s=this.shape(e);return!s&&n?.extend(null,"custom prop",e?.constructor.name,"failed to check custom prop"),s}}const Je=t=>new io(t);ze(io);class wr extends nt{constructor(e){super(),this.shape=e}check(e,n){const s=this.shape.some(r=>r===e);return!s&&n?.extend(null,this.shape.join(" | "),e.toString()),s}}const yr=(...t)=>new wr(t),Oa=ze(wr),Gf=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),Fa=t=>{if(Wn.check(t))return[Gf(t)];if(Oa.check(t))return t.shape.map(e=>e+"");if(Va.check(t))return["[+-]?\\d+.?\\d*"];if(Ha.check(t))return[".*"];if(nr.check(t))return t.shape.map(Fa).flat(1);ut()};class Yf extends nt{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(Fa).map(n=>`(${n.join("|")})`).join("")+"$")}check(e,n){const s=this._r.exec(e)!=null;return!s&&n?.extend(null,this._r.toString(),e.toString(),"String doesn't match string template."),s}}ze(Yf);const Xf=Symbol("optional");class Ma extends nt{constructor(e){super(),this.shape=e}check(e,n){const s=e===void 0||this.shape.check(e);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[Xf](){return!0}}const Qf=ze(Ma);class Zf extends nt{check(e,n){return n?.extend(null,"never",typeof e),!1}}ze(Zf);class br extends nt{constructor(e,n=!1){super(),this.shape=e,this._isPartial=n}static _dilutes=!0;get partial(){return new br(this.shape,!0)}check(e,n){return e==null?(n?.extend(null,"object","null"),!1):vs(this.shape,(s,r)=>{const i=this._isPartial&&!to(e,r)||s.check(e[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof e[r],"Object property does not match"),i})}}const ep=t=>new br(t),tp=ze(br),np=Je(t=>t!=null&&(t.constructor===Object||t.constructor==null));class $a extends nt{constructor(e,n){super(),this.shape={keys:e,values:n}}check(e,n){return e!=null&&vs(e,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof e,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ia=(t,e)=>new $a(t,e),sp=ze($a);class Pa extends nt{constructor(e){super(),this.shape=e}check(e,n){return e!=null&&vs(this.shape,(s,r)=>{const i=s.check(e[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const rp=(...t)=>new Pa(t);ze(Pa);class Ua extends nt{constructor(e){super(),this.shape=e.length===1?e[0]:new oo(e)}check(e,n){const s=zn(e)&&Vi(e,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const za=(...t)=>new Ua(t),ip=ze(Ua),op=Je(t=>zn(t));class Ba extends nt{constructor(e,n){super(),this.shape=e,this._c=n}check(e,n){const s=e instanceof this.shape&&(this._c==null||this._c(e));return!s&&n?.extend(null,this.shape.name,e?.constructor.name),s}}const lp=(t,e=null)=>new Ba(t,e);ze(Ba);const ap=lp(nt);class cp extends nt{constructor(e){super(),this.len=e.length-1,this.args=rp(...e.slice(-1)),this.res=e[this.len]}check(e,n){const s=e.constructor===Function&&e.length<=this.len;return!s&&n?.extend(null,"function",typeof e),s}}const up=ze(cp),dp=Je(t=>typeof t=="function");class hp extends nt{constructor(e){super(),this.shape=e}check(e,n){const s=Vi(this.shape,r=>r.check(e,n));return!s&&n?.extend(null,"Intersectinon",typeof e),s}}ze(hp,t=>t.shape.length>0);class oo extends nt{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,n){const s=Hi(this.shape,r=>r.check(e,n));return n?.extend(null,"Union",typeof e),s}}const Yn=(...t)=>t.findIndex(e=>nr.check(e))>=0?Yn(...t.map(e=>bs(e)).map(e=>nr.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new oo(t),nr=ze(oo),qa=()=>!0,sr=Je(qa),fp=ze(io,t=>t.shape===qa),lo=Je(t=>typeof t=="bigint"),pp=Je(t=>t===lo),Wa=Je(t=>typeof t=="symbol");Je(t=>t===Wa);const Nn=Je(t=>typeof t=="number"),Va=Je(t=>t===Nn),Wn=Je(t=>typeof t=="string"),Ha=Je(t=>t===Wn),xr=Je(t=>typeof t=="boolean"),mp=Je(t=>t===xr),Ka=yr(void 0);ze(wr,t=>t.shape.length===1&&t.shape[0]===void 0);yr(void 0);const Sr=yr(null),gp=ze(wr,t=>t.shape.length===1&&t.shape[0]===null);ze(Uint8Array);ze(ro,t=>t.shape===Uint8Array);const wp=Yn(Nn,Wn,Sr,Ka,lo,xr,Wa);(()=>{const t=za(sr),e=Ia(Wn,sr),n=Yn(Nn,Wn,Sr,xr,t,e);return t.shape=n,e.shape.values=n,n})();const bs=t=>{if(ap.check(t))return t;if(np.check(t)){const e={};for(const n in t)e[n]=bs(t[n]);return ep(e)}else{if(op.check(t))return Yn(...t.map(bs));if(wp.check(t))return yr(t);if(dp.check(t))return ze(t)}ut()},Ol=Rf?()=>{}:(t,e)=>{const n=new Jf;if(!e.check(t,n))throw St(`Expected value to be of type ${e.constructor.name}.
7
- ${n.toString()}`)};class yp{constructor(e){this.patterns=[],this.$state=e}if(e,n){return this.patterns.push({if:bs(e),h:n}),this}else(e){return this.if(sr,e)}done(){return(e,n)=>{for(let s=0;s<this.patterns.length;s++){const r=this.patterns[s];if(r.if.check(e))return r.h(e,n)}throw St("Unhandled pattern")}}}const bp=t=>new yp(t),Ja=bp(sr).if(Va,(t,e)=>ai(e,vl,Zs)).if(Ha,(t,e)=>Hf(e)).if(mp,(t,e)=>Nl(e)).if(pp,(t,e)=>BigInt(ai(e,vl,Zs))).if(nr,(t,e)=>Dn(e,ci(e,t.shape))).if(tp,(t,e)=>{const n={};for(const s in t.shape){let r=t.shape[s];if(Qf.check(r)){if(Nl(e))continue;r=r.shape}n[s]=Ja(r,e)}return n}).if(ip,(t,e)=>{const n=[],s=Na(e,0,42);for(let r=0;r<s;r++)n.push(Dn(e,t.shape));return n}).if(Oa,(t,e)=>ci(e,t.shape)).if(gp,(t,e)=>null).if(up,(t,e)=>{const n=Dn(e,t.res);return()=>n}).if(fp,(t,e)=>Dn(e,ci(e,[Nn,Wn,Sr,Ka,lo,xr,za(Nn),Ia(Yn("a","b","c"),Nn)]))).if(sp,(t,e)=>{const n={},s=ai(e,0,3);for(let r=0;r<s;r++){const i=Dn(e,t.shape.keys),l=Dn(e,t.shape.values);n[i]=l}return n}).done(),Dn=(t,e)=>Ja(bs(e),t),_t=typeof document<"u"?document:{},xp=t=>_t.createElement(t),Sp=()=>_t.createDocumentFragment();Je(t=>t.nodeType===Lp);const kp=t=>_t.createTextNode(t);typeof DOMParser<"u"&&new DOMParser;const Cp=(t,e)=>(Wf(e,(n,s)=>{s===!1?t.removeAttribute(n):s===!0?t.setAttribute(n,""):t.setAttribute(n,s)}),t),jp=t=>{const e=Sp();for(let n=0;n<t.length;n++)Ga(e,t[n]);return e},vp=(t,e)=>(Ga(t,jp(e)),t),ty=(t,e=[],n=[])=>vp(Cp(xp(t),e),n);Je(t=>t.nodeType===Dp);const ny=kp;Je(t=>t.nodeType===_p);const Ep=t=>Fh(t,(e,n)=>`${n}:${e};`).join(""),Ga=(t,e)=>t.appendChild(e),Dp=_t.ELEMENT_NODE,_p=_t.TEXT_NODE;_t.CDATA_SECTION_NODE;_t.COMMENT_NODE;const Tp=_t.DOCUMENT_NODE;_t.DOCUMENT_TYPE_NODE;const Lp=_t.DOCUMENT_FRAGMENT_NODE;Je(t=>t.nodeType===Tp);const It=Symbol,Ya=It(),Xa=It(),Rp=It(),Ap=It(),Np=It(),Qa=It(),Op=It(),ao=It(),Fp=It(),Mp=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());const e=[],n=[];let s=0;for(;s<t.length;s++){const r=t[s];if(r===void 0)break;if(r.constructor===String||r.constructor===Number)e.push(r);else if(r.constructor===Object)break}for(s>0&&n.push(e.join(""));s<t.length;s++){const r=t[s];r instanceof Symbol||n.push(r)}return n},$p={[Ya]:Nt("font-weight","bold"),[Xa]:Nt("font-weight","normal"),[Rp]:Nt("color","blue"),[Np]:Nt("color","green"),[Ap]:Nt("color","grey"),[Qa]:Nt("color","red"),[Op]:Nt("color","purple"),[ao]:Nt("color","orange"),[Fp]:Nt("color","black")},Ip=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());const e=[],n=[],s=rt();let r=[],i=0;for(;i<t.length;i++){const l=t[i],a=$p[l];if(a!==void 0)s.set(a.left,a.right);else{if(l===void 0)break;if(l.constructor===String||l.constructor===Number){const c=Ep(s);i>0||c.length>0?(e.push("%c"+l),n.push(c)):e.push(l)}else break}}for(i>0&&(r=n,r.unshift(e.join("")));i<t.length;i++){const l=t[i];l instanceof Symbol||r.push(l)}return r},Za=Nf?Ip:Mp,Pp=(...t)=>{console.log(...Za(t)),tc.forEach(e=>e.print(t))},ec=(...t)=>{console.warn(...Za(t)),t.unshift(ao),tc.forEach(e=>e.print(t))},tc=Gt(),nc=t=>({[Symbol.iterator](){return this},next:t}),Up=(t,e)=>nc(()=>{let n;do n=t.next();while(!n.done&&!e(n.value));return n}),ui=(t,e)=>nc(()=>{const{done:n,value:s}=t.next();return{done:n,value:n?void 0:e(s)}});class kr{constructor(e,n){this.clock=e,this.len=n}}class Xn{constructor(){this.clients=new Map}}const Vn=(t,e,n)=>e.clients.forEach((s,r)=>{const i=t.doc.store.clients.get(r);if(i!=null){const l=i[i.length-1],a=l.id.clock+l.length;for(let c=0,u=s[c];c<s.length&&u.clock<a;u=s[++c])wc(t,i,u.clock,u.len,n)}}),zp=(t,e)=>{let n=0,s=t.length-1;for(;n<=s;){const r=xt((n+s)/2),i=t[r],l=i.clock;if(l<=e){if(e<l+i.len)return r;n=r+1}else s=r-1}return null},Es=(t,e)=>{const n=t.clients.get(e.client);return n!==void 0&&zp(n,e.clock)!==null},co=t=>{t.clients.forEach(e=>{e.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n<e.length;n++){const r=e[s-1],i=e[n];r.clock+r.len>=i.clock?e[s-1]=new kr(r.clock,gn(r.len,i.clock+i.len-r.clock)):(s<n&&(e[s]=i),s++)}e.length=s})},Ni=t=>{const e=new Xn;for(let n=0;n<t.length;n++)t[n].clients.forEach((s,r)=>{if(!e.clients.has(r)){const i=s.slice();for(let l=n+1;l<t.length;l++)$h(i,t[l].clients.get(r)||[]);e.clients.set(r,i)}});return co(e),e},xs=(t,e,n,s)=>{Dt(t.clients,e,()=>[]).push(new kr(n,s))},Bp=()=>new Xn,qp=t=>{const e=Bp();return t.clients.forEach((n,s)=>{const r=[];for(let i=0;i<n.length;i++){const l=n[i];if(l.deleted){const a=l.id.clock;let c=l.length;if(i+1<n.length)for(let u=n[i+1];i+1<n.length&&u.deleted;u=n[++i+1])c+=u.length;r.push(new kr(a,c))}}r.length>0&&e.clients.set(s,r)}),e},Qn=(t,e)=>{V(t.restEncoder,e.clients.size),$t(e.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{t.resetDsCurVal(),V(t.restEncoder,n);const r=s.length;V(t.restEncoder,r);for(let i=0;i<r;i++){const l=s[i];t.writeDsClock(l.clock),t.writeDsLen(l.len)}})},uo=t=>{const e=new Xn,n=se(t.restDecoder);for(let s=0;s<n;s++){t.resetDsCurVal();const r=se(t.restDecoder),i=se(t.restDecoder);if(i>0){const l=Dt(e.clients,r,()=>[]);for(let a=0;a<i;a++)l.push(new kr(t.readDsClock(),t.readDsLen()))}}return e},Fl=(t,e,n)=>{const s=new Xn,r=se(t.restDecoder);for(let i=0;i<r;i++){t.resetDsCurVal();const l=se(t.restDecoder),a=se(t.restDecoder),c=n.clients.get(l)||[],u=$e(n,l);for(let f=0;f<a;f++){const d=t.readDsClock(),p=d+t.readDsLen();if(d<u){u<p&&xs(s,l,u,p-u);let w=vt(c,d),g=c[w];for(!g.deleted&&g.id.clock<d&&(c.splice(w+1,0,dr(e,g,d-g.id.clock)),w++);w<c.length&&(g=c[w++],g.id.clock<p);)g.deleted||(p<g.id.clock+g.length&&c.splice(w,0,dr(e,g,p-g.id.clock)),g.delete(e))}else xs(s,l,d,p-d)}}if(s.clients.size>0){const i=new fn;return V(i.restEncoder,0),Qn(i,s),i.toUint8Array()}return null},sc=ja;class wn extends Ki{constructor({guid:e=gf(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:l=!1,shouldLoad:a=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=sc(),this.guid=e,this.collectionid=n,this.share=new Map,this.store=new mc,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=a,this.autoLoad=l,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=qn(u=>{this.on("load",()=>{this.isLoaded=!0,u(this)})});const c=()=>qn(u=>{const f=d=>{(d===void 0||d===!0)&&(this.off("sync",f),u())};this.on("sync",f)});this.on("sync",u=>{u===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=u===void 0||u===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const e=this._item;e!==null&&!this.shouldLoad&&ke(e.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(e=>e.guid))}transact(e,n=null){return ke(this,e,n)}get(e,n=He){const s=Dt(this.share,e,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==He&&r!==n)if(r===He){const i=new n;i._map=s._map,s._map.forEach(l=>{for(;l!==null;l=l.left)l.parent=i}),i._start=s._start;for(let l=i._start;l!==null;l=l.right)l.parent=i;return i._length=s._length,this.share.set(e,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return s}getArray(e=""){return this.get(e,Mn)}getText(e=""){return this.get(e,Jn)}getMap(e=""){return this.get(e,Kn)}getXmlElement(e=""){return this.get(e,Gn)}getXmlFragment(e=""){return this.get(e,pn)}toJSON(){const e={};return this.share.forEach((n,s)=>{e[s]=n.toJSON()}),e}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const e=this._item;if(e!==null){this._item=null;const n=e.content;n.doc=new wn({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=e,ke(e.parent.doc,s=>{const r=n.doc;e.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class rc{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return se(this.restDecoder)}readDsLen(){return se(this.restDecoder)}}class ic extends rc{readLeftID(){return oe(se(this.restDecoder),se(this.restDecoder))}readRightID(){return oe(se(this.restDecoder),se(this.restDecoder))}readClient(){return se(this.restDecoder)}readInfo(){return Bn(this.restDecoder)}readString(){return _e(this.restDecoder)}readParentInfo(){return se(this.restDecoder)===1}readTypeRef(){return se(this.restDecoder)}readLen(){return se(this.restDecoder)}readAny(){return ws(this.restDecoder)}readBuf(){return Bf(Qe(this.restDecoder))}readJSON(){return JSON.parse(_e(this.restDecoder))}readKey(){return _e(this.restDecoder)}}class Wp{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=se(this.restDecoder),this.dsCurrVal}readDsLen(){const e=se(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Hn extends Wp{constructor(e){super(e),this.keys=[],se(e),this.keyClockDecoder=new li(Qe(e)),this.clientDecoder=new Hs(Qe(e)),this.leftClockDecoder=new li(Qe(e)),this.rightClockDecoder=new li(Qe(e)),this.infoDecoder=new Rl(Qe(e),Bn),this.stringDecoder=new ff(Qe(e)),this.parentInfoDecoder=new Rl(Qe(e),Bn),this.typeRefDecoder=new Hs(Qe(e)),this.lenDecoder=new Hs(Qe(e))}readLeftID(){return new On(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new On(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return ws(this.restDecoder)}readBuf(){return Qe(this.restDecoder)}readJSON(){return ws(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const n=this.stringDecoder.read();return this.keys.push(n),n}}}class oc{constructor(){this.restEncoder=Ne()}toUint8Array(){return xe(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){V(this.restEncoder,e)}writeDsLen(e){V(this.restEncoder,e)}}class Ds extends oc{writeLeftID(e){V(this.restEncoder,e.client),V(this.restEncoder,e.clock)}writeRightID(e){V(this.restEncoder,e.client),V(this.restEncoder,e.clock)}writeClient(e){V(this.restEncoder,e)}writeInfo(e){_i(this.restEncoder,e)}writeString(e){Xe(this.restEncoder,e)}writeParentInfo(e){V(this.restEncoder,e?1:0)}writeTypeRef(e){V(this.restEncoder,e)}writeLen(e){V(this.restEncoder,e)}writeAny(e){gs(this.restEncoder,e)}writeBuf(e){Ae(this.restEncoder,e)}writeJSON(e){Xe(this.restEncoder,JSON.stringify(e))}writeKey(e){Xe(this.restEncoder,e)}}class lc{constructor(){this.restEncoder=Ne(),this.dsCurrVal=0}toUint8Array(){return xe(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const n=e-this.dsCurrVal;this.dsCurrVal=e,V(this.restEncoder,n)}writeDsLen(e){e===0&&ut(),V(this.restEncoder,e-1),this.dsCurrVal+=e}}class fn extends lc{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new oi,this.clientEncoder=new Vs,this.leftClockEncoder=new oi,this.rightClockEncoder=new oi,this.infoEncoder=new _l(_i),this.stringEncoder=new rf,this.parentInfoEncoder=new _l(_i),this.typeRefEncoder=new Vs,this.lenEncoder=new Vs}toUint8Array(){const e=Ne();return V(e,0),Ae(e,this.keyClockEncoder.toUint8Array()),Ae(e,this.clientEncoder.toUint8Array()),Ae(e,this.leftClockEncoder.toUint8Array()),Ae(e,this.rightClockEncoder.toUint8Array()),Ae(e,xe(this.infoEncoder)),Ae(e,this.stringEncoder.toUint8Array()),Ae(e,xe(this.parentInfoEncoder)),Ae(e,this.typeRefEncoder.toUint8Array()),Ae(e,this.lenEncoder.toUint8Array()),mr(e,xe(this.restEncoder)),xe(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){gs(this.restEncoder,e)}writeBuf(e){Ae(this.restEncoder,e)}writeJSON(e){gs(this.restEncoder,e)}writeKey(e){const n=this.keyMap.get(e);n===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(n)}}const Vp=(t,e,n,s)=>{s=gn(s,e[0].id.clock);const r=vt(e,s);V(t.restEncoder,e.length-r),t.writeClient(n),V(t.restEncoder,s);const i=e[r];i.write(t,s-i.id.clock);for(let l=r+1;l<e.length;l++)e[l].write(t,0)},ho=(t,e,n)=>{const s=new Map;n.forEach((r,i)=>{$e(e,i)>r&&s.set(i,r)}),Cr(e).forEach((r,i)=>{n.has(i)||s.set(i,0)}),V(t.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{Vp(t,e.clients.get(r),r,i)})},Hp=(t,e)=>{const n=rt(),s=se(t.restDecoder);for(let r=0;r<s;r++){const i=se(t.restDecoder),l=new Array(i),a=t.readClient();let c=se(t.restDecoder);n.set(a,{i:0,refs:l});for(let u=0;u<i;u++){const f=t.readInfo();switch(pr&f){case 0:{const d=t.readLen();l[u]=new pt(oe(a,c),d),c+=d;break}case 10:{const d=se(t.restDecoder);l[u]=new mt(oe(a,c),d),c+=d;break}default:{const d=(f&(Mt|ct))===0,p=new je(oe(a,c),null,(f&ct)===ct?t.readLeftID():null,null,(f&Mt)===Mt?t.readRightID():null,d?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,d&&(f&ps)===ps?t.readString():null,$c(t,f));l[u]=p,c+=p.length}}}}return n},Kp=(t,e,n)=>{const s=[];let r=$t(n.keys()).sort((w,g)=>w-g);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let w=n.get(r[r.length-1]);for(;w.refs.length===w.i;)if(r.pop(),r.length>0)w=n.get(r[r.length-1]);else return null;return w};let l=i();if(l===null)return null;const a=new mc,c=new Map,u=(w,g)=>{const b=c.get(w);(b==null||b>g)&&c.set(w,g)};let f=l.refs[l.i++];const d=new Map,p=()=>{for(const w of s){const g=w.id.client,b=n.get(g);b?(b.i--,a.clients.set(g,b.refs.slice(b.i)),n.delete(g),b.i=0,b.refs=[]):a.clients.set(g,[w]),r=r.filter(x=>x!==g)}s.length=0};for(;;){if(f.constructor!==mt){const g=Dt(d,f.id.client,()=>$e(e,f.id.client))-f.id.clock;if(g<0)s.push(f),u(f.id.client,f.id.clock-1),p();else{const b=f.getMissing(t,e);if(b!==null){s.push(f);const x=n.get(b)||{refs:[],i:0};if(x.refs.length===x.i)u(b,$e(e,b)),p();else{f=x.refs[x.i++];continue}}else(g===0||g<f.length)&&(f.integrate(t,g),d.set(f.id.client,f.id.clock+f.length))}}if(s.length>0)f=s.pop();else if(l!==null&&l.i<l.refs.length)f=l.refs[l.i++];else{if(l=i(),l===null)break;f=l.refs[l.i++]}}if(a.clients.size>0){const w=new fn;return ho(w,a,new Map),V(w.restEncoder,0),{missing:c,update:w.toUint8Array()}}return null},Jp=(t,e)=>ho(t,e.doc.store,e.beforeState),Gp=(t,e,n,s=new Hn(t))=>ke(e,r=>{r.local=!1;let i=!1;const l=r.doc,a=l.store,c=Hp(s,l),u=Kp(r,a,c),f=a.pendingStructs;if(f){for(const[p,w]of f.missing)if(w<$e(a,p)){i=!0;break}if(u){for(const[p,w]of u.missing){const g=f.missing.get(p);(g==null||g>w)&&f.missing.set(p,w)}f.update=ir([f.update,u.update])}}else a.pendingStructs=u;const d=Fl(s,r,a);if(a.pendingDs){const p=new Hn(Qt(a.pendingDs));se(p.restDecoder);const w=Fl(p,r,a);d&&w?a.pendingDs=ir([d,w]):a.pendingDs=d||w}else a.pendingDs=d;if(i){const p=a.pendingStructs.update;a.pendingStructs=null,ac(r.doc,p)}},n,!1),ac=(t,e,n,s=Hn)=>{const r=Qt(e);Gp(r,t,n,new s(r))},cc=(t,e,n)=>ac(t,e,n,ic),Yp=(t,e,n=new Map)=>{ho(t,e.store,n),Qn(t,qp(e.store))},Xp=(t,e=new Uint8Array([0]),n=new fn)=>{const s=uc(e);Yp(n,t,s);const r=[n.toUint8Array()];if(t.store.pendingDs&&r.push(t.store.pendingDs),t.store.pendingStructs&&r.push(gm(t.store.pendingStructs.update,e)),r.length>1){if(n.constructor===Ds)return pm(r.map((i,l)=>l===0?i:ym(i)));if(n.constructor===fn)return ir(r)}return r[0]},fo=(t,e)=>Xp(t,e,new Ds),Qp=t=>{const e=new Map,n=se(t.restDecoder);for(let s=0;s<n;s++){const r=se(t.restDecoder),i=se(t.restDecoder);e.set(r,i)}return e},uc=t=>Qp(new rc(Qt(t))),dc=(t,e)=>(V(t.restEncoder,e.size),$t(e.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{V(t.restEncoder,n),V(t.restEncoder,s)}),t),Zp=(t,e)=>dc(t,Cr(e.store)),em=(t,e=new lc)=>(t instanceof Map?dc(e,t):Zp(e,t),e.toUint8Array()),tm=t=>em(t,new oc);class nm{constructor(){this.l=[]}}const Ml=()=>new nm,$l=(t,e)=>t.l.push(e),Il=(t,e)=>{const n=t.l,s=n.length;t.l=n.filter(r=>e!==r),s===t.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},hc=(t,e,n)=>no(t.l,[e,n]);class On{constructor(e,n){this.client=e,this.clock=n}}const Ln=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,oe=(t,e)=>new On(t,e),fc=t=>{for(const[e,n]of t.doc.share.entries())if(n===t)return e;throw ut()},rr=(t,e)=>{for(;e!==null;){if(e.parent===t)return!0;e=e.parent._item}return!1};class pc{constructor(e,n,s,r=0){this.type=e,this.tname=n,this.item=s,this.assoc=r}}const sy=t=>{const e={};return t.type&&(e.type=t.type),t.tname&&(e.tname=t.tname),t.item&&(e.item=t.item),t.assoc!=null&&(e.assoc=t.assoc),e},ry=t=>new pc(t.type==null?null:oe(t.type.client,t.type.clock),t.tname??null,t.item==null?null:oe(t.item.client,t.item.clock),t.assoc==null?0:t.assoc);class sm{constructor(e,n,s=0){this.type=e,this.index=n,this.assoc=s}}const rm=(t,e,n=0)=>new sm(t,e,n),Us=(t,e,n)=>{let s=null,r=null;return t._item===null?r=fc(t):s=oe(t._item.id.client,t._item.id.clock),new pc(s,r,e,n)},iy=(t,e,n=0)=>{let s=t._start;if(n<0){if(e===0)return Us(t,null,n);e--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>e)return Us(t,oe(s.id.client,s.id.clock+e),n);e-=s.length}if(s.right===null&&n<0)return Us(t,s.lastId,n);s=s.right}return Us(t,null,n)},im=(t,e)=>{const n=Fn(t,e),s=e.clock-n.id.clock;return{item:n,diff:s}},oy=(t,e,n=!0)=>{const s=e.store,r=t.item,i=t.type,l=t.tname,a=t.assoc;let c=null,u=0;if(r!==null){if($e(s,r.client)<=r.clock)return null;const f=n?$i(s,r):im(s,r),d=f.item;if(!(d instanceof je))return null;if(c=d.parent,c._item===null||!c._item.deleted){u=d.deleted||!d.countable?0:f.diff+(a>=0?0:1);let p=d.left;for(;p!==null;)!p.deleted&&p.countable&&(u+=p.length),p=p.left}}else{if(l!==null)c=e.get(l);else if(i!==null){if($e(s,i.client)<=i.clock)return null;const{item:f}=n?$i(s,i):{item:Fn(s,i)};if(f instanceof je&&f.content instanceof Tt)c=f.content.type;else return null}else throw ut();a>=0?u=c._length:u=0}return rm(c,u,t.assoc)},ly=(t,e)=>t===e||t!==null&&e!==null&&t.tname===e.tname&&Ln(t.item,e.item)&&Ln(t.type,e.type)&&t.assoc===e.assoc,_n=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!Es(e.ds,t.id),Oi=(t,e)=>{const n=Dt(t.meta,Oi,Gt),s=t.doc.store;n.has(e)||(e.sv.forEach((r,i)=>{r<$e(s,i)&&st(t,oe(i,r))}),Vn(t,e.ds,r=>{}),n.add(e))};class mc{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Cr=t=>{const e=new Map;return t.clients.forEach((n,s)=>{const r=n[n.length-1];e.set(s,r.id.clock+r.length)}),e},$e=(t,e)=>{const n=t.clients.get(e);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},gc=(t,e)=>{let n=t.clients.get(e.id.client);if(n===void 0)n=[],t.clients.set(e.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==e.id.clock)throw ut()}n.push(e)},vt=(t,e)=>{let n=0,s=t.length-1,r=t[s],i=r.id.clock;if(i===e)return s;let l=xt(e/(i+r.length-1)*s);for(;n<=s;){if(r=t[l],i=r.id.clock,i<=e){if(e<i+r.length)return l;n=l+1}else s=l-1;l=xt((n+s)/2)}throw ut()},om=(t,e)=>{const n=t.clients.get(e.client);return n[vt(n,e.clock)]},Fn=om,Fi=(t,e,n)=>{const s=vt(e,n),r=e[s];return r.id.clock<n&&r instanceof je?(e.splice(s+1,0,dr(t,r,n-r.id.clock)),s+1):s},st=(t,e)=>{const n=t.doc.store.clients.get(e.client);return n[Fi(t,n,e.clock)]},Pl=(t,e,n)=>{const s=e.clients.get(n.client),r=vt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pt&&s.splice(r+1,0,dr(t,i,n.clock-i.id.clock+1)),i},lm=(t,e,n)=>{const s=t.clients.get(e.id.client);s[vt(s,e.id.clock)]=n},wc=(t,e,n,s,r)=>{if(s===0)return;const i=n+s;let l=Fi(t,e,n),a;do a=e[l++],i<a.id.clock+a.length&&Fi(t,e,i),r(a);while(l<e.length&&e[l].id.clock<i)};class am{constructor(e,n,s){this.doc=e,this.deleteSet=new Xn,this.beforeState=Cr(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=n,this.meta=new Map,this.local=s,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const Ul=(t,e)=>e.deleteSet.clients.size===0&&!Mh(e.afterState,(n,s)=>e.beforeState.get(s)!==n)?!1:(co(e.deleteSet),Jp(t,e),Qn(t,e.deleteSet),!0),zl=(t,e,n)=>{const s=e._item;(s===null||s.id.clock<(t.beforeState.get(s.id.client)||0)&&!s.deleted)&&Dt(t.changed,e,Gt).add(n)},Ks=(t,e)=>{let n=t[e],s=t[e-1],r=e;for(;r>0;n=s,s=t[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof je&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=e-r;return i&&t.splice(e+1-i,i),i},cm=(t,e,n)=>{for(const[s,r]of t.clients.entries()){const i=e.clients.get(s);for(let l=r.length-1;l>=0;l--){const a=r[l],c=a.clock+a.len;for(let u=vt(i,a.clock),f=i[u];u<i.length&&f.id.clock<c;f=i[++u]){const d=i[u];if(a.clock+a.len<=d.id.clock)break;d instanceof je&&d.deleted&&!d.keep&&n(d)&&d.gc(e,!1)}}}},um=(t,e)=>{t.clients.forEach((n,s)=>{const r=e.clients.get(s);for(let i=n.length-1;i>=0;i--){const l=n[i],a=Ji(r.length-1,1+vt(r,l.clock+l.len-1));for(let c=a,u=r[c];c>0&&u.id.clock>=l.clock;u=r[c])c-=1+Ks(r,c)}})},yc=(t,e)=>{if(e<t.length){const n=t[e],s=n.doc,r=s.store,i=n.deleteSet,l=n._mergeStructs;try{co(i),n.afterState=Cr(n.doc.store),s.emit("beforeObserverCalls",[n,s]);const a=[];n.changed.forEach((c,u)=>a.push(()=>{(u._item===null||!u._item.deleted)&&u._callObserver(n,c)})),a.push(()=>{n.changedParentTypes.forEach((c,u)=>{u._dEH.l.length>0&&(u._item===null||!u._item.deleted)&&(c=c.filter(f=>f.target._item===null||!f.target._item.deleted),c.forEach(f=>{f.currentTarget=u,f._path=null}),c.sort((f,d)=>f.path.length-d.path.length),a.push(()=>{hc(u._dEH,c,n)}))}),a.push(()=>s.emit("afterTransaction",[n,s])),a.push(()=>{n._needFormattingCleanup&&Am(n)})}),no(a,[])}finally{s.gc&&cm(i,r,s.gcFilter),um(i,r),n.afterState.forEach((f,d)=>{const p=n.beforeState.get(d)||0;if(p!==f){const w=r.clients.get(d),g=gn(vt(w,p),1);for(let b=w.length-1;b>=g;)b-=1+Ks(w,b)}});for(let f=l.length-1;f>=0;f--){const{client:d,clock:p}=l[f].id,w=r.clients.get(d),g=vt(w,p);g+1<w.length&&Ks(w,g+1)>1||g>0&&Ks(w,g)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(Pp(ao,Ya,"[yjs] ",Xa,Qa,"Changed the client-id because another client seems to be using it."),s.clientID=sc()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const f=new Ds;Ul(f,n)&&s.emit("update",[f.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const f=new fn;Ul(f,n)&&s.emit("updateV2",[f.toUint8Array(),n.origin,s,n])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:u}=n;(a.size>0||u.size>0||c.size>0)&&(a.forEach(f=>{f.clientID=s.clientID,f.collectionid==null&&(f.collectionid=s.collectionid),s.subdocs.add(f)}),u.forEach(f=>s.subdocs.delete(f)),s.emit("subdocs",[{loaded:c,added:a,removed:u},s,n]),u.forEach(f=>f.destroy())),t.length<=e+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,t])):yc(t,e+1)}}},ke=(t,e,n=null,s=!0)=>{const r=t._transactionCleanups;let i=!1,l=null;t._transaction===null&&(i=!0,t._transaction=new am(t,n,s),r.push(t._transaction),r.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{l=e(t._transaction)}finally{if(i){const a=t._transaction===r[0];t._transaction=null,a&&yc(r,0)}}return l};class dm{constructor(e,n){this.insertions=n,this.deletions=e,this.meta=new Map}}const Bl=(t,e,n)=>{Vn(t,n.deletions,s=>{s instanceof je&&e.scope.some(r=>r===t.doc||rr(r,s))&&So(s,!1)})},ql=(t,e,n)=>{let s=null;const r=t.doc,i=t.scope;ke(r,a=>{for(;e.length>0&&t.currStackItem===null;){const c=r.store,u=e.pop(),f=new Set,d=[];let p=!1;Vn(a,u.insertions,w=>{if(w instanceof je){if(w.redone!==null){let{item:g,diff:b}=$i(c,w.id);b>0&&(g=st(a,oe(g.id.client,g.id.clock+b))),w=g}!w.deleted&&i.some(g=>g===a.doc||rr(g,w))&&d.push(w)}}),Vn(a,u.deletions,w=>{w instanceof je&&i.some(g=>g===a.doc||rr(g,w))&&!Es(u.insertions,w.id)&&f.add(w)}),f.forEach(w=>{p=Mc(a,w,f,u.insertions,t.ignoreRemoteMapChanges,t)!==null||p});for(let w=d.length-1;w>=0;w--){const g=d[w];t.deleteFilter(g)&&(g.delete(a),p=!0)}t.currStackItem=p?u:null}a.changed.forEach((c,u)=>{c.has(null)&&u._searchMarker&&(u._searchMarker.length=0)}),s=a},t);const l=t.currStackItem;if(l!=null){const a=s.changedParentTypes;t.emit("stack-item-popped",[{stackItem:l,type:n,changedParentTypes:a,origin:t},t]),t.currStackItem=null}return l};class hm extends Ki{constructor(e,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:l=!1,doc:a=zn(e)?e[0].doc:e instanceof wn?e:e.doc}={}){super(),this.scope=[],this.doc=a,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=l,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(x=>c.changedParentTypes.has(x)||x===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const u=this.undoing,f=this.redoing,d=u?this.redoStack:this.undoStack;u?this.stopCapturing():f||this.clear(!1,!0);const p=new Xn;c.afterState.forEach((x,E)=>{const R=c.beforeState.get(E)||0,S=x-R;S>0&&xs(p,E,R,S)});const w=Yt();let g=!1;if(this.lastChange>0&&w-this.lastChange<this.captureTimeout&&d.length>0&&!u&&!f){const x=d[d.length-1];x.deletions=Ni([x.deletions,c.deleteSet]),x.insertions=Ni([x.insertions,p])}else d.push(new dm(c.deleteSet,p)),g=!0;!u&&!f&&(this.lastChange=w),Vn(c,c.deleteSet,x=>{x instanceof je&&this.scope.some(E=>E===c.doc||rr(E,x))&&So(x,!0)});const b=[{stackItem:d[d.length-1],origin:c.origin,type:u?"redo":"undo",changedParentTypes:c.changedParentTypes},this];g?this.emit("stack-item-added",b):this.emit("stack-item-updated",b)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const n=new Set(this.scope);e=zn(e)?e:[e],e.forEach(s=>{n.has(s)||(n.add(s),(s instanceof He?s.doc!==this.doc:s!==this.doc)&&ec("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,n=!0){(e&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{e&&(this.undoStack.forEach(r=>Bl(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Bl(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:e,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=ql(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=ql(this,this.redoStack,"redo")}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),super.destroy()}}function*fm(t){const e=se(t.restDecoder);for(let n=0;n<e;n++){const s=se(t.restDecoder),r=t.readClient();let i=se(t.restDecoder);for(let l=0;l<s;l++){const a=t.readInfo();if(a===10){const c=se(t.restDecoder);yield new mt(oe(r,i),c),i+=c}else if((pr&a)!==0){const c=(a&(Mt|ct))===0,u=new je(oe(r,i),null,(a&ct)===ct?t.readLeftID():null,null,(a&Mt)===Mt?t.readRightID():null,c?t.readParentInfo()?t.readString():t.readLeftID():null,c&&(a&ps)===ps?t.readString():null,$c(t,a));yield u,i+=u.length}else{const c=t.readLen();yield new pt(oe(r,i),c),i+=c}}}}class po{constructor(e,n){this.gen=fm(e),this.curr=null,this.done=!1,this.filterSkips=n,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===mt);return this.curr}}class mo{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const pm=t=>ir(t,ic,Ds),mm=(t,e)=>{if(t.constructor===pt){const{client:n,clock:s}=t.id;return new pt(oe(n,s+e),t.length-e)}else if(t.constructor===mt){const{client:n,clock:s}=t.id;return new mt(oe(n,s+e),t.length-e)}else{const n=t,{client:s,clock:r}=n.id;return new je(oe(s,r+e),null,oe(s,r+e-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(e))}},ir=(t,e=Hn,n=fn)=>{if(t.length===1)return t[0];const s=t.map(f=>new e(Qt(f)));let r=s.map(f=>new po(f,!0)),i=null;const l=new n,a=new mo(l);for(;r=r.filter(p=>p.curr!==null),r.sort((p,w)=>{if(p.curr.id.client===w.curr.id.client){const g=p.curr.id.clock-w.curr.id.clock;return g===0?p.curr.constructor===w.curr.constructor?0:p.curr.constructor===mt?1:-1:g}else return w.curr.id.client-p.curr.id.client}),r.length!==0;){const f=r[0],d=f.curr.id.client;if(i!==null){let p=f.curr,w=!1;for(;p!==null&&p.id.clock+p.length<=i.struct.id.clock+i.struct.length&&p.id.client>=i.struct.id.client;)p=f.next(),w=!0;if(p===null||p.id.client!==d||w&&p.id.clock>i.struct.id.clock+i.struct.length)continue;if(d!==i.struct.id.client)Ht(a,i.struct,i.offset),i={struct:p,offset:0},f.next();else if(i.struct.id.clock+i.struct.length<p.id.clock)if(i.struct.constructor===mt)i.struct.length=p.id.clock+p.length-i.struct.id.clock;else{Ht(a,i.struct,i.offset);const g=p.id.clock-i.struct.id.clock-i.struct.length;i={struct:new mt(oe(d,i.struct.id.clock+i.struct.length),g),offset:0}}else{const g=i.struct.id.clock+i.struct.length-p.id.clock;g>0&&(i.struct.constructor===mt?i.struct.length-=g:p=mm(p,g)),i.struct.mergeWith(p)||(Ht(a,i.struct,i.offset),i={struct:p,offset:0},f.next())}}else i={struct:f.curr,offset:0},f.next();for(let p=f.curr;p!==null&&p.id.client===d&&p.id.clock===i.struct.id.clock+i.struct.length&&p.constructor!==mt;p=f.next())Ht(a,i.struct,i.offset),i={struct:p,offset:0}}i!==null&&(Ht(a,i.struct,i.offset),i=null),go(a);const c=s.map(f=>uo(f)),u=Ni(c);return Qn(l,u),l.toUint8Array()},gm=(t,e,n=Hn,s=fn)=>{const r=uc(e),i=new s,l=new mo(i),a=new n(Qt(t)),c=new po(a,!1);for(;c.curr;){const f=c.curr,d=f.id.client,p=r.get(d)||0;if(c.curr.constructor===mt){c.next();continue}if(f.id.clock+f.length>p)for(Ht(l,f,gn(p-f.id.clock,0)),c.next();c.curr&&c.curr.id.client===d;)Ht(l,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===d&&c.curr.id.clock+c.curr.length<=p;)c.next()}go(l);const u=uo(a);return Qn(i,u),i.toUint8Array()},bc=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:xe(t.encoder.restEncoder)}),t.encoder.restEncoder=Ne(),t.written=0)},Ht=(t,e,n)=>{t.written>0&&t.currClient!==e.id.client&&bc(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),V(t.encoder.restEncoder,e.id.clock+n)),e.write(t.encoder,n),t.written++},go=t=>{bc(t);const e=t.encoder.restEncoder;V(e,t.clientStructs.length);for(let n=0;n<t.clientStructs.length;n++){const s=t.clientStructs[n];V(e,s.written),mr(e,s.restEncoder)}},wm=(t,e,n,s)=>{const r=new n(Qt(t)),i=new po(r,!1),l=new s,a=new mo(l);for(let u=i.curr;u!==null;u=i.next())Ht(a,e(u),0);go(a);const c=uo(r);return Qn(l,c),l.toUint8Array()},ym=t=>wm(t,_f,Hn,Ds),Wl="You must not compute changes after the event-handler fired.";class jr{constructor(e,n){this.target=e,this.currentTarget=e,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=bm(this.currentTarget,this.target))}deletes(e){return Es(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw St(Wl);const e=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let l,a;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))l="delete",a=si(c.content.getContent());else return;else c!==null&&this.deletes(c)?(l="update",a=si(c.content.getContent())):(l="add",a=void 0)}else if(this.deletes(i))l="delete",a=si(i.content.getContent());else return;e.set(r,{action:l,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw St(Wl);const n=this.target,s=Gt(),r=Gt(),i=[];if(e={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let a=null;const c=()=>{a&&i.push(a)};for(let u=n._start;u!==null;u=u.right)u.deleted?this.deletes(u)&&!this.adds(u)&&((a===null||a.delete===void 0)&&(c(),a={delete:0}),a.delete+=u.length,r.add(u)):this.adds(u)?((a===null||a.insert===void 0)&&(c(),a={insert:[]}),a.insert=a.insert.concat(u.content.getContent()),s.add(u)):((a===null||a.retain===void 0)&&(c(),a={retain:0}),a.retain+=u.length);a!==null&&a.retain===void 0&&c()}this._changes=e}return e}}const bm=(t,e)=>{const n=[];for(;e._item!==null&&e!==t;){if(e._item.parentSub!==null)n.unshift(e._item.parentSub);else{let s=0,r=e._item.parent._start;for(;r!==e._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}e=e._item.parent}return n},Ze=()=>{ec("Invalid access: Add Yjs type to a document before reading data.")},xc=80;let wo=0;class xm{constructor(e,n){e.marker=!0,this.p=e,this.index=n,this.timestamp=wo++}}const Sm=t=>{t.timestamp=wo++},Sc=(t,e,n)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=n,t.timestamp=wo++},km=(t,e,n)=>{if(t.length>=xc){const s=t.reduce((r,i)=>r.timestamp<i.timestamp?r:i);return Sc(s,e,n),s}else{const s=new xm(e,n);return t.push(s),s}},vr=(t,e)=>{if(t._start===null||e===0||t._searchMarker===null)return null;const n=t._searchMarker.length===0?null:t._searchMarker.reduce((i,l)=>Ws(e-i.index)<Ws(e-l.index)?i:l);let s=t._start,r=0;for(n!==null&&(s=n.p,r=n.index,Sm(n));s.right!==null&&r<e;){if(!s.deleted&&s.countable){if(e<r+s.length)break;r+=s.length}s=s.right}for(;s.left!==null&&r>e;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&Ws(n.index-r)<s.parent.length/xc?(Sc(n,s,r),n):km(t._searchMarker,s,r)},Ss=(t,e,n)=>{for(let s=t.length-1;s>=0;s--){const r=t[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){t.splice(s,1);continue}r.p=i,i.marker=!0}(e<r.index||n>0&&e===r.index)&&(r.index=gn(e,r.index+n))}},Er=(t,e,n)=>{const s=t,r=e.changedParentTypes;for(;Dt(r,t,()=>[]).push(n),t._item!==null;)t=t._item.parent;hc(s._eH,n,e)};class He{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Ml(),this._dEH=Ml(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,n){this.doc=e,this._item=n}_copy(){throw bt()}clone(){throw bt()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,n){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){$l(this._eH,e)}observeDeep(e){$l(this._dEH,e)}unobserve(e){Il(this._eH,e)}unobserveDeep(e){Il(this._dEH,e)}toJSON(){}}const kc=(t,e,n)=>{t.doc??Ze(),e<0&&(e=t._length+e),n<0&&(n=t._length+n);let s=n-e;const r=[];let i=t._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const l=i.content.getContent();if(l.length<=e)e-=l.length;else{for(let a=e;a<l.length&&s>0;a++)r.push(l[a]),s--;e=0}}i=i.right}return r},Cc=t=>{t.doc??Ze();const e=[];let n=t._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r<s.length;r++)e.push(s[r])}n=n.right}return e},ks=(t,e)=>{let n=0,s=t._start;for(t.doc??Ze();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i<r.length;i++)e(r[i],n++,t)}s=s.right}},jc=(t,e)=>{const n=[];return ks(t,(s,r)=>{n.push(e(s,r,t))}),n},Cm=t=>{let e=t._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};n=e.content.getContent(),s=0,e=e.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},vc=(t,e)=>{t.doc??Ze();const n=vr(t,e);let s=t._start;for(n!==null&&(s=n.p,e-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(e<s.length)return s.content.getContent()[e];e-=s.length}},or=(t,e,n,s)=>{let r=n;const i=t.doc,l=i.clientID,a=i.store,c=n===null?e._start:n.right;let u=[];const f=()=>{u.length>0&&(r=new je(oe(l,$e(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new mn(u)),r.integrate(t,0),u=[])};s.forEach(d=>{if(d===null)u.push(d);else switch(d.constructor){case Number:case Object:case Boolean:case Array:case String:u.push(d);break;default:switch(f(),d.constructor){case Uint8Array:case ArrayBuffer:r=new je(oe(l,$e(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new _s(new Uint8Array(d))),r.integrate(t,0);break;case wn:r=new je(oe(l,$e(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Ts(d)),r.integrate(t,0);break;default:if(d instanceof He)r=new je(oe(l,$e(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Tt(d)),r.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),f()},Ec=()=>St("Length exceeded!"),Dc=(t,e,n,s)=>{if(n>e._length)throw Ec();if(n===0)return e._searchMarker&&Ss(e._searchMarker,n,s.length),or(t,e,null,s);const r=n,i=vr(e,n);let l=e._start;for(i!==null&&(l=i.p,n-=i.index,n===0&&(l=l.prev,n+=l&&l.countable&&!l.deleted?l.length:0));l!==null;l=l.right)if(!l.deleted&&l.countable){if(n<=l.length){n<l.length&&st(t,oe(l.id.client,l.id.clock+n));break}n-=l.length}return e._searchMarker&&Ss(e._searchMarker,r,s.length),or(t,e,l,s)},jm=(t,e,n)=>{let r=(e._searchMarker||[]).reduce((i,l)=>l.index>i.index?l:i,{index:0,p:e._start}).p;if(r)for(;r.right;)r=r.right;return or(t,e,r,n)},_c=(t,e,n,s)=>{if(s===0)return;const r=n,i=s,l=vr(e,n);let a=e._start;for(l!==null&&(a=l.p,n-=l.index);a!==null&&n>0;a=a.right)!a.deleted&&a.countable&&(n<a.length&&st(t,oe(a.id.client,a.id.clock+n)),n-=a.length);for(;s>0&&a!==null;)a.deleted||(s<a.length&&st(t,oe(a.id.client,a.id.clock+s)),a.delete(t),s-=a.length),a=a.right;if(s>0)throw Ec();e._searchMarker&&Ss(e._searchMarker,r,-i+s)},lr=(t,e,n)=>{const s=e._map.get(n);s!==void 0&&s.delete(t)},yo=(t,e,n,s)=>{const r=e._map.get(n)||null,i=t.doc,l=i.clientID;let a;if(s==null)a=new mn([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:a=new mn([s]);break;case Uint8Array:a=new _s(s);break;case wn:a=new Ts(s);break;default:if(s instanceof He)a=new Tt(s);else throw new Error("Unexpected content type")}new je(oe(l,$e(i.store,l)),r,r&&r.lastId,null,null,e,n,a).integrate(t,0)},bo=(t,e)=>{t.doc??Ze();const n=t._map.get(e);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Tc=t=>{const e={};return t.doc??Ze(),t._map.forEach((n,s)=>{n.deleted||(e[s]=n.content.getContent()[n.length-1])}),e},Lc=(t,e)=>{t.doc??Ze();const n=t._map.get(e);return n!==void 0&&!n.deleted},vm=(t,e)=>{const n={};return t._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!e.sv.has(i.id.client)||i.id.clock>=(e.sv.get(i.id.client)||0));)i=i.left;i!==null&&_n(i,e)&&(n[r]=i.content.getContent()[i.length-1])}),n},zs=t=>(t.doc??Ze(),Up(t._map.entries(),e=>!e[1].deleted));class Em extends jr{}class Mn extends He{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const n=new Mn;return n.push(e),n}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Mn}clone(){const e=new Mn;return e.insert(0,this.toArray().map(n=>n instanceof He?n.clone():n)),e}get length(){return this.doc??Ze(),this._length}_callObserver(e,n){super._callObserver(e,n),Er(this,e,new Em(this,e))}insert(e,n){this.doc!==null?ke(this.doc,s=>{Dc(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}push(e){this.doc!==null?ke(this.doc,n=>{jm(n,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,n=1){this.doc!==null?ke(this.doc,s=>{_c(s,this,e,n)}):this._prelimContent.splice(e,n)}get(e){return vc(this,e)}toArray(){return Cc(this)}slice(e=0,n=this.length){return kc(this,e,n)}toJSON(){return this.map(e=>e instanceof He?e.toJSON():e)}map(e){return jc(this,e)}forEach(e){ks(this,e)}[Symbol.iterator](){return Cm(this)}_write(e){e.writeTypeRef(Xm)}}const Dm=t=>new Mn;class _m extends jr{constructor(e,n,s){super(e,n),this.keysChanged=s}}class Kn extends He{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,n){super._integrate(e,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Kn}clone(){const e=new Kn;return this.forEach((n,s)=>{e.set(s,n instanceof He?n.clone():n)}),e}_callObserver(e,n){Er(this,e,new _m(this,e,n))}toJSON(){this.doc??Ze();const e={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];e[s]=r instanceof He?r.toJSON():r}}),e}get size(){return[...zs(this)].length}keys(){return ui(zs(this),e=>e[0])}values(){return ui(zs(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return ui(zs(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Ze(),this._map.forEach((n,s)=>{n.deleted||e(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?ke(this.doc,n=>{lr(n,this,e)}):this._prelimContent.delete(e)}set(e,n){return this.doc!==null?ke(this.doc,s=>{yo(s,this,e,n)}):this._prelimContent.set(e,n),n}get(e){return bo(this,e)}has(e){return Lc(this,e)}clear(){this.doc!==null?ke(this.doc,e=>{this.forEach(function(n,s,r){lr(e,r,s)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Qm)}}const Tm=t=>new Kn,Kt=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&Ef(t,e);class Mi{constructor(e,n,s,r){this.left=e,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ut(),this.right.content.constructor===We?this.right.deleted||Zn(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const Vl=(t,e,n)=>{for(;e.right!==null&&n>0;)e.right.content.constructor===We?e.right.deleted||Zn(e.currentAttributes,e.right.content):e.right.deleted||(n<e.right.length&&st(t,oe(e.right.id.client,e.right.id.clock+n)),e.index+=e.right.length,n-=e.right.length),e.left=e.right,e.right=e.right.right;return e},Bs=(t,e,n,s)=>{const r=new Map,i=s?vr(e,n):null;if(i){const l=new Mi(i.p.left,i.p,i.index,r);return Vl(t,l,n-i.index)}else{const l=new Mi(null,e._start,0,r);return Vl(t,l,n)}},Rc=(t,e,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===We&&Kt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=t.doc,i=r.clientID;s.forEach((l,a)=>{const c=n.left,u=n.right,f=new je(oe(i,$e(r.store,i)),c,c&&c.lastId,u,u&&u.id,e,null,new We(a,l));f.integrate(t,0),n.right=f,n.forward()})},Zn=(t,e)=>{const{key:n,value:s}=e;s===null?t.delete(n):t.set(n,s)},Ac=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===We&&Kt(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},Nc=(t,e,n,s)=>{const r=t.doc,i=r.clientID,l=new Map;for(const a in s){const c=s[a],u=n.currentAttributes.get(a)??null;if(!Kt(u,c)){l.set(a,u);const{left:f,right:d}=n;n.right=new je(oe(i,$e(r.store,i)),f,f&&f.lastId,d,d&&d.id,e,null,new We(a,c)),n.right.integrate(t,0),n.forward()}}return l},di=(t,e,n,s,r)=>{n.currentAttributes.forEach((p,w)=>{r[w]===void 0&&(r[w]=null)});const i=t.doc,l=i.clientID;Ac(n,r);const a=Nc(t,e,n,r),c=s.constructor===String?new Et(s):s instanceof He?new Tt(s):new yn(s);let{left:u,right:f,index:d}=n;e._searchMarker&&Ss(e._searchMarker,n.index,c.getLength()),f=new je(oe(l,$e(i.store,l)),u,u&&u.lastId,f,f&&f.id,e,null,c),f.integrate(t,0),n.right=f,n.index=d,n.forward(),Rc(t,e,n,a)},Hl=(t,e,n,s,r)=>{const i=t.doc,l=i.clientID;Ac(n,r);const a=Nc(t,e,n,r);e:for(;n.right!==null&&(s>0||a.size>0&&(n.right.deleted||n.right.content.constructor===We));){if(!n.right.deleted)switch(n.right.content.constructor){case We:{const{key:c,value:u}=n.right.content,f=r[c];if(f!==void 0){if(Kt(f,u))a.delete(c);else{if(s===0)break e;a.set(c,u)}n.right.delete(t)}else n.currentAttributes.set(c,u);break}default:s<n.right.length&&st(t,oe(n.right.id.client,n.right.id.clock+s)),s-=n.right.length;break}n.forward()}if(s>0){let c="";for(;s>0;s--)c+=`
8
- `;n.right=new je(oe(l,$e(i.store,l)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new Et(c)),n.right.integrate(t,0),n.forward()}Rc(t,e,n,a)},Oc=(t,e,n,s,r)=>{let i=e;const l=rt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===We){const u=i.content;l.set(u.key,u)}i=i.right}let a=0,c=!1;for(;e!==i;){if(n===e&&(c=!0),!e.deleted){const u=e.content;if(u.constructor===We){const{key:f,value:d}=u,p=s.get(f)??null;(l.get(f)!==u||p===d)&&(e.delete(t),a++,!c&&(r.get(f)??null)===d&&p!==d&&(p===null?r.delete(f):r.set(f,p))),!c&&!e.deleted&&Zn(r,u)}}e=e.right}return a},Lm=(t,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const n=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===We){const s=e.content.key;n.has(s)?e.delete(t):n.add(s)}e=e.left}},Rm=t=>{let e=0;return ke(t.doc,n=>{let s=t._start,r=t._start,i=rt();const l=Ei(i);for(;r;)r.deleted===!1&&(r.content.constructor===We?Zn(l,r.content):(e+=Oc(n,s,r,i,l),i=Ei(l),s=r)),r=r.right}),e},Am=t=>{const e=new Set,n=t.doc;for(const[s,r]of t.afterState.entries()){const i=t.beforeState.get(s)||0;r!==i&&wc(t,n.store.clients.get(s),i,r,l=>{!l.deleted&&l.content.constructor===We&&l.constructor!==pt&&e.add(l.parent)})}ke(n,s=>{Vn(t,t.deleteSet,r=>{if(r instanceof pt||!r.parent._hasFormatting||e.has(r.parent))return;const i=r.parent;r.content.constructor===We?e.add(i):Lm(s,r)});for(const r of e)Rm(r)})},Kl=(t,e,n)=>{const s=n,r=Ei(e.currentAttributes),i=e.right;for(;n>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case Tt:case yn:case Et:n<e.right.length&&st(t,oe(e.right.id.client,e.right.id.clock+n)),n-=e.right.length,e.right.delete(t);break}e.forward()}i&&Oc(t,i,e.right,r,e.currentAttributes);const l=(e.left||e.right).parent;return l._searchMarker&&Ss(l._searchMarker,e.index,-s+n),e};class Nm extends jr{constructor(e,n,s){super(e,n),this.childListChanged=!1,this.keysChanged=new Set,s.forEach(r=>{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,n=[];ke(e,s=>{const r=new Map,i=new Map;let l=this.target._start,a=null;const c={};let u="",f=0,d=0;const p=()=>{if(a!==null){let w=null;switch(a){case"delete":d>0&&(w={delete:d}),d=0;break;case"insert":(typeof u=="object"||u.length>0)&&(w={insert:u},r.size>0&&(w.attributes={},r.forEach((g,b)=>{g!==null&&(w.attributes[b]=g)}))),u="";break;case"retain":f>0&&(w={retain:f},vf(c)||(w.attributes=Sf({},c))),f=0;break}w&&n.push(w),a=null}};for(;l!==null;){switch(l.content.constructor){case Tt:case yn:this.adds(l)?this.deletes(l)||(p(),a="insert",u=l.content.getContent()[0],p()):this.deletes(l)?(a!=="delete"&&(p(),a="delete"),d+=1):l.deleted||(a!=="retain"&&(p(),a="retain"),f+=1);break;case Et:this.adds(l)?this.deletes(l)||(a!=="insert"&&(p(),a="insert"),u+=l.content.str):this.deletes(l)?(a!=="delete"&&(p(),a="delete"),d+=l.length):l.deleted||(a!=="retain"&&(p(),a="retain"),f+=l.length);break;case We:{const{key:w,value:g}=l.content;if(this.adds(l)){if(!this.deletes(l)){const b=r.get(w)??null;Kt(b,g)?g!==null&&l.delete(s):(a==="retain"&&p(),Kt(g,i.get(w)??null)?delete c[w]:c[w]=g)}}else if(this.deletes(l)){i.set(w,g);const b=r.get(w)??null;Kt(b,g)||(a==="retain"&&p(),c[w]=b)}else if(!l.deleted){i.set(w,g);const b=c[w];b!==void 0&&(Kt(b,g)?b!==null&&l.delete(s):(a==="retain"&&p(),g===null?delete c[w]:c[w]=g))}l.deleted||(a==="insert"&&p(),Zn(r,l.content));break}}l=l.right}for(p();n.length>0;){const w=n[n.length-1];if(w.retain!==void 0&&w.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Jn extends He{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Ze(),this._length}_integrate(e,n){super._integrate(e,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Jn}clone(){const e=new Jn;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const s=new Nm(this,e,n);Er(this,e,s),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Ze();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Et&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?ke(this.doc,s=>{const r=new Mi(null,this._start,0,new Map);for(let i=0;i<e.length;i++){const l=e[i];if(l.insert!==void 0){const a=!n&&typeof l.insert=="string"&&i===e.length-1&&r.right===null&&l.insert.slice(-1)===`
9
- `?l.insert.slice(0,-1):l.insert;(typeof a!="string"||a.length>0)&&di(s,this,r,a,l.attributes||{})}else l.retain!==void 0?Hl(s,this,r,l.retain,l.attributes||{}):l.delete!==void 0&&Kl(s,r,l.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,s){this.doc??Ze();const r=[],i=new Map,l=this.doc;let a="",c=this._start;function u(){if(a.length>0){const d={};let p=!1;i.forEach((g,b)=>{p=!0,d[b]=g});const w={insert:a};p&&(w.attributes=d),r.push(w),a=""}}const f=()=>{for(;c!==null;){if(_n(c,e)||n!==void 0&&_n(c,n))switch(c.content.constructor){case Et:{const d=i.get("ychange");e!==void 0&&!_n(c,e)?(d===void 0||d.user!==c.id.client||d.type!=="removed")&&(u(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!_n(c,n)?(d===void 0||d.user!==c.id.client||d.type!=="added")&&(u(),i.set("ychange",s?s("added",c.id):{type:"added"})):d!==void 0&&(u(),i.delete("ychange")),a+=c.content.str;break}case Tt:case yn:{u();const d={insert:c.content.getContent()[0]};if(i.size>0){const p={};d.attributes=p,i.forEach((w,g)=>{p[g]=w})}r.push(d);break}case We:_n(c,e)&&(u(),Zn(i,c.content));break}c=c.right}u()};return e||n?ke(l,d=>{e&&Oi(d,e),n&&Oi(d,n),f()},"cleanup"):f(),r}insert(e,n,s){if(n.length<=0)return;const r=this.doc;r!==null?ke(r,i=>{const l=Bs(i,this,e,!s);s||(s={},l.currentAttributes.forEach((a,c)=>{s[c]=a})),di(i,this,l,n,s)}):this._pending.push(()=>this.insert(e,n,s))}insertEmbed(e,n,s){const r=this.doc;r!==null?ke(r,i=>{const l=Bs(i,this,e,!s);di(i,this,l,n,s||{})}):this._pending.push(()=>this.insertEmbed(e,n,s||{}))}delete(e,n){if(n===0)return;const s=this.doc;s!==null?ke(s,r=>{Kl(r,Bs(r,this,e,!0),n)}):this._pending.push(()=>this.delete(e,n))}format(e,n,s){if(n===0)return;const r=this.doc;r!==null?ke(r,i=>{const l=Bs(i,this,e,!1);l.right!==null&&Hl(i,this,l,n,s)}):this._pending.push(()=>this.format(e,n,s))}removeAttribute(e){this.doc!==null?ke(this.doc,n=>{lr(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?ke(this.doc,s=>{yo(s,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return bo(this,e)}getAttributes(){return Tc(this)}_write(e){e.writeTypeRef(Zm)}}const Om=t=>new Jn;class hi{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Ze()}[Symbol.iterator](){return this}next(){let e=this._currentNode,n=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(n)))do if(n=e.content.type,!e.deleted&&(n.constructor===Gn||n.constructor===pn)&&n._start!==null)e=n._start;else for(;e!==null;){const s=e.next;if(s!==null){e=s;break}else e.parent===this._root?e=null:e=e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class pn extends He{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new pn}clone(){const e=new pn;return e.insert(0,this.toArray().map(n=>n instanceof He?n.clone():n)),e}get length(){return this.doc??Ze(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new hi(this,e)}querySelector(e){e=e.toUpperCase();const s=new hi(this,r=>r.nodeName&&r.nodeName.toUpperCase()===e).next();return s.done?null:s.value}querySelectorAll(e){return e=e.toUpperCase(),$t(new hi(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){Er(this,e,new $m(this,n,e))}toString(){return jc(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,n={},s){const r=e.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),ks(this,i=>{r.insertBefore(i.toDOM(e,n,s),null)}),r}insert(e,n){this.doc!==null?ke(this.doc,s=>{Dc(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)ke(this.doc,s=>{const r=e&&e instanceof He?e._item:e;or(s,this,r,n)});else{const s=this._prelimContent,r=e===null?0:s.findIndex(i=>i===e)+1;if(r===0&&e!==null)throw St("Reference item not found");s.splice(r,0,...n)}}delete(e,n=1){this.doc!==null?ke(this.doc,s=>{_c(s,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return Cc(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return vc(this,e)}slice(e=0,n=this.length){return kc(this,e,n)}forEach(e){ks(this,e)}_write(e){e.writeTypeRef(tg)}}const Fm=t=>new pn;class Gn extends pn{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,n){super._integrate(e,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Gn(this.nodeName)}clone(){const e=new Gn(this.nodeName),n=this.getAttributes();return Cf(n,(s,r)=>{e.setAttribute(r,s)}),e.insert(0,this.toArray().map(s=>s instanceof He?s.clone():s)),e}toString(){const e=this.getAttributes(),n=[],s=[];for(const a in e)s.push(a);s.sort();const r=s.length;for(let a=0;a<r;a++){const c=s[a];n.push(c+'="'+e[c]+'"')}const i=this.nodeName.toLocaleLowerCase(),l=n.length>0?" "+n.join(" "):"";return`<${i}${l}>${super.toString()}</${i}>`}removeAttribute(e){this.doc!==null?ke(this.doc,n=>{lr(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?ke(this.doc,s=>{yo(s,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return bo(this,e)}hasAttribute(e){return Lc(this,e)}getAttributes(e){return e?vm(this,e):Tc(this)}toDOM(e=document,n={},s){const r=e.createElement(this.nodeName),i=this.getAttributes();for(const l in i){const a=i[l];typeof a=="string"&&r.setAttribute(l,a)}return ks(this,l=>{r.appendChild(l.toDOM(e,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(e){e.writeTypeRef(eg),e.writeKey(this.nodeName)}}const Mm=t=>new Gn(t.readKey());class $m extends jr{constructor(e,n,s){super(e,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class ar extends Kn{constructor(e){super(),this.hookName=e}_copy(){return new ar(this.hookName)}clone(){const e=new ar(this.hookName);return this.forEach((n,s)=>{e.set(s,n)}),e}toDOM(e=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(e){e.writeTypeRef(ng),e.writeKey(this.hookName)}}const Im=t=>new ar(t.readKey());class cr extends Jn{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new cr}clone(){const e=new cr;return e.applyDelta(this.toDelta()),e}toDOM(e=document,n,s){const r=e.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{const n=[];for(const r in e.attributes){const i=[];for(const l in e.attributes[r])i.push({key:l,value:e.attributes[r][l]});i.sort((l,a)=>l.key<a.key?-1:1),n.push({nodeName:r,attrs:i})}n.sort((r,i)=>r.nodeName<i.nodeName?-1:1);let s="";for(let r=0;r<n.length;r++){const i=n[r];s+=`<${i.nodeName}`;for(let l=0;l<i.attrs.length;l++){const a=i.attrs[l];s+=` ${a.key}="${a.value}"`}s+=">"}s+=e.insert;for(let r=n.length-1;r>=0;r--)s+=`</${n[r].nodeName}>`;return s}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(sg)}}const Pm=t=>new cr;class xo{constructor(e,n){this.id=e,this.length=n}get deleted(){throw bt()}mergeWith(e){return!1}write(e,n,s){throw bt()}integrate(e,n){throw bt()}}const Um=0;class pt extends xo{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){n>0&&(this.id.clock+=n,this.length-=n),gc(e.doc.store,this)}write(e,n){e.writeInfo(Um),e.writeLen(this.length-n)}getMissing(e,n){return null}}class _s{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new _s(this.content)}splice(e){throw bt()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const zm=t=>new _s(t.readBuf());class Cs{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Cs(this.len)}splice(e){const n=new Cs(this.len-e);return this.len=e,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,n){xs(e.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(e){}gc(e){}write(e,n){e.writeLen(this.len-n)}getRef(){return 1}}const Bm=t=>new Cs(t.readLen()),Fc=(t,e)=>new wn({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class Ts{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;const n={};this.opts=n,e.gc||(n.gc=!1),e.autoLoad&&(n.autoLoad=!0),e.meta!==null&&(n.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Ts(Fc(this.doc.guid,this.opts))}splice(e){throw bt()}mergeWith(e){return!1}integrate(e,n){this.doc._item=n,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,n){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}const qm=t=>new Ts(Fc(t.readString(),t.readAny()));class yn{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new yn(this.embed)}splice(e){throw bt()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const Wm=t=>new yn(t.readJSON());class We{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new We(this.key,this.value)}splice(e){throw bt()}mergeWith(e){return!1}integrate(e,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(e){}gc(e){}write(e,n){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const Vm=t=>new We(t.readKey(),t.readJSON());class ur{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new ur(this.arr)}splice(e){const n=new ur(this.arr.slice(e));return this.arr=this.arr.slice(0,e),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){const s=this.arr.length;e.writeLen(s-n);for(let r=n;r<s;r++){const i=this.arr[r];e.writeString(i===void 0?"undefined":JSON.stringify(i))}}getRef(){return 2}}const Hm=t=>{const e=t.readLen(),n=[];for(let s=0;s<e;s++){const r=t.readString();r==="undefined"?n.push(void 0):n.push(JSON.parse(r))}return new ur(n)},Km=tr("node_env")==="development";class mn{constructor(e){this.arr=e,Km&&_a(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new mn(this.arr)}splice(e){const n=new mn(this.arr.slice(e));return this.arr=this.arr.slice(0,e),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){const s=this.arr.length;e.writeLen(s-n);for(let r=n;r<s;r++){const i=this.arr[r];e.writeAny(i)}}getRef(){return 8}}const Jm=t=>{const e=t.readLen(),n=[];for(let s=0;s<e;s++)n.push(t.readAny());return new mn(n)};class Et{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Et(this.str)}splice(e){const n=new Et(this.str.slice(e));this.str=this.str.slice(0,e);const s=this.str.charCodeAt(e-1);return s>=55296&&s<=56319&&(this.str=this.str.slice(0,e-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const Gm=t=>new Et(t.readString()),Ym=[Dm,Tm,Om,Mm,Fm,Im,Pm],Xm=0,Qm=1,Zm=2,eg=3,tg=4,ng=5,sg=6;class Tt{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Tt(this.type._copy())}splice(e){throw bt()}mergeWith(e){return!1}integrate(e,n){this.type._integrate(e.doc,n)}delete(e){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(e.beforeState.get(n.id.client)||0)&&e._mergeStructs.push(n):n.delete(e),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(e.beforeState.get(s.id.client)||0)&&e._mergeStructs.push(s):s.delete(e)}),e.changed.delete(this.type)}gc(e){let n=this.type._start;for(;n!==null;)n.gc(e,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(e,!0),s=s.left}),this.type._map=new Map}write(e,n){this.type._write(e)}getRef(){return 7}}const rg=t=>new Tt(Ym[t.readTypeRef()](t)),$i=(t,e)=>{let n=e,s=0,r;do s>0&&(n=oe(n.client,n.clock+s)),r=Fn(t,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof je);return{item:r,diff:s}},So=(t,e)=>{for(;t!==null&&t.keep!==e;)t.keep=e,t=t.parent._item},dr=(t,e,n)=>{const{client:s,clock:r}=e.id,i=new je(oe(s,r+n),e,oe(s,r+n-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(n));return e.deleted&&i.markDeleted(),e.keep&&(i.keep=!0),e.redone!==null&&(i.redone=oe(e.redone.client,e.redone.clock+n)),e.right=i,i.right!==null&&(i.right.left=i),t._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),e.length=n,i},Jl=(t,e)=>Hi(t,n=>Es(n.deletions,e)),Mc=(t,e,n,s,r,i)=>{const l=t.doc,a=l.store,c=l.clientID,u=e.redone;if(u!==null)return st(t,u);let f=e.parent._item,d=null,p;if(f!==null&&f.deleted===!0){if(f.redone===null&&(!n.has(f)||Mc(t,f,n,s,r,i)===null))return null;for(;f.redone!==null;)f=st(t,f.redone)}const w=f===null?e.parent:f.content.type;if(e.parentSub===null){for(d=e.left,p=e;d!==null;){let E=d;for(;E!==null&&E.parent._item!==f;)E=E.redone===null?null:st(t,E.redone);if(E!==null&&E.parent._item===f){d=E;break}d=d.left}for(;p!==null;){let E=p;for(;E!==null&&E.parent._item!==f;)E=E.redone===null?null:st(t,E.redone);if(E!==null&&E.parent._item===f){p=E;break}p=p.right}}else{if(p=null,e.right&&!r){for(d=e;d!==null&&d.right!==null&&(d.right.redone||Es(s,d.right.id)||Jl(i.undoStack,d.right.id)||Jl(i.redoStack,d.right.id));)for(d=d.right;d.redone;)d=st(t,d.redone);if(d&&d.right!==null)return null}else d=w._map.get(e.parentSub)||null;d!==null&&d.parent._item!==f&&(d=w._map.get(e.parentSub)||null)}const g=$e(a,c),b=oe(c,g),x=new je(b,d,d&&d.lastId,p,p&&p.id,w,e.parentSub,e.content.copy());return e.redone=b,So(x,!0),x.integrate(t,0),x};class je extends xo{constructor(e,n,s,r,i,l,a,c){super(e,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=l,this.parentSub=a,this.redone=null,this.content=c,this.info=this.content.isCountable()?jl:0}set marker(e){(this.info&ii)>0!==e&&(this.info^=ii)}get marker(){return(this.info&ii)>0}get keep(){return(this.info&Cl)>0}set keep(e){this.keep!==e&&(this.info^=Cl)}get countable(){return(this.info&jl)>0}get deleted(){return(this.info&ri)>0}set deleted(e){this.deleted!==e&&(this.info^=ri)}markDeleted(){this.info|=ri}getMissing(e,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=$e(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=$e(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===On&&this.id.client!==this.parent.client&&this.parent.clock>=$e(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Pl(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=st(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===pt||this.right&&this.right.constructor===pt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===je?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===je&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===On){const s=Fn(n,this.parent);s.constructor===pt?this.parent=null:this.parent=s.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=Pl(e,e.doc.store,oe(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,l=new Set;for(;r!==null&&r!==this.right;){if(l.add(r),i.add(r),Ln(this.origin,r.origin)){if(r.id.client<this.id.client)s=r,i.clear();else if(Ln(this.rightOrigin,r.rightOrigin))break}else if(r.origin!==null&&l.has(Fn(e.doc.store,r.origin)))i.has(Fn(e.doc.store,r.origin))||(s=r,i.clear());else break;r=r.right}this.left=s}if(this.left!==null){const s=this.left.right;this.right=s,this.left.right=this}else{let s;if(this.parentSub!==null)for(s=this.parent._map.get(this.parentSub)||null;s!==null&&s.left!==null;)s=s.left;else s=this.parent._start,this.parent._start=this;this.right=s}this.right!==null?this.right.left=this:this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)),this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),gc(e.doc.store,this),this.content.integrate(e,this),zl(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new pt(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:oe(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Ln(e.origin,this.lastId)&&this.right===e&&Ln(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const n=this.parent._searchMarker;return n&&n.forEach(s=>{s.p===e&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),xs(e.deleteSet,this.id.client,this.id.clock,this.length),zl(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw ut();this.content.gc(e),n?lm(e,this,new pt(this.id,this.length)):this.content=new Cs(this.length)}write(e,n){const s=n>0?oe(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,l=this.content.getRef()&pr|(s===null?0:ct)|(r===null?0:Mt)|(i===null?0:ps);if(e.writeInfo(l),s!==null&&e.writeLeftID(s),r!==null&&e.writeRightID(r),s===null&&r===null){const a=this.parent;if(a._item!==void 0){const c=a._item;if(c===null){const u=fc(a);e.writeParentInfo(!0),e.writeString(u)}else e.writeParentInfo(!1),e.writeLeftID(c.id)}else a.constructor===String?(e.writeParentInfo(!0),e.writeString(a)):a.constructor===On?(e.writeParentInfo(!1),e.writeLeftID(a)):ut();i!==null&&e.writeString(i)}this.content.write(e,n)}}const $c=(t,e)=>ig[e&pr](t),ig=[()=>{ut()},Bm,Hm,zm,Gm,Wm,Vm,rg,Jm,qm,()=>{ut()}],og=10;class mt extends xo{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){ut()}write(e,n){e.writeInfo(og),V(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const Ic=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Pc="__ $YJS$ __";Ic[Pc]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Ic[Pc]=!0;function lg(t){for(let e=0;e<t.length;e+=1)t[e]=Math.floor(Math.random()*256);return t}function ag(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Ii(t=globalThis.crypto){if(typeof t?.randomUUID=="function")return t.randomUUID();const e=new Uint8Array(16),n=typeof t?.getRandomValues=="function"?t.getRandomValues(e):lg(e);return ag(n)}const Uc=new Map;class cg{constructor(e){this.room=e,this.onmessage=null,this._onChange=n=>n.key===e&&this.onmessage!==null&&this.onmessage({data:zf(n.newValue||"")}),yf(this._onChange)}postMessage(e){Ea.setItem(this.room,Uf(Ff(e)))}close(){bf(this._onChange)}}const ug=typeof BroadcastChannel>"u"?cg:BroadcastChannel,ko=t=>Dt(Uc,t,()=>{const e=Gt(),n=new ug(t);return n.onmessage=s=>e.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:e}}),dg=(t,e)=>(ko(t).subs.add(e),e),hg=(t,e)=>{const n=ko(t),s=n.subs.delete(e);return s&&n.subs.size===0&&(n.bc.close(),Uc.delete(t)),s},Tn=(t,e,n=null)=>{const s=ko(t);s.bc.postMessage(e),s.subs.forEach(r=>r(e,n))},zc=0,Co=1,Bc=2,hr=(t,e)=>{V(t,zc);const n=tm(e);Ae(t,n)},qc=(t,e,n)=>{V(t,Co),Ae(t,fo(e,n))},fg=(t,e,n)=>qc(e,n,Qe(t)),Wc=(t,e,n,s)=>{try{cc(e,Qe(t),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},pg=(t,e)=>{V(t,Bc),Ae(t,e)},mg=Wc,gg=(t,e,n,s,r)=>{const i=se(t);switch(i){case zc:fg(t,e,n);break;case Co:Wc(t,n,s,r);break;case Bc:mg(t,n,s,r);break;default:throw new Error("Unknown message type")}return i},wg=0,yg=(t,e,n)=>{se(t)===wg&&n(e,_e(t))},fi=3e4;class bg extends ba{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Yt();this.getLocalState()!==null&&fi/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&fi<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&jo(this,s,"timeout")},xt(fi/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);e===null?this.states.delete(n):this.states.set(n,e),this.meta.set(n,{clock:r,lastUpdated:Yt()});const l=[],a=[],c=[],u=[];e===null?u.push(n):i==null?e!=null&&l.push(n):(a.push(n),An(i,e)||c.push(n)),(l.length>0||c.length>0||u.length>0)&&this.emit("change",[{added:l,updated:c,removed:u},"local"]),this.emit("update",[{added:l,updated:a,removed:u},"local"])}setLocalStateField(e,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[e]:n})}getStates(){return this.states}}const jo=(t,e,n)=>{const s=[];for(let r=0;r<e.length;r++){const i=e[r];if(t.states.has(i)){if(t.states.delete(i),i===t.clientID){const l=t.meta.get(i);t.meta.set(i,{clock:l.clock+1,lastUpdated:Yt()})}s.push(i)}}s.length>0&&(t.emit("change",[{added:[],updated:[],removed:s},n]),t.emit("update",[{added:[],updated:[],removed:s},n]))},$n=(t,e,n=t.states)=>{const s=e.length,r=Ne();V(r,s);for(let i=0;i<s;i++){const l=e[i],a=n.get(l)||null,c=t.meta.get(l).clock;V(r,l),V(r,c),Xe(r,JSON.stringify(a))}return xe(r)},xg=(t,e,n)=>{const s=Qt(e),r=Yt(),i=[],l=[],a=[],c=[],u=se(s);for(let f=0;f<u;f++){const d=se(s);let p=se(s);const w=JSON.parse(_e(s)),g=t.meta.get(d),b=t.states.get(d),x=g===void 0?0:g.clock;(x<p||x===p&&w===null&&t.states.has(d))&&(w===null?d===t.clientID&&t.getLocalState()!=null?p++:t.states.delete(d):t.states.set(d,w),t.meta.set(d,{clock:p,lastUpdated:r}),g===void 0&&w!==null?i.push(d):g!==void 0&&w===null?c.push(d):w!==null&&(An(w,b)||a.push(d),l.push(d)))}(i.length>0||a.length>0||c.length>0)&&t.emit("change",[{added:i,updated:a,removed:c},n]),(i.length>0||l.length>0||c.length>0)&&t.emit("update",[{added:i,updated:l,removed:c},n])},Sg=t=>jf(t,(e,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(e)}`).join("&"),un=0,Vc=3,In=1,kg=2,Ls=[];Ls[un]=(t,e,n,s,r)=>{V(t,un);const i=gg(e,t,n.doc,n);s&&i===Co&&!n.synced&&(n.synced=!0)};Ls[Vc]=(t,e,n,s,r)=>{V(t,In),Ae(t,$n(n.awareness,Array.from(n.awareness.getStates().keys())))};Ls[In]=(t,e,n,s,r)=>{xg(n.awareness,Qe(e),n)};Ls[kg]=(t,e,n,s,r)=>{yg(e,n.doc,(i,l)=>Cg(n,l))};const Gl=3e4,Cg=(t,e)=>console.warn(`Permission denied to access ${t.url}.
10
- ${e}`),Hc=(t,e,n)=>{const s=Qt(e),r=Ne(),i=se(s),l=t.messageHandlers[i];return l?l(r,s,t,n,i):console.error("Unable to compute message"),r},Pi=(t,e,n)=>{e===t.ws&&(t.emit("connection-close",[n,t]),t.ws=null,e.close(),t.wsconnecting=!1,t.wsconnected?(t.wsconnected=!1,t.synced=!1,jo(t.awareness,Array.from(t.awareness.getStates().keys()).filter(s=>s!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(Kc,Ji(Ph(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t))},Kc=t=>{if(t.shouldConnect&&t.ws===null){const e=new t._WS(t.url,t.protocols);e.binaryType="arraybuffer",t.ws=e,t.wsconnecting=!0,t.wsconnected=!1,t.synced=!1,e.onmessage=n=>{t.wsLastMessageReceived=Yt();const s=Hc(t,new Uint8Array(n.data),!0);Gi(s)>1&&e.send(xe(s))},e.onerror=n=>{t.emit("connection-error",[n,t])},e.onclose=n=>{Pi(t,e,n)},e.onopen=()=>{t.wsLastMessageReceived=Yt(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);const n=Ne();if(V(n,un),hr(n,t.doc),e.send(xe(n)),t.awareness.getLocalState()!==null){const s=Ne();V(s,In),Ae(s,$n(t.awareness,[t.doc.clientID])),e.send(xe(s))}},t.emit("status",[{status:"connecting"}])}},pi=(t,e)=>{const n=t.ws;t.wsconnected&&n&&n.readyState===n.OPEN&&n.send(e),t.bcconnected&&Tn(t.bcChannel,e,t)};class jg extends Ki{constructor(e,n,s,{connect:r=!0,awareness:i=new bg(s),params:l={},protocols:a=[],WebSocketPolyfill:c=WebSocket,resyncInterval:u=-1,maxBackoffTime:f=2500,disableBc:d=!1}={}){for(super();e[e.length-1]==="/";)e=e.slice(0,e.length-1);this.serverUrl=e,this.bcChannel=e+"/"+n,this.maxBackoffTime=f,this.params=l,this.protocols=a,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=d,this.wsUnsuccessfulReconnects=0,this.messageHandlers=Ls.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,u>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const p=Ne();V(p,un),hr(p,s),this.ws.send(xe(p))}},u)),this._bcSubscriber=(p,w)=>{if(w!==this){const g=Hc(this,new Uint8Array(p),!1);Gi(g)>1&&Tn(this.bcChannel,xe(g),this)}},this._updateHandler=(p,w)=>{if(w!==this){const g=Ne();V(g,un),pg(g,p),pi(this,xe(g))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:p,updated:w,removed:g},b)=>{const x=p.concat(w).concat(g),E=Ne();V(E,In),Ae(E,$n(i,x)),pi(this,xe(E))},this._exitHandler=()=>{jo(this.awareness,[s.clientID],"app closed")},Xt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&Gl<Yt()-this.wsLastMessageReceived&&Pi(this,this.ws,null)},Gl/10),r&&this.connect()}get url(){const e=Sg(this.params);return this.serverUrl+"/"+this.roomname+(e.length===0?"":"?"+e)}get synced(){return this._synced}set synced(e){this._synced!==e&&(this._synced=e,this.emit("synced",[e]),this.emit("sync",[e]))}destroy(){this._resyncInterval!==0&&clearInterval(this._resyncInterval),clearInterval(this._checkInterval),this.disconnect(),Xt&&typeof process<"u"&&process.off("exit",this._exitHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.doc.off("update",this._updateHandler),super.destroy()}connectBc(){if(this.disableBc)return;this.bcconnected||(dg(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);const e=Ne();V(e,un),hr(e,this.doc),Tn(this.bcChannel,xe(e),this);const n=Ne();V(n,un),qc(n,this.doc),Tn(this.bcChannel,xe(n),this);const s=Ne();V(s,Vc),Tn(this.bcChannel,xe(s),this);const r=Ne();V(r,In),Ae(r,$n(this.awareness,[this.doc.clientID])),Tn(this.bcChannel,xe(r),this)}disconnectBc(){const e=Ne();V(e,In),Ae(e,$n(this.awareness,[this.doc.clientID],new Map)),pi(this,xe(e)),this.bcconnected&&(hg(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&Pi(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(Kc(this),this.connectBc())}}const bn=t=>qn((e,n)=>{t.onerror=s=>n(new Error(s.target.error)),t.onsuccess=s=>e(s.target.result)}),vg=(t,e)=>qn((n,s)=>{const r=indexedDB.open(t);r.onupgradeneeded=i=>e(i.target.result),r.onerror=i=>s(St(i.target.error)),r.onsuccess=i=>{const l=i.target.result;l.onversionchange=()=>{l.close()},n(l)}}),Eg=t=>bn(indexedDB.deleteDatabase(t)),Dg=(t,e)=>e.forEach(n=>t.createObjectStore.apply(t,n)),ls=(t,e,n="readwrite")=>{const s=t.transaction(e,n);return e.map(r=>Fg(s,r))},Jc=(t,e)=>bn(t.count(e)),_g=(t,e)=>bn(t.get(e)),Gc=(t,e)=>bn(t.delete(e)),Tg=(t,e,n)=>bn(t.put(e,n)),Ui=(t,e)=>bn(t.add(e)),Lg=(t,e,n)=>bn(t.getAll(e,n)),Rg=(t,e,n)=>{let s=null;return Og(t,e,r=>(s=r,!1),n).then(()=>s)},Ag=(t,e=null)=>Rg(t,e,"prev"),Ng=(t,e)=>qn((n,s)=>{t.onerror=s,t.onsuccess=async r=>{const i=r.target.result;if(i===null||await e(i)===!1)return n();i.continue()}}),Og=(t,e,n,s="next")=>Ng(t.openKeyCursor(e,s),r=>n(r.key)),Fg=(t,e)=>t.objectStore(e),Mg=(t,e)=>IDBKeyRange.upperBound(t,e),$g=(t,e)=>IDBKeyRange.lowerBound(t,e),mi="custom",Yc="updates",Xc=500,Qc=(t,e=()=>{},n=()=>{})=>{const[s]=ls(t.db,[Yc]);return Lg(s,$g(t._dbref,!1)).then(r=>{t._destroyed||(e(s),ke(t.doc,()=>{r.forEach(i=>cc(t.doc,i))},t,!1),n(s))}).then(()=>Ag(s).then(r=>{t._dbref=r+1})).then(()=>Jc(s).then(r=>{t._dbsize=r})).then(()=>s)},Ig=(t,e=!0)=>Qc(t).then(n=>{(e||t._dbsize>=Xc)&&Ui(n,fo(t.doc)).then(()=>Gc(n,Mg(t._dbref,!0))).then(()=>Jc(n).then(s=>{t._dbsize=s}))});class Pg extends ba{constructor(e,n){super(),this.doc=n,this.name=e,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=vg(e,s=>Dg(s,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=qn(s=>this.on("synced",()=>s(this))),this._db.then(s=>{this.db=s,Qc(this,l=>Ui(l,fo(n)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(s,r)=>{if(this.db&&r!==this){const[i]=ls(this.db,[Yc]);Ui(i,s),++this._dbsize>=Xc&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{Ig(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},n.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),n.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(e=>{e.close()})}clearData(){return this.destroy().then(()=>{Eg(this.name)})}get(e){return this._db.then(n=>{const[s]=ls(n,[mi],"readonly");return _g(s,e)})}set(e,n){return this._db.then(s=>{const[r]=ls(s,[mi]);return Tg(r,n,e)})}del(e){return this._db.then(n=>{const[s]=ls(n,[mi]);return Gc(s,e)})}}const Yl=[["#1677c8","#1677c833"],["#d65745","#d6574533"],["#16866a","#16866a33"],["#9a58b5","#9a58b533"],["#d27b18","#d27b1833"],["#3f7d20","#3f7d2033"],["#be3e7b","#be3e7b33"],["#4964c6","#4964c633"],["#8a6a14","#8a6a1433"],["#087f8c","#087f8c33"]],Xl=4,Ql=5,Ug=6,zg=7,Bg=8,gi=9,wi=3,qg=6e4,Wg=720*60*60*1e3,Vg=15e3,Hg=5*6e4;function Kg(t){if(!t||typeof t!="object")return null;const e=t,n=e.requestedBy;return typeof e.mainFile!="string"||typeof e.runId!="string"||!["queued","running","succeeded","failed","cleaned"].includes(e.status??"")||e.status==="cleaned"&&e.cleanMode!=="cache"&&e.cleanMode!=="artifacts"||e.stale!==void 0&&typeof e.stale!="boolean"||typeof e.updatedAt!="string"||!n||typeof n.id!="string"||typeof n.username!="string"||typeof n.name!="string"?null:e}function Zl(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[n,s]of Object.entries(t)){const r=Kg(s);r&&r.mainFile===n&&(e[n]=r)}return e}function Jg(t,e,n){return t<=n&&e<=n}function ea(t,e,n){const s=r=>r>0&&n-r<=Hg;return{recoverable:t.some(r=>r.tabId===e||!s(r.activeAt)),otherActive:t.some(r=>r.tabId!==e&&s(r.activeAt))}}class Gg{constructor(e,n){this.projectId=e,this.user=n;const s=window.location.protocol==="https:"?"wss:":"ws:";this.draftTabId=Zg(`texlite:collaboration-tab:${n.id}:${e}`);const r=this.readOwnWritableDraftMarker();this.draftGeneration=r?.generation??0,this.draftUpdatedAt=r?.updatedAt??0,this.draftMarkerPresent=r!==null,this.markDraftTabInactive=()=>this.setOwnDraftActivity(!1),this.markDraftTabActive=()=>this.resumeOwnDraftActivity(),window.addEventListener("pagehide",this.markDraftTabInactive),window.addEventListener("pageshow",this.markDraftTabActive),r&&(this.setOwnDraftActivity(!0),this.startDraftHeartbeat()),this.persistence=new Pg(`texlite:${n.id}:${e}`,this.doc),this.localDraftTransactionObserver=l=>{if(l.local){for(const[a,c]of this.doc.share)if(a.startsWith("source:")&&(l.changed.has(c)||l.changedParentTypes.has(c))){this.markWritableDraft();return}}},this.doc.on("afterTransaction",this.localDraftTransactionObserver),this.persistence.on("synced",()=>{this.localDraftReady=!0;for(const l of this.draftListeners)l()}),this.provider=new jg(`${s}//${window.location.host}/api/collaboration`,e,this.doc,{connect:!1,disableBc:!0,maxBackoffTime:2500}),this.awareness=this.provider.awareness;const i=this.doc.getMap("texlite:meta");this.metaObserver=(l,a)=>{a.origin===this.provider&&l.keysChanged.has("compileStates")&&(this.authoritativeCompileStates=null,this.notifyCompileStateListeners())},i.observe(this.metaObserver),this.provider.messageHandlers[Xl]=(l,a)=>{const c=_e(a),u=this.flushRequests.get(c);if(!u)return;const f=se(a)===1,d=se(a),p=_e(a),w=se(a),g=[];for(let b=0;b<w;b++)g.push(_e(a));if(window.clearTimeout(u.timer),this.flushRequests.delete(c),f)this.clearOwnWritableDraftMarker(u.draftGeneration),u.resolve({revision:d,persistedAt:p,ok:!0,failedPaths:[]});else{const b=Object.assign(new Error(g.length?`保存失败:${g.join(", ")}`:"源码保存到服务器磁盘失败"),{failedPaths:g});u.reject(b)}},this.provider.messageHandlers[Ql]=(l,a)=>{const c=_e(a),u=this.epochStorageKey(),f=ta(u),d=/^([0-9]+):/.exec(c)?.[1]??null,p=f?/^([0-9]+):/.exec(f)?.[1]??null:null,w=!this.epoch&&d===String(wi)&&p!==null&&p!==d;if((this.epoch&&this.epoch!==c||f&&f!==c)&&!w){this.provider.disconnect(),this.rejectFlushes(new Error("Collaboration state changed"));const R=c.endsWith(":reload")||d!==null&&d!==String(wi),S=()=>{yi(u,c.replace(/:reload$/,"")),window.location.reload()};if(R)for(const z of this.protocolUpgradeListeners)z();else this.persistence.clearData().then(()=>{this.clearWritableDraftMarkers(),S()});return}this.epoch=c,yi(u,c);const g=this.provider.ws;if(!g||g.readyState!==WebSocket.OPEN)return;const b=Ne();V(b,Ql),Xe(b,c),V(b,wi),g.send(xe(b));const x=Ne();V(x,0),hr(x,this.doc),g.send(xe(x));const E=Ne();V(E,1),Ae(E,$n(this.awareness,[this.doc.clientID])),g.send(xe(E))},this.provider.messageHandlers[zg]=(l,a)=>{const c=_e(a),u=_e(a);if(c!==this.user.id)return;if(u==="revoked"){this.rejectFlushes(new Error("Project access revoked")),this.provider.disconnect();for(const d of this.permissionListeners)d("revoked",this.permission);return}if(u!=="read"&&u!=="edit"&&u!=="owner")return;const f=this.permission;if(this.setPermission(u),f!==u){u==="read"&&this.rejectFlushes(new Error("Project permission changed to read-only"));for(const d of this.permissionListeners)d(u,f)}},this.provider.messageHandlers[Ug]=(l,a)=>{_e(a)},this.provider.messageHandlers[Bg]=(l,a)=>{let c={};try{c=Zl(JSON.parse(_e(a)))}catch{}this.authoritativeCompileStates=c,this.notifyCompileStateListeners()},this.provider.messageHandlers[gi]=(l,a)=>{const c=_e(a),u=_e(a),f=_e(a),d=_e(a),p=_e(a),w=_e(a);if(c==="state"){const b=Li(a)?_e(a):"",x=Li(a)?_e(a):"",E=Number(p);if(!b||!Number.isFinite(E)||E<=Date.now())this.removeFormatLeaseState(f),this.notifyFormatLeaseListeners(null);else{const R={path:f,holderUserId:b,holderName:x,expiresAt:E};this.formatLeaseStatesByPath.set(f,R);const S=this.formatLeaseExpiryTimers.get(f);S!==void 0&&window.clearTimeout(S);const z=window.setTimeout(()=>{const J=this.formatLeaseStatesByPath.get(f);!J||J.expiresAt>Date.now()||(this.removeFormatLeaseState(f),this.notifyFormatLeaseListeners(null))},Math.max(0,E-Date.now())+25);this.formatLeaseExpiryTimers.set(f,z),this.notifyFormatLeaseListeners(R)}return}const g=this.formatLeaseRequests.get(u);g&&(window.clearTimeout(g.timer),this.formatLeaseRequests.delete(u),c==="denied"?g.reject(new Error(w||"Format lease request was denied")):g.resolve({status:c,filePath:f,token:d,expiresAt:Number(p)}))},this.provider.on("status",({status:l})=>{l==="disconnected"&&(this.authoritativeCompileStates=null,this.notifyCompileStateListeners(),this.rejectFlushes(new Error("Collaboration connection closed")),this.rejectFormatLeaseRequests(new Error("Collaboration connection closed")),this.clearFormatLeaseStates())}),this.updateLocalAwareness()}projectId;user;doc=new wn;provider;awareness;persistence;permission="read";activeFile="";epoch=null;destroyed=!1;localDraftReady=!1;draftListeners=new Set;permissionListeners=new Set;protocolUpgradeListeners=new Set;compileStateListeners=new Set;flushRequests=new Map;formatLeaseRequests=new Map;formatLeaseListeners=new Set;formatLeaseStatesByPath=new Map;formatLeaseExpiryTimers=new Map;draftTabId;draftGeneration=0;draftUpdatedAt=0;draftMarkerPresent=!1;draftHeartbeatTimer=null;markDraftTabInactive;markDraftTabActive;undoManagers=new Map;authoritativeCompileStates=null;metaObserver;localDraftTransactionObserver;connect(){this.destroyed||(this.provider.connect(),this.updateLocalAwareness())}getText(e){return this.doc.getText(`source:${e}`)}getUndoManager(e){const n=this.undoManagers.get(e);if(n)return n;const s=new hm(this.getText(e));return this.undoManagers.set(e,s),s}applyTextEdits(e,n){if(this.permission==="read")throw new Error("Read-only collaborators cannot edit source files");const s=this.getText(e);let r=0;for(const i of n){if(!Number.isInteger(i.from)||!Number.isInteger(i.to)||i.from<r||i.to<i.from||i.to>s.length)throw new RangeError("Invalid collaborative text edits");r=i.to}this.doc.transact(()=>{for(let i=n.length-1;i>=0;i-=1){const l=n[i];l.to>l.from&&s.delete(l.from,l.to-l.from),l.replacement&&s.insert(l.from,l.replacement)}})}get meta(){return this.doc.getMap("texlite:meta")}compileStates(){return this.authoritativeCompileStates??Zl(this.meta.get("compileStates"))}onCompileStates(e){return this.compileStateListeners.add(e),()=>this.compileStateListeners.delete(e)}get synced(){return this.provider.synced}get connected(){return this.provider.wsconnected}get draftReady(){return this.localDraftReady}get currentPermission(){return this.permission}onDraftReady(e){return this.draftListeners.add(e),this.localDraftReady&&e(),()=>this.draftListeners.delete(e)}onPermissionChanged(e){return this.permissionListeners.add(e),()=>this.permissionListeners.delete(e)}onProtocolUpgrade(e){return this.protocolUpgradeListeners.add(e),()=>this.protocolUpgradeListeners.delete(e)}async discardLocalDraft(){return this.hasOtherWritableDraft?!1:(await this.persistence.clearData(),this.localDraftReady=!1,this.clearWritableDraftMarkers(),!0)}get hasWritableDraft(){const e=this.readWritableDraftMarkers();return ea(e.map(({tabId:n,marker:s})=>({tabId:n,activeAt:s.activeAt})),this.draftTabId,Date.now()).recoverable}get hasOtherWritableDraft(){const e=this.readWritableDraftMarkers();return ea(e.map(({tabId:n,marker:s})=>({tabId:n,activeAt:s.activeAt})),this.draftTabId,Date.now()).otherActive}setPermission(e,n=!1){const s=this.permission;if(this.permission=e,e==="read"&&(s!=="read"&&this.rejectFlushes(new Error("Project permission changed to read-only")),this.destroyUndoManagers(),this.clearFormatLeaseStates()),this.updateLocalAwareness(),n&&s!==e)for(const r of this.permissionListeners)r(e,s)}setActiveFile(e){this.activeFile!==e&&(this.activeFile=e,this.awareness.setLocalStateField("cursor",null),this.updateLocalAwareness())}sessions(){const e=[];return this.awareness.getStates().forEach((n,s)=>{const r=n?.user;!r||typeof r.id!="string"||typeof r.name!="string"||e.push({clientId:s,userId:r.id,username:typeof r.username=="string"?r.username:r.name,name:r.name,color:typeof r.color=="string"?r.color:"#1677c8",colorLight:typeof r.colorLight=="string"?r.colorLight:"#1677c833",permission:r.permission==="owner"||r.permission==="edit"?r.permission:"read",filePath:typeof n.filePath=="string"?n.filePath:"",editing:!!n.cursor,local:s===this.doc.clientID})}),e.sort((n,s)=>Number(s.local)-Number(n.local)||n.name.localeCompare(s.name))}flush(){const e=this.provider.ws;if(!this.provider.synced||!e||e.readyState!==WebSocket.OPEN)return Promise.reject(new Error("Collaboration connection is unavailable"));const n=Ii(),s=this.draftGeneration,r=Ne();return V(r,Xl),Xe(r,n),new Promise((i,l)=>{const a=window.setTimeout(()=>{this.flushRequests.delete(n),l(new Error("Collaboration save timed out"))},5e3);this.flushRequests.set(n,{resolve:i,reject:l,timer:a,draftGeneration:s}),e.send(xe(r))})}onFormatLeaseState(e){this.formatLeaseListeners.add(e);for(const n of this.formatLeaseStatesByPath.values())e(n);return()=>this.formatLeaseListeners.delete(e)}formatLeaseStates(){const e=Date.now();for(const[n,s]of this.formatLeaseStatesByPath)s.expiresAt<=e&&this.removeFormatLeaseState(n);return[...this.formatLeaseStatesByPath.values()]}async acquireFormatLease(e){if(this.permission==="read")throw new Error("Formatting requires write permission");const n=await this.requestFormatLease("acquire",e);if(n.status!=="grant"||!n.token||!Number.isFinite(n.expiresAt))throw new Error("Format lease was not granted");let s=n.token,r=n.expiresAt,i=!1;const l=async()=>{if(i)throw new Error("Format lease has already been released");const c=await this.requestFormatLease("renew",e,s);if(c.status!=="renewed"||!Number.isFinite(c.expiresAt))throw new Error("Format lease renewal failed");s=c.token||s,r=c.expiresAt};return{path:e,get token(){return s},get expiresAt(){return r},confirm:l,renew:l,release:async()=>{if(i)return;i=!0;const c=this.provider.ws;if(!(!c||c.readyState!==WebSocket.OPEN))try{await this.requestFormatLease("release",e,s)}catch{}}}}reconnect(){this.destroyed||(this.rejectFlushes(new Error("Collaboration connection reset")),this.provider.disconnect(),this.provider.connect(),this.updateLocalAwareness())}destroy(){this.destroyed=!0,this.setOwnDraftActivity(!1),this.stopDraftHeartbeat(),window.removeEventListener("pagehide",this.markDraftTabInactive),window.removeEventListener("pageshow",this.markDraftTabActive),this.rejectFlushes(new Error("Collaboration connection closed")),this.provider.destroy(),this.persistence.destroy(),this.draftListeners.clear(),this.protocolUpgradeListeners.clear(),this.compileStateListeners.clear(),this.rejectFormatLeaseRequests(new Error("Collaboration connection closed")),this.clearFormatLeaseStates(),this.formatLeaseListeners.clear(),this.meta.unobserve(this.metaObserver),this.doc.off("afterTransaction",this.localDraftTransactionObserver),this.destroyUndoManagers(),this.doc.destroy()}destroyUndoManagers(){for(const e of this.undoManagers.values())e.destroy();this.undoManagers.clear()}notifyCompileStateListeners(){for(const e of this.compileStateListeners)e()}rejectFlushes(e){for(const n of this.flushRequests.values())window.clearTimeout(n.timer),n.reject(e);this.flushRequests.clear()}requestFormatLease(e,n,s=""){const r=this.provider.ws;if(!this.provider.synced||!r||r.readyState!==WebSocket.OPEN)return Promise.reject(new Error("Collaboration connection is unavailable"));const i=Ii(),l=Ne();return V(l,gi),Xe(l,e),Xe(l,i),Xe(l,n),Xe(l,s),new Promise((a,c)=>{const u=window.setTimeout(()=>{if(this.formatLeaseRequests.delete(i),e==="acquire"){const f=this.provider.ws;if(f?.readyState===WebSocket.OPEN){const d=Ne();V(d,gi),Xe(d,"cancel"),Xe(d,i),Xe(d,n),Xe(d,""),f.send(xe(d))}}c(new Error("Format lease request timed out"))},e==="acquire"?qg:5e3);this.formatLeaseRequests.set(i,{resolve:a,reject:c,timer:u}),r.send(xe(l))})}rejectFormatLeaseRequests(e){for(const n of this.formatLeaseRequests.values())window.clearTimeout(n.timer),n.reject(e);this.formatLeaseRequests.clear()}clearFormatLeaseStates(){for(const e of this.formatLeaseExpiryTimers.values())window.clearTimeout(e);this.formatLeaseExpiryTimers.clear(),this.formatLeaseStatesByPath.size&&(this.formatLeaseStatesByPath.clear(),this.notifyFormatLeaseListeners(null))}removeFormatLeaseState(e){const n=this.formatLeaseExpiryTimers.get(e);n!==void 0&&window.clearTimeout(n),this.formatLeaseExpiryTimers.delete(e),this.formatLeaseStatesByPath.delete(e)}notifyFormatLeaseListeners(e){for(const n of this.formatLeaseListeners)n(e)}updateLocalAwareness(){const[e,n]=Yl[Math.abs(this.doc.clientID)%Yl.length];this.awareness.setLocalStateField("user",{id:this.user.id,username:this.user.username,name:this.user.displayName,color:e,colorLight:n,permission:this.permission,sessionId:String(this.doc.clientID)}),this.awareness.setLocalStateField("filePath",this.activeFile)}epochStorageKey(){return`texlite:collaboration-epoch:${this.user.id}:${this.projectId}`}writableDraftStoragePrefix(){return`texlite:collaboration-writable:${this.user.id}:${this.projectId}:`}ownWritableDraftStorageKey(){return`${this.writableDraftStoragePrefix()}${this.draftTabId}`}markWritableDraft(){this.draftGeneration+=1,this.draftUpdatedAt=Date.now(),this.draftMarkerPresent||this.writeOwnWritableDraftMarker(!0),this.startDraftHeartbeat()}clearWritableDraftMarkers(){for(const{key:e}of this.readWritableDraftMarkers())is(e);this.draftMarkerPresent=!1,this.stopDraftHeartbeat(),is(this.writableDraftStoragePrefix().slice(0,-1))}clearOwnWritableDraftMarker(e){const n=this.readOwnWritableDraftMarker();!n||!Jg(n.generation,this.draftGeneration,e)||(is(this.ownWritableDraftStorageKey()),this.draftMarkerPresent=!1,this.stopDraftHeartbeat())}readOwnWritableDraftMarker(){return this.readWritableDraftMarker(this.ownWritableDraftStorageKey())}readWritableDraftMarkers(){const e=this.writableDraftStoragePrefix(),n=[];for(const s of Yg()){if(!s.startsWith(e))continue;const r=this.readWritableDraftMarker(s);r&&n.push({key:s,tabId:s.slice(e.length),marker:r})}return n}readWritableDraftMarker(e){const n=ta(e);if(!n)return null;try{const s=JSON.parse(n);if(!s||typeof s!="object"||Array.isArray(s))return null;const r=s,i=Date.now();if(!Number.isInteger(r.generation)||(r.generation??0)<0||typeof r.updatedAt!="number"||!Number.isFinite(r.updatedAt)||r.updatedAt<=0||i-r.updatedAt>Wg)return is(e),null;const l=typeof r.activeAt=="number"&&Number.isFinite(r.activeAt)?Math.max(0,r.activeAt):0;return{generation:r.generation,updatedAt:r.updatedAt,activeAt:l}}catch{return is(e),null}}writeOwnWritableDraftMarker(e){if(!this.draftMarkerPresent&&this.draftUpdatedAt<=0)return;const n={generation:this.draftGeneration,updatedAt:this.draftUpdatedAt||Date.now(),activeAt:e?Date.now():0};yi(this.ownWritableDraftStorageKey(),JSON.stringify(n)),this.draftMarkerPresent=!0}setOwnDraftActivity(e){this.draftMarkerPresent&&(this.writeOwnWritableDraftMarker(e),e?this.startDraftHeartbeat():this.stopDraftHeartbeat())}resumeOwnDraftActivity(){const e=this.readOwnWritableDraftMarker();if(!e){this.draftMarkerPresent=!1,this.stopDraftHeartbeat();return}this.draftGeneration=Math.max(this.draftGeneration,e.generation),this.draftUpdatedAt=e.updatedAt,this.draftMarkerPresent=!0,this.setOwnDraftActivity(!0)}startDraftHeartbeat(){this.draftHeartbeatTimer!==null||!this.draftMarkerPresent||(this.draftHeartbeatTimer=window.setInterval(()=>{this.writeOwnWritableDraftMarker(!0)},Vg))}stopDraftHeartbeat(){this.draftHeartbeatTimer!==null&&(window.clearInterval(this.draftHeartbeatTimer),this.draftHeartbeatTimer=null)}}function ta(t){try{return window.localStorage.getItem(t)}catch{return null}}function yi(t,e){try{window.localStorage.setItem(t,e)}catch{}}function is(t){try{window.localStorage.removeItem(t)}catch{}}function Yg(){try{const t=[];for(let e=0;e<window.localStorage.length;e+=1){const n=window.localStorage.key(e);n&&t.push(n)}return t}catch{return[]}}function Xg(t){try{return window.sessionStorage.getItem(t)}catch{return null}}function Qg(t,e){try{window.sessionStorage.setItem(t,e)}catch{}}function Zg(t){const e=Xg(t);if(e)return e;const n=Ii();return Qg(t,n),n}function ew(t,e){return Array.from(t.trim()||e.trim()||"?")[0]?.toLocaleUpperCase()??"?"}function tw(t){if(!t||typeof t!="object")return!1;const e=t;return(e.kind==="update"||e.kind==="move"||e.kind==="delete")&&typeof e.revision=="string"}function nw(t,e,n,s,r,i){const[l]=h.useState(()=>new Gg(t,e)),[a,c]=h.useState("connecting"),[u,f]=h.useState(!1),[d,p]=h.useState([]),[w,g]=h.useState(null),[b,x]=h.useState(null),[E,R]=h.useState(""),[S,z]=h.useState(!1),[J,C]=h.useState(""),[k,M]=h.useState([]),[ne,te]=h.useState(!1),[K,B]=h.useState(s),[de,_]=h.useState(null),[O,q]=h.useState(!1),W=h.useRef(n),G=h.useRef(i),he=h.useRef(r);W.current=n,G.current=i,he.current=r,h.useEffect(()=>{const $=l.compileStates();g($[n]??null)},[n,l]),h.useEffect(()=>{const $=()=>p(l.sessions()),F=()=>{f(!1),p([]),g(null),x(null),R(""),z(!1),C(""),M([]),G.current()},ce=({status:ae})=>{c(ae),ae!=="connected"&&F()},Se=ae=>{f(ae),ae||F()},pe=()=>{c("disconnected"),F()},be=()=>{z(l.meta.get("historyWarning")===!0);const ae=l.meta.get("filesEvent");tw(ae)&&x(ae);const me=l.meta.get("commentsRevision");typeof me=="string"&&R(me);const Be=l.meta.get("dictionaryRevision");typeof Be=="string"&&C(Be);const Ee=l.compileStates();g(Ee[W.current]??null)},Ie=()=>{const ae=l.compileStates();g(ae[W.current]??null)};l.awareness.on("change",$),l.provider.on("status",ce),l.provider.on("sync",Se),l.provider.on("connection-close",pe),l.provider.on("connection-error",pe),l.meta.observe(be);const P=l.onCompileStates(Ie),Y=l.onProtocolUpgrade(()=>{q(!0),c("disconnected"),F()}),Oe=()=>M(l.formatLeaseStates()),A=l.onFormatLeaseState(Oe),Ge=()=>{if(!he.current||l.currentPermission!=="read")return;const ae=l.hasWritableDraft,me=l.hasOtherWritableDraft;!ae&&!me||_({previous:"edit",localDraftReady:ae,otherTabDraft:me})},Fe=l.onDraftReady(()=>{te(!0),Ge()}),ve=l.onPermissionChanged((ae,me)=>{if(ae==="revoked"){c("disconnected"),f(!1),G.current();return}B(ae),ae==="read"&&me!=="read"?_({previous:me,localDraftReady:l.hasWritableDraft,otherTabDraft:l.hasOtherWritableDraft}):ae!=="read"&&_(null)});return $(),be(),c(l.connected?"connected":"connecting"),f(l.synced),()=>{l.awareness.off("change",$),l.provider.off("status",ce),l.provider.off("sync",Se),l.provider.off("connection-close",pe),l.provider.off("connection-error",pe),l.meta.unobserve(be),P(),Y(),A(),Fe(),ve(),l.destroy()}},[l]),h.useEffect(()=>{r&&l.connect()},[l,r]),h.useEffect(()=>{l.setPermission(s),B(s),r&&s==="read"&&(l.hasWritableDraft||l.hasOtherWritableDraft)?_({previous:"edit",localDraftReady:l.hasWritableDraft,otherTabDraft:l.hasOtherWritableDraft}):s!=="read"&&_(null)},[l,s,r]);const ge=de!==null;return h.useEffect(()=>{if(!ge)return;const $=()=>{if(l.currentPermission!=="read")return;const ce=l.hasWritableDraft,Se=l.hasOtherWritableDraft;_(pe=>!pe||pe.localDraftReady===ce&&pe.otherTabDraft===Se?pe:{...pe,localDraftReady:ce,otherTabDraft:Se})};$();const F=window.setInterval($,2e3);return()=>window.clearInterval(F)},[l,ge]),{collaboration:l,status:a,synced:u,activeSessions:d,compileState:w,setCompileState:g,formatLeaseStates:k,filesEvent:b,commentsRevision:E,historyWarning:S,dictionaryRevision:J,localDraftReady:ne,permission:K,protocolUpgradeRequired:O,reconnect:()=>{O||(c("connecting"),f(!1),p([]),g(null),M([]),l.reconnect())},permissionDowngrade:de,dismissPermissionDowngrade:()=>_(null),discardLocalDraft:async()=>await l.discardLocalDraft()?(_(null),window.location.reload(),!0):(_(F=>F&&{...F,otherTabDraft:!0}),!1)}}function na(t){return t?.status==="succeeded"?"succeeded":t?.log.includes("Compilation was cancelled.")?"cancelled":t?.status==="failed"?"failed":null}function on(t){return t instanceof Error&&t.name==="AbortError"}function sw(t){return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement}function rw({projectId:t,project:e,mainFile:n,resolveCompileMainFile:s,getCurrentMainFile:r,initialLatest:i,collaborationSynced:l,sharedState:a,onSharedState:c,save:u,loadOutline:f,onPreviewTab:d,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:b}){const{t:x}=Ke(),[E,R]=h.useState(""),[S,z]=h.useState(!0),[J,C]=h.useState(null),[k,M]=h.useState("full"),[ne,te]=h.useState(""),[K,B]=h.useState(null),[de,_]=h.useState(null),[O,q]=h.useState([]),[W,G]=h.useState(null),[he,ge]=h.useState(!1),[ye,T]=h.useState(!1),[fe,$]=h.useState(()=>new Set),[F,ce]=h.useState(()=>new Set),[Se,pe]=h.useState(""),be=h.useRef(n),Ie=h.useRef(""),P=h.useRef(null),Y=h.useRef(null),Oe=h.useRef(null),A=h.useRef(i),Ge=h.useRef(!1),Fe=h.useRef(null),ve=h.useRef(null),ae=h.useRef(new Set),me=h.useRef(new Map),Be=h.useRef(null),Ee=h.useRef(()=>{}),v=h.useRef({onSharedState:c,save:u,loadOutline:f,onPreviewTab:d,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:b,resolveCompileMainFile:s,getCurrentMainFile:r});be.current=n,v.current={onSharedState:c,save:u,loadOutline:f,onPreviewTab:d,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:b,resolveCompileMainFile:s,getCurrentMainFile:r};const re=()=>v.current.getCurrentMainFile?.()||be.current,Ce=N=>{Be.current!==N&&(Be.current=N,v.current.onCompileSuccess())},et=async(N,X)=>{X||(Fe.current?.abort(),Fe.current=new AbortController,X=Fe.current.signal);try{const L=N?`?mainFile=${encodeURIComponent(N)}`:"",Q=await ie(`/api/projects/${t}/compile/artifacts${L}`,{signal:X});be.current===N&&(q(Q.artifacts),G(null))}catch(L){!on(L)&&be.current===N&&(q([]),G(null))}finally{Fe.current?.signal===X&&(Fe.current=null)}};h.useEffect(()=>{if(P.current?.abort(),!n){z(!1),R(""),C(null),M("full"),te(""),B(null),_(null),q([]),G(null),Oe.current=null,v.current.onPdfChanged();return}Oe.current?.mainFile!==n&&(Oe.current=null);const N=new AbortController;P.current=N,z(!0),te(""),B(null),_(null),E&&n&&Ie.current===n||(R(""),C(null),M("full")),q([]),G(null),v.current.onPdfChanged();let L=null;const Q=`?mainFile=${encodeURIComponent(n)}`,tt=Ge.current?null:A.current;tt&&(Ge.current=!0);const ht=()=>ie(`/api/projects/${t}/compile/latest${Q}`,{signal:N.signal}),Pt=tt?tt.then(ue=>ue.mainFile!==n?ht():ue,()=>ht()):ht();let I=!1;const U=()=>{if(I||N.signal.aborted||!n)return;I=!0;const ue=new AbortController;ae.current.add(ue),et(n,ue.signal).finally(()=>{ae.current.delete(ue)}),v.current.loadOutline(N.signal,n).catch(()=>{})};return Pt.then(ue=>{if(N.signal.aborted||n&&ue.mainFile!==be.current)return;const Pe=Oe.current;Pe&&Pe.mainFile===n&&ue.latestRun?.id!==Pe.runId||(te(ue.latestRun?.log??""),B(ue.latestRun?.diagnostics??null),_(na(ue.latestRun)),n&&ue.latestRun?.requestedBy&&(ue.latestRun.status==="queued"||ue.latestRun.status==="running")&&v.current.onSharedState({mainFile:n,runId:ue.latestRun.id,status:ue.latestRun.status,requestedBy:ue.latestRun.requestedBy,updatedAt:new Date().toISOString()}),ue.pdfUrl&&(Ie.current=ue.mainFile,R(ue.pdfUrl),C(ue.pdfCompiledAt),M(ue.pdfLoadingMode??"full"),v.current.onPreviewTab("pdf")))}).catch(ue=>{!on(ue)&&be.current===n&&v.current.onError(le(ue))}).finally(()=>{P.current===N&&(P.current=null),N.signal.aborted||(z(!1),L=window.setTimeout(U,0))}),()=>{L!==null&&window.clearTimeout(L),N.abort(),ve.current?.abort();for(const ue of ae.current)ue.abort();ae.current.clear()}},[t,n]),h.useEffect(()=>{if(!(!a||a.mainFile!==n||a.status!=="cleaned"||!a.cleanMode)){P.current?.abort(),Y.current?.abort(),Fe.current?.abort(),ve.current?.abort();for(const N of ae.current)N.abort();ae.current.clear(),a.cleanMode==="artifacts"?(Oe.current=null,te(""),B(null),_(null),R(""),C(null),M("full"),q([]),G(null),v.current.onPdfChanged(),v.current.onPreviewTab("pdf"),pe(x("editor.cleanArtifactsComplete"))):pe(x("editor.cleanCacheComplete"))}},[a?.runId,a?.status,a?.cleanMode,a?.mainFile,n,x]),h.useEffect(()=>{!n||a?.mainFile===n&&(a.status==="queued"||a.status==="running")||ce(N=>{if(!N.has(n))return N;const X=new Set(N);return X.delete(n),X})},[n,a?.mainFile,a?.status]),h.useEffect(()=>{if(!a||a.mainFile!==n||a.status!=="succeeded"&&a.status!=="failed")return;let N=!1;Y.current?.abort(),ve.current?.abort();const X=new AbortController;return Y.current=X,z(!0),ie(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(n)}`,{signal:X.signal}).then(L=>{N||L.mainFile!==be.current||L.latestRun?.id!==a.runId||(te(L.latestRun.log),B(L.latestRun.diagnostics),_(na(L.latestRun)),a.status==="succeeded"&&a.stale&&pe(x("editor.compileSnapshotStale")),a.status==="succeeded"&&L.pdfUrl?(Oe.current={mainFile:n,runId:a.runId},v.current.onPdfChanged(),R(L.pdfUrl),C(L.pdfCompiledAt),M(L.pdfLoadingMode??"full"),v.current.onPreviewTab("pdf"),Ce(a.runId),et(n)):a.status==="failed"&&v.current.onPreviewTab(L.latestRun.diagnostics.errors.length?"errors":"log"))}).catch(L=>{!on(L)&&!N&&v.current.onError(le(L))}).finally(()=>{Y.current===X&&(Y.current=null),N||z(!1)}),()=>{N=!0,X.abort(),Y.current===X&&(Y.current=null)}},[a?.runId,a?.status,a?.mainFile,a?.stale,n,t,x]);const Re=async()=>{if(!e||e.permission==="read"||!l)return;const N=v.current.resolveCompileMainFile?.()||re();if(!N||me.current.has(N)||a?.mainFile===N&&(a.status==="queued"||a.status==="running"))return;$(L=>new Set([...L,N])),v.current.onCompileStart(),pe(""),ve.current?.abort(),ve.current=null,te(""),B(null),_(null),v.current.onPreviewTab(E?"pdf":"log");const X=new AbortController;me.current.set(N,X);try{if(!await v.current.save())return;const L=await ie(`/api/projects/${t}/compile`,{method:"POST",signal:X.signal,body:JSON.stringify({mainFile:N})});if(L.mainFile!==N||re()!==N)return;te(L.log),B(L.diagnostics),_(L.cancelled?"cancelled":L.ok?"succeeded":"failed"),L.cancelled&&pe(x("compileControls.cancelled")),L.skipped&&pe(x("editor.upToDate")),L.ok&&L.stale&&pe(x("editor.compileSnapshotStale")),L.pdfUrl?(L.ok&&(Oe.current={mainFile:N,runId:L.runId}),v.current.onPdfChanged(),R(L.pdfUrl),C(L.pdfCompiledAt),M(L.pdfLoadingMode??"full"),v.current.onPreviewTab("pdf"),L.ok&&(L.skipped?v.current.onCompileSuccess():Ce(L.runId))):v.current.onPreviewTab(L.diagnostics.errors.length?"errors":"log")}catch(L){!on(L)&&re()===N&&v.current.onError(le(L))}finally{me.current.get(N)===X&&(me.current.delete(N),$(L=>{const Q=new Set(L);return Q.delete(N),Q}),ce(L=>{if(!L.has(N))return L;const Q=new Set(L);return Q.delete(N),Q}))}},we=async()=>{if(!e||e.permission==="read"||!l)return;const N=re();if(N){ce(X=>new Set([...X,N]));try{(await ie(`/api/projects/${t}/compile/cancel`,{method:"POST",body:JSON.stringify({mainFile:N})})).cancelled||ce(L=>{const Q=new Set(L);return Q.delete(N),Q})}catch(X){ce(L=>{const Q=new Set(L);return Q.delete(N),Q}),!on(X)&&re()===N&&v.current.onError(le(X))}}},dt=async N=>{if(!e||e.permission==="read"||!l||ye)return;const X=re();if(!(!X||me.current.has(X)||a?.mainFile===X&&(a.status==="queued"||a.status==="running"))){T(!0),P.current?.abort(),Y.current?.abort(),Fe.current?.abort(),ve.current?.abort();try{if((await ie(`/api/projects/${t}/compile/clean`,{method:"POST",body:JSON.stringify({mainFile:X,mode:N})})).mainFile!==X||re()!==X)return;v.current.onSharedState(null),N==="artifacts"&&(Oe.current=null,te(""),B(null),_(null),R(""),C(null),M("full"),q([]),G(null),v.current.onPdfChanged()),pe(x(N==="cache"?"editor.cleanCacheComplete":"editor.cleanArtifactsComplete"))}catch(L){!on(L)&&re()===X&&v.current.onError(le(L))}finally{T(!1)}}};Ee.current=()=>{Re()},h.useEffect(()=>{if(!Se)return;const N=window.setTimeout(()=>pe(""),3e3);return()=>window.clearTimeout(N)},[Se]),h.useEffect(()=>{const N=X=>{if(!(!(X.ctrlKey||X.metaKey)||X.key.toLocaleLowerCase()!=="s")){if(sw(X.target)){X.preventDefault();return}X.preventDefault(),X.stopPropagation(),X.repeat||Ee.current()}};return window.addEventListener("keydown",N,!0),()=>window.removeEventListener("keydown",N,!0)},[]),h.useEffect(()=>()=>{P.current?.abort(),Y.current?.abort(),Fe.current?.abort(),ve.current?.abort();for(const N of ae.current)N.abort();ae.current.clear();for(const N of me.current.values())N.abort();me.current.clear()},[]);const qe=async N=>{if(!N.viewable)return;ve.current?.abort();const X=new AbortController;ve.current=X,ge(!0);try{const L=await ie(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(n)}&path=${encodeURIComponent(N.path)}`,{signal:X.signal});!X.signal.aborted&&ve.current===X&&be.current===n&&G(L)}catch(L){on(L)||v.current.onError(le(L))}finally{ve.current===X&&(ve.current=null,ge(!1))}};return{pdfUrl:E,pdfCompiledAt:J,pdfLoadingMode:k,pdfLoading:S,compileLog:ne,compileDiagnostics:K,compileOutcome:de,artifacts:O,artifactPreview:W,artifactLoading:he,editorNotice:Se,localCompiling:fe.has(n),cancelling:F.has(n),cleaning:ye,compile:Re,cancelCompile:we,cleanCompile:dt,viewArtifact:qe}}const zi=10*1024*1024,iw=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".bmp",".ico",".avif",".pdf",".zip",".gz",".bz2",".xz",".tar",".rar",".7z",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".odt",".ods",".odp",".mp3",".mp4",".wav",".ogg",".webm",".mov",".avi",".wasm",".exe",".bin",".so",".dll",".class",".jar"]);function sa(t){return t instanceof Error&&t.name==="AbortError"}function as(t){const e=t.split("/").filter(Boolean);return e.pop(),e.map((n,s)=>e.slice(0,s+1).join("/"))}function ln(t,e){return!!(t&&e)&&(e===t||e.startsWith(`${t}/`))}function ow(t){const e=`.${t.split(".").at(-1)?.toLocaleLowerCase()??""}`;return!iw.has(e)}function Pn(t){return/(?:\.(?:tex|bib|sty|cls|txt|md)|latexmkrc)$/i.test(t)}function ra(t){const e=t.split(".").at(-1)?.toLocaleLowerCase()??"";return e==="pdf"?"pdf":["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"].includes(e)?"image":ow(t)?"text":"unsupported"}function lw(t,e){return`/api/projects/${t}/file/raw?path=${encodeURIComponent(e)}`}function aw({projectId:t,site:e,activeFile:n,dirty:s,save:r,onError:i,onProject:l,onActiveFile:a,onActiveMainFile:c,onRootDocuments:u}){const{t:f}=Ke(),[d,p]=h.useState([]),[w,g]=h.useState(!1),[b,x]=h.useState(""),[E,R]=h.useState(null),[S,z]=h.useState(!1),[J,C]=h.useState(!1),[k,M]=h.useState(""),[ne,te]=h.useState(""),[K,B]=h.useState(""),[de,_]=h.useState(new Set),[O,q]=h.useState(null),[W,G]=h.useState(""),[he,ge]=h.useState(""),[ye,T]=h.useState(null),[fe,$]=h.useState(!1),[F,ce]=h.useState(null),[Se,pe]=h.useState(!1),be=h.useRef(null),Ie=h.useRef(null),P=async(v={})=>{be.current?.abort(),be.current=null;const re=v.signal?null:new AbortController;re&&(be.current=re);try{const Ce=await ie(`/api/projects/${t}/files`,{signal:v.signal??re?.signal});return(!v.isCurrent||v.isCurrent())&&p(Ce.files),Ce.files}catch(Ce){if(!sa(Ce))throw Ce;return}finally{re&&be.current===re&&(be.current=null)}},Y=async()=>{if(!(!b.trim()||b.trim().endsWith("/"))){te("");try{await ie(`/api/projects/${t}/file`,{method:"POST",body:JSON.stringify({path:b,content:""})}),await P(),a(b),_(v=>new Set([...v,...as(b)])),g(!1),x("")}catch(v){te(le(v))}}},Oe=async()=>{if(!k.trim())return;te("");const v=K?`${K}/${k.trim()}`:k.trim();try{const re=await ie(`/api/projects/${t}/folders`,{method:"POST",body:JSON.stringify({path:v})});await P(),_(Ce=>new Set([...Ce,...as(re.path),re.path])),B(re.path),C(!1),M("")}catch(re){te(le(re))}},A=async(v,re=new Set,Ce=K)=>{if(!v.length)return;const et=e.maxUploadSizeMB;if(v.find(Q=>Q.size>et*1024*1024))return i(f("errors.fileTooLarge",{size:et}));const we=Ce,dt=v.map(Q=>we?`${we}/${Q.name}`:Q.name),qe=new Map;for(const Q of dt)qe.set(Q,(qe.get(Q)??0)+1);const N=[...qe.entries()].filter(([,Q])=>Q>1).map(([Q])=>Q);if(N.length)return i(f("errors.duplicateUploadNames",{files:N.join(", ")}));const X=new Set(d.map(Q=>Q.path)),L=[...new Set(dt.filter(Q=>X.has(Q)&&!re.has(Q)))];if(L.length){ce({files:v,directory:we,collisions:L});return}ce(null),pe(!0);try{const Q=new URLSearchParams;we&&Q.set("directory",we);let tt="";for(const[ht,Pt]of v.entries()){const I=dt[ht];Q.delete("overwrite"),re.has(I)&&Q.set("overwrite","1");const U=Q.toString()?`?${Q.toString()}`:"",ue=new FormData;ue.append("file",Pt);try{const Pe=await ie(`/api/projects/${t}/upload${U}`,{method:"POST",body:ue});typeof Pe.path=="string"&&Pn(Pe.path)&&(tt=Pe.path)}catch(Pe){if(Pe instanceof Si&&Pe.status===409&&!re.has(I)&&Pe.code==="FILE_EXISTS"){ht>0&&await P(),ce({files:v.slice(ht),directory:we,collisions:[I]});return}throw Pe}}await P(),tt&&a(tt)}catch(Q){i(le(Q))}finally{pe(!1)}},Ge=async v=>{await A(Array.from(v.target.files??[])),v.target.value=""},Fe=async v=>{Ie.current?.abort(),Ie.current=null,z(!1);const re=lw(t,v.path);if((v.size??0)>zi){R({path:v.path,kind:"large",size:v.size??0,url:re});return}const Ce=ra(v.path);if(Ce!=="text"){R({path:v.path,kind:Ce,size:v.size??0,url:re});return}R({path:v.path,kind:Ce,size:v.size??0,url:re,content:""}),z(!0);const et=new AbortController;Ie.current=et;try{let Re;try{Re=await fetch(re,{signal:et.signal})}catch(qe){throw Id(qe)}const we=Re.headers.get("content-type")??"";if(!Re.ok){let qe=null;try{qe=we.includes("application/json")?await Re.json():await Re.text()}catch{}throw new Si(Pd(qe,Re.status),Re.status,Ud(qe))}const dt=await Re.text();R(qe=>qe?.path===v.path?{...qe,content:dt}:qe)}catch(Re){sa(Re)||(R(null),i(le(Re)))}finally{Ie.current===et&&(Ie.current=null,z(!1))}},ve=v=>{const re=ra(v.path),Ce=e.maxCollaborativeFileSizeMB*1024*1024;(v.size??0)>zi||Pn(v.path)&&(v.size??0)>Ce||re!=="text"||!Pn(v.path)?Fe(v):a(v.path)},ae=async()=>{if(!O)return;const v=W.trim();if(v){te("");try{if(!await r())return;const re=await ie(`/api/projects/${t}/path`,{method:"PATCH",body:JSON.stringify({source:O.path,destinationDirectory:he,destinationName:v})}),Ce=we=>we===O.path?re.path:we.startsWith(`${O.path}/`)?`${re.path}${we.slice(O.path.length)}`:we;a(we=>Ce(we)),c(we=>Ce(we)),u(we=>new Set([...we].map(Ce))),B(we=>we&&Ce(we));const[et,Re]=await Promise.all([ie(`/api/projects/${t}/files`),ie(`/api/projects/${t}`)]);p(et.files),l(Re.project),_(we=>new Set([...we,...as(re.path),he].filter(Boolean))),q(null),G(""),ge("")}catch(re){te(le(re))}}},me=async()=>{if(ye){te("");try{if(s&&!await r())return;await ie(`/api/projects/${t}/file?path=${encodeURIComponent(ye.path)}`,{method:"DELETE"}),T(null)}catch(v){te(le(v))}}};h.useEffect(()=>()=>{be.current?.abort(),Ie.current?.abort()},[]),h.useEffect(()=>{Ie.current?.abort(),Ie.current=null,z(!1)},[n]);const Be=d.filter(v=>v.type==="directory"),Ee=d.filter(v=>as(v.path).every(re=>de.has(re)));return{files:d,setFiles:p,loadFiles:P,newFileOpen:w,setNewFileOpen:g,newFilePath:b,setNewFilePath:x,resourcePreview:E,setResourcePreview:R,resourcePreviewLoading:S,setResourcePreviewLoading:z,newFolderOpen:J,setNewFolderOpen:C,newFolderName:k,setNewFolderName:M,fileDialogError:ne,setFileDialogError:te,selectedFolder:K,setSelectedFolder:B,expandedFolders:de,setExpandedFolders:_,moveEntry:O,setMoveEntry:q,moveName:W,setMoveName:G,moveDestination:he,setMoveDestination:ge,deleteEntry:ye,setDeleteEntry:T,fileDragActive:fe,setFileDragActive:$,uploadConflict:F,setUploadConflict:ce,uploadingFiles:Se,directoryEntries:Be,visibleEntries:Ee,createFile:Y,createFolder:Oe,uploadFiles:A,upload:Ge,openFile:ve,movePath:ae,removePath:me}}function cw({active:t,projectId:e,activeFile:n,content:s,dictionaryWords:r}){const[i,l]=h.useState([]),[a,c]=h.useState(""),[u,f]=h.useState(""),[d,p]=h.useState(0),[w,g]=h.useState(null),[b,x]=h.useState(null),[E,R]=h.useState(!1),[S,z]=h.useState(0),J=h.useRef(0),C=h.useRef(!1),k=h.useRef(!1),M=h.useRef(s),ne=h.useRef(n),te=h.useRef(0);M.current=s,ne.current=n,k.current=E,h.useEffect(()=>{l([]),c(""),f(""),g(null),x(null),R(!1)},[n,r]),h.useEffect(()=>{x(null),R(!1)},[e]),h.useEffect(()=>{p(_=>i.length?Math.min(_,i.length-1):0)},[i]),h.useEffect(()=>{const _=++J.current;if(!t||!n){l([]),c(""),f(""),g(null);return}if(b){l([]),c(""),f("");return}const O=s,q=n;let W=!1;const G=window.setTimeout(()=>{x(null),(async()=>{try{const{lintLatex:he,isHarperLintSupersededError:ge}=await kt(async()=>{const{lintLatex:T,isHarperLintSupersededError:fe}=await import("./spellCheck-BJjWgnef.js");return{lintLatex:T,isHarperLintSupersededError:fe}},__vite__mapDeps([0,1,2,3]));if(W||_!==J.current||M.current!==O||ne.current!==q)return;let ye;try{ye=await he(e,q,O,r)}catch(T){if(ge(T))return;throw T}if(W||_!==J.current||M.current!==O||ne.current!==q)return;C.current=!1,R(!1),l(ye),c(O),f(q),p(0),g(null)}catch(he){if(W||_!==J.current||M.current!==O||ne.current!==q)return;l([]),c(""),f(""),x(he instanceof Error?he.message:String(he));const ge=C.current;C.current=!1,R(ge?k.current:!1)}})()},700);return()=>{W=!0,window.clearTimeout(G)}},[t,e,n,s,r,S,b]),h.useEffect(()=>{if(!b||!t)return;let _=!1;const O=()=>{_||(_=!0,C.current=!0,x(null),z(W=>W+1))},q=window.setTimeout(O,15e3);return window.addEventListener("online",O,{once:!0}),()=>{window.clearTimeout(q),window.removeEventListener("online",O)}},[b,t]);const K=u===n&&a===s,B=h.useMemo(()=>K?{total:i.length,unique:new Set(i.map(_=>`${_.kind}:${_.word.toLocaleLowerCase("en-US")}`)).size}:null,[K,i]);return{issues:K?i:[],jump:K?w:null,index:d,summary:B,jumpToIssue:_=>{if(!i.length)return;const O=Math.max(0,Math.min(_,i.length-1)),q=i[O];p(O),g({from:q.from,to:q.to,nonce:++te.current})},error:E?null:b,nativeFallback:t&&!!b,retry:()=>{C.current=!1,x(null),R(!1),z(_=>_+1)},dismissError:()=>{C.current=!1,R(!0)}}}function ia(t){return t instanceof Error&&t.name==="AbortError"}function uw({projectId:t,mainFile:e,activeFile:n,onActiveFile:s,onError:r,onShowPdf:i}){const[l,a]=h.useState(null),[c,u]=h.useState(null),[f,d]=h.useState(null),p=h.useRef(null),w=h.useRef(0),g=h.useRef(n),b=h.useRef(s),x=h.useRef(r),E=h.useRef(i),R=k=>k===e&&/\.tex$/i.test(k);g.current=n,b.current=s,x.current=r,E.current=i,h.useEffect(()=>(p.current?.abort(),p.current=null,a(null),u(null),d(null),()=>p.current?.abort()),[t,e]);const S=(k,M,ne)=>{d({path:k,line:M,column:ne,nonce:++w.current}),g.current!==k&&b.current(k)},z=async(k,M,ne,te={})=>{if(!R(k))return;p.current?.abort();const K=new AbortController;p.current=K;try{const B=await ie(`/api/projects/${t}/sync/pdf?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(k)}&line=${M}&column=${ne}`,{signal:K.signal});if(p.current!==K||!B)return;a({...B,nonce:++w.current}),E.current()}catch(B){!ia(B)&&!te.silent&&x.current(le(B))}finally{p.current===K&&(p.current=null)}},J=async(k,M,ne)=>{if(!R(g.current))return;const te=g.current;p.current?.abort();const K=new AbortController;p.current=K;try{const B=await ie(`/api/projects/${t}/sync/source?mainFile=${encodeURIComponent(e)}&page=${k}&x=${M}&y=${ne}`,{signal:K.signal});if(p.current!==K||g.current!==te||!R(g.current))return;S(B.path,B.line,B.column)}catch(B){ia(B)||x.current(le(B))}finally{p.current===K&&(p.current=null)}};return{pdfTarget:l,pdfViewport:c,sourceJump:f,setPdfViewport:u,clearPdfViewport:()=>u(null),jumpToSource:S,syncSourceToPdf:z,syncPdfToSource:J,syncVisiblePdfToSource:()=>{c&&J(c.page,c.x,c.y)}}}function Zc(t,e){return`texlite.workspaceLayout:${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function oa(t,e){try{const n=window.localStorage.getItem(Zc(t,e));if(n==="editor-pdf"||n==="editor-only"||n==="pdf-only")return n}catch{}return"editor-pdf"}function dw(t,e){const[n,s]=h.useState(()=>oa(t,e));return h.useEffect(()=>{s(oa(t,e))},[t,e]),{workspaceLayout:n,setWorkspaceLayout:i=>{s(i);try{window.localStorage.setItem(Zc(t,e),i)}catch{}}}}function la(t){const n=t.split(/(?<=\n)/).map(s=>{for(let r=0;r<s.length;r+=1){if(s[r]!=="%")continue;let i=0;for(let l=r-1;l>=0&&s[l]==="\\";l-=1)i+=1;if(i%2===0)return s.slice(0,r)+(s.endsWith(`
11
- `)?`
12
- `:"")}return s}).join("").replace(/\\verb\*?([^\s]).*?\1/g,"").replace(/\\begin\{(?:verbatim\*?|Verbatim|lstlisting|minted)\}(?:\[[^\]]*\])?[\s\S]*?\\end\{(?:verbatim\*?|Verbatim|lstlisting|minted)\}/g,"");return/\\documentclass\s*(?:\[[^\]]*\]\s*)?\{/.test(n)}function hw({sessions:t,status:e}){const{t:n}=Ke(),[s,r]=h.useState(!1),i=Math.max(0,t.length-5),l=s&&i>0,a=l?t:t.slice(0,5);return h.useEffect(()=>{t.length<=5&&r(!1)},[t.length]),t.length<=1?null:o.jsxs("div",{className:`collaboration-presence collaboration-${e}`,title:n(`editor.collaboration.${e}`),children:[o.jsx("span",{className:"collaboration-status-dot","aria-label":n(`editor.collaboration.${e}`)}),o.jsxs("div",{className:"collaboration-avatars","aria-label":n("editor.collaboration.activeSessions",{count:t.length}),children:[a.map(c=>{const u=c.editing?n("editor.collaboration.editing"):n("editor.collaboration.viewing"),f=c.permission==="read"?n("common.readOnly"):n("common.readWrite"),d=n("editor.collaboration.sessionTooltip",{name:c.name,username:c.username,file:c.filePath||n("editor.collaboration.joining"),activity:u,permission:f});return o.jsxs("span",{className:`collaboration-avatar${c.editing?" editing":""}${c.local?" local":""}`,style:{"--session-color":c.color},title:d,"aria-label":d,tabIndex:0,children:[ew(c.name,c.username),o.jsxs("span",{className:"collaboration-avatar-tooltip",role:"tooltip",children:[o.jsx("strong",{children:c.name}),o.jsxs("span",{children:["@",c.username]}),o.jsxs("small",{children:[c.filePath||n("editor.collaboration.joining")," · ",u," · ",f]})]})]},c.clientId)}),i>0&&o.jsx("button",{type:"button",className:"collaboration-avatar collaboration-avatar-overflow","aria-expanded":l,"aria-label":l?n("editor.collaboration.showFewerSessions"):n("editor.collaboration.showMoreSessions",{count:i}),title:l?n("editor.collaboration.showFewerSessions"):n("editor.collaboration.showMoreSessions",{count:i}),onClick:()=>r(c=>!c),children:l?"−":`+${i}`})]})]})}function fw({value:t,onChange:e}){const{t:n}=Ke(),[s,r]=h.useState(!1),i=h.useRef(null),l=[{value:"editor-pdf",icon:ml},{value:"editor-only",icon:uh},{value:"pdf-only",icon:dh}];return h.useEffect(()=>{if(!s)return;const a=u=>{i.current?.contains(u.target)||r(!1)},c=u=>{u.key==="Escape"&&r(!1)};return document.addEventListener("pointerdown",a),document.addEventListener("keydown",c),()=>{document.removeEventListener("pointerdown",a),document.removeEventListener("keydown",c)}},[s]),o.jsxs("div",{className:"layout-menu",ref:i,children:[o.jsxs("button",{type:"button",className:`layout-trigger${s?" active":""}`,"aria-haspopup":"menu","aria-expanded":s,title:n("editor.layout.current",{layout:n(`editor.layout.${t}.name`)}),onClick:()=>r(a=>!a),children:[o.jsx(ml,{size:15}),o.jsxs("span",{children:[o.jsx("small",{children:n("editor.layout.label")}),n(`editor.layout.${t}.name`)]}),o.jsx(fa,{size:13})]}),s&&o.jsxs("div",{className:"layout-popover",role:"menu","aria-label":n("editor.layout.label"),children:[o.jsx("div",{className:"layout-popover-title",children:n("editor.layout.choose")}),l.map(a=>{const c=a.icon,u=a.value===t;return o.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":u,className:`layout-option${u?" selected":""}`,onClick:()=>{e(a.value),r(!1)},children:[o.jsx(c,{size:19}),o.jsxs("span",{children:[o.jsx("strong",{children:n(`editor.layout.${a.value}.name`)}),o.jsx("small",{children:n(`editor.layout.${a.value}.description`)})]}),u&&o.jsx(Wd,{size:16})]},a.value)})]})]})}function pw({site:t,project:e,activeFile:n,saveStateLabel:s,editorPreferences:r,activeSessions:i,collaborationStatus:l,reconnectCollaboration:a,protocolUpgradeRequired:c,showEditor:u,filesCollapsed:f,toggleFilesPanel:d,workspaceLayout:p,changeWorkspaceLayout:w,onBack:g,onShare:b,showCitationLibrary:x,citationLibraryOpen:E,onCitationLibrary:R,onSelectionHistory:S,onHistory:z,onGit:J,canManageGit:C,formatting:k,readOnly:M,collaborationSynced:ne,hasSelection:te,onAddComment:K,onToggleComments:B,commentsOpen:de,unresolvedCommentCount:_,hasActiveFile:O,onToggleSettings:q,settingsOpen:W,compileBusy:G,sharedCompiling:he,localCompiling:ge,cancelling:ye,compileState:T,onCompile:fe,onCancelCompile:$}){const{t:F}=Ke();return o.jsxs("header",{className:"editor-topbar",children:[o.jsx("button",{className:"back",title:F("editor.backToProjects"),"aria-label":F("editor.backToProjects"),onClick:g,children:o.jsx(Vd,{size:18})}),o.jsx("a",{className:"brand-link compact-brand-link",href:"/","aria-label":t.siteName,onClick:ce=>{ce.preventDefault(),g()},children:o.jsx(zd,{siteName:t.siteName,compact:!0})}),o.jsxs("div",{className:"project-heading",children:[o.jsx("strong",{children:e.name}),o.jsxs("small",{children:[n," · ",s]})]}),r.vimMode&&o.jsxs("span",{className:"vim-status-badge",title:F("editor.vimOnHint"),children:[o.jsx(ah,{size:14}),F("editor.vimOn")]}),o.jsx(hw,{sessions:i,status:l}),l==="disconnected"&&!c&&o.jsxs("div",{className:"collaboration-recovery",role:"status",children:[o.jsx("span",{children:F("editor.collaboration.disconnected")}),o.jsx("button",{type:"button",onClick:a,children:F("editor.collaboration.reconnect")})]}),o.jsxs("div",{className:"editor-actions",children:[u&&o.jsxs("button",{className:f?"":"active",onClick:d,children:[f?o.jsx(ch,{size:15}):o.jsx(ga,{size:15}),F("common.files")]}),o.jsx(fw,{value:p,onChange:w}),o.jsxs("button",{onClick:b,children:[o.jsx(ki,{size:15}),F("projectSettings.share")]}),x&&o.jsxs("button",{className:E?"active":"",onClick:R,children:[o.jsx(Hd,{size:15}),F("citationLibrary.title")]}),o.jsxs("div",{className:"history-action",role:"group","aria-label":F("history.title"),children:[o.jsxs("div",{className:"history-action-label",children:[o.jsx(oh,{size:14}),o.jsx("span",{children:F("history.title")})]}),o.jsxs("div",{className:"history-action-options",children:[o.jsx("button",{type:"button",className:"history-action-selection",title:F(te?"selectionHistory.title":"selectionHistory.selectSourceHint"),onMouseDown:ce=>ce.preventDefault(),onClick:S,disabled:!te||!O,children:F("selectionHistory.buttonLabel")}),o.jsx("button",{type:"button",className:"history-action-snapshots",title:F("history.projectSnapshots"),onClick:z,children:F("history.projectSnapshotsButton")})]})]}),o.jsxs("div",{className:"comments-action",role:"group","aria-label":F("common.comments"),children:[o.jsxs("div",{className:"comments-action-label",children:[o.jsx(Kd,{size:14}),o.jsx("span",{children:F("common.comments")})]}),o.jsxs("div",{className:"comments-action-options",children:[o.jsx("button",{type:"button",className:"comments-action-add",title:F("editor.addComment"),"aria-label":F("editor.addComment"),onMouseDown:ce=>ce.preventDefault(),onClick:K,disabled:!O,children:F("editor.commentsAdd")}),o.jsxs("button",{type:"button",className:`comments-action-all${de?" active":""}`,title:F("editor.commentsAll"),onClick:B,children:[F("editor.commentsAll")," ",_||""]})]})]}),o.jsxs("button",{className:"git-action",title:F(C?"git.title":"git.ownerOnly"),disabled:!C,onClick:J,children:[o.jsx(Jd,{size:15}),"Git"]}),o.jsxs("button",{className:W?"active":"",onClick:q,children:[o.jsx(gh,{size:15}),F("common.settings")]}),he||ge?o.jsxs("button",{className:"compile cancel-compile",title:F("compileControls.cancel"),onClick:$,disabled:ye||k||M||!ne,children:[ye?o.jsx(it,{className:"spin",size:15}):o.jsx(fs,{size:15}),F(ye?"compileControls.cancelling":"compileControls.cancel")]}):o.jsxs("button",{className:"compile",title:F("editor.compileShortcut"),onClick:fe,disabled:G||k||M||!ne,children:[G?o.jsx(it,{className:"spin",size:15}):o.jsx(hh,{size:15}),F("editor.compile",{engine:e.engine})]})]})]})}function mw({project:t,filesPanel:e,files:n,visibleEntries:s,activeFile:r,activeMainFile:i,rootDocuments:l,selectedFolder:a,expandedFolders:c,fileDragActive:u,uploadingFiles:f,readOnly:d,formatting:p,canFormat:w,activeFormatLease:g,collaborationSynced:b,editorFontSize:x,outline:E,sourceCursorStore:R,wordCountBusy:S,hasSelection:z,hasFormatSelection:J,uploadInput:C,setSelectedFolder:k,setExpandedFolders:M,setMoveEntry:ne,setMoveName:te,setMoveDestination:K,setDeleteEntry:B,setFileDialogError:de,setNewFolderName:_,setNewFolderOpen:O,setNewFilePath:q,setNewFileOpen:W,setQuickOpen:G,setProjectSearchOpen:he,setFileDragActive:ge,setFilesCollapsed:ye,toggleFilesPanel:T,uploadFiles:fe,upload:$,openFile:F,onFormatFile:ce,onFormatSelection:Se,jumpToSource:pe,syncSourceToPdf:be,onWordCount:Ie}){const{t:P}=Ke(),[Y,Oe]=h.useState(!1);return o.jsx(fr,{id:"files",order:1,ref:e,defaultSize:16,minSize:12,maxSize:30,collapsible:!0,collapsedSize:0,onCollapse:()=>ye(!0),onExpand:()=>ye(!1),children:o.jsxs("aside",{className:"left-panel",children:[o.jsxs("section",{className:`files-panel${u?" drop-active":""}`,onDragEnter:A=>{A.dataTransfer.types.includes("Files")&&(A.preventDefault(),!d&&!f&&ge(!0))},onDragOver:A=>{A.dataTransfer.types.includes("Files")&&(A.preventDefault(),A.dataTransfer.dropEffect=d||f?"none":"copy")},onDragLeave:A=>{A.currentTarget.contains(A.relatedTarget)||ge(!1)},onDrop:A=>{A.preventDefault(),ge(!1),!d&&!f&&fe(Array.from(A.dataTransfer.files))},children:[o.jsxs("div",{className:"panel-title",children:[o.jsx("button",{className:"file-size-toggle",type:"button","aria-pressed":Y,title:P(Y?"editor.hideFileSizes":"editor.showFileSizes"),onClick:()=>Oe(A=>!A),children:P("common.files")}),o.jsxs("span",{className:"file-tools",children:[o.jsx("button",{"aria-label":P("navigation.quickOpen"),title:`${P("navigation.quickOpen")} (Ctrl/Cmd+P)`,onClick:()=>G(!0),children:o.jsx(Gd,{size:15})}),o.jsx("button",{"aria-label":P("navigation.projectSearch"),title:`${P("navigation.projectSearch")} (Ctrl/Cmd+Shift+F)`,onClick:()=>he(!0),children:o.jsx(th,{size:15})}),!d&&o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:f,"aria-label":P("editor.uploadAttachment"),title:P("editor.uploadTo",{folder:a||P("editor.projectRoot")}),onClick:()=>C.current?.click(),children:o.jsx(hl,{size:15})}),o.jsx("button",{"aria-label":P("editor.newFolder"),title:P("editor.newFolder"),onClick:()=>{_(""),O(!0)},children:o.jsx(Yd,{size:15})}),o.jsx("button",{"aria-label":P("editor.newFile"),title:P("editor.newFile"),onClick:()=>{q(a?`${a}/`:""),W(!0)},children:o.jsx(lh,{size:15})}),o.jsx("input",{ref:C,type:"file",multiple:!0,hidden:!0,onChange:A=>{$(A)}})]}),o.jsx("button",{"aria-label":P("editor.collapseFiles"),title:P("editor.collapseFiles"),onClick:T,children:o.jsx(ga,{size:15})})]})]}),u&&o.jsxs("div",{className:"file-drop-overlay",children:[o.jsx(hl,{size:24}),o.jsx("strong",{children:P("editor.dropFiles")}),o.jsx("span",{children:P("editor.uploadTo",{folder:a||P("editor.projectRoot")})})]}),o.jsxs("div",{className:"file-list",style:{fontSize:`${x}px`},children:[o.jsx("div",{className:`file-entry folder-entry root-entry${a===""?" selected":""}`,children:o.jsxs("button",{className:"file-entry-main",onClick:()=>k(""),children:[o.jsx(Xd,{size:15}),o.jsx("span",{children:P("editor.projectRoot")})]})}),s.map(A=>{const Ge=A.path.split("/").length-1,Fe=A.path.split("/").at(-1),ve=c.has(A.path),ae=l.has(A.path),me=i===A.path,Be=A.path!==t.mainFile&&!t.mainFile.startsWith(`${A.path}/`);return A.type==="directory"?o.jsxs("div",{className:`file-entry folder-entry${a===A.path?" selected":""}`,style:{paddingLeft:`${Ge*13+5}px`},children:[o.jsxs("button",{className:"file-entry-main",title:A.path,onClick:()=>{k(A.path),M(Ee=>{const v=new Set(Ee);return v.has(A.path)?v.delete(A.path):v.add(A.path),v})},children:[ve?o.jsx(fa,{size:13}):o.jsx(Qd,{size:13}),o.jsx(Zd,{size:14}),o.jsx("span",{children:Fe})]}),!d&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"file-entry-action",title:P("editor.move"),"aria-label":P("editor.move"),onClick:()=>{ne(A),te(Fe??""),K("")},children:o.jsx(wl,{size:13})}),Be&&o.jsx("button",{className:"file-entry-action danger-text",title:P("editor.deletePath"),"aria-label":P("editor.deletePath"),onClick:()=>{B(A),de("")},children:o.jsx(Jt,{size:13})})]})]},A.path):o.jsxs("div",{className:`file-entry${r===A.path?" active":""}${ae?" root-document":""}${me?" compile-target":""}`,style:{paddingLeft:`${Ge*13+18}px`},children:[o.jsxs("button",{className:"file-entry-main",title:me?P("editor.currentMainDocument",{path:A.path}):ae?P("editor.mainDocumentCandidate",{path:A.path}):A.path,onClick:()=>F(A),children:[ae?o.jsx(ha,{size:13}):o.jsx(Un,{size:13}),o.jsx("span",{children:Fe}),me&&o.jsx("small",{children:P("editor.currentMainShort")})]}),Y&&typeof A.size=="number"&&o.jsx("span",{className:"file-entry-size",title:`${A.size.toLocaleString()} B`,children:ww(A.size)}),!d&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"file-entry-action",title:P("editor.move"),"aria-label":P("editor.move"),onClick:()=>{ne(A),te(Fe??""),K("")},children:o.jsx(wl,{size:13})}),Be&&o.jsx("button",{className:"file-entry-action danger-text",title:P("editor.deletePath"),"aria-label":P("editor.deletePath"),onClick:()=>{B(A),de("")},children:o.jsx(Jt,{size:13})})]})]},A.path)})]}),!d&&w&&o.jsxs("div",{className:"file-format-footer",role:"group","aria-label":P("editor.format"),"aria-busy":p,children:[o.jsxs("div",{className:"file-format-label",children:[o.jsx(rh,{size:13}),P("editor.format")]}),o.jsxs("div",{className:"file-format-actions",children:[o.jsx("button",{className:J?"":"active",type:"button",title:P("editor.formatFileHint"),onMouseDown:A=>A.preventDefault(),onClick:ce,disabled:p||g||!b,children:P("editor.formatFile")}),o.jsx("button",{className:J?"active":"",type:"button",title:P(J?"editor.formatSelection":"editor.formatSelectionHint"),onMouseDown:A=>A.preventDefault(),onClick:Se,disabled:p||g||!b||!J,children:P("editor.formatSelected")})]})]})]}),o.jsx(gw,{outline:E,activeFile:r,activeMainFile:i,sourceCursorStore:R,wordCountBusy:S,hasSelection:z,jumpToSource:pe,syncSourceToPdf:be,onWordCount:Ie})]})})}function gw({outline:t,activeFile:e,activeMainFile:n,sourceCursorStore:s,wordCountBusy:r,hasSelection:i,jumpToSource:l,syncSourceToPdf:a,onWordCount:c}){const{t:u}=Ke(),f=h.useSyncExternalStore(s.subscribe,s.getOutlineLine,s.getOutlineLine);return o.jsxs("section",{className:"outline-panel",children:[o.jsxs("div",{className:"panel-title",children:[o.jsxs("span",{className:"outline-heading",children:[o.jsx(eh,{size:14}),u("common.outline")]}),o.jsxs("span",{className:"word-count-actions",role:"group","aria-label":u("editor.wordCountTitle"),children:[o.jsxs("button",{type:"button",title:u("editor.wordCountFullHint"),onClick:()=>c("full"),disabled:r||!n,children:[r?o.jsx(it,{className:"spin",size:12}):o.jsx(gl,{size:12}),u("editor.wordCountFull")]}),o.jsxs("button",{type:"button",title:u("editor.wordCountSelectionHint"),onClick:()=>c("selection"),disabled:r||!i,children:[r?o.jsx(it,{className:"spin",size:12}):o.jsx(gl,{size:12}),u("editor.wordCountSelection")]})]})]}),o.jsxs("div",{className:"outline",children:[t.map((d,p)=>o.jsxs("button",{className:`outline-item${e===d.path&&f===d.line?" current":""}`,title:`${d.path}:${d.line}`,onClick:()=>{l(d.path,d.line,1),a(d.path,d.line,1)},children:[o.jsx("span",{className:"outline-guides","aria-hidden":!0,style:{width:`${d.level*12}px`}}),o.jsx("small",{children:d.path===e?d.line:d.path.split("/").at(-1)}),o.jsx("span",{className:"outline-title",children:d.title})]},`${d.path}-${d.line}-${p}`)),t.length===0&&o.jsx("p",{className:"muted padded",children:u("editor.noOutline")})]})]})}function ww(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/1024/1024).toFixed(1)} MB`:`${(t/1024/1024/1024).toFixed(1)} GB`}const yw=h.lazy(()=>kt(()=>import("./LatexEditor-CM445Tk0.js"),__vite__mapDeps([4,2,5,1,3,6,7,8,9,10])).then(t=>({default:t.LatexEditor})));function bw({project:t,activeFile:e,activeMainFile:n,openTabs:s,content:r,loadedFile:i,readOnly:l,comments:a,focusComment:c,editorPreferences:u,completionIndex:f,nativeSpellCheck:d,spellCheckIssues:p,spellCheckJump:w,sourceJump:g,collaborativeText:b,collaborationAwareness:x,undoManager:E,editorNotice:R,activateTab:S,closeTab:z,handleTabKeyDown:J,updateEditorContent:C,setSelection:k,onCommentClick:M,onSpellCheckReplace:ne,onCursor:te}){const{t:K}=Ke();return o.jsx(fr,{id:"source",order:2,defaultSize:42,minSize:22,children:o.jsxs("main",{className:"source-panel",children:[u.openFilesInTabs&&s.length>0&&o.jsx("div",{className:"editor-tabs-bar",role:"tablist","aria-label":K("editor.openFiles"),children:o.jsx("div",{className:"editor-tabs-scroll",children:s.map((B,de)=>{const _=B===e,O=B===(n||t.mainFile),q=B.split("/").at(-1)||B;return o.jsxs("div",{className:`editor-tab-item${_?" active":""}`,role:"presentation",children:[o.jsxs("button",{id:`editor-tab-${encodeURIComponent(B)}`,type:"button",role:"tab","aria-selected":_,"aria-controls":"editor-source-content",tabIndex:_?0:-1,className:`editor-tab${_?" active":""}${O?" main-tab":""}`,onClick:()=>S(B),onKeyDown:W=>J(W,de),title:B,children:[o.jsx("span",{className:"editor-tab-icon",children:O?o.jsx(ha,{size:13}):o.jsx(Un,{size:13})}),o.jsx("span",{className:"editor-tab-title",children:q}),O&&o.jsx("small",{className:"editor-tab-badge",children:K("editor.currentMainShort")})]}),o.jsx("button",{type:"button",className:"editor-tab-close",title:K("common.close"),"aria-label":`${K("common.close")} ${q}`,onClick:()=>z(B),children:o.jsx(fs,{size:12})})]},B)})})}),o.jsxs("div",{id:"editor-source-content",className:"editor-content-container",children:[o.jsx(h.Suspense,{fallback:o.jsxs("div",{className:"preview-empty",children:[o.jsx(it,{className:"spin",size:22}),o.jsx("span",{children:K("common.loading")})]}),children:o.jsx(yw,{value:r,filePath:e,readOnly:l,comments:a,focusComment:c,preferences:u,nativeSpellCheck:d,completionIndex:f,spellCheckIssues:p,spellCheckJump:w,jumpTo:i===e&&g?.path===e?g:null,searchRequest:0,collaboration:b?{text:b,awareness:x,undoManager:l?void 0:E}:void 0,onChange:C,onSelection:k,onCommentClick:M,onSpellCheckReplace:ne,onCursor:te},e)}),R&&o.jsx("div",{className:"editor-centered-notice",role:"status","aria-live":"polite",children:R})]})]})})}function aa({diagnostics:t,files:e,empty:n,tone:s,onJump:r}){const{t:i}=Ke(),l=s==="error"?qi:Ft;return t.length?o.jsx("div",{className:`compile-diagnostic-list compile-${s}`,children:t.map((a,c)=>{const u=kw(a.file,e),f=!!(u&&a.line);return o.jsxs("button",{type:"button",disabled:!f,className:"compile-diagnostic-row",onClick:()=>{u&&a.line&&r(u,a.line,a.column??1)},children:[o.jsx(l,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:a.message}),o.jsxs("small",{children:[a.phase,u?` · ${u}${a.line?`:${a.line}`:""}`:a.line?` · ${i("editor.lineNumber",{line:a.line})}`:""]})]})]},`${a.phase}-${a.file??""}-${a.line??0}-${c}`)})}):o.jsxs("div",{className:`compile-empty compile-${s}`,children:[o.jsx(l,{size:26}),o.jsx("span",{children:n})]})}function bi({lines:t,empty:e,tone:n="log"}){const s=n==="error"?qi:n==="warning"?Ft:Ci;return t.length?o.jsx("pre",{className:`compile-output compile-${n}`,children:t.join(`
13
- `)}):o.jsxs("div",{className:`compile-empty compile-${n}`,children:[o.jsx(s,{size:26}),o.jsx("span",{children:e})]})}function xw({projectId:t,mainFile:e,artifacts:n,preview:s,loading:r,onView:i}){const{t:l}=Ke(),a=c=>`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(c)}&download=1`;return n.length?o.jsxs("div",{className:"artifact-browser",children:[o.jsx("div",{className:"artifact-list",children:n.map(c=>o.jsxs("div",{className:`artifact-row${s?.path===c.path?" active":""}`,children:[o.jsxs("button",{type:"button",disabled:!c.viewable,title:c.viewable?l("editor.viewArtifact"):l("editor.downloadToView"),onClick:()=>i(c),children:[o.jsx(Un,{size:14}),o.jsxs("span",{children:[o.jsx("strong",{children:c.path}),o.jsx("small",{children:Cw(c.size)})]})]}),o.jsx("a",{href:a(c.path),title:l("editor.downloadArtifact"),"aria-label":l("editor.downloadArtifact"),children:o.jsx(Gs,{size:14})})]},c.path))}),o.jsx("div",{className:"artifact-preview",children:r?o.jsxs("div",{className:"compile-empty",children:[o.jsx(it,{className:"spin",size:24}),o.jsx("span",{children:l("common.loading")})]}):s?o.jsxs(o.Fragment,{children:[o.jsxs("header",{children:[o.jsx("strong",{children:s.path}),o.jsxs("a",{href:a(s.path),children:[o.jsx(Gs,{size:13}),l("projects.download")]})]}),o.jsx("pre",{children:s.content})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(Un,{size:24}),o.jsx("span",{children:l("editor.selectArtifact")})]})})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(ma,{size:26}),o.jsx("span",{children:l("editor.noArtifacts")})]})}function Sw({mainFile:t,disabled:e,cleaning:n,onCleanCache:s,onCleanArtifacts:r}){const{t:i}=Ke();return o.jsxs("div",{className:"compile-clean-panel",children:[o.jsxs("div",{className:"compile-clean-intro",children:[o.jsx(Ft,{size:28}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanTitle")}),o.jsx("p",{children:i("editor.cleanDescription",{file:t})})]})]}),o.jsxs("div",{className:"compile-clean-actions",children:[o.jsxs("article",{children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(ji,{size:19})}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanCache")}),o.jsx("p",{children:i("editor.cleanCacheDescription")}),o.jsxs("button",{type:"button",disabled:e||n,onClick:s,children:[n?o.jsx(it,{className:"spin",size:14}):o.jsx(ji,{size:14}),i("editor.cleanCache")]})]})]}),o.jsxs("article",{className:"danger",children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(Jt,{size:19})}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanArtifacts")}),o.jsx("p",{children:i("editor.cleanArtifactsDescription")}),o.jsxs("button",{type:"button",className:"danger",disabled:e||n,onClick:r,children:[n?o.jsx(it,{className:"spin",size:14}):o.jsx(Jt,{size:14}),i("editor.cleanArtifacts")]})]})]})]})]})}function kw(t,e){if(!t)return null;const n=e.filter(a=>a.type==="file").map(a=>a.path),s=t.replaceAll("\\","/").replace(/^\.\//,"");if(n.includes(s))return s;const r=n.filter(a=>s.endsWith(`/${a}`));if(r.length===1)return r[0];const i=s.split("/").at(-1),l=n.filter(a=>a.split("/").at(-1)===i);return l.length===1?l[0]:null}function Cw(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const jw=h.lazy(()=>ua().then(t=>({default:t.PdfPreview})));function vw({projectId:t,activeMainFile:e,previewTab:n,diagnosticTab:s,pdfUrl:r,pdfLoadingMode:i,pdfLoading:l,pdfCompiledAt:a,pdfCompiledLabel:c,pdfTargetLabel:u,pdfDownloadUrl:f,pdfTarget:d,pdfViewport:p,activeFile:w,compileBusy:g,compileLog:b,compileDiagnostics:x,compileMessages:E,artifacts:R,artifactPreview:S,artifactLoading:z,cleaning:J,readOnly:C,collaborationSynced:k,workspaceLayout:M,showSyncResize:ne,diagnosticCount:te,selectPreviewTab:K,changeWorkspaceLayout:B,onSetNotice:de,onSetPdfViewport:_,syncVisiblePdfToSource:O,syncCurrentSourceToPdf:q,syncPdfToSource:W,canSyncWithPdf:G,files:he,jumpToSource:ge,onSetCleanMode:ye,cleanCompile:T,viewArtifact:fe}){const{t:$}=Ke();return o.jsxs(o.Fragment,{children:[ne&&o.jsxs(Bi,{className:"resize-handle sync-resize-handle",children:[o.jsx(pa,{className:"resize-grip",size:12}),o.jsxs("span",{className:"sync-direction-buttons",onPointerDown:F=>F.stopPropagation(),children:[o.jsx("button",{disabled:!p||!G,title:$(G?"editor.showInSource":"editor.syncTexOnlyForMain"),"aria-label":$("editor.showInSource"),onClick:()=>{if(!G){de($("editor.syncTexOnlyForMain"));return}O()},children:o.jsx("span",{"aria-hidden":!0,children:"←"})}),o.jsx("button",{disabled:!w||!r||!G,title:$(G?"editor.showInPdf":"editor.syncTexOnlyForMain"),"aria-label":$("editor.showInPdf"),onClick:()=>{if(!G){de($("editor.syncTexOnlyForMain"));return}q()},children:o.jsx("span",{"aria-hidden":!0,children:"→"})})]})]}),o.jsx(fr,{id:"preview",order:3,defaultSize:42,minSize:22,children:o.jsxs("section",{className:"preview-panel",children:[o.jsxs("div",{className:"preview-tabs",children:[o.jsxs("div",{className:"preview-tab-list",role:"tablist","aria-label":$("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":n==="pdf",className:`pdf-tab${n==="pdf"?" active":""}`,onClick:()=>K("pdf"),title:a?$("editor.pdfCompiledAtFor",{file:e,time:new Date(a).toLocaleString(cs.resolvedLanguage)}):$("editor.currentMainDocument",{path:e}),children:[o.jsx(Un,{size:16}),o.jsxs("span",{className:"pdf-tab-label",children:["PDF · ",u,c&&o.jsx("small",{children:c})]})]}),o.jsxs("button",{role:"tab","aria-selected":n==="diagnostics",className:`diagnostics-tab${n==="diagnostics"?" active":""}`,onClick:()=>K("diagnostics"),children:[o.jsx(Ci,{size:14}),$("editor.outputTabs"),o.jsx("span",{children:te})]})]}),f&&o.jsxs("a",{className:"pdf-download-top",href:f,download:!0,title:$("editor.downloadPdf"),"aria-label":$("editor.downloadPdf"),children:[o.jsx(Gs,{size:15}),o.jsx("span",{children:$("editor.downloadPdf")})]})]}),n==="diagnostics"&&o.jsxs("div",{className:"preview-subtabs",role:"tablist","aria-label":$("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":s==="log",className:s==="log"?"active":"",onClick:()=>K("log"),children:[o.jsx(Ci,{size:13}),$("editor.log")]}),o.jsxs("button",{role:"tab","aria-selected":s==="warnings",className:s==="warnings"?"active":"",onClick:()=>K("warnings"),children:[o.jsx(Ft,{size:13}),$("editor.warnings"),o.jsx("span",{children:E.warnings.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="errors",className:s==="errors"?"active":"",onClick:()=>K("errors"),children:[o.jsx(qi,{size:13}),$("editor.errors"),o.jsx("span",{children:E.errors.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="artifacts",className:s==="artifacts"?"active":"",onClick:()=>K("artifacts"),children:[o.jsx(ma,{size:13}),$("editor.artifacts"),o.jsx("span",{children:R.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="clean",className:s==="clean"?"active":"",onClick:()=>K("clean"),children:[o.jsx(ji,{size:13}),$("editor.clean")]})]}),o.jsxs("div",{className:`preview-content preview-${n} ${n==="diagnostics"?`preview-${s}`:""}`,children:[n==="pdf"&&(r?o.jsx(h.Suspense,{fallback:o.jsxs("div",{className:"pdf-loading-state",role:"status","aria-live":"polite",children:[o.jsx(it,{className:"spin",size:24}),o.jsx("span",{children:$("editor.loadingPdf")})]}),children:o.jsx(jw,{url:r,loadingMode:i,target:d,compiling:g,onViewportLocation:(F,ce,Se)=>_({page:F,x:ce,y:Se}),onDoubleClickLocation:(F,ce,Se)=>{if(_({page:F,x:ce,y:Se}),!G){de($("editor.syncTexOnlyForMain"));return}W(F,ce,Se)}})}):l?o.jsxs("div",{className:"pdf-loading-state",role:"status","aria-live":"polite",children:[o.jsx(it,{className:"spin",size:24}),o.jsx("span",{children:$("editor.loadingPdf")})]}):o.jsxs("div",{className:"preview-empty",children:[o.jsx(Un,{size:28}),o.jsx("strong",{children:$("editor.preview")}),o.jsx("span",{children:$("editor.previewHint")})]})),n==="diagnostics"&&s==="log"&&o.jsx(bi,{lines:b?b.split(`
14
- `):[],empty:$(g?"editor.compiling":"editor.noLog")}),n==="diagnostics"&&s==="warnings"&&(x?o.jsx(aa,{tone:"warning",diagnostics:x.warnings,files:he,empty:$("editor.noWarnings"),onJump:(F,ce,Se)=>{M==="pdf-only"&&B("editor-pdf"),ge(F,ce,Se)}}):o.jsx(bi,{tone:"warning",lines:E.warnings,empty:$("editor.noWarnings")})),n==="diagnostics"&&s==="errors"&&(x?o.jsx(aa,{tone:"error",diagnostics:x.errors,files:he,empty:$("editor.noErrors"),onJump:(F,ce,Se)=>{M==="pdf-only"&&B("editor-pdf"),ge(F,ce,Se)}}):o.jsx(bi,{tone:"error",lines:E.errors,empty:$("editor.noErrors")})),n==="diagnostics"&&s==="artifacts"&&o.jsx(xw,{projectId:t,mainFile:e,artifacts:R,preview:S,loading:z,onView:F=>{fe(F)}}),n==="diagnostics"&&s==="clean"&&o.jsx(Sw,{mainFile:e,disabled:C||!k||g,cleaning:J,onCleanCache:()=>ye("cache"),onCleanArtifacts:()=>ye("artifacts")})]})]})})]})}function Ew(t,e){const n=t.slice(0,e),s=/(^|[^\p{L}\p{N}_.-])@([\p{L}\p{N}_.-]*)$/u.exec(n);return s?{start:e-s[2].length-1,end:e,query:s[2]}:null}function Js({projectId:t,value:e,onChange:n,onKeyDown:s,onFocus:r,...i}){const{t:l}=Ke(),a=h.useRef(null),[c,u]=h.useState(null),[f,d]=h.useState(!1),[p,w]=h.useState(null),[g,b]=h.useState(0),x=h.useMemo(()=>{if(!p||!c)return[];const C=p.query.toLocaleLowerCase();return(C?c.filter(M=>M.username.toLocaleLowerCase().includes(C)||M.displayName.toLocaleLowerCase().includes(C)):c).slice(0,8)},[c,p]),E=!!(p&&x.length),R=async()=>{if(!(c||f)){d(!0);try{const C=await ie(`/api/projects/${t}/mention-candidates`);u(C.users)}catch{u([])}finally{d(!1)}}},S=(C,k)=>{const M=Ew(C,k);w(M),b(0),M&&R()},z=C=>{if(!p)return;const k=`@${C.username} `,M=`${e.slice(0,p.start)}${k}${e.slice(p.end)}`,ne=p.start+k.length;n(M),w(null),b(0),window.requestAnimationFrame(()=>{a.current?.focus(),a.current?.setSelectionRange(ne,ne)})},J=C=>{if(!C.nativeEvent.isComposing&&E){if(C.key==="ArrowDown"){C.preventDefault(),b(k=>(k+1)%x.length);return}if(C.key==="ArrowUp"){C.preventDefault(),b(k=>(k-1+x.length)%x.length);return}if(C.key==="Enter"&&!C.ctrlKey&&!C.metaKey&&!C.shiftKey){C.preventDefault(),z(x[g]??x[0]);return}if(C.key==="Escape"){w(null);return}}s?.(C)};return o.jsxs("span",{className:"mention-textarea",children:[o.jsx("textarea",{...i,ref:a,value:e,onFocus:C=>{r?.(C),S(e,C.currentTarget.selectionStart??e.length)},onClick:C=>S(e,C.currentTarget.selectionStart??e.length),onChange:C=>{const k=C.currentTarget.value;n(k),S(k,C.currentTarget.selectionStart??k.length)},onKeyDown:J}),E&&o.jsx("span",{className:"mention-menu",role:"listbox","aria-label":l("editor.mentionUsers"),children:x.map((C,k)=>o.jsxs("button",{type:"button",role:"option","aria-selected":k===g,className:k===g?"active":"",onMouseDown:M=>M.preventDefault(),onClick:()=>z(C),children:[o.jsx(Ys,{"aria-hidden":!0,size:13}),o.jsxs("span",{children:[o.jsx("strong",{children:C.displayName}),o.jsxs("small",{children:["(",C.username,")"]})]})]},C.id))})]})}function xi(t,e){!(t.ctrlKey||t.metaKey)||t.key!=="Enter"||t.nativeEvent.isComposing||(t.preventDefault(),t.stopPropagation(),e())}function Dw({projectId:t,comment:e,currentUserId:n,unreadCommentMentionId:s,unreadReplyMentionIds:r,highlightedComment:i,highlightedReplyId:l,onMarkMentionRead:a,onFocus:c,onToggle:u,onReply:f,onEdit:d,onDelete:p,onEditReply:w,onDeleteReply:g}){const{t:b}=Ke(),[x,E]=h.useState(!1),[R,S]=h.useState(""),[z,J]=h.useState(!1),[C,k]=h.useState(e.content),[M,ne]=h.useState(!1),[te,K]=h.useState(null),[B,de]=h.useState(""),[_,O]=h.useState(null),q=async T=>{T?.preventDefault(),R.trim()&&await f(R)&&(S(""),E(!1))},W=async T=>{T?.preventDefault(),C.trim()&&await d(C)&&J(!1)},G=async T=>{T?.preventDefault(),!(!te||!B.trim())&&await w(te,B)&&K(null)},he=e.authorUsername,ge=T=>new Date(T).toLocaleString(cs.resolvedLanguage),ye=async(T,fe)=>{fe.stopPropagation(),await a(T)};return o.jsxs(o.Fragment,{children:[o.jsxs("article",{"data-comment-id":e.id,className:`comment-thread${e.resolved?" resolved":""}${e.orphaned?" orphaned":""}${i?" mention-target":""}`,onClick:()=>{window.getSelection()?.toString()||c()},children:[o.jsxs("header",{className:"comment-header",children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:e.authorDisplayName??he??b("editor.deletedUser")}),he&&o.jsxs("small",{children:["@",he]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:e.createdAt,title:new Date(e.createdAt).toISOString(),children:ge(e.createdAt)}),e.editedAt&&o.jsx("small",{children:b("editor.editedAt",{time:ge(e.editedAt)})})]})]}),o.jsx("div",{className:"comment-location",children:e.orphaned?b("editor.orphaned"):b("editor.line",{line:e.startLine})}),e.selectedText&&o.jsx("blockquote",{className:"comment-selected-text",children:e.selectedText}),z?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:T=>{W(T)},onClick:T=>T.stopPropagation(),children:[o.jsx(Js,{projectId:t,autoFocus:!0,rows:4,value:C,onChange:k,onKeyDown:T=>xi(T,W)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>J(!1),children:b("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!C.trim(),children:[o.jsx(yl,{size:13}),b("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",children:e.content}),s&&o.jsxs("div",{className:"comment-mention",children:[o.jsxs("span",{children:[o.jsx(Ys,{"aria-hidden":!0,size:12}),b("editor.mentionedYou")]}),o.jsx("button",{type:"button",onClick:T=>{ye(s,T)},children:b("editor.markMentionRead")})]}),e.replies.length>0&&o.jsx("div",{className:"comment-replies",children:e.replies.map(T=>{const fe=r?.get(T.id);return o.jsxs("div",{"data-comment-reply-id":T.id,className:`comment-reply${l===T.id?" mention-target":""}`,children:[o.jsxs("header",{children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:T.authorDisplayName??T.authorUsername??b("editor.deletedUser")}),T.authorUsername&&o.jsxs("small",{children:["@",T.authorUsername]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:T.createdAt,title:new Date(T.createdAt).toISOString(),children:ge(T.createdAt)}),T.editedAt&&o.jsx("small",{children:b("editor.editedAt",{time:ge(T.editedAt)})})]})]}),te===T.id?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:$=>{G($)},onClick:$=>$.stopPropagation(),children:[o.jsx(Js,{projectId:t,autoFocus:!0,rows:3,value:B,onChange:de,onKeyDown:$=>xi($,G)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>K(null),children:b("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!B.trim(),children:[o.jsx(yl,{size:13}),b("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",children:T.content}),fe&&o.jsxs("div",{className:"comment-mention",children:[o.jsxs("span",{children:[o.jsx(Ys,{"aria-hidden":!0,size:12}),b("editor.mentionedYou")]}),o.jsx("button",{type:"button",onClick:$=>{ye(fe,$)},children:b("editor.markMentionRead")})]}),T.authorId===n&&te!==T.id&&o.jsxs("div",{className:"comment-owner-actions",children:[o.jsx("button",{title:b("editor.editReply"),"aria-label":b("editor.editReply"),onClick:$=>{$.stopPropagation(),K(T.id),de(T.content)},children:o.jsx(fl,{size:12})}),o.jsx("button",{className:"danger-text",title:b("editor.deleteReply"),"aria-label":b("editor.deleteReply"),onClick:$=>{$.stopPropagation(),O(T.id)},children:o.jsx(Jt,{size:12})})]})]},T.id)})}),o.jsxs("div",{className:"comment-actions",children:[o.jsxs("button",{className:"resolve",onClick:T=>{T.stopPropagation(),u()},children:[e.resolved?o.jsx(ph,{size:13}):o.jsx(ih,{size:13}),e.resolved?b("editor.reopen"):b("editor.resolve")]}),o.jsxs("button",{className:"reply-action",onClick:T=>{T.stopPropagation(),E(fe=>!fe)},children:[o.jsx(fh,{size:13}),b("editor.reply")]}),e.authorId===n&&!z&&o.jsxs("span",{className:"comment-owner-actions",children:[o.jsx("button",{title:b("editor.editComment"),"aria-label":b("editor.editComment"),onClick:T=>{T.stopPropagation(),k(e.content),J(!0)},children:o.jsx(fl,{size:13})}),o.jsx("button",{className:"danger-text",title:b("editor.deleteComment"),"aria-label":b("editor.deleteComment"),onClick:T=>{T.stopPropagation(),ne(!0)},children:o.jsx(Jt,{size:13})})]})]}),x&&o.jsxs("form",{className:"comment-reply-form",onSubmit:T=>{q(T)},onClick:T=>T.stopPropagation(),children:[o.jsx(Js,{projectId:t,autoFocus:!0,rows:3,value:R,placeholder:b("editor.replyPlaceholder"),onChange:S,onKeyDown:T=>xi(T,q)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>{E(!1),S("")},children:b("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!R.trim(),children:[o.jsx(mh,{size:13}),b("editor.sendReply")]})]})]})]}),o.jsx(hs,{open:M,title:b("editor.deleteCommentTitle"),description:b("editor.deleteCommentDescription",{count:e.replies.length}),confirmLabel:b("common.delete"),danger:!0,onCancel:()=>ne(!1),onConfirm:()=>{p().then(T=>{T&&ne(!1)})}}),o.jsx(hs,{open:!!_,title:b("editor.deleteReplyTitle"),description:b("editor.deleteReplyDescription"),confirmLabel:b("common.delete"),danger:!0,onCancel:()=>O(null),onConfirm:()=>{_&&g(_).then(T=>{T&&O(null)})}})]})}function _w({open:t,onOpenChange:e,project:n,projectId:s}){const{t:r}=Ke(),[i,l]=h.useState([]),[a,c]=h.useState([]),[u,f]=h.useState(""),[d,p]=h.useState("read"),[w,g]=h.useState(null),[b,x]=h.useState(""),E=n.permission==="owner",R=async()=>{try{const[k,M]=await Promise.all([ie(`/api/projects/${s}/members`),ie("/api/users")]);l(k.members),c(M.users.filter(ne=>ne.id!==n.ownerId))}catch(k){x(le(k))}};h.useEffect(()=>{t&&R()},[t,s]);const S=async()=>{if(u)try{await ie(`/api/projects/${s}/members/${u}`,{method:"PUT",body:JSON.stringify({permission:d})}),f(""),p("read"),await R()}catch(k){x(le(k))}},z=async(k,M)=>{try{await ie(`/api/projects/${s}/members/${k.id}`,{method:"PUT",body:JSON.stringify({permission:M})}),await R()}catch(ne){x(le(ne))}},J=async()=>{if(w)try{await ie(`/api/projects/${s}/members/${w.id}`,{method:"DELETE"}),g(null),await R()}catch(k){x(le(k))}},C=a.filter(k=>!i.some(M=>M.id===k.id));return o.jsxs(o.Fragment,{children:[o.jsx(Wt,{open:t,wide:!0,title:r("projectSettings.share"),description:r("projectSettings.shareDescription"),onOpenChange:e,footer:o.jsx("button",{onClick:()=>e(!1),children:r("common.close")}),children:o.jsxs("div",{className:"share-dialog",children:[b&&o.jsx("p",{className:"error",children:b}),o.jsxs("div",{className:"share-owner",children:[o.jsx(ki,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:r("projects.owner")}),o.jsx("strong",{children:n.ownerDisplayName??n.ownerUsername})]})]}),E&&o.jsxs("div",{className:"share-add",children:[o.jsxs("label",{className:"form-field",children:[r("common.user"),o.jsxs("select",{value:u,onChange:k=>f(k.target.value),children:[o.jsx("option",{value:"",children:r("projectSettings.chooseUser")}),C.map(k=>o.jsx("option",{value:k.id,children:k.displayName??k.username},k.id))]})]}),o.jsxs("label",{className:"form-field",children:[r("common.permission"),o.jsxs("select",{value:d,onChange:k=>p(k.target.value),children:[o.jsx("option",{value:"read",children:r("common.readOnly")}),o.jsx("option",{value:"edit",children:r("common.readWrite")})]})]}),o.jsxs("button",{className:"primary icon-button",disabled:!u,onClick:()=>{S()},children:[o.jsx(nh,{size:15}),r("projectSettings.addMember")]})]}),o.jsxs("div",{className:"shared-members-heading",children:[o.jsx("strong",{children:r("projectSettings.members")}),o.jsx("span",{children:i.length})]}),o.jsxs("div",{className:"shared-members",children:[i.map(k=>o.jsxs("div",{className:"shared-member",children:[o.jsxs("span",{className:"member-identity",children:[o.jsx("span",{className:"member-avatar",children:(k.displayName??k.username).slice(0,1).toLocaleUpperCase()}),o.jsxs("span",{children:[o.jsx("strong",{children:k.displayName??k.username}),o.jsxs("small",{children:["@",k.username]})]})]}),o.jsxs("span",{className:"member-controls",children:[o.jsxs("select",{"aria-label":r("common.permission"),disabled:!E,value:k.permission,onChange:M=>{z(k,M.target.value)},children:[o.jsx("option",{value:"read",children:r("common.readOnly")}),o.jsx("option",{value:"edit",children:r("common.readWrite")})]}),E&&o.jsx("button",{className:"icon-only danger-text",title:r("common.remove"),"aria-label":r("common.remove"),onClick:()=>g(k),children:o.jsx(Jt,{size:15})})]})]},k.id)),i.length===0&&o.jsxs("div",{className:"share-empty",children:[o.jsx(ki,{size:24}),o.jsx("span",{children:r("projectSettings.noMembers")})]})]})]})}),o.jsx(hs,{open:!!w,title:r("projectSettings.removeTitle"),description:r("projectSettings.removeDescription",{username:w?.username??""}),confirmLabel:r("common.remove"),danger:!0,onCancel:()=>g(null),onConfirm:()=>{J()}})]})}const Tw=h.lazy(()=>kt(()=>import("./CitationLibraryDialog-zPpsUhWJ.js"),__vite__mapDeps([11,2,1,3,12,7,13,6,8,14,15])).then(t=>({default:t.CitationLibraryDialog}))),Lw=h.lazy(()=>kt(()=>import("./GitDialog-BUU2U_LV.js"),__vite__mapDeps([16,2,1,3,7,17,18,19,13,6,8,9,10])).then(t=>({default:t.GitDialog}))),Rw=h.lazy(()=>kt(()=>import("./HistoryDialog-B6aopsrw.js"),__vite__mapDeps([20,2,1,3,21,22,7,18,19,13,6,8,9,10])).then(t=>({default:t.HistoryDialog}))),Aw=h.lazy(()=>kt(()=>import("./SelectionHistoryDialog-CyE0_YDs.js"),__vite__mapDeps([23,2,1,3,21,6,7,8,9,10])).then(t=>({default:t.SelectionHistoryDialog}))),Nw=h.lazy(()=>kt(()=>import("./ProjectNavigationDialogs-TPbe11iR.js"),__vite__mapDeps([24,2,1,3,8,7,6])).then(t=>({default:t.ProjectSearchDialog}))),Ow=h.lazy(()=>kt(()=>import("./ProjectNavigationDialogs-TPbe11iR.js"),__vite__mapDeps([24,2,1,3,8,7,6])).then(t=>({default:t.QuickOpenDialog})));function Fw({user:t,project:e,projectId:n,activeFile:s,content:r,maxCitationBibtexBytes:i,files:l,directoryEntries:a,readOnly:c,workspaceLayout:u,changeWorkspaceLayout:f,resourcePreview:d,resourcePreviewLoading:p,setResourcePreview:w,setResourcePreviewLoading:g,uploadConflict:b,setUploadConflict:x,uploadFiles:E,cleanMode:R,setCleanMode:S,cleanCompile:z,newFileOpen:J,setNewFileOpen:C,newFilePath:k,setNewFilePath:M,newFolderOpen:ne,setNewFolderOpen:te,newFolderName:K,setNewFolderName:B,selectedFolder:de,fileDialogError:_,setFileDialogError:O,createFile:q,createFolder:W,moveEntry:G,setMoveEntry:he,moveName:ge,setMoveName:ye,moveDestination:T,setMoveDestination:fe,movePath:$,deleteEntry:F,setDeleteEntry:ce,deleteActiveSessions:Se,removePath:pe,commentOpen:be,setCommentOpen:Ie,selection:P,commentText:Y,setCommentText:Oe,addComment:A,shareOpen:Ge,setShareOpen:Fe,citationLibraryOpen:ve,setCitationLibraryOpen:ae,insertCitationAtCursor:me,quickOpen:Be,setQuickOpen:Ee,projectSearchOpen:v,setProjectSearchOpen:re,openFile:Ce,jumpToSource:et,selectionHistoryOpen:Re,setSelectionHistoryOpen:we,historyOpen:dt,setHistoryOpen:qe,gitOpen:N,setGitOpen:X,save:L,permissionDowngrade:Q,permissionDowngradeBusy:tt,dismissPermissionDowngrade:ht,discardPermissionDraft:Pt}){const{t:I}=Ke();return o.jsxs(o.Fragment,{children:[Q&&o.jsx(Wt,{open:!0,title:I("editor.collaboration.permissionDowngradeTitle"),description:Q.localDraftReady&&Q.otherTabDraft?I("editor.collaboration.permissionDowngradeMultipleDrafts"):Q.otherTabDraft?I("editor.collaboration.permissionDowngradeOtherTab"):Q.localDraftReady?I("editor.collaboration.permissionDowngradeDescription",{previous:I("common.readWrite")}):I("editor.collaboration.permissionDowngradeNoDraft"),onOpenChange:U=>{!U&&!tt&&ht()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:tt,onClick:ht,children:Q.localDraftReady?I("editor.collaboration.permissionDowngradeKeep"):I("common.close")}),!Q.otherTabDraft&&o.jsxs("button",{type:"button",className:"danger",disabled:tt,onClick:()=>{Pt()},children:[tt?o.jsx(it,{className:"spin",size:14}):Q.localDraftReady?o.jsx(Jt,{size:14}):o.jsx(sh,{size:14}),Q.localDraftReady?I("editor.collaboration.permissionDowngradeDiscard"):I("editor.collaboration.permissionDowngradeReload")]})]}),children:o.jsx("div",{})}),o.jsxs(Wt,{open:!!d,extraWide:d?.kind==="image"||d?.kind==="pdf"||d?.kind==="text",title:d?.path??"",description:d?.kind==="large"?I("editor.resourceTooLarge",{size:Mw(d.size),limit:`${zi/1024/1024} MB`}):I(`editor.resourcePreview.${d?.kind??"text"}`),onOpenChange:U=>{U||(w(null),g(!1))},footer:d&&o.jsxs("a",{className:"primary resource-download",href:`${d.url}&download=1`,download:!0,children:[o.jsx(Gs,{size:14}),I("editor.downloadResource")]}),children:[d?.kind==="large"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(pl,{size:34}),o.jsx("strong",{children:I("editor.resourceTooLargeTitle")}),o.jsx("span",{children:I("editor.resourceTooLargeDescription")})]}),d?.kind==="unsupported"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(pl,{size:34}),o.jsx("strong",{children:I("editor.resourceUnsupportedTitle")}),o.jsx("span",{children:I("editor.resourceUnsupportedDescription")})]}),d?.kind==="image"&&o.jsx("div",{className:"resource-image-wrap",children:o.jsx("img",{className:"resource-image",src:d.url,alt:d.path})}),d?.kind==="pdf"&&o.jsx("iframe",{className:"resource-pdf",src:d.url,title:d.path}),d?.kind==="text"&&(p?o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(it,{className:"spin",size:24}),o.jsx("span",{children:I("common.loading")})]}):o.jsx("pre",{className:"resource-text",children:d.content}))]}),o.jsx(hs,{open:!!b,title:I("editor.uploadOverwriteTitle"),description:I("editor.uploadOverwriteDescription",{files:b?.collisions.join(", ")??""}),confirmLabel:I("editor.uploadOverwrite"),danger:!0,onCancel:()=>x(null),onConfirm:()=>{const U=b;x(null),U&&E(U.files,new Set(U.collisions),U.directory)}}),o.jsx(hs,{open:!!R,title:I(R==="cache"?"editor.cleanCacheConfirmTitle":"editor.cleanArtifactsConfirmTitle"),description:I(R==="cache"?"editor.cleanCacheConfirmDescription":"editor.cleanArtifactsConfirmDescription"),confirmLabel:I("editor.cleanConfirm"),danger:R==="artifacts",onCancel:()=>S(null),onConfirm:()=>{const U=R;S(null),U&&z(U)}}),o.jsx(Wt,{open:J,title:I("editor.newFile"),description:I("editor.newFileDescription"),onOpenChange:U=>{C(U),U||O("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>C(!1),children:I("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{q()},children:I("common.create")})]}),children:o.jsxs(o.Fragment,{children:[_&&o.jsx("p",{className:"error dialog-error",children:_}),o.jsxs("label",{className:"form-field",children:[I("editor.filePath"),o.jsx("input",{autoFocus:!0,value:k,onChange:U=>M(U.target.value),onKeyDown:U=>{U.key==="Enter"&&!U.nativeEvent.isComposing&&(U.preventDefault(),q())}})]})]})}),o.jsx(Wt,{open:ne,title:I("editor.newFolder"),description:I("editor.folderDestination",{folder:de||I("editor.projectRoot")}),onOpenChange:U=>{te(U),U||O("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>te(!1),children:I("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{W()},children:I("common.create")})]}),children:o.jsxs(o.Fragment,{children:[_&&o.jsx("p",{className:"error dialog-error",children:_}),o.jsxs("label",{className:"form-field",children:[I("editor.folderName"),o.jsx("input",{autoFocus:!0,value:K,onChange:U=>B(U.target.value),onKeyDown:U=>{U.key==="Enter"&&W()}})]})]})}),o.jsx(Wt,{open:!!G,title:I("editor.moveTitle",{name:G?.path.split("/").at(-1)??""}),description:I("editor.moveDescription"),onOpenChange:U=>{U||(he(null),ye(""),O(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>he(null),children:I("common.cancel")}),o.jsx("button",{className:"primary",disabled:!ge.trim(),onClick:()=>{$()},children:I("editor.moveApply")})]}),children:o.jsxs(o.Fragment,{children:[_&&o.jsx("p",{className:"error dialog-error",children:_}),o.jsxs("label",{className:"form-field",children:[I("editor.pathName"),o.jsx("input",{autoFocus:!0,value:ge,onChange:U=>ye(U.target.value),onKeyDown:U=>{U.key==="Enter"&&$()}})]}),o.jsxs("label",{className:"form-field",children:[I("editor.destinationFolder"),o.jsxs("select",{value:T,onChange:U=>fe(U.target.value),children:[o.jsx("option",{value:"",children:I("editor.projectRoot")}),a.filter(U=>G?.type!=="directory"||U.path!==G.path&&!U.path.startsWith(`${G.path}/`)).map(U=>o.jsx("option",{value:U.path,children:U.path},U.path))]})]})]})}),o.jsx(Wt,{open:!!F,title:I("editor.deletePathTitle",{name:F?.path.split("/").at(-1)??""}),description:Se.length?I("editor.deletePathActiveDescription",{path:F?.path??"",users:[...new Set(Se.map(U=>U.name))].join(", ")}):I("editor.deletePathDescription",{path:F?.path??""}),onOpenChange:U=>{U||(ce(null),O(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>ce(null),children:I("common.cancel")}),o.jsx("button",{className:"danger",onClick:()=>{pe()},children:I("common.delete")})]}),children:o.jsxs(o.Fragment,{children:[_&&o.jsx("p",{className:"error dialog-error",children:_}),Se.length>0&&o.jsxs("p",{className:"warning",children:[o.jsx(Ft,{size:15}),I("editor.deletePathWillClose")]})]})}),o.jsxs(Wt,{open:be,title:I("editor.addComment"),description:P.selectedText?I("editor.commentDescription",{count:P.endOffset-P.startOffset}):I("editor.pointComment"),onOpenChange:Ie,footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>Ie(!1),children:I("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{A()},children:I("editor.addComment")})]}),children:[o.jsxs("label",{className:"form-field",children:[I("editor.commentContent"),o.jsx(Js,{projectId:n,autoFocus:!0,rows:5,value:Y,onChange:Oe,onKeyDown:U=>{(U.ctrlKey||U.metaKey)&&U.key==="Enter"&&!U.nativeEvent.isComposing&&(U.preventDefault(),U.stopPropagation(),A())}})]}),P.selectedText&&o.jsx("blockquote",{className:"selection-preview",children:P.selectedText})]}),o.jsx(_w,{open:Ge,onOpenChange:Fe,project:e,projectId:n}),ve&&o.jsx(da,{title:I("citationLibrary.title"),onClose:()=>ae(!1),children:o.jsx(Tw,{open:!0,onOpenChange:ae,currentFile:s,currentSource:r,readOnly:c,currentUserId:t.id,maxBibtexBytes:i,onInsert:me})}),Be&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Ow,{open:!0,files:l,onOpenChange:Ee,onOpenFile:U=>{const ue=l.find(Pe=>Pe.path===U);ue&&Ce(ue)}})}),v&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Nw,{open:!0,project:e,onOpenChange:re,onJump:(U,ue,Pe)=>{u==="pdf-only"&&f("editor-pdf"),et(U,ue,Pe)}})}),Re&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Aw,{open:!0,onOpenChange:we,project:e,filePath:s,selection:P,currentSource:r})}),dt&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Rw,{open:!0,onOpenChange:qe,project:e,onBeforeMutation:e.permission==="read"?async()=>!0:L})}),e.ownerId===t.id&&N&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Lw,{open:!0,onOpenChange:X,project:e,onBeforeMutation:L})})]})}function Mw(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const $w=h.lazy(()=>kt(()=>import("./ProjectSettings-CDQvIlQ4.js"),__vite__mapDeps([25,2,1,3,7,26,27,14,10,6,8,9])).then(t=>({default:t.ProjectSettings})));function Iw({sidePanel:t,onClose:e,project:n,projectId:s,site:r,files:i,currentUserId:l,comments:a,unreadMentions:c,onMarkMentionRead:u,onMarkAllMentionsRead:f,targetCommentId:d,targetReplyId:p,onFocusComment:w,onToggleComment:g,onReplyComment:b,onEditComment:x,onDeleteComment:E,onEditCommentReply:R,onDeleteCommentReply:S,dictionaryWords:z,onDictionaryChange:J,editorPreferences:C,onEditorPreferences:k,spellCheckCount:M,spellCheckUniqueCount:ne,spellCheckIndex:te,onSpellCheckNavigate:K,onProject:B}){const{t:de}=Ke();return t?o.jsxs(o.Fragment,{children:[o.jsx(Bi,{className:"resize-handle"}),o.jsx(fr,{id:"context",order:4,defaultSize:20,minSize:15,maxSize:38,children:o.jsxs("aside",{className:"context-panel",children:[t==="comments"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"drawer-title",children:[o.jsx("strong",{children:de("editor.sourceComments")}),o.jsxs("span",{className:"drawer-title-actions",children:[c.length>0&&o.jsxs("button",{className:"drawer-mention-read-all",type:"button",onClick:()=>{f()},title:de("editor.markAllMentionsRead"),children:[o.jsx(Ys,{"aria-hidden":!0,size:13}),o.jsx("span",{children:de("editor.markAllMentionsRead")})]}),o.jsx("button",{"aria-label":de("common.close"),onClick:e,children:o.jsx(fs,{size:17})})]})]}),o.jsxs("div",{className:"comments",children:[a.map(_=>{const O=c.find(W=>W.commentId===_.id&&!W.replyId)?.id,q=new Map(c.filter(W=>W.commentId===_.id&&W.replyId).map(W=>[W.replyId,W.id]));return o.jsx(Dw,{projectId:s,comment:_,currentUserId:l,unreadCommentMentionId:O,unreadReplyMentionIds:q,highlightedComment:d===_.id&&!p,highlightedReplyId:d===_.id?p:null,onMarkMentionRead:u,onFocus:()=>w(_),onToggle:()=>{g(_)},onReply:W=>b(_,W),onEdit:W=>x(_,W),onDelete:()=>E(_),onEditReply:(W,G)=>R(_,W,G),onDeleteReply:W=>S(_,W)},_.id)}),a.length===0&&o.jsx("p",{className:"muted padded",children:de("editor.noComments")})]})]}),t==="settings"&&o.jsx(Bd,{onClose:e,children:o.jsx($w,{onClose:e,project:n,projectId:s,site:r,files:i,dictionaryWords:z,onDictionaryChange:J,editorPreferences:C,onEditorPreferences:k,spellCheckCount:M,spellCheckUniqueCount:ne,spellCheckIndex:te,onSpellCheckNavigate:K,onProject:B})})]})})]}):null}function Pw(t){if(typeof globalThis.requestAnimationFrame=="function"){const n=globalThis.requestAnimationFrame(t);return()=>globalThis.cancelAnimationFrame(n)}const e=globalThis.setTimeout(t,0);return()=>globalThis.clearTimeout(e)}function Uw(){let t={line:1,column:1,offset:0},e=t.line,n=null,s=null;const r=new Set,i=()=>{for(const c of r)c()},l=()=>{s=null;const c=n;n=null,!(c===null||c===e)&&(e=c,i())},a=c=>{n=c,s===null&&(s=Pw(l))};return{getCursor:()=>t,getOutlineLine:()=>e,subscribe:c=>(r.add(c),()=>r.delete(c)),update:(c,u,f)=>{t.line===c&&t.column===u&&t.offset===f||(t={line:c,column:u,offset:f},(c!==e||s!==null)&&a(c))},reset:()=>{s?.(),s=null,n=null,t={line:1,column:1,offset:0},e!==1&&(e=1,i())},dispose:()=>{s?.(),s=null,n=null}}}const zw=h.lazy(()=>kt(()=>import("./WordCountDialog-B4PI0vEk.js"),__vite__mapDeps([28,2,1,3,26,7,6,8,9,10])).then(t=>({default:t.WordCountDialog})));let qs=null;function ca(){return qs||(qs=kt(()=>import("./citationLibrary-ZeQPCv5O.js"),[]).catch(t=>{throw qs=null,t})),qs}function an(t){return t instanceof Error&&t.name==="AbortError"}const Bw=300;function qw({site:t,user:e,projectId:n,preload:s,mentionId:r=null,onMentionTargeted:i,onMentionsRead:l,onBack:a}){const{t:c}=Ke(),[u,f]=h.useState(null),[d,p]=h.useState(!1),[w,g]=h.useState([]),[b,x]=h.useState(null),[E,R]=h.useState([]),[S,z]=h.useState(""),[J,C]=h.useState(""),[k,M]=h.useState(new Set),[ne,te]=h.useState(""),[K,B]=h.useState({filePath:"",content:""}),[de,_]=h.useState(""),[O,q]=h.useState(!1),[W,G]=h.useState("editor.saved"),[he,ge]=h.useState(null),ye=h.useRef(he);ye.current=he;const T=h.useRef(null);T.current||(T.current=Uw());const fe=T.current,[$,F]=h.useState("pdf"),[ce,Se]=h.useState("log"),pe=m=>{if(m==="pdf"){F("pdf");return}if(m==="diagnostics"){F("diagnostics");return}Se(m),F("diagnostics")},{workspaceLayout:be,setWorkspaceLayout:Ie}=dw(e.id,n),[P,Y]=h.useState(""),[Oe,A]=h.useState(""),[Ge,Fe]=h.useState({selectedText:"",startOffset:0,endOffset:0}),ve=h.useRef({selectedText:"",startOffset:0,endOffset:0}),ae=m=>{const y=ve.current;y.selectedText===m.selectedText&&y.startOffset===m.startOffset&&y.endOffset===m.endOffset||(ve.current=m,Fe(m))},[me,Be]=h.useState(null),[Ee,v]=h.useState(null),[re,Ce]=h.useState(!1),[et,Re]=h.useState(!1),[we,dt]=h.useState(!1),[qe,N]=h.useState(!1),[X,L]=h.useState(!1),[Q,tt]=h.useState(!1),[ht,Pt]=h.useState(null),[I,U]=h.useState(!1),[ue,Pe]=h.useState(!1),[eu,Rs]=h.useState(!1),[tu,nu]=h.useState("full"),[su,ru]=h.useState(""),[Dr,_r]=h.useState(!1),[iu,Tr]=h.useState(""),[ou,Lr]=h.useState(null),[es,xn]=h.useState(!1),[Zt,Lt]=h.useState(null),[lu,Rr]=h.useState(!1),[ot,vo]=h.useState(()=>bl(e.id,n)),[Sn,As]=h.useState([]),Ut=h.useRef([]);Ut.current=Sn;const au=h.useRef(null),Ns=h.useRef(null),Os=h.useRef(0),Ar=h.useRef(0),De=h.useRef(""),Ct=h.useRef(""),Eo=h.useRef(0),en=h.useRef(null),tn=h.useRef(null),nn=h.useRef(null),kn=h.useRef(null),Cn=h.useRef(null),jn=h.useRef(null),Nr=h.useRef(null),Rt=h.useRef(!1),zt=h.useRef(null),Do=h.useRef(a),Or=h.useRef(i),Fr=h.useRef(l);Do.current=a,Or.current=i,Fr.current=l,Ct.current=J,h.useEffect(()=>{if(!Oe)return;const m=window.setTimeout(()=>A(""),3e3);return()=>window.clearTimeout(m)},[Oe]);const cu=h.useCallback((m,y,D=0)=>{fe.update(m,y,D)},[fe]);h.useEffect(()=>()=>fe.dispose(),[fe]);const Fs=m=>{const y=Ut.current,D=m(y);D!==y&&(Ut.current=D,As(D))};h.useEffect(()=>{Ut.current=[],As([]),Lt(null),L(!1),Cn.current?.abort(),Cn.current=null,jn.current?.abort(),jn.current=null,Nr.current=null,v(null),Rs(!1),_r(!1),Tr(""),Lr(null)},[n]);const _o=m=>{const y=Ut.current,D=y.indexOf(m);if(D<0)return;const j=y.filter(H=>H!==m);if(Ut.current=j,As(j),De.current!==m)return;const Z=j.length>0?j[Math.min(D,j.length-1)]:u?.mainFile??"";z(Z)},{collaboration:Te,status:Ms,synced:Ye,activeSessions:To,formatLeaseStates:uu,compileState:sn,setCompileState:Lo,filesEvent:Ue,commentsRevision:Ro,historyWarning:du,dictionaryRevision:Ao,localDraftReady:No,permission:Mr,reconnect:hu,protocolUpgradeRequired:Oo,permissionDowngrade:fu,dismissPermissionDowngrade:pu,discardLocalDraft:mu}=nw(n,e,J,u?.permission??"read",d,()=>G("editor.offlineDraft")),{unreadMentions:Fo,refresh:gu,markMentionRead:wu,markAllMentionsRead:yu}=Oh(n,Ro,Y),{pdfTarget:bu,pdfViewport:xu,sourceJump:Su,setPdfViewport:ku,clearPdfViewport:Mo,jumpToSource:$r,syncSourceToPdf:Ir,syncPdfToSource:Cu,syncVisiblePdfToSource:ju}=uw({projectId:n,mainFile:J,activeFile:S,onActiveFile:z,onError:Y,onShowPdf:()=>pe("pdf")}),lt=cw({active:!!(u&&S&&Ye&&ot.spellCheck),projectId:n,activeFile:S,content:ne,dictionaryWords:w});h.useEffect(()=>{vo(bl(e.id,n))},[e.id,n]);const Pr=m=>{te(m)};h.useEffect(()=>{if(!S||de!==S){B(j=>j.filePath||j.content?{filePath:"",content:""}:j);return}const m=S,y=ne,D=window.setTimeout(()=>{B(j=>j.filePath===m&&j.content===y?j:{filePath:m,content:y})},Bw);return()=>window.clearTimeout(D)},[S,de,ne]),h.useEffect(()=>{if(De.current=S,fe.reset(),ae({selectedText:"",startOffset:0,endOffset:0}),!ot.openFilesInTabs){Ut.current.length>0&&(Ut.current=[],As([]));return}S&&Fs(m=>m.includes(S)?m:[...m,S])},[S,ot.openFilesInTabs,n,fe]),h.useEffect(()=>{if(!O)return;const m=y=>{y.preventDefault(),y.returnValue=""};return window.addEventListener("beforeunload",m),()=>window.removeEventListener("beforeunload",m)},[O]),h.useEffect(()=>{if(Ms!=="disconnected")return;const m=new AbortController;return ie(`/api/projects/${n}`,{signal:m.signal}).then(({project:y})=>{m.signal.aborted||(f(y),Y(""))}).catch(y=>{if(!an(y)){if(y instanceof Si&&[401,403,404].includes(y.status)){Y(le(y)),Do.current();return}Y(c("errors.collaborationUnavailable"))}}),()=>m.abort()},[Ms,n,c]);const Ur=async(m={})=>{en.current?.abort(),en.current=null;const y=m.signal?null:new AbortController;y&&(en.current=y);try{const D=await ie(`/api/projects/${n}/completions`,{signal:m.signal??y?.signal});(!m.isCurrent||m.isCurrent())&&x(D.index)}catch(D){if(an(D))return;(!m.isCurrent||m.isCurrent())&&x(null)}finally{y&&en.current===y&&(en.current=null)}},zr=async(m={},y=Ct.current)=>{tn.current?.abort(),tn.current=null;const D=m.signal?null:new AbortController;D&&(tn.current=D);try{const j=y?`?mainFile=${encodeURIComponent(y)}`:"",Z=await ie(`/api/projects/${n}/outline${j}`,{signal:m.signal??D?.signal});(!m.isCurrent||m.isCurrent())&&R(Z.outline)}catch(j){!an(j)&&(!m.isCurrent||m.isCurrent())&&R([])}finally{D&&tn.current===D&&(tn.current=null)}},$o=async(m={})=>{nn.current?.abort(),nn.current=null;const y=m.signal?null:new AbortController;y&&(nn.current=y);try{const D=await ie(`/api/projects/${n}/dictionary`,{signal:m.signal??y?.signal});(!m.isCurrent||m.isCurrent())&&g(D.words)}catch(D){if(an(D))return;(!m.isCurrent||m.isCurrent())&&g([])}finally{y&&nn.current===y&&(nn.current=null)}};h.useEffect(()=>{let m=!1;const y=++Eo.current,D=new AbortController,j=()=>!m&&Eo.current===y;let Z=!1;f(null),Uo([]),R([]),z(""),C(""),M(new Set),te(""),_(""),Lo(null),Mo(),x(null),g([]),ua();const H=(s?.projectId===n?s.project:ie(`/api/projects/${n}`,{signal:D.signal})).then(Me=>{j()&&(Z=!0,f(Me.project),z(Me.project.mainFile),C(Me.project.mainFile),M(new Set),Jo(new Set(as(Me.project.mainFile))))}).catch(Me=>{j()&&Y(le(Me))}),ee=ie(`/api/projects/${n}/files`,{signal:D.signal}).then(Me=>{j()&&Uo(Me.files)}).catch(Me=>{j()&&Y(le(Me))});let ft=null;return Promise.allSettled([H,ee]).then(()=>{!j()||!Z||(ft=window.setTimeout(()=>{j()&&Promise.all([Ur({signal:D.signal,isCurrent:j}),$o({signal:D.signal,isCurrent:j})])},0))}),()=>{m=!0,ft!==null&&window.clearTimeout(ft),D.abort(),en.current?.abort(),en.current=null,tn.current?.abort(),tn.current=null,nn.current?.abort(),nn.current=null,kn.current?.abort(),kn.current=null}},[n,s]),h.useEffect(()=>{if(!r||!u)return;jn.current?.abort();const m=new AbortController;return jn.current=m,ie(`/api/projects/${n}/mentions/${encodeURIComponent(r)}`,{signal:m.signal}).then(({mention:y})=>{m.signal.aborted||(v(y),Be("comments"),z(y.filePath),Or.current?.(y.id))}).catch(y=>{an(y)||m.signal.aborted||(Y(le(y)),Or.current?.(r))}).finally(()=>{jn.current===m&&(jn.current=null)}),()=>m.abort()},[r,u?.id,n]),h.useEffect(()=>{Ao&&$o()},[Ao,n]),h.useEffect(()=>{!u||Ms!=="connected"||Mr===u.permission||f(m=>m&&{...m,permission:Mr})},[Mr,u?.permission]),h.useEffect(()=>{if(!Ue)return;const m=Ue.kind==="delete"&&!!Ue.path&&ln(Ue.path,De.current),y=Ue.kind==="delete"&&!!Ue.path&&ln(Ue.path,Ct.current);if(Ue.kind==="move"&&Ue.source&&Ue.destination){const j=Ue.source,Z=Ue.destination,H=ee=>ee===j?Z:ee.startsWith(`${j}/`)?`${Z}${ee.slice(j.length)}`:ee;z(ee=>H(ee)),C(ee=>H(ee)),M(ee=>new Set([...ee].map(H))),qr(ee=>ee&&H(ee)),Fs(ee=>ee.map(H))}m&&(z(""),_(""),Pr(""),A(c("editor.fileDeletedByCollaborator",{path:Ue.path}))),Ue.kind==="delete"&&Ue.path&&(M(j=>new Set([...j].filter(Z=>!ln(Ue.path,Z)))),qr(j=>ln(Ue.path,j)?"":j),qo(j=>j&&ln(Ue.path,j.path)?null:j),Fs(j=>j.filter(Z=>!ln(Ue.path,Z)))),kn.current?.abort();const D=new AbortController;kn.current=D,Promise.all([Tu({signal:D.signal}),ie(`/api/projects/${n}`,{signal:D.signal})]).then(([j,Z])=>{if(f(Z.project),y&&C(Z.project.mainFile),m&&j){const H=j.find(ee=>ee.type==="file"&&ee.path===Z.project.mainFile)??j.find(ee=>ee.type==="file"&&Pn(ee.path));z(H?.path??"")}Ur({signal:D.signal}),zr({signal:D.signal},y?Z.project.mainFile:Ct.current)}).catch(j=>{an(j)}).finally(()=>{kn.current===D&&(kn.current=null)})},[Ue?.revision]),h.useEffect(()=>{if(Te.setActiveFile(S),!S)return;_(""),G("editor.loading");const m=Te.getText(S),y=(D,j)=>{Pr(m.toString()),_(S),j?.local&&u?.permission!=="read"?(Os.current+=1,q(!0),G("editor.pending")):Os.current<=Ar.current&&G(ye.current?"editor.savedAt":"editor.saved")};return m.observe(y),(Ye||No)&&y(),()=>{m.unobserve(y)}},[S,Te,Ye,No,u?.permission]);const $s=async()=>{if(!Ye)throw new Error("Collaboration is not synchronized");const m=Os.current,y=await Te.flush();return Ar.current=Math.max(Ar.current,m),ge(y.persistedAt),/\.tex$/i.test(De.current)&&zr(),Os.current===m?(q(!1),G("editor.savedAt")):G("editor.pending"),y};h.useEffect(()=>{if(!O||!S)return;if(!Ye){G("editor.offlineDraft");return}G("editor.pending");const m=window.setTimeout(()=>{G("editor.saving"),$s().catch(()=>{G(Te.connected?"editor.saveFailed":"editor.offlineDraft")})},750);return()=>window.clearTimeout(m)},[ne,O,S,Ye]);const ts=async()=>{if(!u||u.permission==="read"||!Ye||!S)return!1;G("editor.saving");try{return await $s(),Ur(),!0}catch(m){return G("editor.saveFailed"),Y(le(m)||c("errors.collaborationUnavailable")),!1}},vu=async m=>{if(!u||Dr)return;const y=m==="full"?Ct.current||u.mainFile:De.current,D=m==="selection"?ve.current.selectedText:"";if(!y)return;if(m==="selection"&&(!D.trim()||!/\.(?:tex|sty|cls)$/i.test(y))){A(c("editor.wordCountSelectionEmpty"));return}Cn.current?.abort();const j=new AbortController;Cn.current=j,nu(m),ru(y),Lr(null),Tr(""),Rs(!0),_r(!0);try{if(m==="full"&&O&&u.permission!=="read"&&!await ts())throw new Error(c("editor.wordCountSaveRequired"));const Z=m==="selection"?{mode:m,path:y,source:D}:{mode:m,mainFile:y},H=await ie(`/api/projects/${n}/word-count`,{method:"POST",body:JSON.stringify(Z),signal:j.signal});if(j.signal.aborted)return;Lr(H)}catch(Z){if(an(Z))return;j.signal.aborted||Tr(le(Z))}finally{Cn.current===j&&(Cn.current=null,_r(!1))}},Br=async(m,y,D=ot.texFmtConfig)=>{if(/\.bib$/i.test(m)){const Z=await ca();try{return{formatted:Z.formatBibtex(y,t.maxCitationBibtexBytes)}}catch(H){throw H instanceof Z.BibtexFormatError?H.kind==="too-large"?new Error(c("citationLibrary.fileTooLarge",{size:Z.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})):new Error(c("citationLibrary.fileInvalid")):H}}return{formatted:(await Ch(y,D)).output}},Io=async m=>{if(!u||u.permission==="read"||!Ye||Rt.current||!Ps(De.current))return;const y=De.current,D=Te.getText(y);Rt.current=!0,xn(!0);let j=()=>{};const Z=new Promise(ee=>{j=ee});zt.current=Z;let H=null;try{H=await Te.acquireFormatLease(y);const ee=D.toString(),{formatted:ft}=await Br(y,ee,m);if(De.current!==y||D.toString()!==ee){Y(c("editor.formatSourceChanged"));return}await H.confirm();const Me=await ni(ee,ft);if(De.current!==y||D.toString()!==ee){Y(c("editor.formatSourceChanged"));return}if(await H.confirm(),De.current!==y||D.toString()!==ee){Y(c("editor.formatSourceChanged"));return}Me.length&&Te.applyTextEdits(y,Me),Me.length&&await $s(),Lt(null),Y(""),A(c("editor.formatFileComplete"))}catch(ee){ti(ee)?(Lt({action:"file",kind:ee.kind,detail:ee.message}),Y("")):Y(c("editor.formatFileFailed",{message:le(ee)}))}finally{H&&await H.release(),Rt.current=!1,xn(!1),j(),zt.current===Z&&(zt.current=null)}},Eu=async()=>{if(!ot.formatOnCompile||!u||u.permission==="read"||!Ye||!Ps(De.current)||Rt.current)return;const m=De.current,y=Te.getText(m);Rt.current=!0,xn(!0);let D=null;try{D=await Te.acquireFormatLease(m);const j=y.toString(),{formatted:Z}=await Br(m,j);await D.confirm();const H=await ni(j,Z);if(De.current!==m||y.toString()!==j)throw new Error(c("editor.formatSourceChanged"));if(await D.confirm(),De.current!==m||y.toString()!==j)throw new Error(c("editor.formatSourceChanged"));H.length&&Te.applyTextEdits(m,H),H.length&&await Te.flush(),Lt(null)}catch(j){ti(j)?(Lt({action:"file",kind:j.kind,detail:j.message}),Y("")):Y(c("editor.formatFailedContinue",{message:le(j)}))}finally{D&&await D.release(),Rt.current=!1,xn(!1)}},Du=async()=>(zt.current&&await zt.current,await Eu(),ts()),Po=async m=>{if(!u||u.permission==="read"||!Ye||Rt.current||!Ps(De.current))return;const y=ve.current;if(!y.selectedText.trim()){A(c("editor.formatSelectionRequired"));return}const D=De.current,{startOffset:j,endOffset:Z,selectedText:H}=y,ee=Te.getText(D);if(ee.toString().slice(j,Z)!==H){Y(c("editor.formatSelectionChanged"));return}Rt.current=!0,xn(!0);let ft=()=>{};const Me=new Promise(At=>{ft=At});zt.current=Me;let rn=null;try{if(rn=await Te.acquireFormatLease(D),ee.toString().slice(j,Z)!==H){Y(c("editor.formatSelectionChanged"));return}const rs=await Br(D,H,m),$d=Eh(H,rs.formatted);await rn.confirm();const ei=await ni(H,$d,j);if(De.current!==D||ee.toString().slice(j,Z)!==H){Y(c("editor.formatSelectionChanged"));return}if(await rn.confirm(),De.current!==D||ee.toString().slice(j,Z)!==H){Y(c("editor.formatSelectionChanged"));return}ei.length&&Te.applyTextEdits(D,ei),ei.length&&await $s(),Lt(null),Y(""),A(c("editor.formatSelectionComplete"))}catch(At){ti(At)?(Lt({action:"selection",kind:At.kind,detail:At.message}),Y("")):Y(c("editor.formatFailed",{message:le(At)}))}finally{rn&&await rn.release(),Rt.current=!1,xn(!1),ft(),zt.current===Me&&(zt.current=null)}},_u=async m=>{const y=De.current;if(!/\.bib$/i.test(y)||u?.permission==="read"||!Ye)return A(c("citationLibrary.importRequiresWrite")),!1;const D=Te.getText(y);let j;try{j=await ca()}catch(rs){return Y(le(rs)),!1}if(De.current!==y||!Ye)return!1;const Z=D.toString(),H=j.parseBibEntriesResult(Z,t.maxCitationBibtexBytes);if(H.status==="too-large")return A(c("citationLibrary.fileTooLarge",{size:j.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})),!1;if(H.status==="invalid")return A(c("citationLibrary.fileInvalid")),!1;if(H.entries.some(rs=>rs.citationKey.toLowerCase()===m.citationKey.toLowerCase()))return A(c("citationErrors.alreadyInFile",{key:m.citationKey})),!1;const ee=Math.max(0,Math.min(Z.length,fe.getCursor().offset)),ft=Z.slice(0,ee),Me=Z.slice(ee),rn=ft?ft.endsWith(`
15
-
16
- `)?"":ft.endsWith(`
17
- `)?`
18
- `:`
19
-
20
- `:"",At=Me?Me.startsWith(`
21
-
22
- `)?"":Me.startsWith(`
23
- `)?`
24
- `:`
25
-
26
- `:"";return Te.applyTextEdits(y,[{from:ee,to:ee,replacement:`${rn}${m.bibtex.trim()}${At}`}]),A(c("citationLibrary.imported",{key:m.citationKey})),!0},{files:gt,setFiles:Uo,loadFiles:Tu,newFileOpen:Lu,setNewFileOpen:zo,newFilePath:Ru,setNewFilePath:Bo,resourcePreview:Au,setResourcePreview:qo,resourcePreviewLoading:Nu,setResourcePreviewLoading:Ou,newFolderOpen:Fu,setNewFolderOpen:Wo,newFolderName:Mu,setNewFolderName:Vo,fileDialogError:$u,setFileDialogError:Ho,selectedFolder:Ko,setSelectedFolder:qr,expandedFolders:Iu,setExpandedFolders:Jo,moveEntry:Pu,setMoveEntry:Go,moveName:Uu,setMoveName:Yo,moveDestination:zu,setMoveDestination:Xo,deleteEntry:Wr,setDeleteEntry:Qo,fileDragActive:Bu,setFileDragActive:qu,uploadConflict:Wu,setUploadConflict:Vu,uploadingFiles:Hu,directoryEntries:Ku,visibleEntries:Ju,createFile:Gu,createFolder:Yu,uploadFiles:Zo,upload:Xu,openFile:Vr,movePath:Qu,removePath:Zu}=aw({projectId:n,site:t,activeFile:S,dirty:O,save:ts,onError:Y,onProject:f,onActiveFile:z,onActiveMainFile:C,onRootDocuments:M}),el=()=>Ct.current||u?.mainFile||"",ed=()=>{const m=el(),y=De.current;if(!y||!/\.tex$/i.test(y))return m;const D=gt.filter(H=>H.type==="file"&&/\.tex$/i.test(H.path)).length,j=Te.getText(y).toString();return la(j)||D===1?(M(H=>{if(H.has(y))return H;const ee=new Set(H);return ee.add(y),ee}),m!==y&&(Ct.current=y,C(y)),y):m===y&&u?.mainFile&&u.mainFile!==y?(Ct.current=u.mainFile,C(u.mainFile),u.mainFile):m};h.useEffect(()=>{if(!S||de!==S||K.filePath!==S||!S.toLocaleLowerCase().endsWith(".tex"))return;const m=gt.filter(Z=>Z.type==="file"&&/\.tex$/i.test(Z.path)).length;if(m===0)return;const y=S===u?.mainFile,j=la(K.content)||m===1;M(Z=>{if(Z.has(S)===j)return Z;const H=new Set(Z);return j?H.add(S):H.delete(S),H}),j&&!y&&Ct.current!==S?C(S):!j&&Ct.current===S&&u?.mainFile&&C(u.mainFile)},[S,de,K,gt,u?.mainFile]),h.useEffect(()=>{if(!ot.openFilesInTabs||gt.length===0)return;const m=new Set(gt.filter(y=>y.type==="file"&&Pn(y.path)).map(y=>y.path));Fs(y=>{const D=y.filter(j=>m.has(j));return D.length===y.length?y:D})},[gt,ot.openFilesInTabs]);const{comments:vn,focusComment:td,setFocusComment:Hr,commentOpen:nd,setCommentOpen:tl,commentText:sd,setCommentText:rd,addComment:id,toggleComment:od,replyToComment:ld,editComment:ad,deleteComment:cd,editCommentReply:ud,deleteCommentReply:dd}=Ah({projectId:n,activeFile:S,permission:u?.permission,revision:Ro,selection:Ge,save:ts,onError:Y,onAdded:()=>Be("comments"),onChanged:()=>{gu()}}),hd=async m=>{const y=await wu(m);return y&&Fr.current?.(1),y},fd=async()=>{const m=Fo.length,y=await yu();return y&&m&&Fr.current?.(m,!0),y};h.useEffect(()=>{if(!Ee||S!==Ee.filePath||me!=="comments")return;const m=vn.find(H=>H.id===Ee.commentId);if(!m||Ee.replyId&&!m.replies.some(H=>H.id===Ee.replyId))return;const y=Ee.replyId?`[data-comment-reply-id="${Ee.replyId}"]`:`[data-comment-id="${Ee.commentId}"]`,D=document.querySelector(y);if(!D||Nr.current===Ee.id)return;Nr.current=Ee.id,Hr({...m});const j=window.requestAnimationFrame(()=>D.scrollIntoView({block:"center",behavior:"smooth"})),Z=window.setTimeout(()=>v(H=>H?.id===Ee.id?null:H),3e3);return()=>{window.cancelAnimationFrame(j),window.clearTimeout(Z)}},[S,vn,me,Ee]);const{pdfUrl:Bt,pdfCompiledAt:ns,pdfLoadingMode:pd,pdfLoading:Kr,compileLog:Jr,compileDiagnostics:md,compileOutcome:ss,artifacts:nl,artifactPreview:gd,artifactLoading:wd,editorNotice:yd,localCompiling:sl,cancelling:bd,cleaning:rl,compile:xd,cancelCompile:Sd,cleanCompile:il,viewArtifact:kd}=rw({projectId:n,project:u,mainFile:J,resolveCompileMainFile:ed,getCurrentMainFile:el,initialLatest:s?.projectId===n?s.latestCompile:null,collaborationSynced:Ye,sharedState:sn,onSharedState:Lo,save:Du,loadOutline:(m,y)=>zr({signal:m},y),onPreviewTab:pe,onError:Y,onCompileStart:()=>{Y(""),A("")},onCompileSuccess:()=>{const m=De.current;if(m){const y=fe.getCursor();Ir(m,y.line,y.column,{silent:!0})}},onPdfChanged:Mo});h.useEffect(()=>{if(!u||!J||!Bt&&Kr)return;const m=window.setTimeout(()=>p(!0),Bt?150:0);return()=>window.clearTimeout(m)},[u,Kr,Bt]),h.useEffect(()=>{const m=y=>{(y.ctrlKey||y.metaKey)&&(!y.shiftKey&&y.key.toLocaleLowerCase()==="p"?(y.preventDefault(),U(!0)):y.shiftKey&&y.key.toLocaleLowerCase()==="f"&&(y.preventDefault(),Pe(!0)))};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[]);const ol=m=>{vo(m),yh(e.id,n,m)},ll=(m=!1)=>{const y=Zt;if(!y)return;Lt(null),Y(""),m&&ol({...ot,texFmtConfig:""});const D=m?"":void 0;y.action==="selection"?Po(D):Io(D)},Cd=async()=>{Rr(!0);try{await mu()||(Y(c("editor.collaboration.permissionDowngradeOtherTabBlocked")),Rr(!1))}catch(m){Y(le(m)),Rr(!1)}},al=()=>{Ns.current?.isCollapsed()?Ns.current.expand():Ns.current?.collapse()},jd=h.useMemo(()=>E.length?E:K.filePath!==S?[]:Ww(K.content).map(m=>({...m,path:S})),[E,K,S]),Gr=h.useMemo(()=>Dh(Jr,ss),[Jr,ss]),En=be!=="pdf-only",cl=be!=="editor-only",Yr=m=>{Ie(m),m==="pdf-only"&&pe("pdf")},vd=Wr?To.filter(m=>m.filePath&&ln(Wr.path,m.filePath)):[];if(!u)return o.jsxs("div",{className:"center-card",children:[o.jsx("p",{children:P||c("common.loading")}),P&&o.jsx("button",{className:"primary",onClick:a,children:c("editor.backToProjects")})]});const qt=u.permission==="read"||!Ye,Xr=uu.find(m=>m.path===S),Qr=Xr&&!es?Xr:null,Ed=(m,y)=>{if(qt)return;const D=De.current;if(!D)return;if(Te.getText(D).toString().slice(m.from,m.to)!==m.word){Y(c("editor.spellCheckSourceChanged"));return}try{Te.applyTextEdits(D,[{from:m.from,to:m.to,replacement:y}])}catch(H){Y(le(H))}},Zr=sn?.mainFile===J&&(sn.status==="queued"||sn.status==="running"),Is=sl||Zr||rl,Dd=S?Te.getText(S):null,_d=ns?new Date(ns).toLocaleString(cs.resolvedLanguage,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"",Td=J.split("/").at(-1)??J,Ld=Gr.warnings.length+Gr.errors.length+nl.length,Rd=Bt?`${Bt}${Bt.includes("?")?"&":"?"}download=1`:"",Ad=J||u.mainFile,Nd=!!(S&&S===Ad&&/\.tex$/i.test(S)),ul=m=>{const y=gt.find(D=>D.path===m);y&&Pn(y.path)?Vr(y):_o(m)},Od=m=>{document.getElementById(`editor-tab-${encodeURIComponent(m)}`)?.focus()},Fd=(m,y)=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(m.key))return;m.preventDefault();const D=m.key==="Home"?0:m.key==="End"?Sn.length-1:(y+(m.key==="ArrowLeft"?-1:1)+Sn.length)%Sn.length,j=Sn[D];j&&(ul(j),window.requestAnimationFrame(()=>Od(j)))},dl=Is?Zr?sn?.status==="queued"?c("editor.compileQueued"):c("editor.compilingBy",{name:sn?.requestedBy.name??c("common.user")}):c("editor.compiling"):ss==="failed"?Bt&&ns?c("editor.compileFailedRetained",{time:new Date(ns).toLocaleString(cs.resolvedLanguage)}):c("editor.compileFailedNoPdf"):ss==="cancelled"?c("compileControls.cancelled"):"",Md=W==="editor.savedAt"&&he?c("editor.savedAt",{time:new Date(he).toLocaleTimeString(cs.resolvedLanguage,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):c(W);return o.jsxs("div",{className:"workspace",children:[o.jsx(pw,{site:t,project:u,activeFile:S,saveStateLabel:Md,editorPreferences:ot,activeSessions:To,collaborationStatus:Ms,reconnectCollaboration:hu,protocolUpgradeRequired:Oo,showEditor:En,filesCollapsed:re,toggleFilesPanel:al,workspaceLayout:be,changeWorkspaceLayout:Yr,onBack:a,onShare:()=>Re(!0),showCitationLibrary:En&&/\.bib$/i.test(S),citationLibraryOpen:Q,onCitationLibrary:()=>tt(!0),onSelectionHistory:()=>L(!0),onHistory:()=>N(!0),onGit:()=>dt(!0),canManageGit:u.ownerId===e.id,formatting:es,readOnly:qt,collaborationSynced:Ye,hasSelection:!!Ge.selectedText.trim(),onAddComment:()=>tl(!0),onToggleComments:()=>Be(me==="comments"?null:"comments"),commentsOpen:me==="comments",unresolvedCommentCount:vn.filter(m=>!m.resolved).length,hasActiveFile:!!S,onToggleSettings:()=>Be(me==="settings"?null:"settings"),settingsOpen:me==="settings",compileBusy:Is,sharedCompiling:Zr,localCompiling:sl,cancelling:bd,compileState:sn,onCompile:xd,onCancelCompile:()=>{Sd()}}),Oo&&o.jsxs("div",{className:"workspace-update-banner",role:"alert",children:[o.jsx(Ft,{size:15}),o.jsx("span",{children:c("workspaceUpdates.protocolUpgrade")}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:c("common.reload")})]}),dl&&o.jsxs("div",{className:`compile-status-strip${ss==="failed"?" failed":""}`,role:"status","aria-live":"polite",children:[o.jsx(it,{className:Is?"spin":"",size:14}),o.jsx("span",{children:dl})]}),(lt.error||Zt||Qr)&&o.jsxs("div",{className:"client-tool-recoveries",children:[lt.error&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:lt.error,children:[o.jsx(Ft,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:c("editor.harperRecoveryTitle")}),c("editor.harperFallbackHint")]}),o.jsx("div",{className:"client-tool-recovery-actions",children:o.jsx("button",{type:"button",onClick:lt.retry,children:c("common.retry")})}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:c("common.close"),"aria-label":c("common.close"),onClick:lt.dismissError,children:o.jsx(fs,{size:13})})]}),Zt&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:Zt.detail,children:[o.jsx(Ft,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:c(Zt.kind==="format"?"editor.texFmtOptionsRecoveryTitle":Zt.kind==="load"?"editor.texFmtRecoveryTitle":"editor.texFmtRuntimeRecoveryTitle")}),c("editor.clientToolRecoveryHint")]}),o.jsxs("div",{className:"client-tool-recovery-actions",children:[o.jsx("button",{type:"button",disabled:es||qt,onClick:()=>ll(),children:c("common.retry")}),Zt.kind==="format"&&ot.texFmtConfig.trim()&&o.jsx("button",{type:"button",disabled:es||qt,onClick:()=>ll(!0),children:c("editor.resetFormatterOptions")}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:c("common.reload")})]}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:c("common.close"),"aria-label":c("common.close"),onClick:()=>Lt(null),children:o.jsx(fs,{size:13})})]}),Qr&&o.jsxs("div",{className:"client-tool-recovery format-lease-status",role:"status",children:[o.jsx(it,{className:"spin",size:15}),o.jsx("span",{children:c("editor.formattingBy",{name:Qr.holderName})})]})]}),du&&o.jsxs("div",{className:"client-tool-recovery",role:"status",children:[o.jsx(Ft,{size:15}),o.jsx("span",{children:c("history.saveWarning")})]}),P&&o.jsx("div",{className:"toast",onClick:()=>Y(""),children:P}),Oe&&o.jsx("div",{className:"toast success",onClick:()=>A(""),children:Oe}),o.jsxs(qd,{autoSaveId:"texlite-workspace-layout",direction:"horizontal",className:"work-grid",children:[En&&o.jsx(mw,{project:u,filesPanel:Ns,files:gt,visibleEntries:Ju,activeFile:S,activeMainFile:J,rootDocuments:k,selectedFolder:Ko,expandedFolders:Iu,fileDragActive:Bu,uploadingFiles:Hu,readOnly:qt,formatting:es,canFormat:Ps(S),activeFormatLease:!!Xr,collaborationSynced:Ye,editorFontSize:ot.fontSize,outline:jd,sourceCursorStore:fe,wordCountBusy:Dr,hasSelection:!!Ge.selectedText.trim()&&/\.(?:tex|sty|cls)$/i.test(S),hasFormatSelection:!!Ge.selectedText.trim(),uploadInput:au,setSelectedFolder:qr,setExpandedFolders:Jo,setMoveEntry:Go,setMoveName:Yo,setMoveDestination:Xo,setDeleteEntry:Qo,setFileDialogError:Ho,setNewFolderName:Vo,setNewFolderOpen:Wo,setNewFilePath:Bo,setNewFileOpen:zo,setQuickOpen:U,setProjectSearchOpen:Pe,setFileDragActive:qu,setFilesCollapsed:Ce,toggleFilesPanel:al,uploadFiles:Zo,upload:Xu,openFile:Vr,onFormatFile:()=>{Io()},onFormatSelection:()=>{Po()},jumpToSource:$r,syncSourceToPdf:Ir,onWordCount:m=>{vu(m)}}),En&&o.jsx(Bi,{className:"resize-handle",children:o.jsx(pa,{size:12})}),En&&o.jsx(bw,{project:u,activeFile:S,activeMainFile:J,openTabs:Sn,content:ne,loadedFile:de,readOnly:qt,comments:vn,focusComment:td,editorPreferences:ot,completionIndex:b,nativeSpellCheck:lt.nativeFallback,spellCheckIssues:lt.issues,spellCheckJump:lt.jump,sourceJump:Su,collaborativeText:Dd,collaborationAwareness:Te.awareness,undoManager:S?Te.getUndoManager(S):void 0,editorNotice:yd,activateTab:ul,closeTab:_o,handleTabKeyDown:Fd,updateEditorContent:Pr,setSelection:(m,y,D)=>ae({selectedText:m,startOffset:y,endOffset:D}),onCommentClick:m=>{const y=vn.find(D=>D.id===m);y&&(Hr({...y}),Be("comments"))},onSpellCheckReplace:Ed,onCursor:cu}),cl&&o.jsx(vw,{projectId:n,activeMainFile:J,previewTab:$,diagnosticTab:ce,pdfUrl:Bt,pdfLoadingMode:pd,pdfLoading:Kr,pdfCompiledAt:ns,pdfCompiledLabel:_d,pdfTargetLabel:Td,pdfDownloadUrl:Rd,pdfTarget:bu,pdfViewport:xu,activeFile:S,compileBusy:Is,compileLog:Jr,compileDiagnostics:md,compileMessages:Gr,artifacts:nl,artifactPreview:gd,artifactLoading:wd,cleaning:rl,readOnly:qt,collaborationSynced:Ye,workspaceLayout:be,showSyncResize:En&&cl,diagnosticCount:Ld,selectPreviewTab:pe,changeWorkspaceLayout:Yr,onSetNotice:A,onSetPdfViewport:ku,syncVisiblePdfToSource:ju,syncCurrentSourceToPdf:()=>{const m=De.current;if(!m)return Promise.resolve();const y=fe.getCursor();return Ir(m,y.line,y.column)},syncPdfToSource:Cu,canSyncWithPdf:Nd,files:gt,jumpToSource:$r,onSetCleanMode:Pt,cleanCompile:il,viewArtifact:kd}),o.jsx(Iw,{sidePanel:me,onClose:()=>Be(null),project:u,projectId:n,site:t,files:gt,currentUserId:e.id,comments:vn,unreadMentions:Fo,onMarkMentionRead:hd,onMarkAllMentionsRead:fd,targetCommentId:Ee?.commentId,targetReplyId:Ee?.replyId,onFocusComment:m=>Hr({...m}),onToggleComment:od,onReplyComment:ld,onEditComment:ad,onDeleteComment:cd,onEditCommentReply:ud,onDeleteCommentReply:dd,dictionaryWords:w,onDictionaryChange:g,editorPreferences:ot,onEditorPreferences:ol,spellCheckCount:lt.summary?.total??null,spellCheckUniqueCount:lt.summary?.unique??null,spellCheckIndex:lt.summary?lt.index:-1,onSpellCheckNavigate:lt.jumpToIssue,onProject:f})]}),eu&&o.jsx(da,{title:c("editor.wordCountTitle"),onClose:()=>Rs(!1),children:o.jsx(zw,{open:!0,mode:tu,path:su,busy:Dr,error:iu,result:ou,onOpenChange:Rs})}),o.jsx(Fw,{user:e,project:u,projectId:n,activeFile:S,content:ne,maxCitationBibtexBytes:t.maxCitationBibtexBytes,files:gt,directoryEntries:Ku,readOnly:qt,workspaceLayout:be,changeWorkspaceLayout:Yr,resourcePreview:Au,resourcePreviewLoading:Nu,setResourcePreview:qo,setResourcePreviewLoading:Ou,uploadConflict:Wu,setUploadConflict:Vu,uploadFiles:Zo,cleanMode:ht,setCleanMode:Pt,cleanCompile:il,newFileOpen:Lu,setNewFileOpen:zo,newFilePath:Ru,setNewFilePath:Bo,newFolderOpen:Fu,setNewFolderOpen:Wo,newFolderName:Mu,setNewFolderName:Vo,selectedFolder:Ko,fileDialogError:$u,setFileDialogError:Ho,createFile:Gu,createFolder:Yu,moveEntry:Pu,setMoveEntry:Go,moveName:Uu,setMoveName:Yo,moveDestination:zu,setMoveDestination:Xo,movePath:Qu,deleteEntry:Wr,setDeleteEntry:Qo,deleteActiveSessions:vd,removePath:Zu,commentOpen:nd,setCommentOpen:tl,selection:Ge,commentText:sd,setCommentText:rd,addComment:id,shareOpen:et,setShareOpen:Re,citationLibraryOpen:Q,setCitationLibraryOpen:tt,insertCitationAtCursor:_u,quickOpen:I,setQuickOpen:U,projectSearchOpen:ue,setProjectSearchOpen:Pe,openFile:Vr,jumpToSource:$r,selectionHistoryOpen:X,setSelectionHistoryOpen:L,historyOpen:qe,setHistoryOpen:N,gitOpen:we,setGitOpen:dt,save:ts,permissionDowngrade:fu,permissionDowngradeBusy:lu,dismissPermissionDowngrade:pu,discardPermissionDraft:Cd})]})}function Ww(t){const e=[],n=/^\s*\\(part|chapter|section|subsection|subsubsection)\*?(?:\[[^\]]*\])?\{([^}]*)\}/,s={part:0,chapter:0,section:1,subsection:2,subsubsection:3};return t.split(`
27
- `).forEach((r,i)=>{const l=r.match(n);l&&e.push({level:s[l[1]],title:l[2],line:i+1})}),e}const ay=Object.freeze(Object.defineProperty({__proto__:null,ProjectWorkspace:qw},Symbol.toStringTag,{value:"Module"}));export{rh as A,ct as B,fa as C,oh as F,gl as H,ay as P,ph as R,yl as S,hm as U,iy as a,oy as b,ry as c,ly as d,gn as e,ty as f,Nt as g,Qw as h,ih as i,ey as j,Vt as k,gh as l,Ji as m,vi as n,Zw as o,jh as p,sy as r,ny as t};