texlite 0.9.1 → 0.9.3

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 (95) hide show
  1. package/DESIGN.md +36 -6
  2. package/OPERATIONS.md +70 -3
  3. package/README.md +11 -3
  4. package/README.zh-CN.md +11 -2
  5. package/THIRD_PARTY_NOTICES.md +29 -0
  6. package/dist/client/assets/AdminUsers-huwQK7Ly.js +1 -0
  7. package/dist/client/assets/CitationLibraryDialog-C5C3sPdw.js +1 -0
  8. package/dist/client/assets/Dashboard-DtHSc55D.js +2 -0
  9. package/dist/client/assets/{GitDialog-C9Loz4Al.js → GitDialog-BI7QIMsh.js} +1 -1
  10. package/dist/client/assets/{HistoryDialog-3UNN_jhU.js → HistoryDialog-DA7O9aF2.js} +1 -1
  11. package/dist/client/assets/LatexEditor-BYWWx5Km.js +138 -0
  12. package/dist/client/assets/{PdfPreview-BKhcS-2c.js → PdfPreview-mO9WS01q.js} +1 -1
  13. package/dist/client/assets/ProjectIconPickerDialog-B0q_r5dX.js +1 -0
  14. package/dist/client/assets/{ProjectNavigationDialogs-CZKTnxrl.js → ProjectNavigationDialogs-DwWYbB1A.js} +1 -1
  15. package/dist/client/assets/ProjectSettings-BpPFgdoj.js +1 -0
  16. package/dist/client/assets/ProjectWorkspace-CI2zKon5.js +32 -0
  17. package/dist/client/assets/{SelectionHistoryDialog-D3dO83lg.js → SelectionHistoryDialog-pWMI5izu.js} +2 -2
  18. package/dist/client/assets/SystemMetricsDialog-BmlO7oNg.js +1 -0
  19. package/dist/client/assets/TagManagementDialog-h4Ves4FR.js +1 -0
  20. package/dist/client/assets/{WordCountDialog-TwpyAP3m.js → WordCountDialog-DlBSP4y7.js} +1 -1
  21. package/dist/client/assets/check-BAdi_Lxq.js +1 -0
  22. package/dist/client/assets/editor-DZS7-wrd.js +14 -0
  23. package/dist/client/assets/{hard-drive-XHSiS_A7.js → hard-drive-DP2OHKMC.js} +1 -1
  24. package/dist/client/assets/index-CBrIrzgg.css +1 -0
  25. package/dist/client/assets/{index-Cd6-F29b.js → index-i5IY_PMw.js} +1 -1
  26. package/dist/client/assets/index-teah8iB2.js +12 -0
  27. package/dist/client/assets/katex-D9PXdmFF.css +1 -0
  28. package/dist/client/assets/{key-round-C-CXCWnz.js → key-round-D8sCqL2b.js} +1 -1
  29. package/dist/client/assets/{latexFormatterWorker-DYkYtcFy.js → latexFormatterWorker-BRmsns8a.js} +2 -2
  30. package/dist/client/assets/{minimize-2-BMDPVaF-.js → minimize-2-6tf519Ts.js} +1 -1
  31. package/dist/client/assets/{minus-BIa7-KuM.js → minus-CqvESp9M.js} +1 -1
  32. package/dist/client/assets/{pdf-BB1XvBIF.js → pdf-DUYcbPMK.js} +1 -1
  33. package/dist/client/assets/{plus-BKDWy4Ui.js → plus-DIrweesj.js} +1 -1
  34. package/dist/client/assets/{refresh-cw-Bo7-a7-I.js → refresh-cw-BDcwKu_d.js} +1 -1
  35. package/dist/client/assets/{search-Bz9Ob5mT.js → search-C9_Jyrnx.js} +1 -1
  36. package/dist/client/assets/{sigma-DxlHf9gv.js → sigma-p9-fBP0d.js} +1 -1
  37. package/dist/client/assets/spellCheck-Y0RlmXbl.js +1 -0
  38. package/dist/client/assets/{tags-IMZehjzE.js → tags-DjF3z21M.js} +1 -1
  39. package/dist/client/assets/{type-DTWpFQNQ.js → type-CNrDJnzR.js} +1 -1
  40. package/dist/client/assets/{user-plus--aVpd8K6.js → user-plus-C7exNawX.js} +1 -1
  41. package/dist/client/assets/x-BEVz0wdw.js +1 -0
  42. package/dist/client/index.html +6 -4
  43. package/dist/server/app.js +130 -83
  44. package/dist/server/cli.js +4 -2
  45. package/dist/server/collaboration.js +6 -19
  46. package/dist/server/compileArtifacts.js +3 -2
  47. package/dist/server/config.js +27 -0
  48. package/dist/server/db.js +91 -10
  49. package/dist/server/index.js +4 -2
  50. package/dist/server/instanceLock.js +4 -2
  51. package/dist/server/latexCompletion.js +126 -63
  52. package/dist/server/latexDocumentGraph.js +217 -0
  53. package/dist/server/latexSpellMask.js +3 -4
  54. package/dist/server/pm2.js +3 -2
  55. package/dist/server/projectOutline.js +103 -91
  56. package/dist/server/projectReferences.js +109 -0
  57. package/dist/server/routes/auth.js +5 -2
  58. package/dist/server/routes/comments.js +10 -4
  59. package/dist/server/routes/compile.js +2 -2
  60. package/dist/server/routes/projectFiles.js +12 -3
  61. package/dist/server/routes/projectReferences.js +36 -0
  62. package/dist/server/routes/projectShared.js +33 -12
  63. package/dist/server/routes/projects.js +5 -0
  64. package/dist/server/routes/system.js +1 -0
  65. package/dist/server/zip.js +2 -16
  66. package/dist/shared/basePath.js +44 -0
  67. package/dist/shared/bibtexReferences.js +135 -0
  68. package/dist/shared/collaborationProtocol.js +31 -0
  69. package/dist/shared/latexCommandSnippets.js +91 -0
  70. package/dist/shared/latexDependencies.js +131 -0
  71. package/dist/shared/latexLiterals.js +215 -0
  72. package/dist/shared/latexReferenceCommands.js +75 -0
  73. package/dist/shared/latexReferences.js +193 -0
  74. package/dist/shared/latexRoot.js +21 -0
  75. package/dist/shared/latexScanner.js +183 -0
  76. package/dist/shared/writingChecks.js +4 -0
  77. package/package.json +11 -4
  78. package/texlite.config.example.json +2 -4
  79. package/dist/client/assets/AdminUsers-Dazar9cj.js +0 -1
  80. package/dist/client/assets/CitationLibraryDialog-VSUiSPgG.js +0 -1
  81. package/dist/client/assets/Dashboard-CoE5ESfb.js +0 -2
  82. package/dist/client/assets/LatexEditor-Bq76v8sO.js +0 -65
  83. package/dist/client/assets/ProjectIconPickerDialog-BoWMjQVm.js +0 -1
  84. package/dist/client/assets/ProjectSettings-DiOQVJ40.js +0 -1
  85. package/dist/client/assets/ProjectWorkspace-DqLwkGpT.js +0 -27
  86. package/dist/client/assets/SystemMetricsDialog-0zCwLtH_.js +0 -1
  87. package/dist/client/assets/TagManagementDialog-C6KDwtvd.js +0 -1
  88. package/dist/client/assets/check-sZxOOKtS.js +0 -1
  89. package/dist/client/assets/chevron-left-32SrOwa5.js +0 -1
  90. package/dist/client/assets/editor-CiK7TK0p.js +0 -14
  91. package/dist/client/assets/index-BRr3Kuxh.css +0 -1
  92. package/dist/client/assets/index-BjzELSQ-.js +0 -12
  93. package/dist/client/assets/katex-CEK31ho9.css +0 -1
  94. package/dist/client/assets/spellCheck-BfZEnpwY.js +0 -1
  95. package/dist/client/assets/x-Tbo3aA0J.js +0 -1
@@ -0,0 +1,32 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./spellCheck-Y0RlmXbl.js","./index-teah8iB2.js","./react-BVUjbTTn.js","./index-CBrIrzgg.css","./check-BAdi_Lxq.js","./x-BEVz0wdw.js","./search-C9_Jyrnx.js","./user-plus-C7exNawX.js","./refresh-cw-BDcwKu_d.js","./LatexEditor-BYWWx5Km.js","./editor-DZS7-wrd.js","./CitationLibraryDialog-C5C3sPdw.js","./citationLibrary-ZeQPCv5O.js","./plus-DIrweesj.js","./tags-DjF3z21M.js","./GitDialog-BI7QIMsh.js","./key-round-D8sCqL2b.js","./minus-CqvESp9M.js","./minimize-2-6tf519Ts.js","./HistoryDialog-DA7O9aF2.js","./index-i5IY_PMw.js","./hard-drive-DP2OHKMC.js","./SelectionHistoryDialog-pWMI5izu.js","./ProjectNavigationDialogs-DwWYbB1A.js","./ProjectSettings-BpPFgdoj.js","./type-CNrDJnzR.js","./sigma-p9-fBP0d.js","./WordCountDialog-DlBSP4y7.js"])))=>i.map(i=>d[i]);
2
+ import{c as Me,s as pn,g as le,h as de,a as Dr,A as Ii,n as Th,l as Ah,r as Nh,_ as vt,S as Fh,d as st,i as ws,j as za,C as xs,M as Yt,e as Ba,k as Oh}from"./index-teah8iB2.js";import{r as d,u as Ge,j as o,P as _r,d as lo,e as Mh}from"./react-BVUjbTTn.js";import{C as $h}from"./check-BAdi_Lxq.js";import{e as Ih,U as Pi,B as Ph,M as Uh,G as zh,X as ks,F as Bh,f as $l,g as qh,a as Wh,C as ao,b as Hh,T as en,c as qa,d as Vn,L as Vh,j as Pt,S as Ui,D as ar,A as cr,P as Il,i as Pl,h as Kh}from"./x-BEVz0wdw.js";import{S as Jh}from"./search-C9_Jyrnx.js";import{U as Gh}from"./user-plus-C7exNawX.js";import{R as Yh}from"./refresh-cw-BDcwKu_d.js";const Xh=Me("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);const co=Me("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const Qh=Me("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const uo=Me("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 Ul=Me("Columns2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]);const zi=Me("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 Zh=Me("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 ef=Me("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 Wa=Me("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 zl=Me("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 tf=Me("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 Bl=Me("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 Ha=Me("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 Va=Me("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 nf=Me("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 sf=Me("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);const rf=Me("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);const of=Me("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);const lf=Me("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 af=Me("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 ql=Me("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 cf=Me("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 uf=Me("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"}]]),df="wrap = false",Bi=[{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'}],mt={font:"jetbrains",fontSize:14,lineHeight:1.65,lineWrapping:!0,showTooltips:!1,spellCheck:!0,mathPreviewOnHover:!1,vimMode:!1,formatOnCompile:!1,texFmtConfig:df,texFmtConfigInitialized:!0,openFilesInTabs:!1},hf="texlite-editor-preferences";function Ka(t,e){return pn(`${hf}:${encodeURIComponent(t)}:${encodeURIComponent(e)}`)}function Nb(t){return Bi.find(e=>e.id===t)?.stack??Bi[0].stack}function Wl(t,e){try{const n=JSON.parse(localStorage.getItem(Ka(t,e))??"{}"),s=typeof n.texFmtConfig=="string"&&n.texFmtConfig.length<=16*1024?n.texFmtConfig:null,r=s!==null&&(n.texFmtConfigInitialized===!0||s.trim().length>0)?s:mt.texFmtConfig;return{font:Bi.some(i=>i.id===n.font)?n.font:mt.font,fontSize:[12,13,14,15,16,18,20].includes(Number(n.fontSize))?Number(n.fontSize):mt.fontSize,lineHeight:[1.45,1.65,1.85].includes(Number(n.lineHeight))?Number(n.lineHeight):mt.lineHeight,lineWrapping:typeof n.lineWrapping=="boolean"?n.lineWrapping:mt.lineWrapping,showTooltips:typeof n.showTooltips=="boolean"?n.showTooltips:mt.showTooltips,spellCheck:typeof n.spellCheck=="boolean"?n.spellCheck:mt.spellCheck,mathPreviewOnHover:typeof n.mathPreviewOnHover=="boolean"?n.mathPreviewOnHover:mt.mathPreviewOnHover,vimMode:typeof n.vimMode=="boolean"?n.vimMode:mt.vimMode,formatOnCompile:typeof n.formatOnCompile=="boolean"?n.formatOnCompile:mt.formatOnCompile,texFmtConfig:r,texFmtConfigInitialized:!0,openFilesInTabs:typeof n.openFilesInTabs=="boolean"?n.openFilesInTabs:mt.openFilesInTabs}}catch{return mt}}function ff(t,e,n){localStorage.setItem(Ka(t,e),JSON.stringify(n))}function pf(){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 Xt=pf(),mf=/\.(?:tex|bib|cls|sty)$/i,Ja=3e4;let xt=null,ur=!1,mn=null,gf=1;const yn=new Map,dr=[];let $n=null,ps=null;class dt extends Error{constructor(e,n){super(n),this.kind=e,this.name="TexFmtError"}kind}function gi(t){return t instanceof dt}function It(t){xt?.terminate(),xt=null,ur=!1,mn!==null&&window.clearTimeout(mn),mn=null,$n=null,dr.length=0,ps=null,Xt.failed(t);for(const e of yn.values())e.timeout!==null&&window.clearTimeout(e.timeout),e.reject(t);yn.clear()}function ys(){if($n!==null||dr.length===0)return;let t;try{t=wf()}catch(s){It(s instanceof dt?s:new dt("load","The bundled tex-fmt formatter could not be loaded."));return}if(!ur)return;const e=dr.shift();if(e===void 0)return;const n=yn.get(e);if(!n){ys();return}$n=e,n.timeout=window.setTimeout(()=>{$n===e&&It(new dt("result","The formatter did not respond within 30 seconds."))},Ja);try{t.postMessage({...n.request,id:e})}catch{It(new dt("load","The formatter worker could not receive the source."))}}function wf(){if(xt)return xt;if(typeof Worker>"u"){const t=new dt("load","This browser does not support formatter workers.");throw Xt.failed(t),t}Xt.loading();try{xt=new Worker(new URL(""+new URL("latexFormatterWorker-BRmsns8a.js",import.meta.url).href,import.meta.url),{type:"module",name:"texlite-latex-formatter"}),mn=window.setTimeout(()=>{ur||It(new dt("load","The formatter did not finish loading within 30 seconds."))},Ja)}catch{const t=new dt("load","The bundled tex-fmt formatter could not be loaded.");throw Xt.failed(t),t}return xt.onmessage=t=>{const e=t.data;if(e&&"type"in e){e.type==="ready"&&(ur=!0,mn!==null&&window.clearTimeout(mn),mn=null,ys());return}if(!e||typeof e.id!="number"){It(new dt("result","The formatter worker returned an invalid response."));return}const n=yn.get(e.id);if(n)if(yn.delete(e.id),n.timeout!==null&&window.clearTimeout(n.timeout),$n===e.id&&($n=null),e.ok)Xt.working(),n.resolve(e.result),ys();else{const s=new dt(e.kind,e.message);e.kind==="format"?(Xt.working(),n.reject(s),ys()):(n.reject(s),It(s))}},xt.onerror=()=>{It(new dt("load","The bundled tex-fmt formatter could not be loaded."))},xt.onmessageerror=()=>{It(new dt("result","The formatter worker returned an unreadable response."))},xt}function ho(t){const e=gf++;return new Promise((n,s)=>{yn.set(e,{request:t,resolve:n,reject:s,timeout:null}),dr.push(e),ys()})}function yf(t,e=""){return ho({action:"format",source:t,config:e})}async function bf(){xt&&Xt.getSnapshot().status==="working"||(ps||(ps=ho({action:"probe"}).then(()=>{}).finally(()=>{ps=null})),await ps)}async function Fb(){(xt||yn.size)&&It(new dt("load","The formatter runtime was reloaded.")),Xt.loading(),await bf()}function Qs(t){return mf.test(t)}function xf(t){return t.match(/(?:\r?\n)+$/)?.[0]??""}function kf(t,e){const n=xf(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 wi(t,e,n=0){return ho({action:"diff",source:t,formatted:e,baseOffset:n})}function Sf(t,e=null){const n=Hl(t),r=e==="succeeded"||e===null&&vf(t)?[]:Vl(n.filter(Kl)),i=Hl(Cf(t));return{warnings:Vl(i.filter(a=>!Kl(a)&&jf(a))),errors:r}}function Hl(t){return t.split(`
5
+ `).map(e=>e.trim()).filter(Boolean)}function Vl(t){return[...new Set(t)]}function Cf(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 vf(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 jf(t){return/\bwarnings?\b|overfull|underfull|badness/i.test(t)}const Jl=1,Gl=2,yi=4,bi=8,Ss=32,Ut=64,rt=128,Ef=1<<29,Lr=31,qi=63,wn=127,Df=2147483647,Dt=(t,e)=>t>>>e|t<<32-e,_f=t=>Dt(t,2)^Dt(t,13)^Dt(t,22),Lf=t=>Dt(t,6)^Dt(t,11)^Dt(t,25),Rf=t=>Dt(t,7)^Dt(t,18)^t>>>3,Tf=t=>Dt(t,17)^Dt(t,19)^t>>>10,Af=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Nf=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);class Ff{constructor(){const e=new ArrayBuffer(320);this._H=new Uint32Array(e,0,8),this._H.set(Nf),this._W=new Uint32Array(e,64,64)}_updateHash(){const e=this._H,n=this._W;for(let h=16;h<64;h++)n[h]=Tf(n[h-2])+n[h-7]+Rf(n[h-15])+n[h-16];let s=e[0],r=e[1],i=e[2],l=e[3],a=e[4],c=e[5],u=e[6],f=e[7];for(let h=0,p,w;h<64;h++)p=f+Lf(a)+(a&c^~a&u)+Af[h]+n[h]>>>0,w=_f(s)+(s&r^s&i^r&i)>>>0,f=u,u=c,c=a,a=l+p>>>0,l=i,i=r,r=s,s=p+w>>>0;e[0]+=s,e[1]+=r,e[2]+=i,e[3]+=l,e[4]+=a,e[5]+=c,e[6]+=u,e[7]+=f}digest(e){let n=0;for(;n+56<=e.length;){let l=0;for(;l<16&&n+3<e.length;l++)this._W[l]=e[n++]<<24|e[n++]<<16|e[n++]<<8|e[n++];if(n%64!==0){for(this._W.fill(0,l,16);n<e.length;)this._W[l]|=e[n]<<(3-n%4)*8,n++;this._W[l]|=rt<<(3-n%4)*8}this._updateHash()}const s=n%64!==0;this._W.fill(0,0,16);let r=0;for(;n<e.length;r++)for(let l=3;l>=0&&n<e.length;l--)this._W[r]|=e[n++]<<l*8;s||(this._W[r-(n%4===0?0:1)]|=rt<<(3-n%4)*8),this._W[14]=e.byteLength/Ef,this._W[15]=e.byteLength*8,this._updateHash();const i=new Uint8Array(32);for(let l=0;l<this._H.length;l++)for(let a=0;a<4;a++)i[l*4+a]=this._H[l]>>>(3-a)*8;return i}}const Of=t=>new Ff().digest(t);function Mf(t){return Array.from(Of(new TextEncoder().encode(t)),e=>e.toString(16).padStart(2,"0")).join("")}function Yl(t){return t instanceof Error&&t.name==="AbortError"}function $f({projectId:t,activeFile:e,content:n,permission:s,revision:r,selection:i,save:l,saveFailureMessage:a,onError:c,onAdded:u,onChanged:f}){const[h,p]=d.useState({filePath:"",comments:[],loading:!1}),[w,g]=d.useState([]),[S,v]=d.useState(!1),[C,$]=d.useState(""),[x,R]=d.useState("file"),[T,D]=d.useState(null),[L,F]=d.useState(!1),[te,re]=d.useState(""),[J,G]=d.useState(null),[me,z]=d.useState(!1),[Q,V]=d.useState(""),ne=d.useRef(null),K=d.useRef(null),fe=d.useRef(!1),Z=d.useRef(e),ge=d.useRef(x),ie=d.useRef(l),pe=d.useRef(c),b=d.useRef(u),O=d.useRef(f);Z.current=e,ge.current=x,ie.current=l,pe.current=c,b.current=u,O.current=f;const X=h.filePath===e?h.comments:[],ye=h.filePath,ce=ye===e&&!h.loading,be=async N=>{ne.current?.abort();const k=new AbortController;ne.current=k,Z.current===N&&p(B=>B.filePath===N?{...B,loading:!0}:{filePath:"",comments:[],loading:!0});try{const B=await le(`/api/projects/${t}/comments?path=${encodeURIComponent(N)}`,{signal:k.signal});ne.current===k&&Z.current===N&&p({filePath:N,comments:B.comments,loading:!1})}catch(B){!Yl(B)&&ne.current===k&&Z.current===N&&p({filePath:N,comments:[],loading:!1})}finally{ne.current===k&&(ne.current=null)}},Se=async()=>{K.current?.abort();const N=new AbortController;K.current=N,ge.current==="project"&&(v(!0),$(""));try{const k=await le(`/api/projects/${t}/comments?scope=project`,{signal:N.signal});K.current===N&&ge.current==="project"&&g(k.comments)}catch(k){!Yl(k)&&K.current===N&&ge.current==="project"&&$(de(k))}finally{K.current===N&&(K.current=null,ge.current==="project"&&v(!1))}};d.useEffect(()=>{ne.current?.abort(),ne.current=null,K.current?.abort(),K.current=null,D(null),p({filePath:"",comments:[],loading:!1}),g([]),v(!1),$(""),R("file"),F(!1),G(null),V("")},[t]),d.useEffect(()=>{F(!1),G(null),V("")},[e]),d.useEffect(()=>(e?be(e):p({filePath:"",comments:[],loading:!1}),()=>{ne.current?.abort(),ne.current=null}),[t,e,r]),d.useEffect(()=>{if(x!=="project"){K.current?.abort(),K.current=null,g([]),v(!1),$("");return}return Se(),()=>{K.current?.abort(),K.current=null}},[t,x,r]);const M=async N=>{const k=[];Z.current===N&&k.push(be(N)),ge.current==="project"&&k.push(Se()),await Promise.all(k)},Te=(N,k)=>{e&&(V(""),G({filePath:e,selection:{...N??i},sourceHash:Mf(k??n)}),F(!0))},_e=()=>{fe.current||(F(!1),G(null),V(""))},_=async()=>{const N=J;if(!(!te.trim()||!N||fe.current)){fe.current=!0,z(!0),V("");try{if(s!=="read"&&!await ie.current()){V(a);return}await le(`/api/projects/${t}/comments`,{method:"POST",body:JSON.stringify({path:N.filePath,content:te,...N.selection,sourceHash:N.sourceHash})}),await M(N.filePath),F(!1),G(null),re(""),b.current(),O.current?.()}catch(k){V(de(k))}finally{fe.current=!1,z(!1)}}},Oe=async N=>{try{await le(`/api/projects/${t}/comments/${N.id}`,{method:"PATCH",body:JSON.stringify({resolved:!N.resolved})}),await M(N.filePath),O.current?.()}catch(k){pe.current(de(k))}},we=async(N,k)=>{try{return await le(`/api/projects/${t}/comments/${N.id}/replies`,{method:"POST",body:JSON.stringify({content:k})}),await M(N.filePath),O.current?.(),!0}catch(B){return pe.current(de(B)),!1}},ke=async(N,k)=>{try{return await le(`/api/projects/${t}/comments/${N.id}`,{method:"PATCH",body:JSON.stringify({content:k})}),await M(N.filePath),O.current?.(),!0}catch(B){return pe.current(de(B)),!1}},A=async N=>{try{return await le(`/api/projects/${t}/comments/${N.id}`,{method:"DELETE"}),await M(N.filePath),D(k=>k?.id===N.id?null:k),O.current?.(),!0}catch(k){return pe.current(de(k)),!1}},ue=async(N,k,B)=>{try{return await le(`/api/projects/${t}/comments/${N.id}/replies/${k}`,{method:"PATCH",body:JSON.stringify({content:B})}),await M(N.filePath),O.current?.(),!0}catch(Ce){return pe.current(de(Ce)),!1}},Re=async(N,k)=>{try{return await le(`/api/projects/${t}/comments/${N.id}/replies/${k}`,{method:"DELETE"}),await M(N.filePath),O.current?.(),!0}catch(B){return pe.current(de(B)),!1}};return{comments:X,commentsFilePath:ye,commentsReady:ce,reviewComments:x==="file"?X:w,reviewCommentsLoading:x==="project"&&S,reviewCommentsError:x==="project"?C:"",retryReviewComments:Se,commentScope:x,setCommentScope:R,focusComment:T,setFocusComment:D,commentOpen:L,openComment:Te,closeComment:_e,commentText:te,setCommentText:re,commentSelection:J?.selection??i,commentSubmitting:me,commentError:Q,addComment:_,toggleComment:Oe,replyToComment:we,editComment:ke,deleteComment:A,editCommentReply:ue,deleteCommentReply:Re}}function Ga(t,e){return e.scope==="project"||t.filePath===e.activeFile}function fo(t,e,n){return e==="unresolved"?!t.resolved:e==="resolved"?t.resolved:n.some(s=>s.commentId===t.id)}function xi(t,e){return t.filter(n=>Ga(n,e)&&fo(n,e.filter,e.unreadMentions))}function If(t,e,n=[]){const s=new Set(n.filter(r=>!!r));return t.filter(r=>Ga(r,e)?s.has(r.id)||fo(r,e.filter,e.unreadMentions):!1)}function Pf(t,e){return t.filter(n=>n.filePath===e)}function Uf(t,e,n){return!t||t.filePath!==e||n!==e?null:t}function zf(t,e,n,s,r,i){return!t||t.filePath!==e||n!==e||s!==e||!r?null:i.find(l=>l.id===t.id&&l.filePath===e)??null}function Bf(t,e,n){return!fo({...t,resolved:!t.resolved},e,n)}function qf(t,e){if(!e)return 0;const n=t.findIndex(s=>s.id===e);return n<0?0:n+1}function Wf(t,e,n){if(!t.length)return null;const s=e?t.findIndex(i=>i.id===e):-1;if(s<0)return n===1?t[0]:null;const r=s+n;return r>=0&&r<t.length?t[r]:null}function Hf(t){return t instanceof Error&&t.name==="AbortError"}function Vf(t,e,n){const[s,r]=d.useState([]),i=d.useRef(null),l=d.useRef(n);l.current=n;const a=d.useCallback(async(f=!1)=>{i.current?.abort();const h=new AbortController;i.current=h;try{const p=await le(`/api/projects/${t}/mentions?unread=1&limit=100`,{signal:h.signal});i.current===h&&r(p.mentions)}catch(p){i.current===h&&!Hf(p)&&(r([]),f&&l.current(de(p)))}finally{i.current===h&&(i.current=null)}},[t]);return d.useEffect(()=>(a(),()=>{i.current?.abort(),i.current=null}),[a,e]),{unreadMentions:s,refresh:a,markMentionRead:async f=>{try{return await le(`/api/projects/${t}/mentions/${encodeURIComponent(f)}/read`,{method:"POST"}),r(h=>h.filter(p=>p.id!==f)),!0}catch(h){return l.current(de(h)),!1}},markAllMentionsRead:async()=>{if(!s.length)return!0;try{return await le(`/api/projects/${t}/mentions/read-all`,{method:"POST"}),r([]),!0}catch(f){return l.current(de(f)),!1}}}}const ct=()=>new Map,Wi=t=>{const e=ct();return t.forEach((n,s)=>{e.set(s,n)}),e},Rt=(t,e,n)=>{let s=t.get(e);return s===void 0&&t.set(e,s=n()),s},Kf=(t,e)=>{const n=[];for(const[s,r]of t)n.push(e(r,s));return n},Jf=(t,e)=>{for(const[n,s]of t)if(e(s,n))return!0;return!1},tn=()=>new Set,ki=t=>t[t.length-1],Gf=(t,e)=>{for(let n=0;n<e.length;n++)t.push(e[n])},zt=Array.from,po=(t,e)=>{for(let n=0;n<t.length;n++)if(!e(t[n],n,t))return!1;return!0},mo=(t,e)=>{for(let n=0;n<t.length;n++)if(e(t[n],n,t))return!0;return!1},Yf=(t,e)=>{const n=new Array(t);for(let s=0;s<t;s++)n[s]=e(s,n);return n},Kn=Array.isArray;class go{constructor(){this._observers=ct()}on(e,n){return Rt(this._observers,e,tn).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 zt((this._observers.get(e)||ct()).values()).forEach(s=>s(...n))}destroy(){this._observers=ct()}}class Ya{constructor(){this._observers=ct()}on(e,n){Rt(this._observers,e,tn).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 zt((this._observers.get(e)||ct()).values()).forEach(s=>s(...n))}destroy(){this._observers=ct()}}const St=Math.floor,sr=Math.abs,wo=(t,e)=>t<e?t:e,Sn=(t,e)=>t>e?t:e,Xf=Math.pow,Xa=t=>t!==0?t<0:1/t<0,hr=Number.MAX_SAFE_INTEGER,Xl=Number.MIN_SAFE_INTEGER,Qf=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&St(t)===t),Qa=String.fromCharCode,Zf=t=>t.toLowerCase(),ep=/^\s*/g,tp=t=>t.replace(ep,""),np=/([A-Z])/g,Ql=(t,e)=>tp(t.replace(np,n=>`${e}${Zf(n)}`)),sp=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},Cs=typeof TextEncoder<"u"?new TextEncoder:null,rp=t=>Cs.encode(t),ip=Cs?rp:sp;let bs=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});bs&&bs.decode(new Uint8Array).length===1&&(bs=null);const op=(t,e)=>Yf(e,()=>t).join("");class Ns{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Ie=()=>new Ns,yo=t=>{let e=t.cpos;for(let n=0;n<t.bufs.length;n++)e+=t.bufs[n].length;return e},je=t=>{const e=new Uint8Array(yo(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},lp=(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(Sn(n,e)*2),t.cpos=0)},Ke=(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},Hi=Ke,H=(t,e)=>{for(;e>wn;)Ke(t,rt|wn&e),e=St(e/128);Ke(t,wn&e)},bo=(t,e)=>{const n=Xa(e);for(n&&(e=-e),Ke(t,(e>qi?rt:0)|(n?Ut:0)|qi&e),e=St(e/64);e>0;)Ke(t,(e>wn?rt:0)|wn&e),e=St(e/128)},Vi=new Uint8Array(3e4),ap=Vi.length/3,cp=(t,e)=>{if(e.length<ap){const n=Cs.encodeInto(e,Vi).written||0;H(t,n);for(let s=0;s<n;s++)Ke(t,Vi[s])}else $e(t,ip(e))},up=(t,e)=>{const n=unescape(encodeURIComponent(e)),s=n.length;H(t,s);for(let r=0;r<s;r++)Ke(t,n.codePointAt(r))},Qe=Cs&&Cs.encodeInto?cp:up,Rr=(t,e)=>{const n=t.cbuf.length,s=t.cpos,r=wo(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(Sn(n*2,i)),t.cbuf.set(e.subarray(r)),t.cpos=i)},$e=(t,e)=>{H(t,e.byteLength),Rr(t,e)},xo=(t,e)=>{lp(t,e);const n=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,n},dp=(t,e)=>xo(t,4).setFloat32(0,e,!1),hp=(t,e)=>xo(t,8).setFloat64(0,e,!1),fp=(t,e)=>xo(t,8).setBigInt64(0,e,!1),Zl=new DataView(new ArrayBuffer(4)),pp=t=>(Zl.setFloat32(0,t),Zl.getFloat32(0)===t),vs=(t,e)=>{switch(typeof e){case"string":Ke(t,119),Qe(t,e);break;case"number":Qf(e)&&sr(e)<=Df?(Ke(t,125),bo(t,e)):pp(e)?(Ke(t,124),dp(t,e)):(Ke(t,123),hp(t,e));break;case"bigint":Ke(t,122),fp(t,e);break;case"object":if(e===null)Ke(t,126);else if(Kn(e)){Ke(t,117),H(t,e.length);for(let n=0;n<e.length;n++)vs(t,e[n])}else if(e instanceof Uint8Array)Ke(t,116),$e(t,e);else{Ke(t,118);const n=Object.keys(e);H(t,n.length);for(let s=0;s<n.length;s++){const r=n[s];Qe(t,r),vs(t,e[r])}}break;case"boolean":Ke(t,e?120:121);break;default:Ke(t,127)}};class ea extends Ns{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&H(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const ta=t=>{t.count>0&&(bo(t.encoder,t.count===1?t.s:-t.s),t.count>1&&H(t.encoder,t.count-2))};class rr{constructor(){this.encoder=new Ns,this.s=0,this.count=0}write(e){this.s===e?this.count++:(ta(this),this.count=1,this.s=e)}toUint8Array(){return ta(this),je(this.encoder)}}const na=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);bo(t.encoder,e),t.count>1&&H(t.encoder,t.count-2)}};class Si{constructor(){this.encoder=new Ns,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(na(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return na(this),je(this.encoder)}}class mp{constructor(){this.sarr=[],this.s="",this.lensE=new rr}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 Ns;return this.sarr.push(this.s),this.s="",Qe(e,this.sarr.join("")),Rr(e,this.lensE.toUint8Array()),je(e)}}const Ct=t=>new Error(t),kt=()=>{throw Ct("Method unimplemented")},ht=()=>{throw Ct("Unexpected case")},Za=Ct("Unexpected end of array"),ec=Ct("Integer out of Range");class Tr{constructor(e){this.arr=e,this.pos=0}}const rn=t=>new Tr(t),Ki=t=>t.pos!==t.arr.length,gp=(t,e)=>{const n=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,n},et=t=>gp(t,oe(t)),Jn=t=>t.arr[t.pos++],oe=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&wn)*n,n*=128,r<rt)return e;if(e>hr)throw ec}throw Za},ko=t=>{let e=t.arr[t.pos++],n=e&qi,s=64;const r=(e&Ut)>0?-1:1;if((e&rt)===0)return r*n;const i=t.arr.length;for(;t.pos<i;){if(e=t.arr[t.pos++],n=n+(e&wn)*s,s*=128,e<rt)return r*n;if(n>hr)throw ec}throw Za},wp=t=>{let e=oe(t);if(e===0)return"";{let n=String.fromCodePoint(Jn(t));if(--e<100)for(;e--;)n+=String.fromCodePoint(Jn(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))}},yp=t=>bs.decode(et(t)),Fe=bs?yp:wp,So=(t,e)=>{const n=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,n},bp=t=>So(t,4).getFloat32(0,!1),xp=t=>So(t,8).getFloat64(0,!1),kp=t=>So(t,8).getBigInt64(0,!1),Sp=[t=>{},t=>null,ko,bp,xp,kp,t=>!1,t=>!0,Fe,t=>{const e=oe(t),n={};for(let s=0;s<e;s++){const r=Fe(t);n[r]=js(t)}return n},t=>{const e=oe(t),n=[];for(let s=0;s<e;s++)n.push(js(t));return n},et],js=t=>Sp[127-Jn(t)](t);class sa extends Tr{constructor(e,n){super(e),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Ki(this)?this.count=oe(this)+1:this.count=-1),this.count--,this.s}}class ir extends Tr{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=ko(this);const e=Xa(this.s);this.count=1,e&&(this.s=-this.s,this.count=oe(this)+2)}return this.count--,this.s}}class Ci extends Tr{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=ko(this),n=e&1;this.diff=St(e/2),this.count=1,n&&(this.count=oe(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Cp{constructor(e){this.decoder=new ir(e),this.str=Fe(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 vp=crypto.getRandomValues.bind(crypto),tc=()=>vp(new Uint32Array(1))[0],jp="10000000-1000-4000-8000"+-1e11,Ep=()=>jp.replace(/[018]/g,t=>(t^tc()&15>>t/4).toString(16)),nn=Date.now,Gn=t=>new Promise(t);Promise.all.bind(Promise);const ra=t=>t===void 0?null:t;class Dp{constructor(){this.map=new Map}setItem(e,n){this.map.set(e,n)}getItem(e){return this.map.get(e)}}let nc=new Dp,Co=!0;try{typeof localStorage<"u"&&localStorage&&(nc=localStorage,Co=!1)}catch{}const sc=nc,_p=t=>Co||addEventListener("storage",t),Lp=t=>Co||removeEventListener("storage",t),Es=Symbol("Equality"),rc=(t,e)=>t===e||!!t?.[Es]?.(e)||!1,Rp=t=>typeof t=="object",Tp=Object.assign,Ap=Object.keys,Np=(t,e)=>{for(const n in t)e(t[n],n)},Fp=(t,e)=>{const n=[];for(const s in t)n.push(e(t[s],s));return n},fr=t=>Ap(t).length,Op=t=>{for(const e in t)return!1;return!0},Fs=(t,e)=>{for(const n in t)if(!e(t[n],n))return!1;return!0},vo=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Mp=(t,e)=>t===e||fr(t)===fr(e)&&Fs(t,(n,s)=>(n!==void 0||vo(e,s))&&rc(e[s],n)),$p=Object.freeze,ic=t=>{for(const e in t){const n=t[e];(typeof n=="object"||typeof n=="function")&&ic(t[e])}return $p(t)},jo=(t,e,n=0)=>{try{for(;n<t.length;n++)t[n](...e)}finally{n<t.length&&jo(t,e,n+1)}},Ip=t=>t,In=(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[Es]!=null)return t[Es](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)||!In(t.get(n),e.get(n)))return!1;break}case void 0:case Object:if(fr(t)!==fr(e))return!1;for(const n in t)if(!vo(t,n)||!In(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(!In(t[n],e[n]))return!1;break;default:return!1}return!0},Pp=(t,e)=>e.includes(t);var oc={};const sn=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",lc=typeof window<"u"&&typeof document<"u"&&!sn;let Et;const Up=()=>{if(Et===void 0)if(sn){Et=ct();const t=process.argv;let e=null;for(let n=0;n<t.length;n++){const s=t[n];s[0]==="-"?(e!==null&&Et.set(e,""),e=s):e!==null&&(Et.set(e,s),e=null)}e!==null&&Et.set(e,"")}else typeof location=="object"?(Et=ct(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){const[e,n]=t.split("=");Et.set(`--${Ql(e,"-")}`,n),Et.set(`-${Ql(e,"-")}`,n)}})):Et=ct();return Et},Ji=t=>Up().has(t),pr=t=>ra(sn?oc[t.toUpperCase().replaceAll("-","_")]:sc.getItem(t)),ac=t=>Ji("--"+t)||pr(t)!==null,zp=ac("production"),Bp=sn&&Pp(oc.FORCE_COLOR,["true","1","2"]),qp=Bp||!Ji("--no-colors")&&!ac("no-color")&&(!sn||process.stdout.isTTY)&&(!sn||Ji("--color")||pr("COLORTERM")!==null||(pr("TERM")||"").includes("color")),cc=t=>new Uint8Array(t),Wp=(t,e,n)=>new Uint8Array(t,e,n),Hp=t=>new Uint8Array(t),Vp=t=>{let e="";for(let n=0;n<t.byteLength;n++)e+=Qa(t[n]);return btoa(e)},Kp=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),Jp=t=>{const e=atob(t),n=cc(e.length);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return n},Gp=t=>{const e=Buffer.from(t,"base64");return Wp(e.buffer,e.byteOffset,e.byteLength)},Yp=lc?Vp:Kp,Xp=lc?Jp:Gp,Qp=t=>{const e=cc(t.byteLength);return e.set(t),e};class Zp{constructor(e,n){this.left=e,this.right=n}}const $t=(t,e)=>new Zp(t,e),em=(t,e)=>t.forEach(n=>e(n.left,n.right)),ia=t=>t.next()>=.5,vi=(t,e,n)=>St(t.next()*(n+1-e)+e),uc=(t,e,n)=>St(t.next()*(n+1-e)+e),Eo=(t,e,n)=>uc(t,e,n),tm=t=>Qa(Eo(t,97,122)),nm=(t,e=0,n=20)=>{const s=Eo(t,e,n);let r="";for(let i=0;i<s;i++)r+=tm(t);return r},ji=(t,e)=>e[Eo(t,0,e.length-1)],sm=Symbol("0schema");class rm{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(op(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return e.join(`
6
+ `)}}const Gi=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[Es]?rc(t,e):Kn(t)?po(t,n=>mo(e,s=>Gi(n,s))):Rp(t)?Fs(t,(n,s)=>Gi(n,e[s])):!1;class it{static _dilutes=!1;extends(e){let[n,s]=[this.shape,e.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Gi(n,s)}equals(e){return this.constructor===e.constructor&&In(this.shape,e.shape)}[sm](){return!0}[Es](e){return this.equals(e)}validate(e){return this.check(e)}check(e,n){kt()}get nullable(){return ns(this,Mr)}get optional(){return new fc(this)}cast(e){return oa(e,this),e}expect(e){return oa(e,this),e}}class Do extends it{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 Be=(t,e=null)=>new Do(t,e);Be(Do);class _o extends it{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 Ye=t=>new _o(t);Be(_o);class Ar extends it{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 Nr=(...t)=>new Ar(t),dc=Be(Ar),im=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),hc=t=>{if(Yn.check(t))return[im(t)];if(dc.check(t))return t.shape.map(e=>e+"");if(Sc.check(t))return["[+-]?\\d+.?\\d*"];if(Cc.check(t))return[".*"];if(mr.check(t))return t.shape.map(hc).flat(1);ht()};class om extends it{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(hc).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}}Be(om);const lm=Symbol("optional");class fc extends it{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[lm](){return!0}}const am=Be(fc);class cm extends it{check(e,n){return n?.extend(null,"never",typeof e),!1}}Be(cm);class Fr extends it{constructor(e,n=!1){super(),this.shape=e,this._isPartial=n}static _dilutes=!0;get partial(){return new Fr(this.shape,!0)}check(e,n){return e==null?(n?.extend(null,"object","null"),!1):Fs(this.shape,(s,r)=>{const i=this._isPartial&&!vo(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 um=t=>new Fr(t),dm=Be(Fr),hm=Ye(t=>t!=null&&(t.constructor===Object||t.constructor==null));class pc extends it{constructor(e,n){super(),this.shape={keys:e,values:n}}check(e,n){return e!=null&&Fs(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 mc=(t,e)=>new pc(t,e),fm=Be(pc);class gc extends it{constructor(e){super(),this.shape=e}check(e,n){return e!=null&&Fs(this.shape,(s,r)=>{const i=s.check(e[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const pm=(...t)=>new gc(t);Be(gc);class wc extends it{constructor(e){super(),this.shape=e.length===1?e[0]:new Lo(e)}check(e,n){const s=Kn(e)&&po(e,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const yc=(...t)=>new wc(t),mm=Be(wc),gm=Ye(t=>Kn(t));class bc extends it{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 wm=(t,e=null)=>new bc(t,e);Be(bc);const ym=wm(it);class bm extends it{constructor(e){super(),this.len=e.length-1,this.args=pm(...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 xm=Be(bm),km=Ye(t=>typeof t=="function");class Sm extends it{constructor(e){super(),this.shape=e}check(e,n){const s=po(this.shape,r=>r.check(e,n));return!s&&n?.extend(null,"Intersectinon",typeof e),s}}Be(Sm,t=>t.shape.length>0);class Lo extends it{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,n){const s=mo(this.shape,r=>r.check(e,n));return n?.extend(null,"Union",typeof e),s}}const ns=(...t)=>t.findIndex(e=>mr.check(e))>=0?ns(...t.map(e=>Ds(e)).map(e=>mr.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new Lo(t),mr=Be(Lo),xc=()=>!0,gr=Ye(xc),Cm=Be(_o,t=>t.shape===xc),Ro=Ye(t=>typeof t=="bigint"),vm=Ye(t=>t===Ro),kc=Ye(t=>typeof t=="symbol");Ye(t=>t===kc);const Pn=Ye(t=>typeof t=="number"),Sc=Ye(t=>t===Pn),Yn=Ye(t=>typeof t=="string"),Cc=Ye(t=>t===Yn),Or=Ye(t=>typeof t=="boolean"),jm=Ye(t=>t===Or),vc=Nr(void 0);Be(Ar,t=>t.shape.length===1&&t.shape[0]===void 0);Nr(void 0);const Mr=Nr(null),Em=Be(Ar,t=>t.shape.length===1&&t.shape[0]===null);Be(Uint8Array);Be(Do,t=>t.shape===Uint8Array);const Dm=ns(Pn,Yn,Mr,vc,Ro,Or,kc);(()=>{const t=yc(gr),e=mc(Yn,gr),n=ns(Pn,Yn,Mr,Or,t,e);return t.shape=n,e.shape.values=n,n})();const Ds=t=>{if(ym.check(t))return t;if(hm.check(t)){const e={};for(const n in t)e[n]=Ds(t[n]);return um(e)}else{if(gm.check(t))return ns(...t.map(Ds));if(Dm.check(t))return Nr(t);if(km.check(t))return Be(t)}ht()},oa=zp?()=>{}:(t,e)=>{const n=new rm;if(!e.check(t,n))throw Ct(`Expected value to be of type ${e.constructor.name}.
7
+ ${n.toString()}`)};class _m{constructor(e){this.patterns=[],this.$state=e}if(e,n){return this.patterns.push({if:Ds(e),h:n}),this}else(e){return this.if(gr,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 Ct("Unhandled pattern")}}}const Lm=t=>new _m(t),jc=Lm(gr).if(Sc,(t,e)=>vi(e,Xl,hr)).if(Cc,(t,e)=>nm(e)).if(jm,(t,e)=>ia(e)).if(vm,(t,e)=>BigInt(vi(e,Xl,hr))).if(mr,(t,e)=>Nn(e,ji(e,t.shape))).if(dm,(t,e)=>{const n={};for(const s in t.shape){let r=t.shape[s];if(am.check(r)){if(ia(e))continue;r=r.shape}n[s]=jc(r,e)}return n}).if(mm,(t,e)=>{const n=[],s=uc(e,0,42);for(let r=0;r<s;r++)n.push(Nn(e,t.shape));return n}).if(dc,(t,e)=>ji(e,t.shape)).if(Em,(t,e)=>null).if(xm,(t,e)=>{const n=Nn(e,t.res);return()=>n}).if(Cm,(t,e)=>Nn(e,ji(e,[Pn,Yn,Mr,vc,Ro,Or,yc(Pn),mc(ns("a","b","c"),Pn)]))).if(fm,(t,e)=>{const n={},s=vi(e,0,3);for(let r=0;r<s;r++){const i=Nn(e,t.shape.keys),l=Nn(e,t.shape.values);n[i]=l}return n}).done(),Nn=(t,e)=>jc(Ds(e),t),Tt=typeof document<"u"?document:{},Rm=t=>Tt.createElement(t),Tm=()=>Tt.createDocumentFragment();Ye(t=>t.nodeType===Um);const Am=t=>Tt.createTextNode(t);typeof DOMParser<"u"&&new DOMParser;const Nm=(t,e)=>(em(e,(n,s)=>{s===!1?t.removeAttribute(n):s===!0?t.setAttribute(n,""):t.setAttribute(n,s)}),t),Fm=t=>{const e=Tm();for(let n=0;n<t.length;n++)Ec(e,t[n]);return e},Om=(t,e)=>(Ec(t,Fm(e)),t),Ob=(t,e=[],n=[])=>Om(Nm(Rm(t),e),n);Ye(t=>t.nodeType===$m);const Mb=Am;Ye(t=>t.nodeType===Im);const Mm=t=>Kf(t,(e,n)=>`${n}:${e};`).join(""),Ec=(t,e)=>t.appendChild(e),$m=Tt.ELEMENT_NODE,Im=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const Pm=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Um=Tt.DOCUMENT_FRAGMENT_NODE;Ye(t=>t.nodeType===Pm);const Bt=Symbol,Dc=Bt(),_c=Bt(),zm=Bt(),Bm=Bt(),qm=Bt(),Lc=Bt(),Wm=Bt(),To=Bt(),Hm=Bt(),Vm=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},Km={[Dc]:$t("font-weight","bold"),[_c]:$t("font-weight","normal"),[zm]:$t("color","blue"),[qm]:$t("color","green"),[Bm]:$t("color","grey"),[Lc]:$t("color","red"),[Wm]:$t("color","purple"),[To]:$t("color","orange"),[Hm]:$t("color","black")},Jm=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());const e=[],n=[],s=ct();let r=[],i=0;for(;i<t.length;i++){const l=t[i],a=Km[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=Mm(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},Rc=qp?Jm:Vm,Gm=(...t)=>{console.log(...Rc(t)),Ac.forEach(e=>e.print(t))},Tc=(...t)=>{console.warn(...Rc(t)),t.unshift(To),Ac.forEach(e=>e.print(t))},Ac=tn(),Nc=t=>({[Symbol.iterator](){return this},next:t}),Ym=(t,e)=>Nc(()=>{let n;do n=t.next();while(!n.done&&!e(n.value));return n}),Ei=(t,e)=>Nc(()=>{const{done:n,value:s}=t.next();return{done:n,value:n?void 0:e(s)}});class $r{constructor(e,n){this.clock=e,this.len=n}}class ss{constructor(){this.clients=new Map}}const Xn=(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])Jc(t,i,u.clock,u.len,n)}}),Xm=(t,e)=>{let n=0,s=t.length-1;for(;n<=s;){const r=St((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},Os=(t,e)=>{const n=t.clients.get(e.client);return n!==void 0&&Xm(n,e.clock)!==null},Ao=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 $r(r.clock,Sn(r.len,i.clock+i.len-r.clock)):(s<n&&(e[s]=i),s++)}e.length=s})},Yi=t=>{const e=new ss;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++)Gf(i,t[l].clients.get(r)||[]);e.clients.set(r,i)}});return Ao(e),e},_s=(t,e,n,s)=>{Rt(t.clients,e,()=>[]).push(new $r(n,s))},Qm=()=>new ss,Zm=t=>{const e=Qm();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 $r(a,c))}}r.length>0&&e.clients.set(s,r)}),e},rs=(t,e)=>{H(t.restEncoder,e.clients.size),zt(e.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{t.resetDsCurVal(),H(t.restEncoder,n);const r=s.length;H(t.restEncoder,r);for(let i=0;i<r;i++){const l=s[i];t.writeDsClock(l.clock),t.writeDsLen(l.len)}})},No=t=>{const e=new ss,n=oe(t.restDecoder);for(let s=0;s<n;s++){t.resetDsCurVal();const r=oe(t.restDecoder),i=oe(t.restDecoder);if(i>0){const l=Rt(e.clients,r,()=>[]);for(let a=0;a<i;a++)l.push(new $r(t.readDsClock(),t.readDsLen()))}}return e},la=(t,e,n)=>{const s=new ss,r=oe(t.restDecoder);for(let i=0;i<r;i++){t.resetDsCurVal();const l=oe(t.restDecoder),a=oe(t.restDecoder),c=n.clients.get(l)||[],u=Pe(n,l);for(let f=0;f<a;f++){const h=t.readDsClock(),p=h+t.readDsLen();if(h<u){u<p&&_s(s,l,u,p-u);let w=_t(c,h),g=c[w];for(!g.deleted&&g.id.clock<h&&(c.splice(w+1,0,vr(e,g,h-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,vr(e,g,p-g.id.clock)),g.delete(e))}else _s(s,l,h,p-h)}}if(s.clients.size>0){const i=new bn;return H(i.restEncoder,0),rs(i,s),i.toUint8Array()}return null},Fc=tc;class Cn extends go{constructor({guid:e=Ep(),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=Fc(),this.guid=e,this.collectionid=n,this.share=new Map,this.store=new Vc,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=Gn(u=>{this.on("load",()=>{this.isLoaded=!0,u(this)})});const c=()=>Gn(u=>{const f=h=>{(h===void 0||h===!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&&De(e.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(zt(this.subdocs).map(e=>e.guid))}transact(e,n=null){return De(this,e,n)}get(e,n=Je){const s=Rt(this.share,e,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==Je&&r!==n)if(r===Je){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,Bn)}getText(e=""){return this.get(e,es)}getMap(e=""){return this.get(e,Zn)}getXmlElement(e=""){return this.get(e,ts)}getXmlFragment(e=""){return this.get(e,xn)}toJSON(){const e={};return this.share.forEach((n,s)=>{e[s]=n.toJSON()}),e}destroy(){this.isDestroyed=!0,zt(this.subdocs).forEach(n=>n.destroy());const e=this._item;if(e!==null){this._item=null;const n=e.content;n.doc=new Cn({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=e,De(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 Oc{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return oe(this.restDecoder)}readDsLen(){return oe(this.restDecoder)}}class Mc extends Oc{readLeftID(){return he(oe(this.restDecoder),oe(this.restDecoder))}readRightID(){return he(oe(this.restDecoder),oe(this.restDecoder))}readClient(){return oe(this.restDecoder)}readInfo(){return Jn(this.restDecoder)}readString(){return Fe(this.restDecoder)}readParentInfo(){return oe(this.restDecoder)===1}readTypeRef(){return oe(this.restDecoder)}readLen(){return oe(this.restDecoder)}readAny(){return js(this.restDecoder)}readBuf(){return Qp(et(this.restDecoder))}readJSON(){return JSON.parse(Fe(this.restDecoder))}readKey(){return Fe(this.restDecoder)}}class eg{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=oe(this.restDecoder),this.dsCurrVal}readDsLen(){const e=oe(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Qn extends eg{constructor(e){super(e),this.keys=[],oe(e),this.keyClockDecoder=new Ci(et(e)),this.clientDecoder=new ir(et(e)),this.leftClockDecoder=new Ci(et(e)),this.rightClockDecoder=new Ci(et(e)),this.infoDecoder=new sa(et(e),Jn),this.stringDecoder=new Cp(et(e)),this.parentInfoDecoder=new sa(et(e),Jn),this.typeRefDecoder=new ir(et(e)),this.lenDecoder=new ir(et(e))}readLeftID(){return new Un(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Un(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 js(this.restDecoder)}readBuf(){return et(this.restDecoder)}readJSON(){return js(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 $c{constructor(){this.restEncoder=Ie()}toUint8Array(){return je(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){H(this.restEncoder,e)}writeDsLen(e){H(this.restEncoder,e)}}class Ms extends $c{writeLeftID(e){H(this.restEncoder,e.client),H(this.restEncoder,e.clock)}writeRightID(e){H(this.restEncoder,e.client),H(this.restEncoder,e.clock)}writeClient(e){H(this.restEncoder,e)}writeInfo(e){Hi(this.restEncoder,e)}writeString(e){Qe(this.restEncoder,e)}writeParentInfo(e){H(this.restEncoder,e?1:0)}writeTypeRef(e){H(this.restEncoder,e)}writeLen(e){H(this.restEncoder,e)}writeAny(e){vs(this.restEncoder,e)}writeBuf(e){$e(this.restEncoder,e)}writeJSON(e){Qe(this.restEncoder,JSON.stringify(e))}writeKey(e){Qe(this.restEncoder,e)}}class Ic{constructor(){this.restEncoder=Ie(),this.dsCurrVal=0}toUint8Array(){return je(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const n=e-this.dsCurrVal;this.dsCurrVal=e,H(this.restEncoder,n)}writeDsLen(e){e===0&&ht(),H(this.restEncoder,e-1),this.dsCurrVal+=e}}class bn extends Ic{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Si,this.clientEncoder=new rr,this.leftClockEncoder=new Si,this.rightClockEncoder=new Si,this.infoEncoder=new ea(Hi),this.stringEncoder=new mp,this.parentInfoEncoder=new ea(Hi),this.typeRefEncoder=new rr,this.lenEncoder=new rr}toUint8Array(){const e=Ie();return H(e,0),$e(e,this.keyClockEncoder.toUint8Array()),$e(e,this.clientEncoder.toUint8Array()),$e(e,this.leftClockEncoder.toUint8Array()),$e(e,this.rightClockEncoder.toUint8Array()),$e(e,je(this.infoEncoder)),$e(e,this.stringEncoder.toUint8Array()),$e(e,je(this.parentInfoEncoder)),$e(e,this.typeRefEncoder.toUint8Array()),$e(e,this.lenEncoder.toUint8Array()),Rr(e,je(this.restEncoder)),je(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){vs(this.restEncoder,e)}writeBuf(e){$e(this.restEncoder,e)}writeJSON(e){vs(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 tg=(t,e,n,s)=>{s=Sn(s,e[0].id.clock);const r=_t(e,s);H(t.restEncoder,e.length-r),t.writeClient(n),H(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)},Fo=(t,e,n)=>{const s=new Map;n.forEach((r,i)=>{Pe(e,i)>r&&s.set(i,r)}),Ir(e).forEach((r,i)=>{n.has(i)||s.set(i,0)}),H(t.restEncoder,s.size),zt(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{tg(t,e.clients.get(r),r,i)})},ng=(t,e)=>{const n=ct(),s=oe(t.restDecoder);for(let r=0;r<s;r++){const i=oe(t.restDecoder),l=new Array(i),a=t.readClient();let c=oe(t.restDecoder);n.set(a,{i:0,refs:l});for(let u=0;u<i;u++){const f=t.readInfo();switch(Lr&f){case 0:{const h=t.readLen();l[u]=new gt(he(a,c),h),c+=h;break}case 10:{const h=oe(t.restDecoder);l[u]=new wt(he(a,c),h),c+=h;break}default:{const h=(f&(Ut|rt))===0,p=new Le(he(a,c),null,(f&rt)===rt?t.readLeftID():null,null,(f&Ut)===Ut?t.readRightID():null,h?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,h&&(f&Ss)===Ss?t.readString():null,pu(t,f));l[u]=p,c+=p.length}}}}return n},sg=(t,e,n)=>{const s=[];let r=zt(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 Vc,c=new Map,u=(w,g)=>{const S=c.get(w);(S==null||S>g)&&c.set(w,g)};let f=l.refs[l.i++];const h=new Map,p=()=>{for(const w of s){const g=w.id.client,S=n.get(g);S?(S.i--,a.clients.set(g,S.refs.slice(S.i)),n.delete(g),S.i=0,S.refs=[]):a.clients.set(g,[w]),r=r.filter(v=>v!==g)}s.length=0};for(;;){if(f.constructor!==wt){const g=Rt(h,f.id.client,()=>Pe(e,f.id.client))-f.id.clock;if(g<0)s.push(f),u(f.id.client,f.id.clock-1),p();else{const S=f.getMissing(t,e);if(S!==null){s.push(f);const v=n.get(S)||{refs:[],i:0};if(v.refs.length===v.i)u(S,Pe(e,S)),p();else{f=v.refs[v.i++];continue}}else(g===0||g<f.length)&&(f.integrate(t,g),h.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 bn;return Fo(w,a,new Map),H(w.restEncoder,0),{missing:c,update:w.toUint8Array()}}return null},rg=(t,e)=>Fo(t,e.doc.store,e.beforeState),ig=(t,e,n,s=new Qn(t))=>De(e,r=>{r.local=!1;let i=!1;const l=r.doc,a=l.store,c=ng(s,l),u=sg(r,a,c),f=a.pendingStructs;if(f){for(const[p,w]of f.missing)if(w<Pe(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=yr([f.update,u.update])}}else a.pendingStructs=u;const h=la(s,r,a);if(a.pendingDs){const p=new Qn(rn(a.pendingDs));oe(p.restDecoder);const w=la(p,r,a);h&&w?a.pendingDs=yr([h,w]):a.pendingDs=h||w}else a.pendingDs=h;if(i){const p=a.pendingStructs.update;a.pendingStructs=null,Pc(r.doc,p)}},n,!1),Pc=(t,e,n,s=Qn)=>{const r=rn(e);ig(r,t,n,new s(r))},Uc=(t,e,n)=>Pc(t,e,n,Mc),og=(t,e,n=new Map)=>{Fo(t,e.store,n),rs(t,Zm(e.store))},lg=(t,e=new Uint8Array([0]),n=new bn)=>{const s=zc(e);og(n,t,s);const r=[n.toUint8Array()];if(t.store.pendingDs&&r.push(t.store.pendingDs),t.store.pendingStructs&&r.push(Eg(t.store.pendingStructs.update,e)),r.length>1){if(n.constructor===Ms)return vg(r.map((i,l)=>l===0?i:_g(i)));if(n.constructor===bn)return yr(r)}return r[0]},Oo=(t,e)=>lg(t,e,new Ms),ag=t=>{const e=new Map,n=oe(t.restDecoder);for(let s=0;s<n;s++){const r=oe(t.restDecoder),i=oe(t.restDecoder);e.set(r,i)}return e},zc=t=>ag(new Oc(rn(t))),Bc=(t,e)=>(H(t.restEncoder,e.size),zt(e.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{H(t.restEncoder,n),H(t.restEncoder,s)}),t),cg=(t,e)=>Bc(t,Ir(e.store)),ug=(t,e=new Ic)=>(t instanceof Map?Bc(e,t):cg(e,t),e.toUint8Array()),dg=t=>ug(t,new $c);class hg{constructor(){this.l=[]}}const aa=()=>new hg,ca=(t,e)=>t.l.push(e),ua=(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.")},qc=(t,e,n)=>jo(t.l,[e,n]);class Un{constructor(e,n){this.client=e,this.clock=n}}const Mn=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,he=(t,e)=>new Un(t,e),Wc=t=>{for(const[e,n]of t.doc.share.entries())if(n===t)return e;throw ht()},wr=(t,e)=>{for(;e!==null;){if(e.parent===t)return!0;e=e.parent._item}return!1};class Hc{constructor(e,n,s,r=0){this.type=e,this.tname=n,this.item=s,this.assoc=r}}const $b=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},Ib=t=>new Hc(t.type==null?null:he(t.type.client,t.type.clock),t.tname??null,t.item==null?null:he(t.item.client,t.item.clock),t.assoc==null?0:t.assoc);class fg{constructor(e,n,s=0){this.type=e,this.index=n,this.assoc=s}}const pg=(t,e,n=0)=>new fg(t,e,n),Zs=(t,e,n)=>{let s=null,r=null;return t._item===null?r=Wc(t):s=he(t._item.id.client,t._item.id.clock),new Hc(s,r,e,n)},Pb=(t,e,n=0)=>{let s=t._start;if(n<0){if(e===0)return Zs(t,null,n);e--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>e)return Zs(t,he(s.id.client,s.id.clock+e),n);e-=s.length}if(s.right===null&&n<0)return Zs(t,s.lastId,n);s=s.right}return Zs(t,null,n)},mg=(t,e)=>{const n=zn(t,e),s=e.clock-n.id.clock;return{item:n,diff:s}},Ub=(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(Pe(s,r.client)<=r.clock)return null;const f=n?eo(s,r):mg(s,r),h=f.item;if(!(h instanceof Le))return null;if(c=h.parent,c._item===null||!c._item.deleted){u=h.deleted||!h.countable?0:f.diff+(a>=0?0:1);let p=h.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(Pe(s,i.client)<=i.clock)return null;const{item:f}=n?eo(s,i):{item:zn(s,i)};if(f instanceof Le&&f.content instanceof At)c=f.content.type;else return null}else throw ht();a>=0?u=c._length:u=0}return pg(c,u,t.assoc)},zb=(t,e)=>t===e||t!==null&&e!==null&&t.tname===e.tname&&Mn(t.item,e.item)&&Mn(t.type,e.type)&&t.assoc===e.assoc,Fn=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!Os(e.ds,t.id),Xi=(t,e)=>{const n=Rt(t.meta,Xi,tn),s=t.doc.store;n.has(e)||(e.sv.forEach((r,i)=>{r<Pe(s,i)&&at(t,he(i,r))}),Xn(t,e.ds,r=>{}),n.add(e))};class Vc{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Ir=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},Pe=(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},Kc=(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 ht()}n.push(e)},_t=(t,e)=>{let n=0,s=t.length-1,r=t[s],i=r.id.clock;if(i===e)return s;let l=St(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=St((n+s)/2)}throw ht()},gg=(t,e)=>{const n=t.clients.get(e.client);return n[_t(n,e.clock)]},zn=gg,Qi=(t,e,n)=>{const s=_t(e,n),r=e[s];return r.id.clock<n&&r instanceof Le?(e.splice(s+1,0,vr(t,r,n-r.id.clock)),s+1):s},at=(t,e)=>{const n=t.doc.store.clients.get(e.client);return n[Qi(t,n,e.clock)]},da=(t,e,n)=>{const s=e.clients.get(n.client),r=_t(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==gt&&s.splice(r+1,0,vr(t,i,n.clock-i.id.clock+1)),i},wg=(t,e,n)=>{const s=t.clients.get(e.id.client);s[_t(s,e.id.clock)]=n},Jc=(t,e,n,s,r)=>{if(s===0)return;const i=n+s;let l=Qi(t,e,n),a;do a=e[l++],i<a.id.clock+a.length&&Qi(t,e,i),r(a);while(l<e.length&&e[l].id.clock<i)};class yg{constructor(e,n,s){this.doc=e,this.deleteSet=new ss,this.beforeState=Ir(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 ha=(t,e)=>e.deleteSet.clients.size===0&&!Jf(e.afterState,(n,s)=>e.beforeState.get(s)!==n)?!1:(Ao(e.deleteSet),rg(t,e),rs(t,e.deleteSet),!0),fa=(t,e,n)=>{const s=e._item;(s===null||s.id.clock<(t.beforeState.get(s.id.client)||0)&&!s.deleted)&&Rt(t.changed,e,tn).add(n)},or=(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 Le&&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},bg=(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=_t(i,a.clock),f=i[u];u<i.length&&f.id.clock<c;f=i[++u]){const h=i[u];if(a.clock+a.len<=h.id.clock)break;h instanceof Le&&h.deleted&&!h.keep&&n(h)&&h.gc(e,!1)}}}},xg=(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=wo(r.length-1,1+_t(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+or(r,c)}})},Gc=(t,e)=>{if(e<t.length){const n=t[e],s=n.doc,r=s.store,i=n.deleteSet,l=n._mergeStructs;try{Ao(i),n.afterState=Ir(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,h)=>f.path.length-h.path.length),a.push(()=>{qc(u._dEH,c,n)}))}),a.push(()=>s.emit("afterTransaction",[n,s])),a.push(()=>{n._needFormattingCleanup&&Bg(n)})}),jo(a,[])}finally{s.gc&&bg(i,r,s.gcFilter),xg(i,r),n.afterState.forEach((f,h)=>{const p=n.beforeState.get(h)||0;if(p!==f){const w=r.clients.get(h),g=Sn(_t(w,p),1);for(let S=w.length-1;S>=g;)S-=1+or(w,S)}});for(let f=l.length-1;f>=0;f--){const{client:h,clock:p}=l[f].id,w=r.clients.get(h),g=_t(w,p);g+1<w.length&&or(w,g+1)>1||g>0&&or(w,g)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(Gm(To,Dc,"[yjs] ",_c,Lc,"Changed the client-id because another client seems to be using it."),s.clientID=Fc()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const f=new Ms;ha(f,n)&&s.emit("update",[f.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const f=new bn;ha(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])):Gc(t,e+1)}}},De=(t,e,n=null,s=!0)=>{const r=t._transactionCleanups;let i=!1,l=null;t._transaction===null&&(i=!0,t._transaction=new yg(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&&Gc(r,0)}}return l};class kg{constructor(e,n){this.insertions=n,this.deletions=e,this.meta=new Map}}const pa=(t,e,n)=>{Xn(t,n.deletions,s=>{s instanceof Le&&e.scope.some(r=>r===t.doc||wr(r,s))&&qo(s,!1)})},ma=(t,e,n)=>{let s=null;const r=t.doc,i=t.scope;De(r,a=>{for(;e.length>0&&t.currStackItem===null;){const c=r.store,u=e.pop(),f=new Set,h=[];let p=!1;Xn(a,u.insertions,w=>{if(w instanceof Le){if(w.redone!==null){let{item:g,diff:S}=eo(c,w.id);S>0&&(g=at(a,he(g.id.client,g.id.clock+S))),w=g}!w.deleted&&i.some(g=>g===a.doc||wr(g,w))&&h.push(w)}}),Xn(a,u.deletions,w=>{w instanceof Le&&i.some(g=>g===a.doc||wr(g,w))&&!Os(u.insertions,w.id)&&f.add(w)}),f.forEach(w=>{p=fu(a,w,f,u.insertions,t.ignoreRemoteMapChanges,t)!==null||p});for(let w=h.length-1;w>=0;w--){const g=h[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 Sg extends go{constructor(e,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:l=!1,doc:a=Kn(e)?e[0].doc:e instanceof Cn?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(v=>c.changedParentTypes.has(v)||v===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const u=this.undoing,f=this.redoing,h=u?this.redoStack:this.undoStack;u?this.stopCapturing():f||this.clear(!1,!0);const p=new ss;c.afterState.forEach((v,C)=>{const $=c.beforeState.get(C)||0,x=v-$;x>0&&_s(p,C,$,x)});const w=nn();let g=!1;if(this.lastChange>0&&w-this.lastChange<this.captureTimeout&&h.length>0&&!u&&!f){const v=h[h.length-1];v.deletions=Yi([v.deletions,c.deleteSet]),v.insertions=Yi([v.insertions,p])}else h.push(new kg(c.deleteSet,p)),g=!0;!u&&!f&&(this.lastChange=w),Xn(c,c.deleteSet,v=>{v instanceof Le&&this.scope.some(C=>C===c.doc||wr(C,v))&&qo(v,!0)});const S=[{stackItem:h[h.length-1],origin:c.origin,type:u?"redo":"undo",changedParentTypes:c.changedParentTypes},this];g?this.emit("stack-item-added",S):this.emit("stack-item-updated",S)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const n=new Set(this.scope);e=Kn(e)?e:[e],e.forEach(s=>{n.has(s)||(n.add(s),(s instanceof Je?s.doc!==this.doc:s!==this.doc)&&Tc("[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=>pa(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>pa(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=ma(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=ma(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*Cg(t){const e=oe(t.restDecoder);for(let n=0;n<e;n++){const s=oe(t.restDecoder),r=t.readClient();let i=oe(t.restDecoder);for(let l=0;l<s;l++){const a=t.readInfo();if(a===10){const c=oe(t.restDecoder);yield new wt(he(r,i),c),i+=c}else if((Lr&a)!==0){const c=(a&(Ut|rt))===0,u=new Le(he(r,i),null,(a&rt)===rt?t.readLeftID():null,null,(a&Ut)===Ut?t.readRightID():null,c?t.readParentInfo()?t.readString():t.readLeftID():null,c&&(a&Ss)===Ss?t.readString():null,pu(t,a));yield u,i+=u.length}else{const c=t.readLen();yield new gt(he(r,i),c),i+=c}}}}class Mo{constructor(e,n){this.gen=Cg(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===wt);return this.curr}}class $o{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const vg=t=>yr(t,Mc,Ms),jg=(t,e)=>{if(t.constructor===gt){const{client:n,clock:s}=t.id;return new gt(he(n,s+e),t.length-e)}else if(t.constructor===wt){const{client:n,clock:s}=t.id;return new wt(he(n,s+e),t.length-e)}else{const n=t,{client:s,clock:r}=n.id;return new Le(he(s,r+e),null,he(s,r+e-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(e))}},yr=(t,e=Qn,n=bn)=>{if(t.length===1)return t[0];const s=t.map(f=>new e(rn(f)));let r=s.map(f=>new Mo(f,!0)),i=null;const l=new n,a=new $o(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===wt?1:-1:g}else return w.curr.id.client-p.curr.id.client}),r.length!==0;){const f=r[0],h=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!==h||w&&p.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Qt(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===wt)i.struct.length=p.id.clock+p.length-i.struct.id.clock;else{Qt(a,i.struct,i.offset);const g=p.id.clock-i.struct.id.clock-i.struct.length;i={struct:new wt(he(h,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===wt?i.struct.length-=g:p=jg(p,g)),i.struct.mergeWith(p)||(Qt(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===h&&p.id.clock===i.struct.id.clock+i.struct.length&&p.constructor!==wt;p=f.next())Qt(a,i.struct,i.offset),i={struct:p,offset:0}}i!==null&&(Qt(a,i.struct,i.offset),i=null),Io(a);const c=s.map(f=>No(f)),u=Yi(c);return rs(l,u),l.toUint8Array()},Eg=(t,e,n=Qn,s=bn)=>{const r=zc(e),i=new s,l=new $o(i),a=new n(rn(t)),c=new Mo(a,!1);for(;c.curr;){const f=c.curr,h=f.id.client,p=r.get(h)||0;if(c.curr.constructor===wt){c.next();continue}if(f.id.clock+f.length>p)for(Qt(l,f,Sn(p-f.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Qt(l,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=p;)c.next()}Io(l);const u=No(a);return rs(i,u),i.toUint8Array()},Yc=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:je(t.encoder.restEncoder)}),t.encoder.restEncoder=Ie(),t.written=0)},Qt=(t,e,n)=>{t.written>0&&t.currClient!==e.id.client&&Yc(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),H(t.encoder.restEncoder,e.id.clock+n)),e.write(t.encoder,n),t.written++},Io=t=>{Yc(t);const e=t.encoder.restEncoder;H(e,t.clientStructs.length);for(let n=0;n<t.clientStructs.length;n++){const s=t.clientStructs[n];H(e,s.written),Rr(e,s.restEncoder)}},Dg=(t,e,n,s)=>{const r=new n(rn(t)),i=new Mo(r,!1),l=new s,a=new $o(l);for(let u=i.curr;u!==null;u=i.next())Qt(a,e(u),0);Io(a);const c=No(r);return rs(l,c),l.toUint8Array()},_g=t=>Dg(t,Ip,Qn,Ms),ga="You must not compute changes after the event-handler fired.";class Pr{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=Lg(this.currentTarget,this.target))}deletes(e){return Os(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ga);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=ki(c.content.getContent());else return;else c!==null&&this.deletes(c)?(l="update",a=ki(c.content.getContent())):(l="add",a=void 0)}else if(this.deletes(i))l="delete",a=ki(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 Ct(ga);const n=this.target,s=tn(),r=tn(),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 Lg=(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},tt=()=>{Tc("Invalid access: Add Yjs type to a document before reading data.")},Xc=80;let Po=0;class Rg{constructor(e,n){e.marker=!0,this.p=e,this.index=n,this.timestamp=Po++}}const Tg=t=>{t.timestamp=Po++},Qc=(t,e,n)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=n,t.timestamp=Po++},Ag=(t,e,n)=>{if(t.length>=Xc){const s=t.reduce((r,i)=>r.timestamp<i.timestamp?r:i);return Qc(s,e,n),s}else{const s=new Rg(e,n);return t.push(s),s}},Ur=(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)=>sr(e-i.index)<sr(e-l.index)?i:l);let s=t._start,r=0;for(n!==null&&(s=n.p,r=n.index,Tg(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&&sr(n.index-r)<s.parent.length/Xc?(Qc(n,s,r),n):Ag(t._searchMarker,s,r)},Ls=(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=Sn(e,r.index+n))}},zr=(t,e,n)=>{const s=t,r=e.changedParentTypes;for(;Rt(r,t,()=>[]).push(n),t._item!==null;)t=t._item.parent;qc(s._eH,n,e)};class Je{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=aa(),this._dEH=aa(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,n){this.doc=e,this._item=n}_copy(){throw kt()}clone(){throw kt()}_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){ca(this._eH,e)}observeDeep(e){ca(this._dEH,e)}unobserve(e){ua(this._eH,e)}unobserveDeep(e){ua(this._dEH,e)}toJSON(){}}const Zc=(t,e,n)=>{t.doc??tt(),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},eu=t=>{t.doc??tt();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},Rs=(t,e)=>{let n=0,s=t._start;for(t.doc??tt();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}},tu=(t,e)=>{const n=[];return Rs(t,(s,r)=>{n.push(e(s,r,t))}),n},Ng=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}}}},nu=(t,e)=>{t.doc??tt();const n=Ur(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}},br=(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 Le(he(l,Pe(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new kn(u)),r.integrate(t,0),u=[])};s.forEach(h=>{if(h===null)u.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:u.push(h);break;default:switch(f(),h.constructor){case Uint8Array:case ArrayBuffer:r=new Le(he(l,Pe(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new $s(new Uint8Array(h))),r.integrate(t,0);break;case Cn:r=new Le(he(l,Pe(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Is(h)),r.integrate(t,0);break;default:if(h instanceof Je)r=new Le(he(l,Pe(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new At(h)),r.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),f()},su=()=>Ct("Length exceeded!"),ru=(t,e,n,s)=>{if(n>e._length)throw su();if(n===0)return e._searchMarker&&Ls(e._searchMarker,n,s.length),br(t,e,null,s);const r=n,i=Ur(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&&at(t,he(l.id.client,l.id.clock+n));break}n-=l.length}return e._searchMarker&&Ls(e._searchMarker,r,s.length),br(t,e,l,s)},Fg=(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 br(t,e,r,n)},iu=(t,e,n,s)=>{if(s===0)return;const r=n,i=s,l=Ur(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&&at(t,he(a.id.client,a.id.clock+n)),n-=a.length);for(;s>0&&a!==null;)a.deleted||(s<a.length&&at(t,he(a.id.client,a.id.clock+s)),a.delete(t),s-=a.length),a=a.right;if(s>0)throw su();e._searchMarker&&Ls(e._searchMarker,r,-i+s)},xr=(t,e,n)=>{const s=e._map.get(n);s!==void 0&&s.delete(t)},Uo=(t,e,n,s)=>{const r=e._map.get(n)||null,i=t.doc,l=i.clientID;let a;if(s==null)a=new kn([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:a=new kn([s]);break;case Uint8Array:a=new $s(s);break;case Cn:a=new Is(s);break;default:if(s instanceof Je)a=new At(s);else throw new Error("Unexpected content type")}new Le(he(l,Pe(i.store,l)),r,r&&r.lastId,null,null,e,n,a).integrate(t,0)},zo=(t,e)=>{t.doc??tt();const n=t._map.get(e);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},ou=t=>{const e={};return t.doc??tt(),t._map.forEach((n,s)=>{n.deleted||(e[s]=n.content.getContent()[n.length-1])}),e},lu=(t,e)=>{t.doc??tt();const n=t._map.get(e);return n!==void 0&&!n.deleted},Og=(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&&Fn(i,e)&&(n[r]=i.content.getContent()[i.length-1])}),n},er=t=>(t.doc??tt(),Ym(t._map.entries(),e=>!e[1].deleted));class Mg extends Pr{}class Bn extends Je{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const n=new Bn;return n.push(e),n}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Bn}clone(){const e=new Bn;return e.insert(0,this.toArray().map(n=>n instanceof Je?n.clone():n)),e}get length(){return this.doc??tt(),this._length}_callObserver(e,n){super._callObserver(e,n),zr(this,e,new Mg(this,e))}insert(e,n){this.doc!==null?De(this.doc,s=>{ru(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}push(e){this.doc!==null?De(this.doc,n=>{Fg(n,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,n=1){this.doc!==null?De(this.doc,s=>{iu(s,this,e,n)}):this._prelimContent.splice(e,n)}get(e){return nu(this,e)}toArray(){return eu(this)}slice(e=0,n=this.length){return Zc(this,e,n)}toJSON(){return this.map(e=>e instanceof Je?e.toJSON():e)}map(e){return tu(this,e)}forEach(e){Rs(this,e)}[Symbol.iterator](){return Ng(this)}_write(e){e.writeTypeRef(lw)}}const $g=t=>new Bn;class Ig extends Pr{constructor(e,n,s){super(e,n),this.keysChanged=s}}class Zn extends Je{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 Zn}clone(){const e=new Zn;return this.forEach((n,s)=>{e.set(s,n instanceof Je?n.clone():n)}),e}_callObserver(e,n){zr(this,e,new Ig(this,e,n))}toJSON(){this.doc??tt();const e={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];e[s]=r instanceof Je?r.toJSON():r}}),e}get size(){return[...er(this)].length}keys(){return Ei(er(this),e=>e[0])}values(){return Ei(er(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return Ei(er(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??tt(),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?De(this.doc,n=>{xr(n,this,e)}):this._prelimContent.delete(e)}set(e,n){return this.doc!==null?De(this.doc,s=>{Uo(s,this,e,n)}):this._prelimContent.set(e,n),n}get(e){return zo(this,e)}has(e){return lu(this,e)}clear(){this.doc!==null?De(this.doc,e=>{this.forEach(function(n,s,r){xr(e,r,s)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(aw)}}const Pg=t=>new Zn,Zt=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&Mp(t,e);class Zi{constructor(e,n,s,r){this.left=e,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ht(),this.right.content.constructor===He?this.right.deleted||is(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const wa=(t,e,n)=>{for(;e.right!==null&&n>0;)e.right.content.constructor===He?e.right.deleted||is(e.currentAttributes,e.right.content):e.right.deleted||(n<e.right.length&&at(t,he(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},tr=(t,e,n,s)=>{const r=new Map,i=s?Ur(e,n):null;if(i){const l=new Zi(i.p.left,i.p,i.index,r);return wa(t,l,n-i.index)}else{const l=new Zi(null,e._start,0,r);return wa(t,l,n)}},au=(t,e,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===He&&Zt(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 Le(he(i,Pe(r.store,i)),c,c&&c.lastId,u,u&&u.id,e,null,new He(a,l));f.integrate(t,0),n.right=f,n.forward()})},is=(t,e)=>{const{key:n,value:s}=e;s===null?t.delete(n):t.set(n,s)},cu=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===He&&Zt(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},uu=(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(!Zt(u,c)){l.set(a,u);const{left:f,right:h}=n;n.right=new Le(he(i,Pe(r.store,i)),f,f&&f.lastId,h,h&&h.id,e,null,new He(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;cu(n,r);const a=uu(t,e,n,r),c=s.constructor===String?new Lt(s):s instanceof Je?new At(s):new vn(s);let{left:u,right:f,index:h}=n;e._searchMarker&&Ls(e._searchMarker,n.index,c.getLength()),f=new Le(he(l,Pe(i.store,l)),u,u&&u.lastId,f,f&&f.id,e,null,c),f.integrate(t,0),n.right=f,n.index=h,n.forward(),au(t,e,n,a)},ya=(t,e,n,s,r)=>{const i=t.doc,l=i.clientID;cu(n,r);const a=uu(t,e,n,r);e:for(;n.right!==null&&(s>0||a.size>0&&(n.right.deleted||n.right.content.constructor===He));){if(!n.right.deleted)switch(n.right.content.constructor){case He:{const{key:c,value:u}=n.right.content,f=r[c];if(f!==void 0){if(Zt(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&&at(t,he(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 Le(he(l,Pe(i.store,l)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new Lt(c)),n.right.integrate(t,0),n.forward()}au(t,e,n,a)},du=(t,e,n,s,r)=>{let i=e;const l=ct();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===He){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===He){const{key:f,value:h}=u,p=s.get(f)??null;(l.get(f)!==u||p===h)&&(e.delete(t),a++,!c&&(r.get(f)??null)===h&&p!==h&&(p===null?r.delete(f):r.set(f,p))),!c&&!e.deleted&&is(r,u)}}e=e.right}return a},Ug=(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===He){const s=e.content.key;n.has(s)?e.delete(t):n.add(s)}e=e.left}},zg=t=>{let e=0;return De(t.doc,n=>{let s=t._start,r=t._start,i=ct();const l=Wi(i);for(;r;)r.deleted===!1&&(r.content.constructor===He?is(l,r.content):(e+=du(n,s,r,i,l),i=Wi(l),s=r)),r=r.right}),e},Bg=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&&Jc(t,n.store.clients.get(s),i,r,l=>{!l.deleted&&l.content.constructor===He&&l.constructor!==gt&&e.add(l.parent)})}De(n,s=>{Xn(t,t.deleteSet,r=>{if(r instanceof gt||!r.parent._hasFormatting||e.has(r.parent))return;const i=r.parent;r.content.constructor===He?e.add(i):Ug(s,r)});for(const r of e)zg(r)})},ba=(t,e,n)=>{const s=n,r=Wi(e.currentAttributes),i=e.right;for(;n>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case At:case vn:case Lt:n<e.right.length&&at(t,he(e.right.id.client,e.right.id.clock+n)),n-=e.right.length,e.right.delete(t);break}e.forward()}i&&du(t,i,e.right,r,e.currentAttributes);const l=(e.left||e.right).parent;return l._searchMarker&&Ls(l._searchMarker,e.index,-s+n),e};class qg extends Pr{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=[];De(e,s=>{const r=new Map,i=new Map;let l=this.target._start,a=null;const c={};let u="",f=0,h=0;const p=()=>{if(a!==null){let w=null;switch(a){case"delete":h>0&&(w={delete:h}),h=0;break;case"insert":(typeof u=="object"||u.length>0)&&(w={insert:u},r.size>0&&(w.attributes={},r.forEach((g,S)=>{g!==null&&(w.attributes[S]=g)}))),u="";break;case"retain":f>0&&(w={retain:f},Op(c)||(w.attributes=Tp({},c))),f=0;break}w&&n.push(w),a=null}};for(;l!==null;){switch(l.content.constructor){case At:case vn:this.adds(l)?this.deletes(l)||(p(),a="insert",u=l.content.getContent()[0],p()):this.deletes(l)?(a!=="delete"&&(p(),a="delete"),h+=1):l.deleted||(a!=="retain"&&(p(),a="retain"),f+=1);break;case Lt:this.adds(l)?this.deletes(l)||(a!=="insert"&&(p(),a="insert"),u+=l.content.str):this.deletes(l)?(a!=="delete"&&(p(),a="delete"),h+=l.length):l.deleted||(a!=="retain"&&(p(),a="retain"),f+=l.length);break;case He:{const{key:w,value:g}=l.content;if(this.adds(l)){if(!this.deletes(l)){const S=r.get(w)??null;Zt(S,g)?g!==null&&l.delete(s):(a==="retain"&&p(),Zt(g,i.get(w)??null)?delete c[w]:c[w]=g)}}else if(this.deletes(l)){i.set(w,g);const S=r.get(w)??null;Zt(S,g)||(a==="retain"&&p(),c[w]=S)}else if(!l.deleted){i.set(w,g);const S=c[w];S!==void 0&&(Zt(S,g)?S!==null&&l.delete(s):(a==="retain"&&p(),g===null?delete c[w]:c[w]=g))}l.deleted||(a==="insert"&&p(),is(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 es extends Je{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??tt(),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 es}clone(){const e=new es;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const s=new qg(this,e,n);zr(this,e,s),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??tt();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Lt&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?De(this.doc,s=>{const r=new Zi(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?ya(s,this,r,l.retain,l.attributes||{}):l.delete!==void 0&&ba(s,r,l.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,s){this.doc??tt();const r=[],i=new Map,l=this.doc;let a="",c=this._start;function u(){if(a.length>0){const h={};let p=!1;i.forEach((g,S)=>{p=!0,h[S]=g});const w={insert:a};p&&(w.attributes=h),r.push(w),a=""}}const f=()=>{for(;c!==null;){if(Fn(c,e)||n!==void 0&&Fn(c,n))switch(c.content.constructor){case Lt:{const h=i.get("ychange");e!==void 0&&!Fn(c,e)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(u(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!Fn(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(u(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(u(),i.delete("ychange")),a+=c.content.str;break}case At:case vn:{u();const h={insert:c.content.getContent()[0]};if(i.size>0){const p={};h.attributes=p,i.forEach((w,g)=>{p[g]=w})}r.push(h);break}case He:Fn(c,e)&&(u(),is(i,c.content));break}c=c.right}u()};return e||n?De(l,h=>{e&&Xi(h,e),n&&Xi(h,n),f()},"cleanup"):f(),r}insert(e,n,s){if(n.length<=0)return;const r=this.doc;r!==null?De(r,i=>{const l=tr(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?De(r,i=>{const l=tr(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?De(s,r=>{ba(r,tr(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?De(r,i=>{const l=tr(i,this,e,!1);l.right!==null&&ya(i,this,l,n,s)}):this._pending.push(()=>this.format(e,n,s))}removeAttribute(e){this.doc!==null?De(this.doc,n=>{xr(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?De(this.doc,s=>{Uo(s,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return zo(this,e)}getAttributes(){return ou(this)}_write(e){e.writeTypeRef(cw)}}const Wg=t=>new es;class _i{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??tt()}[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===ts||n.constructor===xn)&&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 xn extends Je{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 xn}clone(){const e=new xn;return e.insert(0,this.toArray().map(n=>n instanceof Je?n.clone():n)),e}get length(){return this.doc??tt(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new _i(this,e)}querySelector(e){e=e.toUpperCase();const s=new _i(this,r=>r.nodeName&&r.nodeName.toUpperCase()===e).next();return s.done?null:s.value}querySelectorAll(e){return e=e.toUpperCase(),zt(new _i(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){zr(this,e,new Kg(this,n,e))}toString(){return tu(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),Rs(this,i=>{r.insertBefore(i.toDOM(e,n,s),null)}),r}insert(e,n){this.doc!==null?De(this.doc,s=>{ru(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)De(this.doc,s=>{const r=e&&e instanceof Je?e._item:e;br(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 Ct("Reference item not found");s.splice(r,0,...n)}}delete(e,n=1){this.doc!==null?De(this.doc,s=>{iu(s,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return eu(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return nu(this,e)}slice(e=0,n=this.length){return Zc(this,e,n)}forEach(e){Rs(this,e)}_write(e){e.writeTypeRef(dw)}}const Hg=t=>new xn;class ts extends xn{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 ts(this.nodeName)}clone(){const e=new ts(this.nodeName),n=this.getAttributes();return Np(n,(s,r)=>{e.setAttribute(r,s)}),e.insert(0,this.toArray().map(s=>s instanceof Je?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?De(this.doc,n=>{xr(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?De(this.doc,s=>{Uo(s,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return zo(this,e)}hasAttribute(e){return lu(this,e)}getAttributes(e){return e?Og(this,e):ou(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 Rs(this,l=>{r.appendChild(l.toDOM(e,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(e){e.writeTypeRef(uw),e.writeKey(this.nodeName)}}const Vg=t=>new ts(t.readKey());class Kg extends Pr{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 kr extends Zn{constructor(e){super(),this.hookName=e}_copy(){return new kr(this.hookName)}clone(){const e=new kr(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(hw),e.writeKey(this.hookName)}}const Jg=t=>new kr(t.readKey());class Sr extends es{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 Sr}clone(){const e=new Sr;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(fw)}}const Gg=t=>new Sr;class Bo{constructor(e,n){this.id=e,this.length=n}get deleted(){throw kt()}mergeWith(e){return!1}write(e,n,s){throw kt()}integrate(e,n){throw kt()}}const Yg=0;class gt extends Bo{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),Kc(e.doc.store,this)}write(e,n){e.writeInfo(Yg),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 kt()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const Xg=t=>new $s(t.readBuf());class Ts{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Ts(this.len)}splice(e){const n=new Ts(this.len-e);return this.len=e,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,n){_s(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 Qg=t=>new Ts(t.readLen()),hu=(t,e)=>new Cn({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class Is{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 Is(hu(this.doc.guid,this.opts))}splice(e){throw kt()}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 Zg=t=>new Is(hu(t.readString(),t.readAny()));class vn{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new vn(this.embed)}splice(e){throw kt()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const ew=t=>new vn(t.readJSON());class He{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new He(this.key,this.value)}splice(e){throw kt()}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 tw=t=>new He(t.readKey(),t.readJSON());class Cr{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Cr(this.arr)}splice(e){const n=new Cr(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 nw=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 Cr(n)},sw=pr("node_env")==="development";class kn{constructor(e){this.arr=e,sw&&ic(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new kn(this.arr)}splice(e){const n=new kn(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 rw=t=>{const e=t.readLen(),n=[];for(let s=0;s<e;s++)n.push(t.readAny());return new kn(n)};class Lt{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Lt(this.str)}splice(e){const n=new Lt(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 iw=t=>new Lt(t.readString()),ow=[$g,Pg,Wg,Vg,Hg,Jg,Gg],lw=0,aw=1,cw=2,uw=3,dw=4,hw=5,fw=6;class At{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new At(this.type._copy())}splice(e){throw kt()}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 pw=t=>new At(ow[t.readTypeRef()](t)),eo=(t,e)=>{let n=e,s=0,r;do s>0&&(n=he(n.client,n.clock+s)),r=zn(t,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof Le);return{item:r,diff:s}},qo=(t,e)=>{for(;t!==null&&t.keep!==e;)t.keep=e,t=t.parent._item},vr=(t,e,n)=>{const{client:s,clock:r}=e.id,i=new Le(he(s,r+n),e,he(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=he(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},xa=(t,e)=>mo(t,n=>Os(n.deletions,e)),fu=(t,e,n,s,r,i)=>{const l=t.doc,a=l.store,c=l.clientID,u=e.redone;if(u!==null)return at(t,u);let f=e.parent._item,h=null,p;if(f!==null&&f.deleted===!0){if(f.redone===null&&(!n.has(f)||fu(t,f,n,s,r,i)===null))return null;for(;f.redone!==null;)f=at(t,f.redone)}const w=f===null?e.parent:f.content.type;if(e.parentSub===null){for(h=e.left,p=e;h!==null;){let C=h;for(;C!==null&&C.parent._item!==f;)C=C.redone===null?null:at(t,C.redone);if(C!==null&&C.parent._item===f){h=C;break}h=h.left}for(;p!==null;){let C=p;for(;C!==null&&C.parent._item!==f;)C=C.redone===null?null:at(t,C.redone);if(C!==null&&C.parent._item===f){p=C;break}p=p.right}}else{if(p=null,e.right&&!r){for(h=e;h!==null&&h.right!==null&&(h.right.redone||Os(s,h.right.id)||xa(i.undoStack,h.right.id)||xa(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=at(t,h.redone);if(h&&h.right!==null)return null}else h=w._map.get(e.parentSub)||null;h!==null&&h.parent._item!==f&&(h=w._map.get(e.parentSub)||null)}const g=Pe(a,c),S=he(c,g),v=new Le(S,h,h&&h.lastId,p,p&&p.id,w,e.parentSub,e.content.copy());return e.redone=S,qo(v,!0),v.integrate(t,0),v};class Le extends Bo{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()?Gl:0}set marker(e){(this.info&bi)>0!==e&&(this.info^=bi)}get marker(){return(this.info&bi)>0}get keep(){return(this.info&Jl)>0}set keep(e){this.keep!==e&&(this.info^=Jl)}get countable(){return(this.info&Gl)>0}get deleted(){return(this.info&yi)>0}set deleted(e){this.deleted!==e&&(this.info^=yi)}markDeleted(){this.info|=yi}getMissing(e,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Pe(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Pe(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Un&&this.id.client!==this.parent.client&&this.parent.clock>=Pe(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=da(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=at(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===gt||this.right&&this.right.constructor===gt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===Le?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===Le&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Un){const s=zn(n,this.parent);s.constructor===gt?this.parent=null:this.parent=s.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=da(e,e.doc.store,he(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),Mn(this.origin,r.origin)){if(r.id.client<this.id.client)s=r,i.clear();else if(Mn(this.rightOrigin,r.rightOrigin))break}else if(r.origin!==null&&l.has(zn(e.doc.store,r.origin)))i.has(zn(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),Kc(e.doc.store,this),this.content.integrate(e,this),fa(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new gt(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:he(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Mn(e.origin,this.lastId)&&this.right===e&&Mn(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(),_s(e.deleteSet,this.id.client,this.id.clock,this.length),fa(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw ht();this.content.gc(e),n?wg(e,this,new gt(this.id,this.length)):this.content=new Ts(this.length)}write(e,n){const s=n>0?he(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,l=this.content.getRef()&Lr|(s===null?0:rt)|(r===null?0:Ut)|(i===null?0:Ss);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=Wc(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===Un?(e.writeParentInfo(!1),e.writeLeftID(a)):ht();i!==null&&e.writeString(i)}this.content.write(e,n)}}const pu=(t,e)=>mw[e&Lr](t),mw=[()=>{ht()},Qg,nw,Xg,iw,ew,tw,pw,rw,Zg,()=>{ht()}],gw=10;class wt extends Bo{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){ht()}write(e,n){e.writeInfo(gw),H(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const mu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},gu="__ $YJS$ __";mu[gu]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");mu[gu]=!0;function ww(t){for(let e=0;e<t.length;e+=1)t[e]=Math.floor(Math.random()*256);return t}function yw(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 to(t=globalThis.crypto){if(typeof t?.randomUUID=="function")return t.randomUUID();const e=new Uint8Array(16),n=typeof t?.getRandomValues=="function"?t.getRandomValues(e):ww(e);return yw(n)}const wu=new Map;class bw{constructor(e){this.room=e,this.onmessage=null,this._onChange=n=>n.key===e&&this.onmessage!==null&&this.onmessage({data:Xp(n.newValue||"")}),_p(this._onChange)}postMessage(e){sc.setItem(this.room,Yp(Hp(e)))}close(){Lp(this._onChange)}}const xw=typeof BroadcastChannel>"u"?bw:BroadcastChannel,Wo=t=>Rt(wu,t,()=>{const e=tn(),n=new xw(t);return n.onmessage=s=>e.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:e}}),kw=(t,e)=>(Wo(t).subs.add(e),e),Sw=(t,e)=>{const n=Wo(t),s=n.subs.delete(e);return s&&n.subs.size===0&&(n.bc.close(),wu.delete(t)),s},On=(t,e,n=null)=>{const s=Wo(t);s.bc.postMessage(e),s.subs.forEach(r=>r(e,n))},yu=0,Ho=1,bu=2,jr=(t,e)=>{H(t,yu);const n=dg(e);$e(t,n)},xu=(t,e,n)=>{H(t,Ho),$e(t,Oo(e,n))},Cw=(t,e,n)=>xu(e,n,et(t)),ku=(t,e,n,s)=>{try{Uc(e,et(t),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},vw=(t,e)=>{H(t,bu),$e(t,e)},jw=ku,Ew=(t,e,n,s,r)=>{const i=oe(t);switch(i){case yu:Cw(t,e,n);break;case Ho:ku(t,n,s,r);break;case bu:jw(t,n,s,r);break;default:throw new Error("Unknown message type")}return i},Dw=0,_w=(t,e,n)=>{oe(t)===Dw&&n(e,Fe(t))},Li=3e4;class Lw extends Ya{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=nn();this.getLocalState()!==null&&Li/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Li<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&Vo(this,s,"timeout")},St(Li/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:nn()});const l=[],a=[],c=[],u=[];e===null?u.push(n):i==null?e!=null&&l.push(n):(a.push(n),In(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 Vo=(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:nn()})}s.push(i)}}s.length>0&&(t.emit("change",[{added:[],updated:[],removed:s},n]),t.emit("update",[{added:[],updated:[],removed:s},n]))},qn=(t,e,n=t.states)=>{const s=e.length,r=Ie();H(r,s);for(let i=0;i<s;i++){const l=e[i],a=n.get(l)||null,c=t.meta.get(l).clock;H(r,l),H(r,c),Qe(r,JSON.stringify(a))}return je(r)},Rw=(t,e,n)=>{const s=rn(e),r=nn(),i=[],l=[],a=[],c=[],u=oe(s);for(let f=0;f<u;f++){const h=oe(s);let p=oe(s);const w=JSON.parse(Fe(s)),g=t.meta.get(h),S=t.states.get(h),v=g===void 0?0:g.clock;(v<p||v===p&&w===null&&t.states.has(h))&&(w===null?h===t.clientID&&t.getLocalState()!=null?p++:t.states.delete(h):t.states.set(h,w),t.meta.set(h,{clock:p,lastUpdated:r}),g===void 0&&w!==null?i.push(h):g!==void 0&&w===null?c.push(h):w!==null&&(In(w,S)||a.push(h),l.push(h)))}(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])},Tw=t=>Fp(t,(e,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(e)}`).join("&"),gn=0,Su=3,Wn=1,Aw=2,Ps=[];Ps[gn]=(t,e,n,s,r)=>{H(t,gn);const i=Ew(e,t,n.doc,n);s&&i===Ho&&!n.synced&&(n.synced=!0)};Ps[Su]=(t,e,n,s,r)=>{H(t,Wn),$e(t,qn(n.awareness,Array.from(n.awareness.getStates().keys())))};Ps[Wn]=(t,e,n,s,r)=>{Rw(n.awareness,et(e),n)};Ps[Aw]=(t,e,n,s,r)=>{_w(e,n.doc,(i,l)=>Nw(n,l))};const ka=3e4,Nw=(t,e)=>console.warn(`Permission denied to access ${t.url}.
10
+ ${e}`),Cu=(t,e,n)=>{const s=rn(e),r=Ie(),i=oe(s),l=t.messageHandlers[i];return l?l(r,s,t,n,i):console.error("Unable to compute message"),r},no=(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,Vo(t.awareness,Array.from(t.awareness.getStates().keys()).filter(s=>s!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(vu,wo(Xf(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t))},vu=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=nn();const s=Cu(t,new Uint8Array(n.data),!0);yo(s)>1&&e.send(je(s))},e.onerror=n=>{t.emit("connection-error",[n,t])},e.onclose=n=>{no(t,e,n)},e.onopen=()=>{t.wsLastMessageReceived=nn(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);const n=Ie();if(H(n,gn),jr(n,t.doc),e.send(je(n)),t.awareness.getLocalState()!==null){const s=Ie();H(s,Wn),$e(s,qn(t.awareness,[t.doc.clientID])),e.send(je(s))}},t.emit("status",[{status:"connecting"}])}},Ri=(t,e)=>{const n=t.ws;t.wsconnected&&n&&n.readyState===n.OPEN&&n.send(e),t.bcconnected&&On(t.bcChannel,e,t)};class Fw extends go{constructor(e,n,s,{connect:r=!0,awareness:i=new Lw(s),params:l={},protocols:a=[],WebSocketPolyfill:c=WebSocket,resyncInterval:u=-1,maxBackoffTime:f=2500,disableBc:h=!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=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=Ps.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=Ie();H(p,gn),jr(p,s),this.ws.send(je(p))}},u)),this._bcSubscriber=(p,w)=>{if(w!==this){const g=Cu(this,new Uint8Array(p),!1);yo(g)>1&&On(this.bcChannel,je(g),this)}},this._updateHandler=(p,w)=>{if(w!==this){const g=Ie();H(g,gn),vw(g,p),Ri(this,je(g))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:p,updated:w,removed:g},S)=>{const v=p.concat(w).concat(g),C=Ie();H(C,Wn),$e(C,qn(i,v)),Ri(this,je(C))},this._exitHandler=()=>{Vo(this.awareness,[s.clientID],"app closed")},sn&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&ka<nn()-this.wsLastMessageReceived&&no(this,this.ws,null)},ka/10),r&&this.connect()}get url(){const e=Tw(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(),sn&&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||(kw(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);const e=Ie();H(e,gn),jr(e,this.doc),On(this.bcChannel,je(e),this);const n=Ie();H(n,gn),xu(n,this.doc),On(this.bcChannel,je(n),this);const s=Ie();H(s,Su),On(this.bcChannel,je(s),this);const r=Ie();H(r,Wn),$e(r,qn(this.awareness,[this.doc.clientID])),On(this.bcChannel,je(r),this)}disconnectBc(){const e=Ie();H(e,Wn),$e(e,qn(this.awareness,[this.doc.clientID],new Map)),Ri(this,je(e)),this.bcconnected&&(Sw(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&no(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(vu(this),this.connectBc())}}const jn=t=>Gn((e,n)=>{t.onerror=s=>n(new Error(s.target.error)),t.onsuccess=s=>e(s.target.result)}),Ow=(t,e)=>Gn((n,s)=>{const r=indexedDB.open(t);r.onupgradeneeded=i=>e(i.target.result),r.onerror=i=>s(Ct(i.target.error)),r.onsuccess=i=>{const l=i.target.result;l.onversionchange=()=>{l.close()},n(l)}}),Mw=t=>jn(indexedDB.deleteDatabase(t)),$w=(t,e)=>e.forEach(n=>t.createObjectStore.apply(t,n)),ms=(t,e,n="readwrite")=>{const s=t.transaction(e,n);return e.map(r=>Hw(s,r))},ju=(t,e)=>jn(t.count(e)),Iw=(t,e)=>jn(t.get(e)),Eu=(t,e)=>jn(t.delete(e)),Pw=(t,e,n)=>jn(t.put(e,n)),so=(t,e)=>jn(t.add(e)),Uw=(t,e,n)=>jn(t.getAll(e,n)),zw=(t,e,n)=>{let s=null;return Ww(t,e,r=>(s=r,!1),n).then(()=>s)},Bw=(t,e=null)=>zw(t,e,"prev"),qw=(t,e)=>Gn((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()}}),Ww=(t,e,n,s="next")=>qw(t.openKeyCursor(e,s),r=>n(r.key)),Hw=(t,e)=>t.objectStore(e),Vw=(t,e)=>IDBKeyRange.upperBound(t,e),Kw=(t,e)=>IDBKeyRange.lowerBound(t,e),Ti="custom",Du="updates",_u=500,Lu=(t,e=()=>{},n=()=>{})=>{const[s]=ms(t.db,[Du]);return Uw(s,Kw(t._dbref,!1)).then(r=>{t._destroyed||(e(s),De(t.doc,()=>{r.forEach(i=>Uc(t.doc,i))},t,!1),n(s))}).then(()=>Bw(s).then(r=>{t._dbref=r+1})).then(()=>ju(s).then(r=>{t._dbsize=r})).then(()=>s)},Jw=(t,e=!0)=>Lu(t).then(n=>{(e||t._dbsize>=_u)&&so(n,Oo(t.doc)).then(()=>Eu(n,Vw(t._dbref,!0))).then(()=>ju(n).then(s=>{t._dbsize=s}))});class Gw extends Ya{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=Ow(e,s=>$w(s,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=Gn(s=>this.on("synced",()=>s(this))),this._db.then(s=>{this.db=s,Lu(this,l=>so(l,Oo(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]=ms(this.db,[Du]);so(i,s),++this._dbsize>=_u&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{Jw(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(()=>{Mw(this.name)})}get(e){return this._db.then(n=>{const[s]=ms(n,[Ti],"readonly");return Iw(s,e)})}set(e,n){return this._db.then(s=>{const[r]=ms(s,[Ti]);return Pw(r,n,e)})}del(e){return this._db.then(n=>{const[s]=ms(n,[Ti]);return Eu(s,e)})}}const Yw={Sync:0,Awareness:1,Flush:4,Protocol:5,Maintenance:6,Permission:7,CompileStates:8,FormatLease:9},Ai=3,Xw=["queued","running","succeeded","failed","cleaned"],Qw=["cache","artifacts"];function Zw(t){return typeof t=="string"&&Xw.includes(t)}function ey(t){return typeof t=="string"&&Qw.includes(t)}const Sa=[["#1677c8","#1677c833"],["#d65745","#d6574533"],["#16866a","#16866a33"],["#9a58b5","#9a58b533"],["#d27b18","#d27b1833"],["#3f7d20","#3f7d2033"],["#be3e7b","#be3e7b33"],["#4964c6","#4964c633"],["#8a6a14","#8a6a1433"],["#087f8c","#087f8c33"]],{Sync:ty,Awareness:ny,Flush:Ca,Protocol:va,Maintenance:sy,Permission:ry,CompileStates:iy,FormatLease:Ni}=Yw,oy=6e4,ly=720*60*60*1e3,ay=15e3,cy=5*6e4;function uy(t){if(!t||typeof t!="object")return null;const e=t,n=e.requestedBy;return typeof e.mainFile!="string"||typeof e.runId!="string"||!Zw(e.status)||e.status==="cleaned"&&!ey(e.cleanMode)||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 ja(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[n,s]of Object.entries(t)){const r=uy(s);r&&r.mainFile===n&&(e[n]=r)}return e}function dy(t,e,n){return t<=n&&e<=n}function Ea(t,e,n){const s=r=>r>0&&n-r<=cy;return{recoverable:t.some(r=>r.tabId===e||!s(r.activeAt)),otherActive:t.some(r=>r.tabId!==e&&s(r.activeAt))}}class hy{constructor(e,n){this.projectId=e,this.user=n;const s=window.location.protocol==="https:"?"wss:":"ws:";this.draftTabId=gy(pn(`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 Gw(pn(`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 Fw(`${s}//${window.location.host}${Dr("/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[Ca]=(l,a)=>{const c=Fe(a),u=this.flushRequests.get(c);if(!u)return;const f=oe(a)===1,h=oe(a),p=Fe(a),w=oe(a),g=[];for(let S=0;S<w;S++)g.push(Fe(a));if(window.clearTimeout(u.timer),this.flushRequests.delete(c),f)this.clearOwnWritableDraftMarker(u.draftGeneration),u.resolve({revision:h,persistedAt:p,ok:!0,failedPaths:[]});else{const S=Object.assign(new Error(g.length?`保存失败:${g.join(", ")}`:"源码保存到服务器磁盘失败"),{failedPaths:g});u.reject(S)}},this.provider.messageHandlers[va]=(l,a)=>{const c=Fe(a),u=this.epochStorageKey(),f=Da(u),h=/^([0-9]+):/.exec(c)?.[1]??null,p=f?/^([0-9]+):/.exec(f)?.[1]??null:null,w=!this.epoch&&h===String(Ai)&&p!==null&&p!==h;if((this.epoch&&this.epoch!==c||f&&f!==c)&&!w){this.provider.disconnect(),this.rejectFlushes(new Error("Collaboration state changed"));const $=c.endsWith(":reload")||h!==null&&h!==String(Ai),x=()=>{Fi(u,c.replace(/:reload$/,"")),window.location.reload()};if($)for(const R of this.protocolUpgradeListeners)R();else this.persistence.clearData().then(()=>{this.clearWritableDraftMarkers(),x()});return}this.epoch=c,Fi(u,c);const g=this.provider.ws;if(!g||g.readyState!==WebSocket.OPEN)return;const S=Ie();H(S,va),Qe(S,c),H(S,Ai),g.send(je(S));const v=Ie();H(v,ty),jr(v,this.doc),g.send(je(v));const C=Ie();H(C,ny),$e(C,qn(this.awareness,[this.doc.clientID])),g.send(je(C))},this.provider.messageHandlers[ry]=(l,a)=>{const c=Fe(a),u=Fe(a);if(c!==this.user.id)return;if(u==="revoked"){this.rejectFlushes(new Error("Project access revoked")),this.provider.disconnect();for(const h of this.permissionListeners)h("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 h of this.permissionListeners)h(u,f)}},this.provider.messageHandlers[sy]=(l,a)=>{Fe(a)},this.provider.messageHandlers[iy]=(l,a)=>{let c={};try{c=ja(JSON.parse(Fe(a)))}catch{}this.authoritativeCompileStates=c,this.notifyCompileStateListeners()},this.provider.messageHandlers[Ni]=(l,a)=>{const c=Fe(a),u=Fe(a),f=Fe(a),h=Fe(a),p=Fe(a),w=Fe(a);if(c==="state"){const S=Ki(a)?Fe(a):"",v=Ki(a)?Fe(a):"",C=Number(p);if(!S||!Number.isFinite(C)||C<=Date.now())this.removeFormatLeaseState(f),this.notifyFormatLeaseListeners(null);else{const $={path:f,holderUserId:S,holderName:v,expiresAt:C};this.formatLeaseStatesByPath.set(f,$);const x=this.formatLeaseExpiryTimers.get(f);x!==void 0&&window.clearTimeout(x);const R=window.setTimeout(()=>{const T=this.formatLeaseStatesByPath.get(f);!T||T.expiresAt>Date.now()||(this.removeFormatLeaseState(f),this.notifyFormatLeaseListeners(null))},Math.max(0,C-Date.now())+25);this.formatLeaseExpiryTimers.set(f,R),this.notifyFormatLeaseListeners($)}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:h,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 Cn;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 Sg(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??ja(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=to(),s=this.draftGeneration,r=Ie();return H(r,Ca),Qe(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(je(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=to(),l=Ie();return H(l,Ni),Qe(l,e),Qe(l,i),Qe(l,n),Qe(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 h=Ie();H(h,Ni),Qe(h,"cancel"),Qe(h,i),Qe(h,n),Qe(h,""),f.send(je(h))}}c(new Error("Format lease request timed out"))},e==="acquire"?oy:5e3);this.formatLeaseRequests.set(i,{resolve:a,reject:c,timer:u}),r.send(je(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]=Sa[Math.abs(this.doc.clientID)%Sa.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 pn(`texlite:collaboration-epoch:${this.user.id}:${this.projectId}`)}writableDraftStoragePrefix(){return`${pn(`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())fs(e);this.draftMarkerPresent=!1,this.stopDraftHeartbeat(),fs(this.writableDraftStoragePrefix().slice(0,-1))}clearOwnWritableDraftMarker(e){const n=this.readOwnWritableDraftMarker();!n||!dy(n.generation,this.draftGeneration,e)||(fs(this.ownWritableDraftStorageKey()),this.draftMarkerPresent=!1,this.stopDraftHeartbeat())}readOwnWritableDraftMarker(){return this.readWritableDraftMarker(this.ownWritableDraftStorageKey())}readWritableDraftMarkers(){const e=this.writableDraftStoragePrefix(),n=[];for(const s of fy()){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=Da(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>ly)return fs(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 fs(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};Fi(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)},ay))}stopDraftHeartbeat(){this.draftHeartbeatTimer!==null&&(window.clearInterval(this.draftHeartbeatTimer),this.draftHeartbeatTimer=null)}}function Da(t){try{return window.localStorage.getItem(t)}catch{return null}}function Fi(t,e){try{window.localStorage.setItem(t,e)}catch{}}function fs(t){try{window.localStorage.removeItem(t)}catch{}}function fy(){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 py(t){try{return window.sessionStorage.getItem(t)}catch{return null}}function my(t,e){try{window.sessionStorage.setItem(t,e)}catch{}}function gy(t){const e=py(t);if(e)return e;const n=to();return my(t,n),n}function wy(t,e){return Array.from(t.trim()||e.trim()||"?")[0]?.toLocaleUpperCase()??"?"}function yy(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 by(t,e,n,s,r,i){const[l]=d.useState(()=>new hy(t,e)),[a,c]=d.useState("connecting"),[u,f]=d.useState(!1),[h,p]=d.useState([]),[w,g]=d.useState(null),[S,v]=d.useState(null),[C,$]=d.useState(""),[x,R]=d.useState(!1),[T,D]=d.useState(""),[L,F]=d.useState([]),[te,re]=d.useState(!1),[J,G]=d.useState(s),[me,z]=d.useState(null),[Q,V]=d.useState(!1),ne=d.useRef(n),K=d.useRef(i),fe=d.useRef(r);ne.current=n,K.current=i,fe.current=r,d.useEffect(()=>{const b=l.compileStates();g(b[n]??null)},[n,l]),d.useEffect(()=>{const b=()=>p(l.sessions()),O=()=>{f(!1),p([]),g(null),v(null),$(""),R(!1),D(""),F([]),K.current()},X=({status:A})=>{c(A),A!=="connected"&&O()},ye=A=>{f(A),A||O()},ce=()=>{c("disconnected"),O()},be=()=>{R(l.meta.get("historyWarning")===!0);const A=l.meta.get("filesEvent");yy(A)&&v(A);const ue=l.meta.get("commentsRevision");typeof ue=="string"&&$(ue);const Re=l.meta.get("dictionaryRevision");typeof Re=="string"&&D(Re);const N=l.compileStates();g(N[ne.current]??null)},Se=()=>{const A=l.compileStates();g(A[ne.current]??null)};l.awareness.on("change",b),l.provider.on("status",X),l.provider.on("sync",ye),l.provider.on("connection-close",ce),l.provider.on("connection-error",ce),l.meta.observe(be);const M=l.onCompileStates(Se),Te=l.onProtocolUpgrade(()=>{V(!0),c("disconnected"),O()}),_e=()=>F(l.formatLeaseStates()),_=l.onFormatLeaseState(_e),Oe=()=>{if(!fe.current||l.currentPermission!=="read")return;const A=l.hasWritableDraft,ue=l.hasOtherWritableDraft;!A&&!ue||z({previous:"edit",localDraftReady:A,otherTabDraft:ue})},we=l.onDraftReady(()=>{re(!0),Oe()}),ke=l.onPermissionChanged((A,ue)=>{if(A==="revoked"){c("disconnected"),f(!1),K.current();return}G(A),A==="read"&&ue!=="read"?z({previous:ue,localDraftReady:l.hasWritableDraft,otherTabDraft:l.hasOtherWritableDraft}):A!=="read"&&z(null)});return b(),be(),c(l.connected?"connected":"connecting"),f(l.synced),()=>{l.awareness.off("change",b),l.provider.off("status",X),l.provider.off("sync",ye),l.provider.off("connection-close",ce),l.provider.off("connection-error",ce),l.meta.unobserve(be),M(),Te(),_(),we(),ke(),l.destroy()}},[l]),d.useEffect(()=>{r&&l.connect()},[l,r]),d.useEffect(()=>{l.setPermission(s),G(s),r&&s==="read"&&(l.hasWritableDraft||l.hasOtherWritableDraft)?z({previous:"edit",localDraftReady:l.hasWritableDraft,otherTabDraft:l.hasOtherWritableDraft}):s!=="read"&&z(null)},[l,s,r]);const Z=me!==null;return d.useEffect(()=>{if(!Z)return;const b=()=>{if(l.currentPermission!=="read")return;const X=l.hasWritableDraft,ye=l.hasOtherWritableDraft;z(ce=>!ce||ce.localDraftReady===X&&ce.otherTabDraft===ye?ce:{...ce,localDraftReady:X,otherTabDraft:ye})};b();const O=window.setInterval(b,2e3);return()=>window.clearInterval(O)},[l,Z]),{collaboration:l,status:a,synced:u,activeSessions:h,compileState:w,setCompileState:g,formatLeaseStates:L,filesEvent:S,commentsRevision:C,historyWarning:x,dictionaryRevision:T,localDraftReady:te,permission:J,protocolUpgradeRequired:Q,reconnect:()=>{Q||(c("connecting"),f(!1),p([]),g(null),F([]),l.reconnect())},permissionDowngrade:me,dismissPermissionDowngrade:()=>z(null),discardLocalDraft:async()=>await l.discardLocalDraft()?(z(null),window.location.reload(),!0):(z(O=>O&&{...O,otherTabDraft:!0}),!1)}}function _a(t){return t?.status==="succeeded"?"succeeded":t?.log.includes("Compilation was cancelled.")?"cancelled":t?.status==="failed"?"failed":null}function hn(t){return t instanceof Error&&t.name==="AbortError"}function xy(t){return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement}function ky({projectId:t,project:e,mainFile:n,resolveCompileMainFile:s,getCurrentMainFile:r,initialLatest:i,collaborationSynced:l,sharedState:a,onSharedState:c,save:u,loadOutline:f,onPreviewTab:h,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:S}){const{t:v}=Ge(),[C,$]=d.useState(""),[x,R]=d.useState(!0),[T,D]=d.useState(null),[L,F]=d.useState("full"),[te,re]=d.useState(""),[J,G]=d.useState(null),[me,z]=d.useState(null),[Q,V]=d.useState([]),[ne,K]=d.useState(null),[fe,Z]=d.useState(!1),[ge,ie]=d.useState(!1),[pe,b]=d.useState(()=>new Set),[O,X]=d.useState(()=>new Set),[ye,ce]=d.useState(""),be=d.useRef(n),Se=d.useRef(""),M=d.useRef(null),Te=d.useRef(null),_e=d.useRef(null),_=d.useRef(i),Oe=d.useRef(!1),we=d.useRef(null),ke=d.useRef(null),A=d.useRef(new Set),ue=d.useRef(new Map),Re=d.useRef(null),N=d.useRef(()=>{}),k=d.useRef({onSharedState:c,save:u,loadOutline:f,onPreviewTab:h,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:S,resolveCompileMainFile:s,getCurrentMainFile:r});be.current=n,k.current={onSharedState:c,save:u,loadOutline:f,onPreviewTab:h,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:S,resolveCompileMainFile:s,getCurrentMainFile:r};const B=()=>k.current.getCurrentMainFile?.()||be.current,Ce=I=>{Re.current!==I&&(Re.current=I,k.current.onCompileSuccess())},Ve=async(I,ee)=>{ee||(we.current?.abort(),we.current=new AbortController,ee=we.current.signal);try{const P=I?`?mainFile=${encodeURIComponent(I)}`:"",ae=await le(`/api/projects/${t}/compile/artifacts${P}`,{signal:ee});be.current===I&&(V(ae.artifacts),K(null))}catch(P){!hn(P)&&be.current===I&&(V([]),K(null))}finally{we.current?.signal===ee&&(we.current=null)}};d.useEffect(()=>{if(M.current?.abort(),!n){R(!1),$(""),D(null),F("full"),re(""),G(null),z(null),V([]),K(null),_e.current=null,k.current.onPdfChanged();return}_e.current?.mainFile!==n&&(_e.current=null);const I=new AbortController;M.current=I,R(!0),re(""),G(null),z(null),C&&n&&Se.current===n||($(""),D(null),F("full")),V([]),K(null),k.current.onPdfChanged();let P=null;const ae=`?mainFile=${encodeURIComponent(n)}`,ft=Oe.current?null:_.current;ft&&(Oe.current=!0);const pt=()=>le(`/api/projects/${t}/compile/latest${ae}`,{signal:I.signal}),Xe=ft?ft.then(xe=>xe.mainFile!==n?pt():xe,()=>pt()):pt();let ot=!1;const Nt=()=>{if(ot||I.signal.aborted||!n)return;ot=!0;const xe=new AbortController;A.current.add(xe),Ve(n,xe.signal).finally(()=>{A.current.delete(xe)}),k.current.loadOutline(I.signal,n).catch(()=>{})};return Xe.then(xe=>{if(I.signal.aborted||n&&xe.mainFile!==be.current)return;const U=_e.current;U&&U.mainFile===n&&xe.latestRun?.id!==U.runId||(re(xe.latestRun?.log??""),G(xe.latestRun?.diagnostics??null),z(_a(xe.latestRun)),n&&xe.latestRun?.requestedBy&&(xe.latestRun.status==="queued"||xe.latestRun.status==="running")&&k.current.onSharedState({mainFile:n,runId:xe.latestRun.id,status:xe.latestRun.status,requestedBy:xe.latestRun.requestedBy,updatedAt:new Date().toISOString()}),xe.pdfUrl&&(Se.current=xe.mainFile,$(xe.pdfUrl),D(xe.pdfCompiledAt),F(xe.pdfLoadingMode??"full"),k.current.onPreviewTab("pdf")))}).catch(xe=>{!hn(xe)&&be.current===n&&k.current.onError(de(xe))}).finally(()=>{M.current===I&&(M.current=null),I.signal.aborted||(R(!1),P=window.setTimeout(Nt,0))}),()=>{P!==null&&window.clearTimeout(P),I.abort(),ke.current?.abort();for(const xe of A.current)xe.abort();A.current.clear()}},[t,n]),d.useEffect(()=>{if(!(!a||a.mainFile!==n||a.status!=="cleaned"||!a.cleanMode)){M.current?.abort(),Te.current?.abort(),we.current?.abort(),ke.current?.abort();for(const I of A.current)I.abort();A.current.clear(),a.cleanMode==="artifacts"?(_e.current=null,re(""),G(null),z(null),$(""),D(null),F("full"),V([]),K(null),k.current.onPdfChanged(),k.current.onPreviewTab("pdf"),ce(v("editor.cleanArtifactsComplete"))):ce(v("editor.cleanCacheComplete"))}},[a?.runId,a?.status,a?.cleanMode,a?.mainFile,n,v]),d.useEffect(()=>{!n||a?.mainFile===n&&(a.status==="queued"||a.status==="running")||X(I=>{if(!I.has(n))return I;const ee=new Set(I);return ee.delete(n),ee})},[n,a?.mainFile,a?.status]),d.useEffect(()=>{if(!a||a.mainFile!==n||a.status!=="succeeded"&&a.status!=="failed")return;let I=!1;Te.current?.abort(),ke.current?.abort();const ee=new AbortController;return Te.current=ee,R(!0),le(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(n)}`,{signal:ee.signal}).then(P=>{I||P.mainFile!==be.current||P.latestRun?.id!==a.runId||(re(P.latestRun.log),G(P.latestRun.diagnostics),z(_a(P.latestRun)),a.status==="succeeded"&&a.stale&&ce(v("editor.compileSnapshotStale")),a.status==="succeeded"&&P.pdfUrl?(_e.current={mainFile:n,runId:a.runId},k.current.onPdfChanged(),$(P.pdfUrl),D(P.pdfCompiledAt),F(P.pdfLoadingMode??"full"),k.current.onPreviewTab("pdf"),Ce(a.runId),Ve(n)):a.status==="failed"&&k.current.onPreviewTab(P.latestRun.diagnostics.errors.length?"errors":"log"))}).catch(P=>{!hn(P)&&!I&&k.current.onError(de(P))}).finally(()=>{Te.current===ee&&(Te.current=null),I||R(!1)}),()=>{I=!0,ee.abort(),Te.current===ee&&(Te.current=null)}},[a?.runId,a?.status,a?.mainFile,a?.stale,n,t,v]);const Ne=async()=>{if(!e||e.permission==="read"||!l)return;const I=k.current.resolveCompileMainFile?.()||B();if(!I||ue.current.has(I)||a?.mainFile===I&&(a.status==="queued"||a.status==="running"))return;b(P=>new Set([...P,I])),k.current.onCompileStart(),ce(""),ke.current?.abort(),ke.current=null,re(""),G(null),z(null),k.current.onPreviewTab(C?"pdf":"log");const ee=new AbortController;ue.current.set(I,ee);try{if(!await k.current.save())return;const P=await le(`/api/projects/${t}/compile`,{method:"POST",signal:ee.signal,body:JSON.stringify({mainFile:I})});if(P.mainFile!==I||B()!==I)return;re(P.log),G(P.diagnostics),z(P.cancelled?"cancelled":P.ok?"succeeded":"failed"),P.cancelled&&ce(v("compileControls.cancelled")),P.skipped&&ce(v("editor.upToDate")),P.ok&&P.stale&&ce(v("editor.compileSnapshotStale")),P.pdfUrl?(P.ok&&(_e.current={mainFile:I,runId:P.runId}),k.current.onPdfChanged(),$(P.pdfUrl),D(P.pdfCompiledAt),F(P.pdfLoadingMode??"full"),k.current.onPreviewTab("pdf"),P.ok&&(P.skipped?k.current.onCompileSuccess():Ce(P.runId))):k.current.onPreviewTab(P.diagnostics.errors.length?"errors":"log")}catch(P){!hn(P)&&B()===I&&k.current.onError(de(P))}finally{ue.current.get(I)===ee&&(ue.current.delete(I),b(P=>{const ae=new Set(P);return ae.delete(I),ae}),X(P=>{if(!P.has(I))return P;const ae=new Set(P);return ae.delete(I),ae}))}},ve=async()=>{if(!e||e.permission==="read"||!l)return;const I=B();if(I){X(ee=>new Set([...ee,I]));try{(await le(`/api/projects/${t}/compile/cancel`,{method:"POST",body:JSON.stringify({mainFile:I})})).cancelled||X(P=>{const ae=new Set(P);return ae.delete(I),ae})}catch(ee){X(P=>{const ae=new Set(P);return ae.delete(I),ae}),!hn(ee)&&B()===I&&k.current.onError(de(ee))}}},yt=async I=>{if(!e||e.permission==="read"||!l||ge)return;const ee=B();if(!(!ee||ue.current.has(ee)||a?.mainFile===ee&&(a.status==="queued"||a.status==="running"))){ie(!0),M.current?.abort(),Te.current?.abort(),we.current?.abort(),ke.current?.abort();try{if((await le(`/api/projects/${t}/compile/clean`,{method:"POST",body:JSON.stringify({mainFile:ee,mode:I})})).mainFile!==ee||B()!==ee)return;k.current.onSharedState(null),I==="artifacts"&&(_e.current=null,re(""),G(null),z(null),$(""),D(null),F("full"),V([]),K(null),k.current.onPdfChanged()),ce(v(I==="cache"?"editor.cleanCacheComplete":"editor.cleanArtifactsComplete"))}catch(P){!hn(P)&&B()===ee&&k.current.onError(de(P))}finally{ie(!1)}}};N.current=()=>{Ne()},d.useEffect(()=>{if(!ye)return;const I=window.setTimeout(()=>ce(""),3e3);return()=>window.clearTimeout(I)},[ye]),d.useEffect(()=>{const I=ee=>{if(!(!(ee.ctrlKey||ee.metaKey)||ee.key.toLocaleLowerCase()!=="s")){if(xy(ee.target)){ee.preventDefault();return}ee.preventDefault(),ee.stopPropagation(),ee.repeat||N.current()}};return window.addEventListener("keydown",I,!0),()=>window.removeEventListener("keydown",I,!0)},[]),d.useEffect(()=>()=>{M.current?.abort(),Te.current?.abort(),we.current?.abort(),ke.current?.abort();for(const I of A.current)I.abort();A.current.clear();for(const I of ue.current.values())I.abort();ue.current.clear()},[]);const qe=async I=>{if(!I.viewable)return;ke.current?.abort();const ee=new AbortController;ke.current=ee,Z(!0);try{const P=await le(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(n)}&path=${encodeURIComponent(I.path)}`,{signal:ee.signal});!ee.signal.aborted&&ke.current===ee&&be.current===n&&K(P)}catch(P){hn(P)||k.current.onError(de(P))}finally{ke.current===ee&&(ke.current=null,Z(!1))}};return{pdfUrl:C,pdfCompiledAt:T,pdfLoadingMode:L,pdfLoading:x,compileLog:te,compileDiagnostics:J,compileOutcome:me,artifacts:Q,artifactPreview:ne,artifactLoading:fe,editorNotice:ye,localCompiling:pe.has(n),cancelling:O.has(n),cleaning:ge,compile:Ne,cancelCompile:ve,cleanCompile:yt,viewArtifact:qe}}const ro=10*1024*1024,Sy=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 La(t){return t instanceof Error&&t.name==="AbortError"}function gs(t){const e=t.split("/").filter(Boolean);return e.pop(),e.map((n,s)=>e.slice(0,s+1).join("/"))}function fn(t,e){return!!(t&&e)&&(e===t||e.startsWith(`${t}/`))}function Cy(t){const e=`.${t.split(".").at(-1)?.toLocaleLowerCase()??""}`;return!Sy.has(e)}function Hn(t){return/(?:\.(?:tex|bib|bst|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":Cy(t)?"text":"unsupported"}function vy(t,e){return Dr(`/api/projects/${t}/file/raw?path=${encodeURIComponent(e)}`)}function jy({projectId:t,site:e,activeFile:n,dirty:s,save:r,onError:i,onProject:l,onActiveFile:a,onActiveMainFile:c,onRootDocuments:u}){const{t:f}=Ge(),[h,p]=d.useState([]),[w,g]=d.useState(!1),[S,v]=d.useState(""),[C,$]=d.useState(null),[x,R]=d.useState(!1),[T,D]=d.useState(!1),[L,F]=d.useState(""),[te,re]=d.useState(""),[J,G]=d.useState(""),[me,z]=d.useState(new Set),[Q,V]=d.useState(null),[ne,K]=d.useState(""),[fe,Z]=d.useState(""),[ge,ie]=d.useState(null),[pe,b]=d.useState(!1),[O,X]=d.useState(null),[ye,ce]=d.useState(!1),be=d.useRef(null),Se=d.useRef(null),M=async(k={})=>{be.current?.abort(),be.current=null;const B=k.signal?null:new AbortController;B&&(be.current=B);try{const Ce=await le(`/api/projects/${t}/files`,{signal:k.signal??B?.signal});return(!k.isCurrent||k.isCurrent())&&p(Ce.files),Ce.files}catch(Ce){if(!La(Ce))throw Ce;return}finally{B&&be.current===B&&(be.current=null)}},Te=async()=>{if(!(!S.trim()||S.trim().endsWith("/"))){re("");try{await le(`/api/projects/${t}/file`,{method:"POST",body:JSON.stringify({path:S,content:""})}),await M(),a(S),z(k=>new Set([...k,...gs(S)])),g(!1),v("")}catch(k){re(de(k))}}},_e=async()=>{if(!L.trim())return;re("");const k=J?`${J}/${L.trim()}`:L.trim();try{const B=await le(`/api/projects/${t}/folders`,{method:"POST",body:JSON.stringify({path:k})});await M(),z(Ce=>new Set([...Ce,...gs(B.path),B.path])),G(B.path),D(!1),F("")}catch(B){re(de(B))}},_=async(k,B=new Set,Ce=J)=>{if(!k.length)return;const Ve=e.maxUploadSizeMB;if(k.find(ae=>ae.size>Ve*1024*1024))return i(f("errors.fileTooLarge",{size:Ve}));const ve=Ce,yt=k.map(ae=>ve?`${ve}/${ae.name}`:ae.name),qe=new Map;for(const ae of yt)qe.set(ae,(qe.get(ae)??0)+1);const I=[...qe.entries()].filter(([,ae])=>ae>1).map(([ae])=>ae);if(I.length)return i(f("errors.duplicateUploadNames",{files:I.join(", ")}));const ee=new Set(h.map(ae=>ae.path)),P=[...new Set(yt.filter(ae=>ee.has(ae)&&!B.has(ae)))];if(P.length){X({files:k,directory:ve,collisions:P});return}X(null),ce(!0);try{const ae=new URLSearchParams;ve&&ae.set("directory",ve);let ft="";for(const[pt,Xe]of k.entries()){const ot=yt[pt];ae.delete("overwrite"),B.has(ot)&&ae.set("overwrite","1");const Nt=ae.toString()?`?${ae.toString()}`:"",xe=new FormData;xe.append("file",Xe);try{const U=await le(`/api/projects/${t}/upload${Nt}`,{method:"POST",body:xe});typeof U.path=="string"&&Hn(U.path)&&(ft=U.path)}catch(U){if(U instanceof Ii&&U.status===409&&!B.has(ot)&&U.code==="FILE_EXISTS"){pt>0&&await M(),X({files:k.slice(pt),directory:ve,collisions:[ot]});return}throw U}}await M(),ft&&a(ft)}catch(ae){i(de(ae))}finally{ce(!1)}},Oe=async k=>{await _(Array.from(k.target.files??[])),k.target.value=""},we=async k=>{Se.current?.abort(),Se.current=null,R(!1);const B=vy(t,k.path);if((k.size??0)>ro){$({path:k.path,kind:"large",size:k.size??0,url:B});return}const Ce=Ra(k.path);if(Ce!=="text"){$({path:k.path,kind:Ce,size:k.size??0,url:B});return}$({path:k.path,kind:Ce,size:k.size??0,url:B,content:""}),R(!0);const Ve=new AbortController;Se.current=Ve;try{let Ne;try{Ne=await fetch(B,{signal:Ve.signal})}catch(qe){throw Th(qe)}const ve=Ne.headers.get("content-type")??"";if(!Ne.ok){let qe=null;try{qe=ve.includes("application/json")?await Ne.json():await Ne.text()}catch{}throw new Ii(Ah(qe,Ne.status),Ne.status,Nh(qe))}const yt=await Ne.text();$(qe=>qe?.path===k.path?{...qe,content:yt}:qe)}catch(Ne){La(Ne)||($(null),i(de(Ne)))}finally{Se.current===Ve&&(Se.current=null,R(!1))}},ke=k=>{const B=Ra(k.path),Ce=e.maxCollaborativeFileSizeMB*1024*1024;(k.size??0)>ro||Hn(k.path)&&(k.size??0)>Ce||B!=="text"||!Hn(k.path)?we(k):a(k.path)},A=async()=>{if(!Q)return;const k=ne.trim();if(k){re("");try{if(!await r())return;const B=await le(`/api/projects/${t}/path`,{method:"PATCH",body:JSON.stringify({source:Q.path,destinationDirectory:fe,destinationName:k})}),Ce=ve=>ve===Q.path?B.path:ve.startsWith(`${Q.path}/`)?`${B.path}${ve.slice(Q.path.length)}`:ve;a(ve=>Ce(ve)),c(ve=>Ce(ve)),u(ve=>new Set([...ve].map(Ce))),G(ve=>ve&&Ce(ve));const[Ve,Ne]=await Promise.all([le(`/api/projects/${t}/files`),le(`/api/projects/${t}`)]);p(Ve.files),l(Ne.project),z(ve=>new Set([...ve,...gs(B.path),fe].filter(Boolean))),V(null),K(""),Z("")}catch(B){re(de(B))}}},ue=async()=>{if(ge){re("");try{if(s&&!await r())return;await le(`/api/projects/${t}/file?path=${encodeURIComponent(ge.path)}`,{method:"DELETE"}),ie(null)}catch(k){re(de(k))}}};d.useEffect(()=>()=>{be.current?.abort(),Se.current?.abort()},[]),d.useEffect(()=>{Se.current?.abort(),Se.current=null,R(!1)},[n]);const Re=h.filter(k=>k.type==="directory"),N=h.filter(k=>gs(k.path).every(B=>me.has(B)));return{files:h,setFiles:p,loadFiles:M,newFileOpen:w,setNewFileOpen:g,newFilePath:S,setNewFilePath:v,resourcePreview:C,setResourcePreview:$,resourcePreviewLoading:x,setResourcePreviewLoading:R,newFolderOpen:T,setNewFolderOpen:D,newFolderName:L,setNewFolderName:F,fileDialogError:te,setFileDialogError:re,selectedFolder:J,setSelectedFolder:G,expandedFolders:me,setExpandedFolders:z,moveEntry:Q,setMoveEntry:V,moveName:ne,setMoveName:K,moveDestination:fe,setMoveDestination:Z,deleteEntry:ge,setDeleteEntry:ie,fileDragActive:pe,setFileDragActive:b,uploadConflict:O,setUploadConflict:X,uploadingFiles:ye,directoryEntries:Re,visibleEntries:N,createFile:Te,createFolder:_e,uploadFiles:_,upload:Oe,openFile:ke,movePath:A,removePath:ue}}function Ey({active:t,projectId:e,activeFile:n,content:s,dictionaryWords:r}){const[i,l]=d.useState([]),[a,c]=d.useState(""),[u,f]=d.useState(""),[h,p]=d.useState(0),[w,g]=d.useState(null),[S,v]=d.useState(null),[C,$]=d.useState(!1),[x,R]=d.useState(0),T=d.useRef(0),D=d.useRef(!1),L=d.useRef(!1),F=d.useRef(s),te=d.useRef(n),re=d.useRef(0);F.current=s,te.current=n,L.current=C,d.useEffect(()=>{l([]),c(""),f(""),g(null),v(null),$(!1)},[n,r]),d.useEffect(()=>{v(null),$(!1)},[e]),d.useEffect(()=>{p(z=>i.length?Math.min(z,i.length-1):0)},[i]),d.useEffect(()=>{const z=++T.current;if(!t||!n){l([]),c(""),f(""),g(null);return}if(S){l([]),c(""),f("");return}const Q=s,V=n;let ne=!1;const K=window.setTimeout(()=>{v(null),(async()=>{try{const{lintLatex:fe,isHarperLintSupersededError:Z}=await vt(async()=>{const{lintLatex:ie,isHarperLintSupersededError:pe}=await import("./spellCheck-Y0RlmXbl.js");return{lintLatex:ie,isHarperLintSupersededError:pe}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url);if(ne||z!==T.current||F.current!==Q||te.current!==V)return;let ge;try{ge=await fe(e,V,Q,r)}catch(ie){if(Z(ie))return;throw ie}if(ne||z!==T.current||F.current!==Q||te.current!==V)return;D.current=!1,$(!1),l(ge),c(Q),f(V),p(0),g(null)}catch(fe){if(ne||z!==T.current||F.current!==Q||te.current!==V)return;l([]),c(""),f(""),v(fe instanceof Error?fe.message:String(fe));const Z=D.current;D.current=!1,$(Z?L.current:!1)}})()},700);return()=>{ne=!0,window.clearTimeout(K)}},[t,e,n,s,r,x,S]),d.useEffect(()=>{if(!S||!t)return;let z=!1;const Q=()=>{z||(z=!0,D.current=!0,v(null),R(ne=>ne+1))},V=window.setTimeout(Q,15e3);return window.addEventListener("online",Q,{once:!0}),()=>{window.clearTimeout(V),window.removeEventListener("online",Q)}},[S,t]);const J=t&&u===n&&a===s,G=d.useMemo(()=>J?{total:i.length,unique:new Set(i.map(z=>`${z.kind}:${z.word.toLocaleLowerCase("en-US")}`)).size}:null,[J,i]);return{issues:J?i:[],jump:J?w:null,index:h,summary:G,jumpToIssue:z=>{if(!i.length)return;const Q=Math.max(0,Math.min(z,i.length-1)),V=i[Q];p(Q),g({from:V.from,to:V.to,nonce:++re.current})},error:t&&!C?S:null,nativeFallback:t&&!!S,retry:()=>{D.current=!1,v(null),$(!1),R(z=>z+1)},dismissError:()=>{D.current=!1,$(!0)}}}function Ta(t){return t instanceof Error&&t.name==="AbortError"}function Dy({projectId:t,mainFile:e,activeFile:n,onActiveFile:s,onError:r,onShowPdf:i}){const[l,a]=d.useState(null),[c,u]=d.useState(null),[f,h]=d.useState(null),p=d.useRef(null),w=d.useRef(0),g=d.useRef(n),S=d.useRef(s),v=d.useRef(r),C=d.useRef(i),$=L=>L===e&&/\.tex$/i.test(L);g.current=n,S.current=s,v.current=r,C.current=i,d.useEffect(()=>(p.current?.abort(),p.current=null,a(null),u(null),h(null),()=>p.current?.abort()),[t,e]);const x=(L,F,te)=>{h({path:L,line:F,column:te,nonce:++w.current}),g.current!==L&&S.current(L)},R=async(L,F,te,re={})=>{if(!$(L))return;p.current?.abort();const J=new AbortController;p.current=J;try{const G=await le(`/api/projects/${t}/sync/pdf?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(L)}&line=${F}&column=${te}`,{signal:J.signal});if(p.current!==J||!G)return;a({...G,nonce:++w.current}),C.current()}catch(G){!Ta(G)&&!re.silent&&v.current(de(G))}finally{p.current===J&&(p.current=null)}},T=async(L,F,te)=>{if(!$(g.current))return;const re=g.current;p.current?.abort();const J=new AbortController;p.current=J;try{const G=await le(`/api/projects/${t}/sync/source?mainFile=${encodeURIComponent(e)}&page=${L}&x=${F}&y=${te}`,{signal:J.signal});if(p.current!==J||g.current!==re||!$(g.current))return;x(G.path,G.line,G.column)}catch(G){Ta(G)||v.current(de(G))}finally{p.current===J&&(p.current=null)}};return{pdfTarget:l,pdfViewport:c,sourceJump:f,setPdfViewport:u,clearPdfViewport:()=>u(null),jumpToSource:x,syncSourceToPdf:R,syncPdfToSource:T,syncVisiblePdfToSource:()=>{c&&T(c.page,c.x,c.y)}}}function Ru(t,e){return pn(`texlite.workspaceLayout:${encodeURIComponent(t)}:${encodeURIComponent(e)}`)}function Aa(t,e){try{const n=window.localStorage.getItem(Ru(t,e));if(n==="editor-pdf"||n==="editor-only"||n==="pdf-only")return n}catch{}return"editor-pdf"}function _y(t,e){const[n,s]=d.useState(()=>Aa(t,e));return d.useEffect(()=>{s(Aa(t,e))},[t,e]),{workspaceLayout:n,setWorkspaceLayout:i=>{s(i);try{window.localStorage.setItem(Ru(t,e),i)}catch{}}}}function Ly(t){return!/\.(?:bib|bst)$/i.test(t.trim())}const Tu=["verbatim","verbatim*","Verbatim","BVerbatim","LVerbatim","SaveVerbatim","VerbatimOut","bverbatim","bverbatim*","lverbatim","lverbatim*","saveverbatim","saveverbatim*","verbatimout","verbatimwrite","lstlisting","lstlisting*","minted","minted*","tcblisting","tcblisting*","pygmented","alltt","filecontents","filecontents*","luacode","luacodestar","comment"],Ry=new Set(Tu);function Ty(t){return Ry.has(t)}function Ay(t,e,n){if(t[e]!=="[")return e;let s=1;for(let r=e+1;r<n;r+=1){if(t[r]==="\\"){r+=1;continue}if(t[r]==="["&&(s+=1),t[r]==="]"&&(s-=1,s===0))return r+1}return null}function Na(t,e,n){if(t[e]!=="{")return null;let s=1;for(let r=e+1;r<n;r+=1){if(t[r]==="\\"){r+=1;continue}if(t[r]==="{"&&(s+=1),t[r]==="}"&&(s-=1,s===0))return r+1}return null}function Au(t,e,n=t.length){const s=t.indexOf(`
11
+ `,e);s>=0&&(n=Math.min(n,s));const r=/^\\(verb\*?|Verb\*?|lstinline\*?|mintinline\*?)(?![A-Za-z@])/.exec(t.slice(e,n));if(!r)return null;const i=r[1].replace(/\*$/,"");let l=e+r[0].length;if(i!=="verb"){const u=Ay(t,l,n);if(u===null)return null;l=u}if(i==="mintinline"){const u=Na(t,l,n);if(u===null)return null;l=u}const a=t[l];if(!a||/\s/.test(a))return null;if(a==="{"&&i!=="verb"){const u=Na(t,l,n);return{end:u??n,closed:u!==null}}const c=t.indexOf(a,l+1);return c<0||c>=n?{end:n,closed:!1}:{end:c+1,closed:!0}}function Nu(t,e,n=t.length){return Au(t,e,n)?.end??null}function Ko(t,e,n){const s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(String.raw`\\end\s*\{\s*${s}\s*\}`,"g");r.lastIndex=e;const i=r.exec(t);return i?{from:i.index,to:i.index+i[0].length}:null}function As(t,e){let n=0;for(let s=e-1;s>=0&&t[s]==="\\";s-=1)n+=1;return n%2===1}function Ny(t,e){let n=e+1;if(/[A-Za-z@]/.test(t[n]??"")){for(;/[A-Za-z@]/.test(t[n]??"");)n+=1;return t[n]==="*"&&(n+=1),n}return Math.min(t.length,n+1)}function Fu(t,e){const n=/^\\begin\s*\{\s*([A-Za-z0-9@:_*.\-]+)\s*\}/.exec(t.slice(e));return!n||!Ty(n[1])?null:{name:n[1],to:e+n[0].length}}function Bb(t,e){const n=Math.max(0,Math.min(t.length,e));for(let s=0;s<n;){if(t[s]==="%"&&!As(t,s)){const l=t.indexOf(`
12
+ `,s),a=l<0?t.length:l;if(n<=a)return"comment";s=a+1;continue}if(t[s]!=="\\"||As(t,s)){s+=1;continue}const r=Au(t,s);if(r!==null){if(n<r.end||!r.closed&&n<=r.end)return"literal";s=r.end;continue}const i=Fu(t,s);if(i){const l=Ko(t,i.to,i.name),a=l?.to??t.length;if(n<a||!l&&n<=a)return"literal";s=a;continue}s=Ny(t,s)}return null}function Fa(t,e,n){return t.slice(e,n).replace(/[^\r\n]/g," ")}function Fy(t){const e=t.split("");for(let n=0;n<t.length;n+=1){if(t[n]!=="%"||As(t,n))continue;const s=t.indexOf(`
13
+ `,n),r=s<0?t.length:s;for(let i=n;i<r;i+=1)e[i]=" ";n=r}return e.join("")}function Oy(t){let e="",n=0;for(;n<t.length;){if(t[n]==="%"&&!As(t,n)){const i=t.indexOf(`
14
+ `,n),l=i<0?t.length:i;e+=t.slice(n,l),n=l;continue}if(t[n]!=="\\"||As(t,n)){e+=t[n],n+=1;continue}const s=Nu(t,n);if(s!==null){e+=Fa(t,n,s),n=s;continue}const r=Fu(t,n);if(r){const l=Ko(t,r.to,r.name)?.to??t.length;e+=Fa(t,n,l),n=l;continue}e+=t[n],n+=1}return e}function My(t,e){let n=0;for(let s=e-1;s>=0&&t[s]==="\\";s-=1)n+=1;return n%2===1}function Oa(t){const e=Fy(Oy(t)),n=/\\documentclass(?![A-Za-z@])\s*(?:\[[^\]]*\]\s*)?\{/g;for(const s of e.matchAll(n))if(s.index!==void 0&&!My(e,s.index))return!0;return!1}const $y=new Set(Tu);function Iy(t){return/[A-Za-z@0-9:_-]/.test(t)}function Py(t,e){let n=0;for(let s=e-1;s>=0&&t[s]==="\\";s-=1)n+=1;return n%2===1}function os(t,e){return t[e]==="%"&&!Py(t,e)}function Us(t,e){const n=t.indexOf(`
15
+ `,e);return n===-1?t.length:n}function Er(t,e){let n=e;for(;n<t.length;){if(/\s/.test(t[n])){n+=1;continue}if(os(t,n)){n=Us(t,n);continue}break}return n}function io(t,e,n,s){if(t[e]!==n)return null;let r=0,i=0;for(let l=e;l<t.length;l+=1){const a=t[l];if(a==="\\"&&l+1<t.length){l+=1;continue}if(os(t,l)){l=Us(t,l)-1;continue}if(n==="["){if(a==="{"){i+=1;continue}if(a==="}"&&i>0){i-=1;continue}if(i>0)continue}if(a===n){r+=1;continue}if(a===s&&(r-=1,r===0))return{from:e,to:l+1,contentFrom:e+1,contentTo:l}}return null}function oo(t,e,n){const s=[];let r=e;for(;s.length<n;){for(r=Er(t,r);t[r]==="[";){const l=io(t,r,"[","]");if(!l)return s;r=Er(t,l.to)}if(t[r]!=="{")break;const i=io(t,r,"{","}");if(!i)break;s.push(i),r=i.to}return s}function qb(t,e,n){const s=[];let r=e;for(;s.length<n&&(r=Er(t,r),t[r]==="[");){const i=io(t,r,"[","]");if(!i)break;s.push(i),r=i.to}return s}function Uy(t,e){if(t[e]!=="\\"||e+1>=t.length)return null;let n=e+1;if(!/[A-Za-z@]/.test(t[n]))return{name:t[n],from:e,to:n+1};for(;n<t.length&&Iy(t[n]);)n+=1;const s=t.slice(e+1,n);return t[n]==="*"&&(n+=1),{name:s,from:e,to:n}}function zy(t,e){if(e.name!=="begin")return e.to;const n=oo(t,e.to,1)[0];if(!n)return e.to;const s=t.slice(n.contentFrom,n.contentTo).trim();return $y.has(s)?Ko(t,n.to,s)?.to??t.length:e.to}function By(t,e){let n=0;for(;n<t.length;){if(os(t,n)){n=Us(t,n);continue}if(t[n]!=="\\"){n+=1;continue}const s=Uy(t,n);if(!s){n+=1;continue}const r=Nu(t,s.from);if(r!==null&&r>s.to){n=r;continue}const i=zy(t,s);if(i>s.to){n=i;continue}e(s),n=s.to}}function Oi(t,e,n){const s=[];let r=e.contentFrom,i=e.contentFrom;for(;i<=e.contentTo;){if(i<e.contentTo&&os(t,i)){i=Us(t,i),t[i]===`
16
+ `&&(i+=1);continue}if(i!==e.contentTo){i+=1;continue}const l=qy(t,r,i);l&&s.push(l),r=i+1,i+=1}return s}function qy(t,e,n){const s=[];let r=e;for(;r<n;){if(os(t,r)){r=Us(t,r),t[r]===`
17
+ `&&(r+=1);continue}s.push({character:t[r],index:r}),r+=1}let i=0,l=s.length;for(;i<l&&/\s/.test(s[i].character);)i+=1;for(;l>i&&/\s/.test(s[l-1].character);)l-=1;return i===l?null:{path:s.slice(i,l).map(a=>a.character).join(""),command:"",from:s[i].index,to:s[l-1].index+1}}function Wy(t,e){const n=Er(t,e);if(n>=t.length||/[\\{}\[\]#~]/.test(t[n]))return null;let s=n;for(;s<t.length&&!/\s/.test(t[s])&&!os(t,s)&&!/[\\{}\[\]#~]/.test(t[s]);)s+=1;return s===n?null:{path:t.slice(n,s),command:"",from:n,to:s}}function Ma(t){const e=[];return By(t,n=>{const s=n.name.toLowerCase();if(s==="input"||s==="include"||s==="subfile"){const c=oo(t,n.to,1)[0];if(c)for(const u of Oi(t,c))e.push({...u,command:n.name});else if(s==="input"){const u=Wy(t,n.to);u&&e.push({...u,command:n.name})}return}if(s!=="import"&&s!=="subimport"&&s!=="includefrom"&&s!=="inputfrom"&&s!=="subinputfrom"&&s!=="subincludefrom")return;const r=oo(t,n.to,2);if(r.length!==2)return;const i=Oi(t,r[0])[0]?.path??"",l=Oi(t,r[1])[0];if(!l)return;const a=i&&!i.endsWith("/")?"/":"";e.push({path:i+a+l.path,command:n.name,from:l.from,to:l.to,directory:i})}),e}function Hy({sessions:t,status:e}){const{t:n}=Ge(),[s,r]=d.useState(!1),i=Math.max(0,t.length-5),l=s&&i>0,a=l?t:t.slice(0,5);return d.useEffect(()=>{t.length<=5&&r(!1)},[t.length]),t.length<=1?null:o.jsxs("div",{className:`collaboration-presence collaboration-${e}`,children:[o.jsx("span",{className:"collaboration-status-dot","data-tooltip":n(`editor.collaboration.${e}`),"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"),h=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},"aria-label":h,tabIndex:0,children:[wy(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 Vy({value:t,onChange:e}){const{t:n}=Ge(),[s,r]=d.useState(!1),i=d.useRef(null),l=[{value:"editor-pdf",icon:Ul},{value:"editor-only",icon:sf},{value:"pdf-only",icon:rf}];return d.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(Ul,{size:15}),o.jsxs("span",{children:[o.jsx("small",{children:n("editor.layout.label")}),n(`editor.layout.${t}.name`)]}),o.jsx(co,{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($h,{size:16})]},a.value)})]})]})}function Ky({site:t,project:e,activeFile:n,saveStateLabel:s,editorPreferences:r,activeSessions:i,collaborationStatus:l,reconnectCollaboration:a,protocolUpgradeRequired:c,showEditor:u,filesCollapsed:f,toggleFilesPanel:h,workspaceLayout:p,changeWorkspaceLayout:w,onBack:g,onShare:S,showCitationLibrary:v,citationLibraryOpen:C,onCitationLibrary:$,onSelectionHistory:x,onHistory:R,onGit:T,canManageGit:D,formatting:L,readOnly:F,collaborationSynced:te,hasSelection:re,onToggleComments:J,commentsOpen:G,unresolvedCommentCount:me,hasActiveFile:z,onToggleSettings:Q,settingsOpen:V,compileBusy:ne,sharedCompiling:K,localCompiling:fe,cancelling:Z,compileState:ge,onCompile:ie,onCancelCompile:pe}){const{t:b}=Ge();return o.jsxs("header",{className:"editor-topbar",children:[o.jsx("button",{className:"back",title:b("editor.backToProjects"),"aria-label":b("editor.backToProjects"),onClick:g,children:o.jsx(Ih,{size:18})}),o.jsx("a",{className:"brand-link compact-brand-link",href:Dr("/"),"aria-label":t.siteName,onClick:O=>{O.preventDefault(),g()},children:o.jsx(Fh,{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:b("editor.vimOnHint"),children:[o.jsx(tf,{size:14}),b("editor.vimOn")]}),o.jsx(Hy,{sessions:i,status:l}),l==="disconnected"&&!c&&o.jsxs("div",{className:"collaboration-recovery",role:"status",children:[o.jsx("span",{children:b("editor.collaboration.disconnected")}),o.jsx("button",{type:"button",onClick:a,children:b("editor.collaboration.reconnect")})]}),o.jsxs("div",{className:"editor-actions",children:[u&&o.jsxs("button",{className:f?"":"active",onClick:h,children:[f?o.jsx(nf,{size:15}):o.jsx(Va,{size:15}),b("common.files")]}),o.jsx(Vy,{value:p,onChange:w}),o.jsxs("button",{onClick:S,children:[o.jsx(Pi,{size:15}),b("projectSettings.share")]}),v&&o.jsxs("button",{className:C?"active":"",onClick:$,children:[o.jsx(Ph,{size:15}),b("citationLibrary.title")]}),o.jsxs("div",{className:"history-action",role:"group","aria-label":b("history.title"),children:[o.jsxs("div",{className:"history-action-label",children:[o.jsx(Zh,{size:14}),o.jsx("span",{children:b("history.title")})]}),o.jsxs("div",{className:"history-action-options",children:[o.jsx("button",{type:"button",className:"history-action-selection",title:b(re?"selectionHistory.title":"selectionHistory.selectSourceHint"),onMouseDown:O=>O.preventDefault(),onClick:x,disabled:!re||!z,children:b("selectionHistory.buttonLabel")}),o.jsx("button",{type:"button",className:"history-action-snapshots",title:b("history.projectSnapshots"),onClick:R,children:b("history.projectSnapshotsButton")})]})]}),o.jsxs("button",{type:"button",className:`comments-action${G?" active":""}`,title:b("editor.commentsAll"),"aria-label":me>0?`${b("common.comments")} (${me})`:b("common.comments"),onClick:J,children:[o.jsx(Uh,{size:15}),o.jsx("span",{children:b("common.comments")}),me>0&&o.jsx("sup",{className:"comments-action-count",children:me})]}),o.jsxs("button",{className:"git-action",title:b(D?"git.title":"git.ownerOnly"),disabled:!D,onClick:T,children:[o.jsx(zh,{size:15}),"Git"]}),o.jsxs("button",{className:V?"active":"",onClick:Q,children:[o.jsx(uf,{size:15}),b("common.settings")]}),K||fe?o.jsxs("button",{className:"compile cancel-compile",title:b("compileControls.cancel"),onClick:pe,disabled:Z||L||F||!te,children:[Z?o.jsx(st,{className:"spin",size:15}):o.jsx(ks,{size:15}),b(Z?"compileControls.cancelling":"compileControls.cancel")]}):o.jsxs("button",{className:"compile",title:b("editor.compileShortcut"),onClick:ie,disabled:ne||L||F||!te,children:[ne?o.jsx(st,{className:"spin",size:15}):o.jsx(of,{size:15}),b("editor.compile",{engine:e.engine})]})]})]})}function Jy(t){return`${t.path}\0${t.line}`}function Gy(t){const e=[],n=[];for(const s of t){for(;n.length&&n.at(-1).level>=s.level;)n.pop();const r=n.at(-1);r&&(e[r.index].hasChildren=!0),e.push({item:s,key:Jy(s),ancestorKeys:n.map(({index:i})=>e[i].key),hasChildren:!1}),n.push({level:s.level,index:e.length-1})}return e}function Yy(t,e){return t.filter(n=>!n.ancestorKeys.some(s=>e.has(s)))}function Xy({project:t,filesPanel:e,files:n,visibleEntries:s,activeFile:r,activeMainFile:i,rootDocuments:l,selectedFolder:a,expandedFolders:c,fileDragActive:u,uploadingFiles:f,readOnly:h,formatting:p,canFormat:w,activeFormatLease:g,collaborationSynced:S,editorFontSize:v,outline:C,sourceCursorStore:$,wordCountBusy:x,hasSelection:R,hasFormatSelection:T,uploadInput:D,setSelectedFolder:L,setExpandedFolders:F,setMoveEntry:te,setMoveName:re,setMoveDestination:J,setDeleteEntry:G,setFileDialogError:me,setNewFolderName:z,setNewFolderOpen:Q,setNewFilePath:V,setNewFileOpen:ne,setQuickOpen:K,setProjectSearchOpen:fe,setFileDragActive:Z,setFilesCollapsed:ge,toggleFilesPanel:ie,uploadFiles:pe,upload:b,openFile:O,onFormatFile:X,onFormatSelection:ye,jumpToSource:ce,syncSourceToPdf:be,onWordCount:Se}){const{t:M}=Ge(),[Te,_e]=d.useState(!1);return o.jsx(_r,{id:"files",order:1,ref:e,defaultSize:16,minSize:12,maxSize:30,collapsible:!0,collapsedSize:0,onCollapse:()=>ge(!0),onExpand:()=>ge(!1),children:o.jsxs("aside",{className:"left-panel",children:[o.jsxs("section",{className:`files-panel${u?" drop-active":""}`,onDragEnter:_=>{_.dataTransfer.types.includes("Files")&&(_.preventDefault(),!h&&!f&&Z(!0))},onDragOver:_=>{_.dataTransfer.types.includes("Files")&&(_.preventDefault(),_.dataTransfer.dropEffect=h||f?"none":"copy")},onDragLeave:_=>{_.currentTarget.contains(_.relatedTarget)||Z(!1)},onDrop:_=>{_.preventDefault(),Z(!1),!h&&!f&&pe(Array.from(_.dataTransfer.files))},children:[o.jsxs("div",{className:"panel-title",children:[o.jsx("button",{className:"file-size-toggle",type:"button","aria-pressed":Te,title:M(Te?"editor.hideFileSizes":"editor.showFileSizes"),onClick:()=>_e(_=>!_),children:M("common.files")}),o.jsxs("span",{className:"file-tools",children:[o.jsx("button",{"aria-label":M("navigation.quickOpen"),title:`${M("navigation.quickOpen")} (Ctrl/Cmd+P)`,onClick:()=>K(!0),children:o.jsx(Bh,{size:15})}),o.jsx("button",{"aria-label":M("navigation.projectSearch"),title:`${M("navigation.projectSearch")} (Ctrl/Cmd+Shift+F)`,onClick:()=>fe(!0),children:o.jsx(Jh,{size:15})}),!h&&o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:f,"aria-label":M("editor.uploadAttachment"),title:M("editor.uploadTo",{folder:a||M("editor.projectRoot")}),onClick:()=>D.current?.click(),children:o.jsx($l,{size:15})}),o.jsx("button",{"aria-label":M("editor.newFolder"),title:M("editor.newFolder"),onClick:()=>{z(""),Q(!0)},children:o.jsx(qh,{size:15})}),o.jsx("button",{"aria-label":M("editor.newFile"),title:M("editor.newFile"),onClick:()=>{V(a?`${a}/`:""),ne(!0)},children:o.jsx(ef,{size:15})}),o.jsx("input",{ref:D,type:"file",multiple:!0,hidden:!0,onChange:_=>{b(_)}})]}),o.jsx("button",{"aria-label":M("editor.collapseFiles"),title:M("editor.collapseFiles"),onClick:ie,children:o.jsx(Va,{size:15})})]})]}),u&&o.jsxs("div",{className:"file-drop-overlay",children:[o.jsx($l,{size:24}),o.jsx("strong",{children:M("editor.dropFiles")}),o.jsx("span",{children:M("editor.uploadTo",{folder:a||M("editor.projectRoot")})})]}),o.jsxs("div",{className:"file-list",style:{fontSize:`${v}px`},children:[o.jsx("div",{className:`file-entry folder-entry root-entry${a===""?" selected":""}`,children:o.jsxs("button",{className:"file-entry-main",onClick:()=>L(""),children:[o.jsx(Wh,{size:15}),o.jsx("span",{children:M("editor.projectRoot")})]})}),s.map(_=>{const Oe=_.path.split("/").length-1,we=_.path.split("/").at(-1),ke=c.has(_.path),A=l.has(_.path),ue=i===_.path,Re=_.path!==t.mainFile&&!t.mainFile.startsWith(`${_.path}/`);return _.type==="directory"?o.jsxs("div",{className:`file-entry folder-entry${a===_.path?" selected":""}`,style:{paddingLeft:`${Oe*13+5}px`},children:[o.jsxs("button",{className:"file-entry-main",onClick:()=>{L(_.path),F(N=>{const k=new Set(N);return k.has(_.path)?k.delete(_.path):k.add(_.path),k})},children:[ke?o.jsx(co,{size:13}):o.jsx(ao,{size:13}),o.jsx(Hh,{size:14}),o.jsx("span",{children:we})]}),!h&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"file-entry-action",title:M("editor.move"),"aria-label":M("editor.move"),onClick:()=>{te(_),re(we??""),J("")},children:o.jsx(Bl,{size:13})}),Re&&o.jsx("button",{className:"file-entry-action danger-text",title:M("editor.deletePath"),"aria-label":M("editor.deletePath"),onClick:()=>{G(_),me("")},children:o.jsx(en,{size:13})})]})]},_.path):o.jsxs("div",{className:`file-entry${r===_.path?" active":""}${A?" root-document":""}${ue?" compile-target":""}`,style:{paddingLeft:`${Oe*13+18}px`},children:[o.jsxs("button",{className:"file-entry-main",onClick:()=>O(_),children:[A?o.jsx(qa,{size:13}):o.jsx(Vn,{size:13}),o.jsx("span",{children:we}),ue&&o.jsx("small",{children:M("editor.currentMainShort")})]}),Te&&typeof _.size=="number"&&o.jsx("span",{className:"file-entry-size",children:Zy(_.size)}),!h&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"file-entry-action",title:M("editor.move"),"aria-label":M("editor.move"),onClick:()=>{te(_),re(we??""),J("")},children:o.jsx(Bl,{size:13})}),Re&&o.jsx("button",{className:"file-entry-action danger-text",title:M("editor.deletePath"),"aria-label":M("editor.deletePath"),onClick:()=>{G(_),me("")},children:o.jsx(en,{size:13})})]})]},_.path)})]}),!h&&w&&o.jsxs("div",{className:"file-format-footer",role:"group","aria-label":M("editor.format"),"aria-busy":p,children:[o.jsxs("div",{className:"file-format-label",children:[o.jsx(Xh,{size:13}),M("editor.format")]}),o.jsxs("div",{className:"file-format-actions",children:[o.jsx("button",{className:T?"":"active",type:"button",title:M("editor.formatFileHint"),onMouseDown:_=>_.preventDefault(),onClick:X,disabled:p||g||!S,children:M("editor.formatFile")}),o.jsx("button",{className:T?"active":"",type:"button",title:M(T?"editor.formatSelection":"editor.formatSelectionHint"),onMouseDown:_=>_.preventDefault(),onClick:ye,disabled:p||g||!S||!T,children:M("editor.formatSelected")})]})]})]}),o.jsx(Qy,{outline:C,activeFile:r,activeMainFile:i,sourceCursorStore:$,wordCountBusy:x,hasSelection:R,jumpToSource:ce,syncSourceToPdf:be,onWordCount:Se})]})})}function Qy({outline:t,activeFile:e,activeMainFile:n,sourceCursorStore:s,wordCountBusy:r,hasSelection:i,jumpToSource:l,syncSourceToPdf:a,onWordCount:c}){const{t:u}=Ge(),f=d.useSyncExternalStore(s.subscribe,s.getOutlineLine,s.getOutlineLine),h=d.useMemo(()=>Gy(t),[t]),p=d.useMemo(()=>h.filter(x=>x.hasChildren).map(x=>x.key),[h]),[w,g]=d.useState(()=>new Set);d.useEffect(()=>{const x=new Set(p);g(R=>{const T=new Set([...R].filter(D=>x.has(D)));return T.size===R.size?R:T})},[p]);const S=p.length>0&&p.every(x=>w.has(x)),v=d.useMemo(()=>Yy(h,w),[h,w]),C=()=>g(x=>S?new Set([...x].filter(R=>!p.includes(R))):new Set([...x,...p])),$=x=>g(R=>{const T=new Set(R);return T.has(x)?T.delete(x):T.add(x),T});return o.jsxs("section",{className:"outline-panel",children:[o.jsxs("div",{className:"panel-title",children:[o.jsxs("button",{className:"outline-heading",type:"button","aria-expanded":!S,title:u(S?"editor.expandOutline":"editor.collapseOutline"),onClick:C,disabled:p.length===0,children:[o.jsx(Vh,{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(st,{className:"spin",size:12}):o.jsx(zl,{size:12}),u("editor.wordCountFull")]}),o.jsxs("button",{type:"button",title:u("editor.wordCountSelectionHint"),onClick:()=>c("selection"),disabled:r||!i,children:[r?o.jsx(st,{className:"spin",size:12}):o.jsx(zl,{size:12}),u("editor.wordCountSelection")]})]})]}),o.jsxs("div",{className:"outline",children:[v.map(x=>{const{item:R}=x,T=w.has(x.key),D=e===R.path&&f===R.line;return o.jsxs("div",{className:`outline-row${D?" current":""}`,children:[o.jsx("span",{className:"outline-guides","aria-hidden":!0,style:{width:`${R.level*12}px`}}),x.hasChildren?o.jsx("button",{className:"outline-toggle",type:"button","aria-label":u(T?"editor.expandOutlineItem":"editor.collapseOutlineItem",{title:R.title}),"aria-expanded":!T,onClick:()=>$(x.key),children:T?o.jsx(ao,{size:13}):o.jsx(co,{size:13})}):o.jsx("span",{className:"outline-toggle-spacer","aria-hidden":!0}),o.jsxs("button",{className:"outline-item",type:"button",onClick:()=>{l(R.path,R.line,1),a(R.path,R.line,1)},children:[o.jsx("small",{children:R.path===e?R.line:R.path.split("/").at(-1)}),o.jsx("span",{className:"outline-title",children:R.title})]})]},x.key)}),t.length===0&&o.jsx("p",{className:"muted padded",children:u("editor.noOutline")})]})]})}function Zy(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 eb=d.lazy(()=>vt(()=>import("./LatexEditor-BYWWx5Km.js"),__vite__mapDeps([9,2,10,1,3,4,5,6,7,8]),import.meta.url).then(t=>({default:t.LatexEditor})));function tb({project:t,activeFile:e,activeMainFile:n,openTabs:s,content:r,loadedFile:i,readOnly:l,comments:a,focusComment:c,editorPreferences:u,completionIndex:f,nativeSpellCheck:h,spellCheckIssues:p,spellCheckJump:w,sourceJump:g,collaborativeText:S,collaborationAwareness:v,undoManager:C,editorNotice:$,activateTab:x,closeTab:R,handleTabKeyDown:T,updateEditorContent:D,setSelection:L,onAddComment:F,onCommentClick:te,onSpellCheckReplace:re,onReferenceNavigate:J,onCursor:G}){const{t:me}=Ge(),z=Pf(a,e),Q=Uf(c,e,i);return o.jsx(_r,{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":me("editor.openFiles"),children:o.jsx("div",{className:"editor-tabs-scroll",children:s.map((V,ne)=>{const K=V===e,fe=V===(n||t.mainFile),Z=V.split("/").at(-1)||V;return o.jsxs("div",{className:`editor-tab-item${K?" active":""}`,role:"presentation",children:[o.jsxs("button",{id:`editor-tab-${encodeURIComponent(V)}`,type:"button",role:"tab","aria-selected":K,"aria-controls":"editor-source-content",tabIndex:K?0:-1,className:`editor-tab${K?" active":""}${fe?" main-tab":""}`,onClick:()=>x(V),onKeyDown:ge=>T(ge,ne),title:V,children:[o.jsx("span",{className:"editor-tab-icon",children:fe?o.jsx(qa,{size:13}):o.jsx(Vn,{size:13})}),o.jsx("span",{className:"editor-tab-title",children:Z}),fe&&o.jsx("small",{className:"editor-tab-badge",children:me("editor.currentMainShort")})]}),o.jsx("button",{type:"button",className:"editor-tab-close",title:me("common.close"),"aria-label":`${me("common.close")} ${Z}`,onClick:()=>R(V),children:o.jsx(ks,{size:12})})]},V)})})}),o.jsxs("div",{id:"editor-source-content",className:"editor-content-container",children:[o.jsx(d.Suspense,{fallback:o.jsxs("div",{className:"preview-empty",children:[o.jsx(st,{className:"spin",size:22}),o.jsx("span",{children:me("common.loading")})]}),children:o.jsx(eb,{value:r,filePath:e,readOnly:l,comments:z,focusComment:Q,preferences:u,nativeSpellCheck:h,completionIndex:f,spellCheckIssues:p,spellCheckJump:w,jumpTo:i===e&&g?.path===e?g:null,searchRequest:0,collaboration:S?{text:S,awareness:v,undoManager:l?void 0:C}:void 0,onChange:D,onSelection:L,onAddComment:F,onCommentClick:te,onSpellCheckReplace:re,onReferenceNavigate:J,onCursor:G},e)}),$&&o.jsx("div",{className:"editor-centered-notice",role:"status","aria-live":"polite",children:$})]})]})})}function $a({diagnostics:t,files:e,empty:n,tone:s,onJump:r}){const{t:i}=Ge(),l=s==="error"?uo:Pt;return t.length?o.jsx("div",{className:`compile-diagnostic-list compile-${s}`,children:t.map((a,c)=>{const u=rb(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 Mi({lines:t,empty:e,tone:n="log"}){const s=n==="error"?uo:n==="warning"?Pt:Ui;return t.length?o.jsx("pre",{className:`compile-output compile-${n}`,children:t.join(`
18
+ `)}):o.jsxs("div",{className:`compile-empty compile-${n}`,children:[o.jsx(s,{size:26}),o.jsx("span",{children:e})]})}function nb({projectId:t,mainFile:e,artifacts:n,preview:s,loading:r,onView:i}){const{t:l}=Ge(),a=c=>Dr(`/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(Vn,{size:14}),o.jsxs("span",{children:[o.jsx("strong",{children:c.path}),o.jsx("small",{children:ib(c.size)})]})]}),o.jsx("a",{href:a(c.path),title:l("editor.downloadArtifact"),"aria-label":l("editor.downloadArtifact"),children:o.jsx(ar,{size:14})})]},c.path))}),o.jsx("div",{className:"artifact-preview",children:r?o.jsxs("div",{className:"compile-empty",children:[o.jsx(st,{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(ar,{size:13}),l("projects.download")]})]}),o.jsx("pre",{children:s.content})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(Vn,{size:24}),o.jsx("span",{children:l("editor.selectArtifact")})]})})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(Ha,{size:26}),o.jsx("span",{children:l("editor.noArtifacts")})]})}function sb({mainFile:t,disabled:e,cleaning:n,onCleanCache:s,onCleanArtifacts:r}){const{t:i}=Ge();return o.jsxs("div",{className:"compile-clean-panel",children:[o.jsxs("div",{className:"compile-clean-intro",children:[o.jsx(Pt,{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(zi,{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(st,{className:"spin",size:14}):o.jsx(zi,{size:14}),i("editor.cleanCache")]})]})]}),o.jsxs("article",{className:"danger",children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(en,{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(st,{className:"spin",size:14}):o.jsx(en,{size:14}),i("editor.cleanArtifacts")]})]})]})]})]})}function rb(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 ib(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const ob=d.lazy(()=>za().then(t=>({default:t.PdfPreview})));function lb({projectId:t,activeMainFile:e,previewTab:n,diagnosticTab:s,pdfUrl:r,pdfLoadingMode:i,pdfLoading:l,pdfCompiledAt:a,pdfCompiledLabel:c,pdfTargetLabel:u,pdfDownloadUrl:f,pdfTarget:h,pdfViewport:p,activeFile:w,compileBusy:g,compileLog:S,compileDiagnostics:v,compileMessages:C,artifacts:$,artifactPreview:x,artifactLoading:R,cleaning:T,readOnly:D,collaborationSynced:L,workspaceLayout:F,showSyncResize:te,diagnosticCount:re,selectPreviewTab:J,changeWorkspaceLayout:G,onSetNotice:me,onSetPdfViewport:z,syncVisiblePdfToSource:Q,syncCurrentSourceToPdf:V,syncPdfToSource:ne,canSyncWithPdf:K,files:fe,jumpToSource:Z,onSetCleanMode:ge,cleanCompile:ie,viewArtifact:pe}){const{t:b}=Ge();return o.jsxs(o.Fragment,{children:[te&&o.jsxs(lo,{className:"resize-handle sync-resize-handle",children:[o.jsx(Wa,{className:"resize-grip",size:12}),o.jsxs("span",{className:"sync-direction-buttons",onPointerDown:O=>O.stopPropagation(),children:[o.jsx("button",{disabled:!p||!K,title:b(K?"editor.showInSource":"editor.syncTexOnlyForMain"),"aria-label":b("editor.showInSource"),onClick:()=>{if(!K){me(b("editor.syncTexOnlyForMain"));return}Q()},children:o.jsx("span",{"aria-hidden":!0,children:"←"})}),o.jsx("button",{disabled:!w||!r||!K,title:b(K?"editor.showInPdf":"editor.syncTexOnlyForMain"),"aria-label":b("editor.showInPdf"),onClick:()=>{if(!K){me(b("editor.syncTexOnlyForMain"));return}V()},children:o.jsx("span",{"aria-hidden":!0,children:"→"})})]})]}),o.jsx(_r,{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":b("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":n==="pdf",className:`pdf-tab${n==="pdf"?" active":""}`,onClick:()=>J("pdf"),title:a?b("editor.pdfCompiledAtFor",{file:e,time:new Date(a).toLocaleString(ws.resolvedLanguage)}):b("editor.currentMainDocument",{path:e}),children:[o.jsx(Vn,{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:()=>J("diagnostics"),children:[o.jsx(Ui,{size:14}),b("editor.outputTabs"),o.jsx("span",{children:re})]})]}),f&&o.jsxs("a",{className:"pdf-download-top",href:f,download:!0,title:b("editor.downloadPdf"),"aria-label":b("editor.downloadPdf"),children:[o.jsx(ar,{size:15}),o.jsx("span",{children:b("editor.downloadPdf")})]})]}),n==="diagnostics"&&o.jsxs("div",{className:"preview-subtabs",role:"tablist","aria-label":b("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":s==="log",className:s==="log"?"active":"",onClick:()=>J("log"),children:[o.jsx(Ui,{size:13}),b("editor.log")]}),o.jsxs("button",{role:"tab","aria-selected":s==="warnings",className:s==="warnings"?"active":"",onClick:()=>J("warnings"),children:[o.jsx(Pt,{size:13}),b("editor.warnings"),o.jsx("span",{children:C.warnings.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="errors",className:s==="errors"?"active":"",onClick:()=>J("errors"),children:[o.jsx(uo,{size:13}),b("editor.errors"),o.jsx("span",{children:C.errors.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="artifacts",className:s==="artifacts"?"active":"",onClick:()=>J("artifacts"),children:[o.jsx(Ha,{size:13}),b("editor.artifacts"),o.jsx("span",{children:$.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="clean",className:s==="clean"?"active":"",onClick:()=>J("clean"),children:[o.jsx(zi,{size:13}),b("editor.clean")]})]}),o.jsxs("div",{className:`preview-content preview-${n} ${n==="diagnostics"?`preview-${s}`:""}`,children:[n==="pdf"&&(r?o.jsx(d.Suspense,{fallback:o.jsxs("div",{className:"pdf-loading-state",role:"status","aria-live":"polite",children:[o.jsx(st,{className:"spin",size:24}),o.jsx("span",{children:b("editor.loadingPdf")})]}),children:o.jsx(ob,{url:r,loadingMode:i,target:h,compiling:g,onViewportLocation:(O,X,ye)=>z({page:O,x:X,y:ye}),onDoubleClickLocation:(O,X,ye)=>{if(z({page:O,x:X,y:ye}),!K){me(b("editor.syncTexOnlyForMain"));return}ne(O,X,ye)}})}):l?o.jsxs("div",{className:"pdf-loading-state",role:"status","aria-live":"polite",children:[o.jsx(st,{className:"spin",size:24}),o.jsx("span",{children:b("editor.loadingPdf")})]}):o.jsxs("div",{className:"preview-empty",children:[o.jsx(Vn,{size:28}),o.jsx("strong",{children:b("editor.preview")}),o.jsx("span",{children:b("editor.previewHint")})]})),n==="diagnostics"&&s==="log"&&o.jsx(Mi,{lines:S?S.split(`
19
+ `):[],empty:b(g?"editor.compiling":"editor.noLog")}),n==="diagnostics"&&s==="warnings"&&(v?o.jsx($a,{tone:"warning",diagnostics:v.warnings,files:fe,empty:b("editor.noWarnings"),onJump:(O,X,ye)=>{F==="pdf-only"&&G("editor-pdf"),Z(O,X,ye)}}):o.jsx(Mi,{tone:"warning",lines:C.warnings,empty:b("editor.noWarnings")})),n==="diagnostics"&&s==="errors"&&(v?o.jsx($a,{tone:"error",diagnostics:v.errors,files:fe,empty:b("editor.noErrors"),onJump:(O,X,ye)=>{F==="pdf-only"&&G("editor-pdf"),Z(O,X,ye)}}):o.jsx(Mi,{tone:"error",lines:C.errors,empty:b("editor.noErrors")})),n==="diagnostics"&&s==="artifacts"&&o.jsx(nb,{projectId:t,mainFile:e,artifacts:$,preview:x,loading:R,onView:O=>{pe(O)}}),n==="diagnostics"&&s==="clean"&&o.jsx(sb,{mainFile:e,disabled:D||!L||g,cleaning:T,onCleanCache:()=>ge("cache"),onCleanArtifacts:()=>ge("artifacts")})]})]})})]})}function ab(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 lr({projectId:t,value:e,onChange:n,onKeyDown:s,onFocus:r,...i}){const{t:l}=Ge(),a=d.useRef(null),[c,u]=d.useState(null),[f,h]=d.useState(!1),[p,w]=d.useState(null),[g,S]=d.useState(0),v=d.useMemo(()=>{if(!p||!c)return[];const D=p.query.toLocaleLowerCase();return(D?c.filter(F=>F.username.toLocaleLowerCase().includes(D)||F.displayName.toLocaleLowerCase().includes(D)):c).slice(0,8)},[c,p]),C=!!(p&&v.length),$=async()=>{if(!(c||f)){h(!0);try{const D=await le(`/api/projects/${t}/mention-candidates`);u(D.users)}catch{u([])}finally{h(!1)}}},x=(D,L)=>{const F=ab(D,L);w(F),S(0),F&&$()},R=D=>{if(!p)return;const L=`@${D.username} `,F=`${e.slice(0,p.start)}${L}${e.slice(p.end)}`,te=p.start+L.length;n(F),w(null),S(0),window.requestAnimationFrame(()=>{a.current?.focus(),a.current?.setSelectionRange(te,te)})},T=D=>{if(!D.nativeEvent.isComposing&&C){if(D.key==="ArrowDown"){D.preventDefault(),S(L=>(L+1)%v.length);return}if(D.key==="ArrowUp"){D.preventDefault(),S(L=>(L-1+v.length)%v.length);return}if(D.key==="Enter"&&!D.ctrlKey&&!D.metaKey&&!D.shiftKey){D.preventDefault(),R(v[g]??v[0]);return}if(D.key==="Escape"){w(null);return}}s?.(D)};return o.jsxs("span",{className:"mention-textarea",children:[o.jsx("textarea",{...i,ref:a,value:e,onFocus:D=>{r?.(D),x(e,D.currentTarget.selectionStart??e.length)},onClick:D=>x(e,D.currentTarget.selectionStart??e.length),onChange:D=>{const L=D.currentTarget.value;n(L),x(L,D.currentTarget.selectionStart??L.length)},onKeyDown:T}),C&&o.jsx("span",{className:"mention-menu",role:"listbox","aria-label":l("editor.mentionUsers"),children:v.map((D,L)=>o.jsxs("button",{type:"button",role:"option","aria-selected":L===g,className:L===g?"active":"",onMouseDown:F=>F.preventDefault(),onClick:()=>R(D),children:[o.jsx(cr,{"aria-hidden":!0,size:13}),o.jsxs("span",{children:[o.jsx("strong",{children:D.displayName}),o.jsxs("small",{children:["(",D.username,")"]})]})]},D.id))})]})}function $i(t,e){!(t.ctrlKey||t.metaKey)||t.key!=="Enter"||t.nativeEvent.isComposing||(t.preventDefault(),t.stopPropagation(),e())}function Ia(t){const e=/(^|\s)(@[\p{L}\p{N}_.-]+)/gu,n=[];let s=0;for(const r of t.matchAll(e)){const i=r.index??0,l=r[1],a=r[2],c=i+l.length;c>s&&n.push(t.slice(s,c)),n.push(o.jsx("span",{className:"comment-inline-mention",children:a},`${c}:${a}`)),s=c+a.length}return n.length?(s<t.length&&n.push(t.slice(s)),n):t}function cb({projectId:t,comment:e,currentUserId:n,unreadCommentMentionId:s,unreadReplyMentionIds:r,highlightedComment:i,highlightedReplyId:l,currentComment:a,showFilePath:c,onMarkMentionRead:u,onFocus:f,onToggle:h,onReply:p,onEdit:w,onDelete:g,onEditReply:S,onDeleteReply:v}){const{t:C}=Ge(),[$,x]=d.useState(!1),[R,T]=d.useState(""),[D,L]=d.useState(!1),[F,te]=d.useState(e.content),[re,J]=d.useState(!1),[G,me]=d.useState(null),[z,Q]=d.useState(""),[V,ne]=d.useState(null),K=async b=>{b?.preventDefault(),R.trim()&&await p(R)&&(T(""),x(!1))},fe=async b=>{b?.preventDefault(),F.trim()&&await w(F)&&L(!1)},Z=async b=>{b?.preventDefault(),!(!G||!z.trim())&&await S(G,z)&&me(null)},ge=e.authorUsername,ie=b=>new Date(b).toLocaleString(ws.resolvedLanguage),pe=async(b,O)=>{O.stopPropagation(),await u(b)};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":""}${a?" review-current":""}`,onClick:()=>{window.getSelection()?.toString()||f()},children:[o.jsxs("header",{className:"comment-header",children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:e.authorDisplayName??ge??C("editor.deletedUser")}),ge&&o.jsxs("small",{children:["@",ge]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:e.createdAt,title:new Date(e.createdAt).toISOString(),children:ie(e.createdAt)}),e.editedAt&&o.jsx("small",{children:C("editor.editedAt",{time:ie(e.editedAt)})})]})]}),o.jsx("div",{className:"comment-location",children:e.orphaned?C("editor.orphaned"):c?C("editor.commentLocation",{path:e.filePath,line:e.startLine}):C("editor.line",{line:e.startLine})}),e.selectedText&&o.jsx("blockquote",{className:"comment-selected-text",children:e.selectedText}),D?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:b=>{fe(b)},onClick:b=>b.stopPropagation(),children:[o.jsx(lr,{projectId:t,autoFocus:!0,rows:4,value:F,onChange:te,onKeyDown:b=>$i(b,fe)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>L(!1),children:C("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!F.trim(),children:[o.jsx(ql,{size:13}),C("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",children:Ia(e.content)}),s&&o.jsxs("div",{className:"comment-mention",children:[o.jsxs("span",{children:[o.jsx(cr,{"aria-hidden":!0,size:12}),C("editor.mentionedYou")]}),o.jsx("button",{type:"button",onClick:b=>{pe(s,b)},children:C("editor.markMentionRead")})]}),e.replies.length>0&&o.jsx("div",{className:"comment-replies",children:e.replies.map(b=>{const O=r?.get(b.id);return o.jsxs("div",{"data-comment-reply-id":b.id,className:`comment-reply${l===b.id?" mention-target":""}`,children:[o.jsxs("header",{children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:b.authorDisplayName??b.authorUsername??C("editor.deletedUser")}),b.authorUsername&&o.jsxs("small",{children:["@",b.authorUsername]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:b.createdAt,title:new Date(b.createdAt).toISOString(),children:ie(b.createdAt)}),b.editedAt&&o.jsx("small",{children:C("editor.editedAt",{time:ie(b.editedAt)})})]})]}),G===b.id?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:X=>{Z(X)},onClick:X=>X.stopPropagation(),children:[o.jsx(lr,{projectId:t,autoFocus:!0,rows:3,value:z,onChange:Q,onKeyDown:X=>$i(X,Z)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>me(null),children:C("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!z.trim(),children:[o.jsx(ql,{size:13}),C("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",children:Ia(b.content)}),O&&o.jsxs("div",{className:"comment-mention",children:[o.jsxs("span",{children:[o.jsx(cr,{"aria-hidden":!0,size:12}),C("editor.mentionedYou")]}),o.jsx("button",{type:"button",onClick:X=>{pe(O,X)},children:C("editor.markMentionRead")})]}),b.authorId===n&&G!==b.id&&o.jsxs("div",{className:"comment-owner-actions",children:[o.jsx("button",{title:C("editor.editReply"),"aria-label":C("editor.editReply"),onClick:X=>{X.stopPropagation(),me(b.id),Q(b.content)},children:o.jsx(Il,{size:12})}),o.jsx("button",{className:"danger-text",title:C("editor.deleteReply"),"aria-label":C("editor.deleteReply"),onClick:X=>{X.stopPropagation(),ne(b.id)},children:o.jsx(en,{size:12})})]})]},b.id)})}),o.jsxs("div",{className:"comment-actions",children:[o.jsxs("button",{className:"resolve",onClick:b=>{b.stopPropagation(),h()},children:[e.resolved?o.jsx(af,{size:13}):o.jsx(Qh,{size:13}),e.resolved?C("editor.reopen"):C("editor.resolve")]}),o.jsxs("button",{className:"reply-action",onClick:b=>{b.stopPropagation(),x(O=>!O)},children:[o.jsx(lf,{size:13}),C("editor.reply")]}),e.authorId===n&&!D&&o.jsxs("span",{className:"comment-owner-actions",children:[o.jsx("button",{title:C("editor.editComment"),"aria-label":C("editor.editComment"),onClick:b=>{b.stopPropagation(),te(e.content),L(!0)},children:o.jsx(Il,{size:13})}),o.jsx("button",{className:"danger-text",title:C("editor.deleteComment"),"aria-label":C("editor.deleteComment"),onClick:b=>{b.stopPropagation(),J(!0)},children:o.jsx(en,{size:13})})]})]}),$&&o.jsxs("form",{className:"comment-reply-form",onSubmit:b=>{K(b)},onClick:b=>b.stopPropagation(),children:[o.jsx(lr,{projectId:t,autoFocus:!0,rows:3,value:R,placeholder:C("editor.replyPlaceholder"),onChange:T,onKeyDown:b=>$i(b,K)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>{x(!1),T("")},children:C("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!R.trim(),children:[o.jsx(cf,{size:13}),C("editor.sendReply")]})]})]})]}),o.jsx(xs,{open:re,title:C("editor.deleteCommentTitle"),description:C("editor.deleteCommentDescription",{count:e.replies.length}),confirmLabel:C("common.delete"),danger:!0,onCancel:()=>J(!1),onConfirm:()=>{g().then(b=>{b&&J(!1)})}}),o.jsx(xs,{open:!!V,title:C("editor.deleteReplyTitle"),description:C("editor.deleteReplyDescription"),confirmLabel:C("common.delete"),danger:!0,onCancel:()=>ne(null),onConfirm:()=>{V&&v(V).then(b=>{b&&ne(null)})}})]})}function ub({open:t,onOpenChange:e,project:n,projectId:s}){const{t:r}=Ge(),[i,l]=d.useState([]),[a,c]=d.useState([]),[u,f]=d.useState(""),[h,p]=d.useState("read"),[w,g]=d.useState(null),[S,v]=d.useState(""),C=n.permission==="owner",$=async()=>{try{const[L,F]=await Promise.all([le(`/api/projects/${s}/members`),le("/api/users")]);l(L.members),c(F.users.filter(te=>te.id!==n.ownerId))}catch(L){v(de(L))}};d.useEffect(()=>{t&&$()},[t,s]);const x=async()=>{if(u)try{await le(`/api/projects/${s}/members/${u}`,{method:"PUT",body:JSON.stringify({permission:h})}),f(""),p("read"),await $()}catch(L){v(de(L))}},R=async(L,F)=>{try{await le(`/api/projects/${s}/members/${L.id}`,{method:"PUT",body:JSON.stringify({permission:F})}),await $()}catch(te){v(de(te))}},T=async()=>{if(w)try{await le(`/api/projects/${s}/members/${w.id}`,{method:"DELETE"}),g(null),await $()}catch(L){v(de(L))}},D=a.filter(L=>!i.some(F=>F.id===L.id));return o.jsxs(o.Fragment,{children:[o.jsx(Yt,{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:[S&&o.jsx("p",{className:"error",children:S}),o.jsxs("div",{className:"share-owner",children:[o.jsx(Pi,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:r("projects.owner")}),o.jsx("strong",{children:n.ownerDisplayName??n.ownerUsername})]})]}),C&&o.jsxs("div",{className:"share-add",children:[o.jsxs("label",{className:"form-field",children:[r("common.user"),o.jsxs("select",{value:u,onChange:L=>f(L.target.value),children:[o.jsx("option",{value:"",children:r("projectSettings.chooseUser")}),D.map(L=>o.jsx("option",{value:L.id,children:L.displayName??L.username},L.id))]})]}),o.jsxs("label",{className:"form-field",children:[r("common.permission"),o.jsxs("select",{value:h,onChange:L=>p(L.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:()=>{x()},children:[o.jsx(Gh,{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(L=>o.jsxs("div",{className:"shared-member",children:[o.jsxs("span",{className:"member-identity",children:[o.jsx("span",{className:"member-avatar",children:(L.displayName??L.username).slice(0,1).toLocaleUpperCase()}),o.jsxs("span",{children:[o.jsx("strong",{children:L.displayName??L.username}),o.jsxs("small",{children:["@",L.username]})]})]}),o.jsxs("span",{className:"member-controls",children:[o.jsxs("select",{"aria-label":r("common.permission"),disabled:!C,value:L.permission,onChange:F=>{R(L,F.target.value)},children:[o.jsx("option",{value:"read",children:r("common.readOnly")}),o.jsx("option",{value:"edit",children:r("common.readWrite")})]}),C&&o.jsx("button",{className:"icon-only danger-text",title:r("common.remove"),"aria-label":r("common.remove"),onClick:()=>g(L),children:o.jsx(en,{size:15})})]})]},L.id)),i.length===0&&o.jsxs("div",{className:"share-empty",children:[o.jsx(Pi,{size:24}),o.jsx("span",{children:r("projectSettings.noMembers")})]})]})]})}),o.jsx(xs,{open:!!w,title:r("projectSettings.removeTitle"),description:r("projectSettings.removeDescription",{username:w?.username??""}),confirmLabel:r("common.remove"),danger:!0,onCancel:()=>g(null),onConfirm:()=>{T()}})]})}const db=d.lazy(()=>vt(()=>import("./CitationLibraryDialog-C5C3sPdw.js"),__vite__mapDeps([11,2,1,3,12,5,13,4,6,14]),import.meta.url).then(t=>({default:t.CitationLibraryDialog}))),hb=d.lazy(()=>vt(()=>import("./GitDialog-BI7QIMsh.js"),__vite__mapDeps([15,2,1,3,5,16,17,13,18,4,6,7,8]),import.meta.url).then(t=>({default:t.GitDialog}))),fb=d.lazy(()=>vt(()=>import("./HistoryDialog-DA7O9aF2.js"),__vite__mapDeps([19,2,1,3,20,21,5,17,13,18,4,6,7,8]),import.meta.url).then(t=>({default:t.HistoryDialog}))),pb=d.lazy(()=>vt(()=>import("./SelectionHistoryDialog-pWMI5izu.js"),__vite__mapDeps([22,2,1,3,20,4,5,6,7,8]),import.meta.url).then(t=>({default:t.SelectionHistoryDialog}))),mb=d.lazy(()=>vt(()=>import("./ProjectNavigationDialogs-DwWYbB1A.js"),__vite__mapDeps([23,2,1,3,6,5,4]),import.meta.url).then(t=>({default:t.ProjectSearchDialog}))),gb=d.lazy(()=>vt(()=>import("./ProjectNavigationDialogs-DwWYbB1A.js"),__vite__mapDeps([23,2,1,3,6,5,4]),import.meta.url).then(t=>({default:t.QuickOpenDialog})));function wb({user:t,project:e,projectId:n,activeFile:s,content:r,maxCitationBibtexBytes:i,files:l,directoryEntries:a,readOnly:c,workspaceLayout:u,changeWorkspaceLayout:f,resourcePreview:h,resourcePreviewLoading:p,setResourcePreview:w,setResourcePreviewLoading:g,uploadConflict:S,setUploadConflict:v,uploadFiles:C,cleanMode:$,setCleanMode:x,cleanCompile:R,newFileOpen:T,setNewFileOpen:D,newFilePath:L,setNewFilePath:F,newFolderOpen:te,setNewFolderOpen:re,newFolderName:J,setNewFolderName:G,selectedFolder:me,fileDialogError:z,setFileDialogError:Q,createFile:V,createFolder:ne,moveEntry:K,setMoveEntry:fe,moveName:Z,setMoveName:ge,moveDestination:ie,setMoveDestination:pe,movePath:b,deleteEntry:O,setDeleteEntry:X,deleteActiveSessions:ye,removePath:ce,commentOpen:be,closeComment:Se,commentSelection:M,selection:Te,commentText:_e,setCommentText:_,commentSubmitting:Oe,commentError:we,addComment:ke,shareOpen:A,setShareOpen:ue,citationLibraryOpen:Re,setCitationLibraryOpen:N,insertCitationAtCursor:k,quickOpen:B,setQuickOpen:Ce,projectSearchOpen:Ve,setProjectSearchOpen:Ne,openFile:ve,jumpToSource:yt,selectionHistoryOpen:qe,setSelectionHistoryOpen:I,historyOpen:ee,setHistoryOpen:P,gitOpen:ae,setGitOpen:ft,save:pt,permissionDowngrade:Xe,permissionDowngradeBusy:ot,dismissPermissionDowngrade:Nt,discardPermissionDraft:xe}){const{t:U}=Ge();return o.jsxs(o.Fragment,{children:[Xe&&o.jsx(Yt,{open:!0,title:U("editor.collaboration.permissionDowngradeTitle"),description:Xe.localDraftReady&&Xe.otherTabDraft?U("editor.collaboration.permissionDowngradeMultipleDrafts"):Xe.otherTabDraft?U("editor.collaboration.permissionDowngradeOtherTab"):Xe.localDraftReady?U("editor.collaboration.permissionDowngradeDescription",{previous:U("common.readWrite")}):U("editor.collaboration.permissionDowngradeNoDraft"),onOpenChange:W=>{!W&&!ot&&Nt()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:ot,onClick:Nt,children:Xe.localDraftReady?U("editor.collaboration.permissionDowngradeKeep"):U("common.close")}),!Xe.otherTabDraft&&o.jsxs("button",{type:"button",className:"danger",disabled:ot,onClick:()=>{xe()},children:[ot?o.jsx(st,{className:"spin",size:14}):Xe.localDraftReady?o.jsx(en,{size:14}):o.jsx(Yh,{size:14}),Xe.localDraftReady?U("editor.collaboration.permissionDowngradeDiscard"):U("editor.collaboration.permissionDowngradeReload")]})]}),children:o.jsx("div",{})}),o.jsxs(Yt,{open:!!h,extraWide:h?.kind==="image"||h?.kind==="pdf"||h?.kind==="text",title:h?.path??"",description:h?.kind==="large"?U("editor.resourceTooLarge",{size:yb(h.size),limit:`${ro/1024/1024} MB`}):U(`editor.resourcePreview.${h?.kind??"text"}`),onOpenChange:W=>{W||(w(null),g(!1))},footer:h&&o.jsxs("a",{className:"primary resource-download",href:`${h.url}&download=1`,download:!0,children:[o.jsx(ar,{size:14}),U("editor.downloadResource")]}),children:[h?.kind==="large"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(Pl,{size:34}),o.jsx("strong",{children:U("editor.resourceTooLargeTitle")}),o.jsx("span",{children:U("editor.resourceTooLargeDescription")})]}),h?.kind==="unsupported"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(Pl,{size:34}),o.jsx("strong",{children:U("editor.resourceUnsupportedTitle")}),o.jsx("span",{children:U("editor.resourceUnsupportedDescription")})]}),h?.kind==="image"&&o.jsx("div",{className:"resource-image-wrap",children:o.jsx("img",{className:"resource-image",src:h.url,alt:h.path})}),h?.kind==="pdf"&&o.jsx("iframe",{className:"resource-pdf",src:h.url,title:h.path}),h?.kind==="text"&&(p?o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(st,{className:"spin",size:24}),o.jsx("span",{children:U("common.loading")})]}):o.jsx("pre",{className:"resource-text",children:h.content}))]}),o.jsx(xs,{open:!!S,title:U("editor.uploadOverwriteTitle"),description:U("editor.uploadOverwriteDescription",{files:S?.collisions.join(", ")??""}),confirmLabel:U("editor.uploadOverwrite"),danger:!0,onCancel:()=>v(null),onConfirm:()=>{const W=S;v(null),W&&C(W.files,new Set(W.collisions),W.directory)}}),o.jsx(xs,{open:!!$,title:U($==="cache"?"editor.cleanCacheConfirmTitle":"editor.cleanArtifactsConfirmTitle"),description:U($==="cache"?"editor.cleanCacheConfirmDescription":"editor.cleanArtifactsConfirmDescription"),confirmLabel:U("editor.cleanConfirm"),danger:$==="artifacts",onCancel:()=>x(null),onConfirm:()=>{const W=$;x(null),W&&R(W)}}),o.jsx(Yt,{open:T,title:U("editor.newFile"),description:U("editor.newFileDescription"),onOpenChange:W=>{D(W),W||Q("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>D(!1),children:U("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{V()},children:U("common.create")})]}),children:o.jsxs(o.Fragment,{children:[z&&o.jsx("p",{className:"error dialog-error",children:z}),o.jsxs("label",{className:"form-field",children:[U("editor.filePath"),o.jsx("input",{autoFocus:!0,value:L,onChange:W=>F(W.target.value),onKeyDown:W=>{W.key==="Enter"&&!W.nativeEvent.isComposing&&(W.preventDefault(),V())}})]})]})}),o.jsx(Yt,{open:te,title:U("editor.newFolder"),description:U("editor.folderDestination",{folder:me||U("editor.projectRoot")}),onOpenChange:W=>{re(W),W||Q("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>re(!1),children:U("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{ne()},children:U("common.create")})]}),children:o.jsxs(o.Fragment,{children:[z&&o.jsx("p",{className:"error dialog-error",children:z}),o.jsxs("label",{className:"form-field",children:[U("editor.folderName"),o.jsx("input",{autoFocus:!0,value:J,onChange:W=>G(W.target.value),onKeyDown:W=>{W.key==="Enter"&&ne()}})]})]})}),o.jsx(Yt,{open:!!K,title:U("editor.moveTitle",{name:K?.path.split("/").at(-1)??""}),description:U("editor.moveDescription"),onOpenChange:W=>{W||(fe(null),ge(""),Q(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>fe(null),children:U("common.cancel")}),o.jsx("button",{className:"primary",disabled:!Z.trim(),onClick:()=>{b()},children:U("editor.moveApply")})]}),children:o.jsxs(o.Fragment,{children:[z&&o.jsx("p",{className:"error dialog-error",children:z}),o.jsxs("label",{className:"form-field",children:[U("editor.pathName"),o.jsx("input",{autoFocus:!0,value:Z,onChange:W=>ge(W.target.value),onKeyDown:W=>{W.key==="Enter"&&b()}})]}),o.jsxs("label",{className:"form-field",children:[U("editor.destinationFolder"),o.jsxs("select",{value:ie,onChange:W=>pe(W.target.value),children:[o.jsx("option",{value:"",children:U("editor.projectRoot")}),a.filter(W=>K?.type!=="directory"||W.path!==K.path&&!W.path.startsWith(`${K.path}/`)).map(W=>o.jsx("option",{value:W.path,children:W.path},W.path))]})]})]})}),o.jsx(Yt,{open:!!O,title:U("editor.deletePathTitle",{name:O?.path.split("/").at(-1)??""}),description:ye.length?U("editor.deletePathActiveDescription",{path:O?.path??"",users:[...new Set(ye.map(W=>W.name))].join(", ")}):U("editor.deletePathDescription",{path:O?.path??""}),onOpenChange:W=>{W||(X(null),Q(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>X(null),children:U("common.cancel")}),o.jsx("button",{className:"danger",onClick:()=>{ce()},children:U("common.delete")})]}),children:o.jsxs(o.Fragment,{children:[z&&o.jsx("p",{className:"error dialog-error",children:z}),ye.length>0&&o.jsxs("p",{className:"warning",children:[o.jsx(Pt,{size:15}),U("editor.deletePathWillClose")]})]})}),o.jsxs(Yt,{open:be,draggable:!0,title:U("editor.addComment"),description:M.selectedText?U("editor.commentDescription",{count:M.endOffset-M.startOffset}):U("editor.pointComment"),onOpenChange:W=>{W||Se()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:Oe,onClick:Se,children:U("common.cancel")}),o.jsxs("button",{type:"button",className:"primary",disabled:Oe||!_e.trim(),onClick:()=>{ke()},children:[Oe&&o.jsx(st,{className:"spin",size:14}),U("editor.addComment")]})]}),children:[we&&o.jsx("p",{className:"error dialog-error",children:we}),o.jsxs("label",{className:"form-field",children:[U("editor.commentContent"),o.jsx(lr,{projectId:n,autoFocus:!0,rows:5,disabled:Oe,value:_e,onChange:_,onKeyDown:W=>{(W.ctrlKey||W.metaKey)&&W.key==="Enter"&&!W.nativeEvent.isComposing&&(W.preventDefault(),W.stopPropagation(),ke())}})]}),M.selectedText&&o.jsx("blockquote",{className:"selection-preview",children:M.selectedText})]}),o.jsx(ub,{open:A,onOpenChange:ue,project:e,projectId:n}),Re&&o.jsx(Ba,{title:U("citationLibrary.title"),onClose:()=>N(!1),children:o.jsx(db,{open:!0,onOpenChange:N,currentFile:s,currentSource:r,readOnly:c,currentUserId:t.id,maxBibtexBytes:i,onInsert:k})}),B&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(gb,{open:!0,files:l,onOpenChange:Ce,onOpenFile:W=>{const qt=l.find(ls=>ls.path===W);qt&&ve(qt)}})}),Ve&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(mb,{open:!0,project:e,onOpenChange:Ne,onJump:(W,qt,ls)=>{u==="pdf-only"&&f("editor-pdf"),yt(W,qt,ls)}})}),qe&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(pb,{open:!0,onOpenChange:I,project:e,filePath:s,selection:Te,currentSource:r})}),ee&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(fb,{open:!0,onOpenChange:P,project:e,onBeforeMutation:e.permission==="read"?async()=>!0:pt})}),e.ownerId===t.id&&ae&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(hb,{open:!0,onOpenChange:ft,project:e,onBeforeMutation:pt})})]})}function yb(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const bb=d.lazy(()=>vt(()=>import("./ProjectSettings-BpPFgdoj.js"),__vite__mapDeps([24,2,1,3,5,25,26,8,4,6,7]),import.meta.url).then(t=>({default:t.ProjectSettings})));function xb({sidePanel:t,onClose:e,project:n,projectId:s,site:r,files:i,currentUserId:l,comments:a,commentsLoading:c,commentsError:u,onRetryComments:f,unreadMentions:h,activeFile:p,hasProjectCommentsScope:w,commentScope:g,onCommentScopeChange:S,focusedCommentId:v,onMarkMentionRead:C,onMarkAllMentionsRead:$,onClearFocusComment:x,targetCommentId:R,targetReplyId:T,onFocusComment:D,onToggleComment:L,onReplyComment:F,onEditComment:te,onDeleteComment:re,onEditCommentReply:J,onDeleteCommentReply:G,dictionaryWords:me,onDictionaryChange:z,editorPreferences:Q,onEditorPreferences:V,spellCheckCount:ne,spellCheckUniqueCount:K,spellCheckIndex:fe,onSpellCheckNavigate:Z,onProject:ge}){const{t:ie}=Ge(),[pe,b]=d.useState("unresolved"),[O,X]=d.useState(null),ye=d.useMemo(()=>({unresolved:xi(a,{activeFile:p,scope:g,filter:"unresolved",unreadMentions:h}).length,mentions:xi(a,{activeFile:p,scope:g,filter:"mentions",unreadMentions:h}).length,resolved:xi(a,{activeFile:p,scope:g,filter:"resolved",unreadMentions:h}).length}),[p,g,a,h]),ce=d.useMemo(()=>If(a,{activeFile:p,scope:g,filter:pe,unreadMentions:h},[O,R,v]),[p,pe,g,a,v,O,R,h]),be=v&&ce.some(A=>A.id===v)?v:O&&ce.some(A=>A.id===O)?O:R&&ce.some(A=>A.id===R)?R:null,Se=qf(ce,be);d.useEffect(()=>{O&&!a.some(A=>A.id===O)&&X(null)},[a,O]),d.useEffect(()=>{!w&&g!=="file"&&(X(null),x(),S("file"))},[g,w,x,S]),d.useEffect(()=>{const A=R&&T?`[data-comment-reply-id="${T}"]`:R?`[data-comment-id="${R}"]`:be?`[data-comment-id="${be}"]`:"";if(!A)return;const ue=document.querySelector(A);if(!ue)return;const Re=window.requestAnimationFrame(()=>ue.scrollIntoView({block:R?"center":"nearest",behavior:"smooth"}));return()=>window.cancelAnimationFrame(Re)},[be,R,T,ce]);const M=A=>{O!==A.id&&X(null),D(A)},Te=async A=>{D(A),X(Bf(A,pe,h)?A.id:null),await L(A)},_e=A=>{const ue=Wf(ce,be,A);X(null),ue?M(ue):x()},_=async A=>{const ue=await C(A);if(!ue||pe!=="mentions")return ue;const Re=h.find(k=>k.id===A)?.commentId;return Re&&(h.some(k=>k.id!==A&&k.commentId===Re)||(O===Re&&X(null),v===Re&&x())),ue},Oe=async()=>{await $()&&pe==="mentions"&&(X(null),x())},we=A=>{A!==g&&(X(null),x(),S(A))},ke=A=>{A!==pe&&(X(null),x(),b(A))};return t?o.jsxs(o.Fragment,{children:[o.jsx(lo,{className:"resize-handle"}),o.jsx(_r,{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:ie("editor.sourceComments")}),o.jsxs("span",{className:"drawer-title-actions",children:[h.length>0&&o.jsxs("button",{className:"drawer-mention-read-all",type:"button",onClick:()=>{Oe()},title:ie("editor.markAllMentionsRead"),children:[o.jsx(cr,{"aria-hidden":!0,size:13}),o.jsx("span",{children:ie("editor.markAllMentionsRead")})]}),o.jsx("button",{"aria-label":ie("common.close"),onClick:e,children:o.jsx(ks,{size:17})})]})]}),o.jsxs("div",{className:"comment-review-controls",children:[w&&o.jsxs("div",{className:"comment-review-group",role:"group","aria-label":ie("editor.commentScope"),children:[o.jsx("button",{type:"button",className:g==="file"?"active":"","aria-pressed":g==="file",onClick:()=>we("file"),children:ie("editor.commentScopeFile")}),o.jsx("button",{type:"button",className:g==="project"?"active":"","aria-pressed":g==="project",onClick:()=>we("project"),children:ie("editor.commentScopeProject")})]}),o.jsxs("div",{className:"comment-review-group",role:"group","aria-label":ie("editor.commentFilter"),children:[o.jsx("button",{type:"button",className:pe==="unresolved"?"active":"","aria-pressed":pe==="unresolved",onClick:()=>ke("unresolved"),children:ie("editor.commentFilterUnresolved",{count:ye.unresolved})}),o.jsx("button",{type:"button",className:pe==="mentions"?"active":"","aria-pressed":pe==="mentions",onClick:()=>ke("mentions"),children:ie("editor.commentFilterMentions",{count:ye.mentions})}),o.jsx("button",{type:"button",className:pe==="resolved"?"active":"","aria-pressed":pe==="resolved",onClick:()=>ke("resolved"),children:ie("editor.commentFilterResolved",{count:ye.resolved})})]}),o.jsxs("div",{className:"comment-review-navigation",children:[o.jsx("button",{type:"button",disabled:Se<=1,"aria-label":ie("editor.commentPrevious"),title:ie("editor.commentPrevious"),onClick:()=>_e(-1),children:o.jsx(Kh,{size:14})}),o.jsx("output",{"aria-live":"polite",children:ie("editor.commentPosition",{current:Se,total:ce.length})}),o.jsx("button",{type:"button",disabled:ce.length===0||Se>0&&Se>=ce.length,"aria-label":ie("editor.commentNext"),title:ie("editor.commentNext"),onClick:()=>_e(1),children:o.jsx(ao,{size:14})})]})]}),u&&o.jsxs("div",{className:"comment-review-error",role:"alert",children:[o.jsx("span",{children:u}),o.jsx("button",{type:"button",onClick:()=>{f()},children:ie("common.retry")})]}),c&&o.jsx("div",{className:"comment-review-loading",role:"status",children:ie("common.loading")}),o.jsxs("div",{className:"comments",children:[ce.map(A=>{const ue=h.find(N=>N.commentId===A.id&&!N.replyId)?.id,Re=new Map(h.filter(N=>N.commentId===A.id&&N.replyId).map(N=>[N.replyId,N.id]));return o.jsx(cb,{projectId:s,comment:A,currentUserId:l,unreadCommentMentionId:ue,unreadReplyMentionIds:Re,highlightedComment:R===A.id&&!T,highlightedReplyId:R===A.id?T:null,currentComment:be===A.id,showFilePath:g==="project",onMarkMentionRead:_,onFocus:()=>M(A),onToggle:()=>{Te(A)},onReply:N=>F(A,N),onEdit:N=>te(A,N),onDelete:()=>re(A),onEditReply:(N,k)=>J(A,N,k),onDeleteReply:N=>G(A,N)},A.id)}),ce.length===0&&!c&&!u&&o.jsx("p",{className:"muted padded",children:a.length?ie("editor.commentNoMatches"):ie("editor.noComments")})]})]}),t==="settings"&&o.jsx(Oh,{onClose:e,children:o.jsx(bb,{onClose:e,project:n,projectId:s,site:r,files:i,dictionaryWords:me,onDictionaryChange:z,editorPreferences:Q,onEditorPreferences:V,spellCheckCount:ne,spellCheckUniqueCount:K,spellCheckIndex:fe,onSpellCheckNavigate:Z,onProject:ge})})]})})]}):null}function kb(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 Sb(){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=kb(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 Cb=d.lazy(()=>vt(()=>import("./WordCountDialog-DlBSP4y7.js"),__vite__mapDeps([27,2,1,3,25,5,4,6,7,8]),import.meta.url).then(t=>({default:t.WordCountDialog})));let nr=null;function Pa(){return nr||(nr=vt(()=>import("./citationLibrary-ZeQPCv5O.js"),[],import.meta.url).catch(t=>{throw nr=null,t})),nr}function Gt(t){return t instanceof Error&&t.name==="AbortError"}const Ua=300;function vb({site:t,user:e,projectId:n,preload:s,mentionId:r=null,onMentionTargeted:i,onMentionsRead:l,onBack:a}){const{t:c}=Ge(),[u,f]=d.useState(null),[h,p]=d.useState(!1),[w,g]=d.useState([]),[S,v]=d.useState(null),[C,$]=d.useState([]),[x,R]=d.useState(""),[T,D]=d.useState(""),[L,F]=d.useState(new Set),[te,re]=d.useState(""),[J,G]=d.useState({filePath:"",content:""}),[me,z]=d.useState({path:"",hasIncludes:!1}),[Q,V]=d.useState(""),[ne,K]=d.useState(!1),[fe,Z]=d.useState("editor.saved"),[ge,ie]=d.useState(null),pe=d.useRef(ge);pe.current=ge;const b=d.useRef(null);b.current||(b.current=Sb());const O=b.current,[X,ye]=d.useState("pdf"),[ce,be]=d.useState("log"),Se=m=>{if(m==="pdf"){ye("pdf");return}if(m==="diagnostics"){ye("diagnostics");return}be(m),ye("diagnostics")},{workspaceLayout:M,setWorkspaceLayout:Te}=_y(e.id,n),[_e,_]=d.useState(""),[Oe,we]=d.useState(""),[ke,A]=d.useState({selectedText:"",startOffset:0,endOffset:0}),ue=d.useRef({selectedText:"",startOffset:0,endOffset:0}),Re=m=>{const y=ue.current;y.selectedText===m.selectedText&&y.startOffset===m.startOffset&&y.endOffset===m.endOffset||(ue.current=m,A(m))},[N,k]=d.useState(null),[B,Ce]=d.useState(null),[Ve,Ne]=d.useState(null),[ve,yt]=d.useState(!1),[qe,I]=d.useState(!1),[ee,P]=d.useState(!1),[ae,ft]=d.useState(!1),[pt,Xe]=d.useState(!1),[ot,Nt]=d.useState(!1),[xe,U]=d.useState(null),[W,qt]=d.useState(!1),[ls,Br]=d.useState(!1),[Ou,zs]=d.useState(!1),[Mu,$u]=d.useState("full"),[Iu,Pu]=d.useState(""),[qr,Wr]=d.useState(!1),[Uu,Hr]=d.useState(""),[zu,Vr]=d.useState(null),[as,En]=d.useState(!1),[on,Ft]=d.useState(null),[Bu,Kr]=d.useState(!1),[Ze,Jo]=d.useState(()=>Wl(e.id,n));d.useEffect(()=>{const m=document.documentElement,y=Ze.showTooltips?"on":"off";return m.setAttribute("data-texlite-tooltips",y),()=>{m.getAttribute("data-texlite-tooltips")===y&&m.removeAttribute("data-texlite-tooltips")}},[Ze.showTooltips]);const[Dn,Bs]=d.useState([]),Wt=d.useRef([]);Wt.current=Dn;const qu=d.useRef(null),qs=d.useRef(null),Ws=d.useRef(0),Jr=d.useRef(0),Ee=d.useRef(""),nt=d.useRef(""),Go=d.useRef(M),Yo=d.useRef(0),ln=d.useRef(null),Xo=d.useRef(null),an=d.useRef(null),cn=d.useRef(null),_n=d.useRef(null),Ln=d.useRef(null),Rn=d.useRef(null),Ht=d.useRef(null),Gr=d.useRef(null),Ot=d.useRef(!1),Vt=d.useRef(null),Qo=d.useRef(a),Yr=d.useRef(i),Xr=d.useRef(l);Qo.current=a,Yr.current=i,Xr.current=l,Ee.current=x,nt.current=T,Go.current=M,d.useEffect(()=>{if(!Oe)return;const m=window.setTimeout(()=>we(""),3e3);return()=>window.clearTimeout(m)},[Oe]);const Wu=d.useCallback((m,y,E=0)=>{O.update(m,y,E)},[O]);d.useEffect(()=>()=>O.dispose(),[O]),d.useEffect(()=>()=>{Ht.current?.abort(),Ht.current=null},[]);const Hs=m=>{const y=Wt.current,E=m(y);E!==y&&(Wt.current=E,Bs(E))};d.useEffect(()=>{Wt.current=[],Bs([]),Ft(null),Xe(!1),Ln.current?.abort(),Ln.current=null,Rn.current?.abort(),Rn.current=null,Ht.current?.abort(),Ht.current=null,Gr.current=null,Ce(null),Ne(null),zs(!1),Wr(!1),Hr(""),Vr(null)},[n]);const Zo=m=>{const y=Wt.current,E=y.indexOf(m);if(E<0)return;const j=y.filter(q=>q!==m);if(Wt.current=j,Bs(j),Ee.current!==m)return;const Y=j.length>0?j[Math.min(E,j.length-1)]:u?.mainFile??"";R(Y)},{collaboration:Ae,status:Vs,synced:We,activeSessions:el,formatLeaseStates:Hu,compileState:un,setCompileState:tl,filesEvent:Ue,commentsRevision:nl,historyWarning:Vu,dictionaryRevision:sl,localDraftReady:rl,permission:Qr,reconnect:Ku,protocolUpgradeRequired:il,permissionDowngrade:Ju,dismissPermissionDowngrade:Gu,discardLocalDraft:Yu}=by(n,e,T,u?.permission??"read",h,()=>Z("editor.offlineDraft")),{unreadMentions:ol,refresh:Xu,markMentionRead:Qu,markAllMentionsRead:Zu}=Vf(n,nl,_),{pdfTarget:ed,pdfViewport:td,sourceJump:nd,setPdfViewport:sd,clearPdfViewport:ll,jumpToSource:Tn,syncSourceToPdf:Zr,syncPdfToSource:rd,syncVisiblePdfToSource:id}=Dy({projectId:n,mainFile:T,activeFile:x,onActiveFile:R,onError:_,onShowPdf:()=>Se("pdf")}),ut=Ey({active:!!(u&&x&&We&&Ze.spellCheck&&Ly(x)),projectId:n,activeFile:x,content:te,dictionaryWords:w});d.useEffect(()=>{Jo(Wl(e.id,n))},[e.id,n]);const ei=m=>{re(m)};d.useEffect(()=>{if(!x||Q!==x){G(j=>j.filePath||j.content?{filePath:"",content:""}:j);return}const m=x,y=te,E=window.setTimeout(()=>{G(j=>j.filePath===m&&j.content===y?j:{filePath:m,content:y})},Ua);return()=>window.clearTimeout(E)},[x,Q,te]),d.useEffect(()=>{if(Ee.current=x,O.reset(),Re({selectedText:"",startOffset:0,endOffset:0}),!Ze.openFilesInTabs){Wt.current.length>0&&(Wt.current=[],Bs([]));return}x&&Hs(m=>m.includes(x)?m:[...m,x])},[x,Ze.openFilesInTabs,n,O]),d.useEffect(()=>{if(!ne)return;const m=y=>{y.preventDefault(),y.returnValue=""};return window.addEventListener("beforeunload",m),()=>window.removeEventListener("beforeunload",m)},[ne]),d.useEffect(()=>{if(Vs!=="disconnected")return;const m=new AbortController;return le(`/api/projects/${n}`,{signal:m.signal}).then(({project:y})=>{m.signal.aborted||(f(y),_(""))}).catch(y=>{if(!Gt(y)){if(y instanceof Ii&&[401,403,404].includes(y.status)){_(de(y)),Qo.current();return}_(c("errors.collaborationUnavailable"))}}),()=>m.abort()},[Vs,n,c]);const Ks=async(m={},y=nt.current)=>{ln.current?.abort(),ln.current=null;const E=m.signal?null:new AbortController;E&&(ln.current=E);try{const j=y?`?mainFile=${encodeURIComponent(y)}`:"",Y=await le(`/api/projects/${n}/completions${j}`,{signal:m.signal??E?.signal});(!m.isCurrent||m.isCurrent())&&v(Y.index)}catch(j){if(Gt(j))return;(!m.isCurrent||m.isCurrent())&&v(null)}finally{E&&ln.current===E&&(ln.current=null)}},ti=async(m={},y=nt.current)=>{an.current?.abort(),an.current=null;const E=m.signal?null:new AbortController;E&&(an.current=E);try{const j=y?`?mainFile=${encodeURIComponent(y)}`:"",Y=await le(`/api/projects/${n}/outline${j}`,{signal:m.signal??E?.signal});(!m.isCurrent||m.isCurrent())&&$(Y.outline)}catch(j){!Gt(j)&&(!m.isCurrent||m.isCurrent())&&$([])}finally{E&&an.current===E&&(an.current=null)}},al=async(m={})=>{cn.current?.abort(),cn.current=null;const y=m.signal?null:new AbortController;y&&(cn.current=y);try{const E=await le(`/api/projects/${n}/dictionary`,{signal:m.signal??y?.signal});(!m.isCurrent||m.isCurrent())&&g(E.words)}catch(E){if(Gt(E))return;(!m.isCurrent||m.isCurrent())&&g([])}finally{y&&cn.current===y&&(cn.current=null)}};d.useEffect(()=>{let m=!1;const y=++Yo.current,E=new AbortController,j=()=>!m&&Yo.current===y;let Y=!1,q="";f(null),dl([]),$([]),R(""),D(""),z({path:"",hasIncludes:!1}),F(new Set),re(""),V(""),tl(null),ll(),v(null),g([]),za();const se=(s?.projectId===n?s.project:le(`/api/projects/${n}`,{signal:E.signal})).then(ze=>{j()&&(Y=!0,q=ze.project.mainFile,f(ze.project),R(ze.project.mainFile),nt.current=ze.project.mainFile,D(ze.project.mainFile),F(new Set),bl(new Set(gs(ze.project.mainFile))))}).catch(ze=>{j()&&_(de(ze))}),jt=le(`/api/projects/${n}/files`,{signal:E.signal}).then(ze=>{j()&&dl(ze.files)}).catch(ze=>{j()&&_(de(ze))});let lt=null;return Promise.allSettled([se,jt]).then(()=>{!j()||!Y||(lt=window.setTimeout(()=>{j()&&Promise.all([Ks({signal:E.signal,isCurrent:j},nt.current||q),al({signal:E.signal,isCurrent:j})])},0))}),()=>{m=!0,lt!==null&&window.clearTimeout(lt),E.abort(),ln.current?.abort(),ln.current=null,an.current?.abort(),an.current=null,cn.current?.abort(),cn.current=null,_n.current?.abort(),_n.current=null}},[n,s]),d.useEffect(()=>{if(!(!u||!T)){if(Xo.current!==n){Xo.current=n;return}Ks({},T)}},[T,u?.id,n]),d.useEffect(()=>{if(!r||!u)return;Rn.current?.abort();const m=new AbortController;return Rn.current=m,le(`/api/projects/${n}/mentions/${encodeURIComponent(r)}`,{signal:m.signal}).then(({mention:y})=>{m.signal.aborted||(Ce(y),k("comments"),R(y.filePath),Yr.current?.(y.id))}).catch(y=>{Gt(y)||m.signal.aborted||(_(de(y)),Yr.current?.(r))}).finally(()=>{Rn.current===m&&(Rn.current=null)}),()=>m.abort()},[r,u?.id,n]),d.useEffect(()=>{sl&&al()},[sl,n]),d.useEffect(()=>{!u||Vs!=="connected"||Qr===u.permission||f(m=>m&&{...m,permission:Qr})},[Qr,u?.permission]),d.useEffect(()=>{if(!Ue)return;const m=Ue.kind==="delete"&&!!Ue.path&&fn(Ue.path,Ee.current),y=Ue.kind==="delete"&&!!Ue.path&&fn(Ue.path,nt.current);if(Ue.kind==="move"&&Ue.source&&Ue.destination){const j=Ue.source,Y=Ue.destination,q=se=>se===j?Y:se.startsWith(`${j}/`)?`${Y}${se.slice(j.length)}`:se;R(se=>q(se)),D(se=>q(se)),F(se=>new Set([...se].map(q))),si(se=>se&&q(se)),Hs(se=>se.map(q))}m&&(R(""),V(""),ei(""),we(c("editor.fileDeletedByCollaborator",{path:Ue.path}))),Ue.kind==="delete"&&Ue.path&&(F(j=>new Set([...j].filter(Y=>!fn(Ue.path,Y)))),si(j=>fn(Ue.path,j)?"":j),pl(j=>j&&fn(Ue.path,j.path)?null:j),Hs(j=>j.filter(Y=>!fn(Ue.path,Y)))),_n.current?.abort();const E=new AbortController;_n.current=E,Promise.all([ud({signal:E.signal}),le(`/api/projects/${n}`,{signal:E.signal})]).then(([j,Y])=>{if(f(Y.project),y&&D(Y.project.mainFile),m&&j){const q=j.find(se=>se.type==="file"&&se.path===Y.project.mainFile)??j.find(se=>se.type==="file"&&Hn(se.path));R(q?.path??"")}Ks({signal:E.signal}),ti({signal:E.signal},y?Y.project.mainFile:nt.current)}).catch(j=>{Gt(j)}).finally(()=>{_n.current===E&&(_n.current=null)})},[Ue?.revision]),d.useEffect(()=>{if(Ae.setActiveFile(x),!x)return;V(""),Z("editor.loading");const m=Ae.getText(x),y=(E,j)=>{ei(m.toString()),V(x),j?.local&&u?.permission!=="read"?(Ws.current+=1,K(!0),Z("editor.pending")):Ws.current<=Jr.current&&Z(pe.current?"editor.savedAt":"editor.saved")};return m.observe(y),(We||rl)&&y(),()=>{m.unobserve(y)}},[x,Ae,We,rl,u?.permission]);const Js=async()=>{if(!We)throw new Error("Collaboration is not synchronized");const m=Ws.current,y=await Ae.flush();return Jr.current=Math.max(Jr.current,m),ie(y.persistedAt),/\.tex$/i.test(Ee.current)&&ti(),Ws.current===m?(K(!1),Z("editor.savedAt")):Z("editor.pending"),y};d.useEffect(()=>{if(!ne||!x)return;if(!We){Z("editor.offlineDraft");return}Z("editor.pending");const m=window.setTimeout(()=>{Z("editor.saving"),Js().catch(()=>{Z(Ae.connected?"editor.saveFailed":"editor.offlineDraft")})},750);return()=>window.clearTimeout(m)},[te,ne,x,We]);const cs=async()=>{if(!u||u.permission==="read"||!We||!x)return!1;Z("editor.saving");try{return await Js(),Ks(),!0}catch(m){return Z("editor.saveFailed"),_(de(m)||c("errors.collaborationUnavailable")),!1}},od=async m=>{if(!u||qr)return;const y=m==="full"?nt.current||u.mainFile:Ee.current,E=m==="selection"?ue.current.selectedText:"";if(!y)return;if(m==="selection"&&(!E.trim()||!/\.(?:tex|sty|cls)$/i.test(y))){we(c("editor.wordCountSelectionEmpty"));return}Ln.current?.abort();const j=new AbortController;Ln.current=j,$u(m),Pu(y),Vr(null),Hr(""),zs(!0),Wr(!0);try{if(m==="full"&&ne&&u.permission!=="read"&&!await cs())throw new Error(c("editor.wordCountSaveRequired"));const Y=m==="selection"?{mode:m,path:y,source:E}:{mode:m,mainFile:y},q=await le(`/api/projects/${n}/word-count`,{method:"POST",body:JSON.stringify(Y),signal:j.signal});if(j.signal.aborted)return;Vr(q)}catch(Y){if(Gt(Y))return;j.signal.aborted||Hr(de(Y))}finally{Ln.current===j&&(Ln.current=null,Wr(!1))}},ni=async(m,y,E=Ze.texFmtConfig)=>{if(/\.bib$/i.test(m)){const Y=await Pa();try{return{formatted:Y.formatBibtex(y,t.maxCitationBibtexBytes)}}catch(q){throw q instanceof Y.BibtexFormatError?q.kind==="too-large"?new Error(c("citationLibrary.fileTooLarge",{size:Y.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})):new Error(c("citationLibrary.fileInvalid")):q}}return{formatted:(await yf(y,E)).output}},cl=async m=>{if(!u||u.permission==="read"||!We||Ot.current||!Qs(Ee.current))return;const y=Ee.current,E=Ae.getText(y);Ot.current=!0,En(!0);let j=()=>{};const Y=new Promise(se=>{j=se});Vt.current=Y;let q=null;try{q=await Ae.acquireFormatLease(y);const se=E.toString(),{formatted:jt}=await ni(y,se,m);if(Ee.current!==y||E.toString()!==se){_(c("editor.formatSourceChanged"));return}await q.confirm();const lt=await wi(se,jt);if(Ee.current!==y||E.toString()!==se){_(c("editor.formatSourceChanged"));return}if(await q.confirm(),Ee.current!==y||E.toString()!==se){_(c("editor.formatSourceChanged"));return}lt.length&&Ae.applyTextEdits(y,lt),lt.length&&await Js(),Ft(null),_(""),we(c("editor.formatFileComplete"))}catch(se){gi(se)?(Ft({action:"file",kind:se.kind,detail:se.message}),_("")):_(c("editor.formatFileFailed",{message:de(se)}))}finally{q&&await q.release(),Ot.current=!1,En(!1),j(),Vt.current===Y&&(Vt.current=null)}},ld=async()=>{if(!Ze.formatOnCompile||!u||u.permission==="read"||!We||!Qs(Ee.current)||Ot.current)return;const m=Ee.current,y=Ae.getText(m);Ot.current=!0,En(!0);let E=null;try{E=await Ae.acquireFormatLease(m);const j=y.toString(),{formatted:Y}=await ni(m,j);await E.confirm();const q=await wi(j,Y);if(Ee.current!==m||y.toString()!==j)throw new Error(c("editor.formatSourceChanged"));if(await E.confirm(),Ee.current!==m||y.toString()!==j)throw new Error(c("editor.formatSourceChanged"));q.length&&Ae.applyTextEdits(m,q),q.length&&await Ae.flush(),Ft(null)}catch(j){gi(j)?(Ft({action:"file",kind:j.kind,detail:j.message}),_("")):_(c("editor.formatFailedContinue",{message:de(j)}))}finally{E&&await E.release(),Ot.current=!1,En(!1)}},ad=async()=>(Vt.current&&await Vt.current,await ld(),cs()),ul=async m=>{if(!u||u.permission==="read"||!We||Ot.current||!Qs(Ee.current))return;const y=ue.current;if(!y.selectedText.trim()){we(c("editor.formatSelectionRequired"));return}const E=Ee.current,{startOffset:j,endOffset:Y,selectedText:q}=y,se=Ae.getText(E);if(se.toString().slice(j,Y)!==q){_(c("editor.formatSelectionChanged"));return}Ot.current=!0,En(!0);let jt=()=>{};const lt=new Promise(Mt=>{jt=Mt});Vt.current=lt;let ze=null;try{if(ze=await Ae.acquireFormatLease(E),se.toString().slice(j,Y)!==q){_(c("editor.formatSelectionChanged"));return}const hs=await ni(E,q,m),Rh=kf(q,hs.formatted);await ze.confirm();const mi=await wi(q,Rh,j);if(Ee.current!==E||se.toString().slice(j,Y)!==q){_(c("editor.formatSelectionChanged"));return}if(await ze.confirm(),Ee.current!==E||se.toString().slice(j,Y)!==q){_(c("editor.formatSelectionChanged"));return}mi.length&&Ae.applyTextEdits(E,mi),mi.length&&await Js(),Ft(null),_(""),we(c("editor.formatSelectionComplete"))}catch(Mt){gi(Mt)?(Ft({action:"selection",kind:Mt.kind,detail:Mt.message}),_("")):_(c("editor.formatFailed",{message:de(Mt)}))}finally{ze&&await ze.release(),Ot.current=!1,En(!1),jt(),Vt.current===lt&&(Vt.current=null)}},cd=async m=>{const y=Ee.current;if(!/\.bib$/i.test(y)||u?.permission==="read"||!We)return we(c("citationLibrary.importRequiresWrite")),!1;const E=Ae.getText(y);let j;try{j=await Pa()}catch(hs){return _(de(hs)),!1}if(Ee.current!==y||!We)return!1;const Y=E.toString(),q=j.parseBibEntriesResult(Y,t.maxCitationBibtexBytes);if(q.status==="too-large")return we(c("citationLibrary.fileTooLarge",{size:j.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})),!1;if(q.status==="invalid")return we(c("citationLibrary.fileInvalid")),!1;if(q.entries.some(hs=>hs.citationKey.toLowerCase()===m.citationKey.toLowerCase()))return we(c("citationErrors.alreadyInFile",{key:m.citationKey})),!1;const se=Math.max(0,Math.min(Y.length,O.getCursor().offset)),jt=Y.slice(0,se),lt=Y.slice(se),ze=jt?jt.endsWith(`
20
+
21
+ `)?"":jt.endsWith(`
22
+ `)?`
23
+ `:`
24
+
25
+ `:"",Mt=lt?lt.startsWith(`
26
+
27
+ `)?"":lt.startsWith(`
28
+ `)?`
29
+ `:`
30
+
31
+ `:"";return Ae.applyTextEdits(y,[{from:se,to:se,replacement:`${ze}${m.bibtex.trim()}${Mt}`}]),we(c("citationLibrary.imported",{key:m.citationKey})),!0},{files:bt,setFiles:dl,loadFiles:ud,newFileOpen:dd,setNewFileOpen:hl,newFilePath:hd,setNewFilePath:fl,resourcePreview:fd,setResourcePreview:pl,resourcePreviewLoading:pd,setResourcePreviewLoading:md,newFolderOpen:gd,setNewFolderOpen:ml,newFolderName:wd,setNewFolderName:gl,fileDialogError:yd,setFileDialogError:wl,selectedFolder:yl,setSelectedFolder:si,expandedFolders:bd,setExpandedFolders:bl,moveEntry:xd,setMoveEntry:xl,moveName:kd,setMoveName:kl,moveDestination:Sd,setMoveDestination:Sl,deleteEntry:ri,setDeleteEntry:Cl,fileDragActive:Cd,setFileDragActive:vd,uploadConflict:jd,setUploadConflict:Ed,uploadingFiles:Dd,directoryEntries:_d,visibleEntries:Ld,createFile:Rd,createFolder:Td,uploadFiles:vl,upload:Ad,openFile:ii,movePath:Nd,removePath:Fd}=jy({projectId:n,site:t,activeFile:x,dirty:ne,save:cs,onError:_,onProject:f,onActiveFile:R,onActiveMainFile:D,onRootDocuments:F}),jl=()=>nt.current||u?.mainFile||"",Od=()=>{const m=jl(),y=Ee.current;if(!y||!/\.tex$/i.test(y))return m;const E=bt.filter(q=>q.type==="file"&&/\.tex$/i.test(q.path)).length,j=Ae.getText(y).toString();return Oa(j)||E===1?(F(q=>{if(q.has(y))return q;const se=new Set(q);return se.add(y),se}),m!==y&&(nt.current=y,D(y)),y):m===y&&u?.mainFile&&u.mainFile!==y?(nt.current=u.mainFile,D(u.mainFile),u.mainFile):m};d.useEffect(()=>{if(!x||Q!==x||J.filePath!==x||!x.toLocaleLowerCase().endsWith(".tex"))return;const m=bt.filter(Y=>Y.type==="file"&&/\.tex$/i.test(Y.path)).length;if(m===0)return;const y=x===u?.mainFile,j=Oa(J.content)||m===1;F(Y=>{if(Y.has(x)===j)return Y;const q=new Set(Y);return j?q.add(x):q.delete(x),q}),j&&!y&&nt.current!==x?D(x):!j&&nt.current===x&&u?.mainFile&&D(u.mainFile)},[x,Q,J,bt,u?.mainFile]),d.useEffect(()=>{if(!Ze.openFilesInTabs||bt.length===0)return;const m=new Set(bt.filter(y=>y.type==="file"&&Hn(y.path)).map(y=>y.path));Hs(y=>{const E=y.filter(j=>m.has(j));return E.length===y.length?y:E})},[bt,Ze.openFilesInTabs]);const{comments:dn,commentsFilePath:oi,commentsReady:li,reviewComments:Md,reviewCommentsLoading:$d,reviewCommentsError:Id,retryReviewComments:Pd,commentScope:Ud,setCommentScope:zd,focusComment:El,setFocusComment:Gs,commentOpen:Bd,openComment:qd,closeComment:Wd,commentText:Hd,setCommentText:Vd,commentSelection:Kd,commentSubmitting:Jd,commentError:Gd,addComment:Yd,toggleComment:Xd,replyToComment:Qd,editComment:Zd,deleteComment:eh,editCommentReply:th,deleteCommentReply:nh}=$f({projectId:n,activeFile:x,content:te,permission:u?.permission,revision:nl,selection:ke,save:cs,saveFailureMessage:c("errors.collaborationUnavailable"),onError:_,onAdded:()=>k("comments"),onChanged:()=>{Xu()}});d.useEffect(()=>{if(!T||J.filePath!==T)return;const m=Ma(J.content).length>0;z(y=>y.path===T&&y.hasIncludes===m?y:{path:T,hasIncludes:m})},[T,J]),d.useEffect(()=>{if(!T||!We||x===T)return;const m=Ae.getText(T);let y=null;const E=()=>{const Y=Ma(m.toString()).length>0;z(q=>q.path===T&&q.hasIncludes===Y?q:{path:T,hasIncludes:Y})},j=()=>{y!==null&&window.clearTimeout(y),y=window.setTimeout(()=>{y=null,E()},Ua)};return E(),m.observe(j),()=>{y!==null&&window.clearTimeout(y),m.unobserve(j)}},[x,T,Ae,We]);const sh=d.useMemo(()=>me.path===T&&me.hasIncludes,[T,me]),ai=m=>{k("comments"),Gs(null),Ne(m),Ee.current!==m.filePath&&Tn(m.filePath,m.startLine,1)};d.useEffect(()=>{if(!Ve)return;const m=zf(Ve,x,Q,oi,li,dn);if(m){Gs({...m}),Ne(null);return}Ve.filePath===x&&Q===x&&oi===x&&li&&Ne(null)},[x,dn,oi,li,Q,Ve,Gs]);const rh=async m=>{const y=await Qu(m);return y&&Xr.current?.(1),y},ih=async()=>{const m=ol.length,y=await Zu();return y&&m&&Xr.current?.(m,!0),y};d.useEffect(()=>{if(!B||x!==B.filePath||N!=="comments")return;const m=dn.find(E=>E.id===B.commentId);if(!m||B.replyId&&!m.replies.some(E=>E.id===B.replyId)||Gr.current===B.id)return;Gr.current=B.id,ai(m);const y=window.setTimeout(()=>Ce(E=>E?.id===B.id?null:E),3e3);return()=>window.clearTimeout(y)},[x,dn,N,B]);const{pdfUrl:Kt,pdfCompiledAt:us,pdfLoadingMode:oh,pdfLoading:ci,compileLog:ui,compileDiagnostics:lh,compileOutcome:ds,artifacts:Dl,artifactPreview:ah,artifactLoading:ch,editorNotice:uh,localCompiling:_l,cancelling:dh,cleaning:Ll,compile:hh,cancelCompile:fh,cleanCompile:Rl,viewArtifact:ph}=ky({projectId:n,project:u,mainFile:T,resolveCompileMainFile:Od,getCurrentMainFile:jl,initialLatest:s?.projectId===n?s.latestCompile:null,collaborationSynced:We,sharedState:un,onSharedState:tl,save:ad,loadOutline:(m,y)=>ti({signal:m},y),onPreviewTab:Se,onError:_,onCompileStart:()=>{_(""),we("")},onCompileSuccess:()=>{const m=Ee.current;if(m){const y=O.getCursor();Zr(m,y.line,y.column,{silent:!0})}},onPdfChanged:ll});d.useEffect(()=>{if(!u||!T||!Kt&&ci)return;const m=window.setTimeout(()=>p(!0),Kt?150:0);return()=>window.clearTimeout(m)},[u,ci,Kt]),d.useEffect(()=>{const m=y=>{(y.ctrlKey||y.metaKey)&&(!y.shiftKey&&y.key.toLocaleLowerCase()==="p"?(y.preventDefault(),qt(!0)):y.shiftKey&&y.key.toLocaleLowerCase()==="f"&&(y.preventDefault(),Br(!0)))};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[]);const Tl=m=>{Jo(m),ff(e.id,n,m)},Al=(m=!1)=>{const y=on;if(!y)return;Ft(null),_(""),m&&Tl({...Ze,texFmtConfig:""});const E=m?"":void 0;y.action==="selection"?ul(E):cl(E)},mh=async()=>{Kr(!0);try{await Yu()||(_(c("editor.collaboration.permissionDowngradeOtherTabBlocked")),Kr(!1))}catch(m){_(de(m)),Kr(!1)}},Nl=()=>{qs.current?.isCollapsed()?qs.current.expand():qs.current?.collapse()},gh=d.useMemo(()=>C.length?C:J.filePath!==x?[]:jb(J.content).map(m=>({...m,path:x})),[C,J,x]),di=d.useMemo(()=>Sf(ui,ds),[ui,ds]),An=M!=="pdf-only",Fl=M!=="editor-only",Ys=m=>{Te(m),m==="pdf-only"&&Se("pdf")},wh=d.useCallback(m=>{Ht.current?.abort();const y=new AbortController;Ht.current=y;const E=Ee.current,j=nt.current,Y=new URLSearchParams({kind:m.kind,key:m.key,...E?{path:E}:{},...j?{mainFile:j}:{}});le(`/api/projects/${n}/references/resolve?${Y}`,{signal:y.signal}).then(({target:q})=>{if(!(y.signal.aborted||Ee.current!==E||nt.current!==j)){if(!q){_(c(m.kind==="citation"?"editor.citationTargetNotFound":"editor.labelTargetNotFound",{key:m.key}));return}Go.current==="pdf-only"&&Ys("editor-pdf"),Tn(q.path,q.line,q.column)}}).catch(q=>{!y.signal.aborted&&!Gt(q)&&_(de(q))}).finally(()=>{Ht.current===y&&(Ht.current=null)})},[Tn,n,c]),yh=ri?el.filter(m=>m.filePath&&fn(ri.path,m.filePath)):[];if(!u)return o.jsxs("div",{className:"center-card",children:[o.jsx("p",{children:_e||c("common.loading")}),_e&&o.jsx("button",{className:"primary",onClick:a,children:c("editor.backToProjects")})]});const Jt=u.permission==="read"||!We,hi=Hu.find(m=>m.path===x),fi=hi&&!as?hi:null,bh=(m,y)=>{if(Jt)return;const E=Ee.current;if(!E)return;if(Ae.getText(E).toString().slice(m.from,m.to)!==m.word){_(c("editor.spellCheckSourceChanged"));return}try{Ae.applyTextEdits(E,[{from:m.from,to:m.to,replacement:y}])}catch(q){_(de(q))}},pi=un?.mainFile===T&&(un.status==="queued"||un.status==="running"),Xs=_l||pi||Ll,xh=x?Ae.getText(x):null,kh=us?new Date(us).toLocaleString(ws.resolvedLanguage,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"",Sh=T.split("/").at(-1)??T,Ch=di.warnings.length+di.errors.length+Dl.length,vh=Kt?`${Kt}${Kt.includes("?")?"&":"?"}download=1`:"",jh=T||u.mainFile,Eh=!!(x&&x===jh&&/\.tex$/i.test(x)),Ol=m=>{const y=bt.find(E=>E.path===m);y&&Hn(y.path)?ii(y):Zo(m)},Dh=m=>{document.getElementById(`editor-tab-${encodeURIComponent(m)}`)?.focus()},_h=(m,y)=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(m.key))return;m.preventDefault();const E=m.key==="Home"?0:m.key==="End"?Dn.length-1:(y+(m.key==="ArrowLeft"?-1:1)+Dn.length)%Dn.length,j=Dn[E];j&&(Ol(j),window.requestAnimationFrame(()=>Dh(j)))},Ml=Xs?pi?un?.status==="queued"?c("editor.compileQueued"):c("editor.compilingBy",{name:un?.requestedBy.name??c("common.user")}):c("editor.compiling"):ds==="failed"?Kt&&us?c("editor.compileFailedRetained",{time:new Date(us).toLocaleString(ws.resolvedLanguage)}):c("editor.compileFailedNoPdf"):ds==="cancelled"?c("compileControls.cancelled"):"",Lh=fe==="editor.savedAt"&&ge?c("editor.savedAt",{time:new Date(ge).toLocaleTimeString(ws.resolvedLanguage,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):c(fe);return o.jsxs("div",{className:"workspace","data-texlite-tooltips":Ze.showTooltips?"on":"off",children:[o.jsx(Ky,{site:t,project:u,activeFile:x,saveStateLabel:Lh,editorPreferences:Ze,activeSessions:el,collaborationStatus:Vs,reconnectCollaboration:Ku,protocolUpgradeRequired:il,showEditor:An,filesCollapsed:ve,toggleFilesPanel:Nl,workspaceLayout:M,changeWorkspaceLayout:Ys,onBack:a,onShare:()=>I(!0),showCitationLibrary:An&&/\.bib$/i.test(x),citationLibraryOpen:ot,onCitationLibrary:()=>Nt(!0),onSelectionHistory:()=>Xe(!0),onHistory:()=>ft(!0),onGit:()=>P(!0),canManageGit:u.ownerId===e.id,formatting:as,readOnly:Jt,collaborationSynced:We,hasSelection:!!ke.selectedText.trim(),onToggleComments:()=>k(N==="comments"?null:"comments"),commentsOpen:N==="comments",unresolvedCommentCount:dn.filter(m=>!m.resolved).length,hasActiveFile:!!x,onToggleSettings:()=>k(N==="settings"?null:"settings"),settingsOpen:N==="settings",compileBusy:Xs,sharedCompiling:pi,localCompiling:_l,cancelling:dh,compileState:un,onCompile:hh,onCancelCompile:()=>{fh()}}),il&&o.jsxs("div",{className:"workspace-update-banner",role:"alert",children:[o.jsx(Pt,{size:15}),o.jsx("span",{children:c("workspaceUpdates.protocolUpgrade")}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:c("common.reload")})]}),Ml&&o.jsxs("div",{className:`compile-status-strip${ds==="failed"?" failed":""}`,role:"status","aria-live":"polite",children:[o.jsx(st,{className:Xs?"spin":"",size:14}),o.jsx("span",{children:Ml})]}),(ut.error||on||fi)&&o.jsxs("div",{className:"client-tool-recoveries",children:[ut.error&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:ut.error,children:[o.jsx(Pt,{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:ut.retry,children:c("common.retry")})}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:c("common.close"),"aria-label":c("common.close"),onClick:ut.dismissError,children:o.jsx(ks,{size:13})})]}),on&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:on.detail,children:[o.jsx(Pt,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:c(on.kind==="format"?"editor.texFmtOptionsRecoveryTitle":on.kind==="load"?"editor.texFmtRecoveryTitle":"editor.texFmtRuntimeRecoveryTitle")}),c("editor.clientToolRecoveryHint")]}),o.jsxs("div",{className:"client-tool-recovery-actions",children:[o.jsx("button",{type:"button",disabled:as||Jt,onClick:()=>Al(),children:c("common.retry")}),on.kind==="format"&&Ze.texFmtConfig.trim()&&o.jsx("button",{type:"button",disabled:as||Jt,onClick:()=>Al(!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:()=>Ft(null),children:o.jsx(ks,{size:13})})]}),fi&&o.jsxs("div",{className:"client-tool-recovery format-lease-status",role:"status",children:[o.jsx(st,{className:"spin",size:15}),o.jsx("span",{children:c("editor.formattingBy",{name:fi.holderName})})]})]}),Vu&&o.jsxs("div",{className:"client-tool-recovery",role:"status",children:[o.jsx(Pt,{size:15}),o.jsx("span",{children:c("history.saveWarning")})]}),_e&&o.jsx("div",{className:"toast",onClick:()=>_(""),children:_e}),Oe&&o.jsx("div",{className:"toast success",onClick:()=>we(""),children:Oe}),o.jsxs(Mh,{autoSaveId:pn("texlite-workspace-layout"),direction:"horizontal",className:"work-grid",children:[An&&o.jsx(Xy,{project:u,filesPanel:qs,files:bt,visibleEntries:Ld,activeFile:x,activeMainFile:T,rootDocuments:L,selectedFolder:yl,expandedFolders:bd,fileDragActive:Cd,uploadingFiles:Dd,readOnly:Jt,formatting:as,canFormat:Qs(x),activeFormatLease:!!hi,collaborationSynced:We,editorFontSize:Ze.fontSize,outline:gh,sourceCursorStore:O,wordCountBusy:qr,hasSelection:!!ke.selectedText.trim()&&/\.(?:tex|sty|cls)$/i.test(x),hasFormatSelection:!!ke.selectedText.trim(),uploadInput:qu,setSelectedFolder:si,setExpandedFolders:bl,setMoveEntry:xl,setMoveName:kl,setMoveDestination:Sl,setDeleteEntry:Cl,setFileDialogError:wl,setNewFolderName:gl,setNewFolderOpen:ml,setNewFilePath:fl,setNewFileOpen:hl,setQuickOpen:qt,setProjectSearchOpen:Br,setFileDragActive:vd,setFilesCollapsed:yt,toggleFilesPanel:Nl,uploadFiles:vl,upload:Ad,openFile:ii,onFormatFile:()=>{cl()},onFormatSelection:()=>{ul()},jumpToSource:Tn,syncSourceToPdf:Zr,onWordCount:m=>{od(m)}}),An&&o.jsx(lo,{className:"resize-handle",children:o.jsx(Wa,{size:12})}),An&&o.jsx(tb,{project:u,activeFile:x,activeMainFile:T,openTabs:Dn,content:te,loadedFile:Q,readOnly:Jt,comments:dn,focusComment:El,editorPreferences:Ze,completionIndex:S,nativeSpellCheck:ut.nativeFallback,spellCheckIssues:ut.issues,spellCheckJump:ut.jump,sourceJump:nd,collaborativeText:xh,collaborationAwareness:Ae.awareness,undoManager:x?Ae.getUndoManager(x):void 0,editorNotice:uh,activateTab:Ol,closeTab:Zo,handleTabKeyDown:_h,updateEditorContent:ei,setSelection:(m,y,E)=>Re({selectedText:m,startOffset:y,endOffset:E}),onAddComment:(m,y,E,j)=>qd({selectedText:m,startOffset:y,endOffset:E},j),onCommentClick:m=>{const y=dn.find(E=>E.id===m);y&&ai(y)},onSpellCheckReplace:bh,onReferenceNavigate:wh,onCursor:Wu}),Fl&&o.jsx(lb,{projectId:n,activeMainFile:T,previewTab:X,diagnosticTab:ce,pdfUrl:Kt,pdfLoadingMode:oh,pdfLoading:ci,pdfCompiledAt:us,pdfCompiledLabel:kh,pdfTargetLabel:Sh,pdfDownloadUrl:vh,pdfTarget:ed,pdfViewport:td,activeFile:x,compileBusy:Xs,compileLog:ui,compileDiagnostics:lh,compileMessages:di,artifacts:Dl,artifactPreview:ah,artifactLoading:ch,cleaning:Ll,readOnly:Jt,collaborationSynced:We,workspaceLayout:M,showSyncResize:An&&Fl,diagnosticCount:Ch,selectPreviewTab:Se,changeWorkspaceLayout:Ys,onSetNotice:we,onSetPdfViewport:sd,syncVisiblePdfToSource:id,syncCurrentSourceToPdf:()=>{const m=Ee.current;if(!m)return Promise.resolve();const y=O.getCursor();return Zr(m,y.line,y.column)},syncPdfToSource:rd,canSyncWithPdf:Eh,files:bt,jumpToSource:Tn,onSetCleanMode:U,cleanCompile:Rl,viewArtifact:ph}),o.jsx(xb,{sidePanel:N,onClose:()=>k(null),project:u,projectId:n,site:t,files:bt,currentUserId:e.id,comments:Md,commentsLoading:$d,commentsError:Id,onRetryComments:Pd,activeFile:x,hasProjectCommentsScope:sh,commentScope:Ud,onCommentScopeChange:zd,focusedCommentId:El?.id,onClearFocusComment:()=>Gs(null),unreadMentions:ol,onMarkMentionRead:rh,onMarkAllMentionsRead:ih,targetCommentId:B?.commentId,targetReplyId:B?.replyId,onFocusComment:ai,onToggleComment:Xd,onReplyComment:Qd,onEditComment:Zd,onDeleteComment:eh,onEditCommentReply:th,onDeleteCommentReply:nh,dictionaryWords:w,onDictionaryChange:g,editorPreferences:Ze,onEditorPreferences:Tl,spellCheckCount:ut.summary?.total??null,spellCheckUniqueCount:ut.summary?.unique??null,spellCheckIndex:ut.summary?ut.index:-1,onSpellCheckNavigate:ut.jumpToIssue,onProject:f})]}),Ou&&o.jsx(Ba,{title:c("editor.wordCountTitle"),onClose:()=>zs(!1),children:o.jsx(Cb,{open:!0,mode:Mu,path:Iu,busy:qr,error:Uu,result:zu,onOpenChange:zs})}),o.jsx(wb,{user:e,project:u,projectId:n,activeFile:x,content:te,maxCitationBibtexBytes:t.maxCitationBibtexBytes,files:bt,directoryEntries:_d,readOnly:Jt,workspaceLayout:M,changeWorkspaceLayout:Ys,resourcePreview:fd,resourcePreviewLoading:pd,setResourcePreview:pl,setResourcePreviewLoading:md,uploadConflict:jd,setUploadConflict:Ed,uploadFiles:vl,cleanMode:xe,setCleanMode:U,cleanCompile:Rl,newFileOpen:dd,setNewFileOpen:hl,newFilePath:hd,setNewFilePath:fl,newFolderOpen:gd,setNewFolderOpen:ml,newFolderName:wd,setNewFolderName:gl,selectedFolder:yl,fileDialogError:yd,setFileDialogError:wl,createFile:Rd,createFolder:Td,moveEntry:xd,setMoveEntry:xl,moveName:kd,setMoveName:kl,moveDestination:Sd,setMoveDestination:Sl,movePath:Nd,deleteEntry:ri,setDeleteEntry:Cl,deleteActiveSessions:yh,removePath:Fd,commentOpen:Bd,closeComment:Wd,commentSelection:Kd,selection:ke,commentText:Hd,setCommentText:Vd,commentSubmitting:Jd,commentError:Gd,addComment:Yd,shareOpen:qe,setShareOpen:I,citationLibraryOpen:ot,setCitationLibraryOpen:Nt,insertCitationAtCursor:cd,quickOpen:W,setQuickOpen:qt,projectSearchOpen:ls,setProjectSearchOpen:Br,openFile:ii,jumpToSource:Tn,selectionHistoryOpen:pt,setSelectionHistoryOpen:Xe,historyOpen:ae,setHistoryOpen:ft,gitOpen:ee,setGitOpen:P,save:cs,permissionDowngrade:Ju,permissionDowngradeBusy:Bu,dismissPermissionDowngrade:Gu,discardPermissionDraft:mh})]})}function jb(t){const e=[],n=/^\s*\\(part|chapter|section|subsection|subsubsection)\*?(?:\[[^\]]*\])?\{([^}]*)\}/,s={part:0,chapter:0,section:1,subsection:2,subsubsection:3};return t.split(`
32
+ `).forEach((r,i)=>{const l=r.match(n);l&&e.push({level:s[l[1]],title:l[2],line:i+1})}),e}const Wb=Object.freeze(Object.defineProperty({__proto__:null,ProjectWorkspace:vb},Symbol.toStringTag,{value:"Module"}));export{Qh as A,Mf as B,co as C,Xt as D,bf as E,Zh as F,uf as G,zl as H,Bi as I,Xh as J,Fb as K,Wb as P,af as R,ql as S,Sg as U,Ib as a,Pb as b,to as c,Ub as d,zb as e,Sn as f,Ob as g,$t as h,Nu as i,Ty as j,Bb as k,Ko as l,wo as m,os as n,Us as o,Er as p,By as q,$b as r,Ly as s,Mb as t,qb as u,oo as v,Fy as w,io as x,Oy as y,Nb as z};