texlite 0.21.0 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DESIGN.md +174 -22
- package/OPERATIONS.md +23 -3
- package/README.md +44 -37
- package/README.zh-CN.md +38 -31
- package/addon.md +76 -0
- package/dist/client/assets/AdminUsers-xuVuiwoh.js +1 -0
- package/dist/client/assets/AdminUsers-xuVuiwoh.js.br +0 -0
- package/dist/client/assets/AdminUsers-xuVuiwoh.js.gz +0 -0
- package/dist/client/assets/{AgentIcon-dCMgWJG-.css → AgentIcon-DJGGRJnV.css} +1 -1
- package/dist/client/assets/AgentIcon-DJGGRJnV.css.br +0 -0
- package/dist/client/assets/AgentIcon-DJGGRJnV.css.gz +0 -0
- package/dist/client/assets/{AgentManagement-0n1UkKZ5.js → AgentManagement-D-0hrv6f.js} +1 -1
- package/dist/client/assets/AgentManagement-D-0hrv6f.js.br +0 -0
- package/dist/client/assets/AgentManagement-D-0hrv6f.js.gz +0 -0
- package/dist/client/assets/AgentTerminal-DZo-22RN.js +2 -0
- package/dist/client/assets/AgentTerminal-DZo-22RN.js.br +0 -0
- package/dist/client/assets/AgentTerminal-DZo-22RN.js.gz +0 -0
- package/dist/client/assets/AgentTerminalSurface-CcC17_CY.js +16 -0
- package/dist/client/assets/AgentTerminalSurface-CcC17_CY.js.br +0 -0
- package/dist/client/assets/AgentTerminalSurface-CcC17_CY.js.gz +0 -0
- package/dist/client/assets/AvatarSettingsDialog-ChKrdDqp.js +1 -0
- package/dist/client/assets/AvatarSettingsDialog-ChKrdDqp.js.br +0 -0
- package/dist/client/assets/AvatarSettingsDialog-ChKrdDqp.js.gz +0 -0
- package/dist/client/assets/CitationBibtexEditor-BZIU4Lif.js +1 -0
- package/dist/client/assets/CitationLibraryDialog-DqO9e0GV.js +3 -0
- package/dist/client/assets/CitationLibraryDialog-DqO9e0GV.js.br +0 -0
- package/dist/client/assets/CitationLibraryDialog-DqO9e0GV.js.gz +0 -0
- package/dist/client/assets/CitationNotesPreview-D3CjBD0p.js +1 -0
- package/dist/client/assets/Dashboard-BYgqCgBM.js +5 -0
- package/dist/client/assets/Dashboard-BYgqCgBM.js.br +0 -0
- package/dist/client/assets/Dashboard-BYgqCgBM.js.gz +0 -0
- package/dist/client/assets/GitDialog-CA68baSd.js +4 -0
- package/dist/client/assets/GitDialog-CA68baSd.js.br +0 -0
- package/dist/client/assets/GitDialog-CA68baSd.js.gz +0 -0
- package/dist/client/assets/GitHubAccountDialog-CnxfR0JD.js +1 -0
- package/dist/client/assets/GitHubAccountDialog-CnxfR0JD.js.br +0 -0
- package/dist/client/assets/GitHubAccountDialog-CnxfR0JD.js.gz +0 -0
- package/dist/client/assets/HistoryDialog-c2EEaFsl.js +8 -0
- package/dist/client/assets/HistoryDialog-c2EEaFsl.js.br +0 -0
- package/dist/client/assets/HistoryDialog-c2EEaFsl.js.gz +0 -0
- package/dist/client/assets/InfoPopover-BJYnFn1P.js +1 -0
- package/dist/client/assets/LatexEditor-vNOVTIl7.js +25 -0
- package/dist/client/assets/LatexEditor-vNOVTIl7.js.br +0 -0
- package/dist/client/assets/LatexEditor-vNOVTIl7.js.gz +0 -0
- package/dist/client/assets/MarkdownContent-BeKi2gI5.js +36 -0
- package/dist/client/assets/MarkdownContent-BeKi2gI5.js.br +0 -0
- package/dist/client/assets/MarkdownContent-BeKi2gI5.js.gz +0 -0
- package/dist/client/assets/MarkdownPreview-BJPqGTcw.js +1 -0
- package/dist/client/assets/MarkdownPreview-BJPqGTcw.js.br +0 -0
- package/dist/client/assets/MarkdownPreview-BJPqGTcw.js.gz +0 -0
- package/dist/client/assets/{ProjectIconPickerDialog-DAiP7wVe.js → ProjectIconPickerDialog-ChiEUQ0g.js} +1 -1
- package/dist/client/assets/ProjectIconPickerDialog-ChiEUQ0g.js.br +0 -0
- package/dist/client/assets/ProjectIconPickerDialog-ChiEUQ0g.js.gz +0 -0
- package/dist/client/assets/ProjectSearchDialog-DxgjbnmY.js +1 -0
- package/dist/client/assets/ProjectSearchDialog-DxgjbnmY.js.br +0 -0
- package/dist/client/assets/ProjectSearchDialog-DxgjbnmY.js.gz +0 -0
- package/dist/client/assets/ProjectSettings-BwQTbXhh.js +4 -0
- package/dist/client/assets/ProjectSettings-BwQTbXhh.js.br +0 -0
- package/dist/client/assets/ProjectSettings-BwQTbXhh.js.gz +0 -0
- package/dist/client/assets/ProjectWorkspace-C2QAb-Fc.js +25 -0
- package/dist/client/assets/ProjectWorkspace-C2QAb-Fc.js.br +0 -0
- package/dist/client/assets/ProjectWorkspace-C2QAb-Fc.js.gz +0 -0
- package/dist/client/assets/{QuickOpenDialog-kW-97LBY.js → QuickOpenDialog-B7NTqOpu.js} +1 -1
- package/dist/client/assets/QuickOpenDialog-B7NTqOpu.js.br +0 -0
- package/dist/client/assets/QuickOpenDialog-B7NTqOpu.js.gz +0 -0
- package/dist/client/assets/{ReadOnlySource-B-ZZIpJq.js → ReadOnlySource-DIalHHvP.js} +2 -2
- package/dist/client/assets/SelectionHistoryDialog-BhOyneNx.js +3 -0
- package/dist/client/assets/SelectionHistoryDialog-BhOyneNx.js.br +0 -0
- package/dist/client/assets/SelectionHistoryDialog-BhOyneNx.js.gz +0 -0
- package/dist/client/assets/SharedProjectPage-s-khOyvB.js +2 -0
- package/dist/client/assets/SharedProjectPage-s-khOyvB.js.br +0 -0
- package/dist/client/assets/SharedProjectPage-s-khOyvB.js.gz +0 -0
- package/dist/client/assets/{SystemMetricsDialog-Dz_zxjfR.js → SystemMetricsDialog-Bycm88U1.js} +1 -1
- package/dist/client/assets/SystemMetricsDialog-Bycm88U1.js.br +0 -0
- package/dist/client/assets/SystemMetricsDialog-Bycm88U1.js.gz +0 -0
- package/dist/client/assets/TagManagementDialog-DwUAA8uC.js +1 -0
- package/dist/client/assets/TagManagementDialog-DwUAA8uC.js.br +0 -0
- package/dist/client/assets/TagManagementDialog-DwUAA8uC.js.gz +0 -0
- package/dist/client/assets/ThemeSwitcher-RSqZi7kx.js +1 -0
- package/dist/client/assets/TikzGalleryDialog-Bqzl2256.css +1 -0
- package/dist/client/assets/TikzGalleryDialog-Bqzl2256.css.br +0 -0
- package/dist/client/assets/TikzGalleryDialog-Bqzl2256.css.gz +0 -0
- package/dist/client/assets/TikzGalleryDialog-CLAmKmS6.js +1 -0
- package/dist/client/assets/TikzGalleryDialog-CLAmKmS6.js.br +0 -0
- package/dist/client/assets/TikzGalleryDialog-CLAmKmS6.js.gz +0 -0
- package/dist/client/assets/WordCountDialog-ByxE-RUs.js +1 -0
- package/dist/client/assets/WordCountDialog-ByxE-RUs.js.br +0 -0
- package/dist/client/assets/WordCountDialog-ByxE-RUs.js.gz +0 -0
- package/dist/client/assets/{bibtexFormatterWorker-B_jvobIv.js → bibtexFormatterWorker-Bp8kjjvw.js} +14 -14
- package/dist/client/assets/bibtexFormatterWorker-Bp8kjjvw.js.br +0 -0
- package/dist/client/assets/bibtexFormatterWorker-Bp8kjjvw.js.gz +0 -0
- package/dist/client/assets/bibtexMetadataWorker-CQozbzep.js +2 -0
- package/dist/client/assets/bibtexMetadataWorker-CQozbzep.js.br +0 -0
- package/dist/client/assets/bibtexMetadataWorker-CQozbzep.js.gz +0 -0
- package/dist/client/assets/bibtexNames-CPGbBJxd.js +1 -0
- package/dist/client/assets/bibtexReferences-xpSF8IXH.js +1 -0
- package/dist/client/assets/bot-ClmnQ29j.js +1 -0
- package/dist/client/assets/{chktex-CCcr_9m7.js → chktex-22lKGvKa.js} +2 -2
- package/dist/client/assets/citationAuthors-BWHXhKvT.js +1 -0
- package/dist/client/assets/citationAuthors-BWHXhKvT.js.br +0 -0
- package/dist/client/assets/citationAuthors-BWHXhKvT.js.gz +0 -0
- package/dist/client/assets/citationLibrary-DxGdbZEQ.js +1 -0
- package/dist/client/assets/citationLibrary-DxGdbZEQ.js.br +0 -0
- package/dist/client/assets/citationLibrary-DxGdbZEQ.js.gz +0 -0
- package/dist/client/assets/dist-Dxkdrap6.js +2 -0
- package/dist/client/assets/dist-Dxkdrap6.js.br +0 -0
- package/dist/client/assets/dist-Dxkdrap6.js.gz +0 -0
- package/dist/client/assets/editor-CkUEg2La.js +14 -0
- package/dist/client/assets/editor-CkUEg2La.js.br +0 -0
- package/dist/client/assets/editor-CkUEg2La.js.gz +0 -0
- package/dist/client/assets/editor-languages-kcWr1Z3Q.js +36 -0
- package/dist/client/assets/editor-languages-kcWr1Z3Q.js.br +0 -0
- package/dist/client/assets/editor-languages-kcWr1Z3Q.js.gz +0 -0
- package/dist/client/assets/editorThemeExtension-BWtZV1Af.js +1 -0
- package/dist/client/assets/editorThemeExtension-BWtZV1Af.js.br +0 -0
- package/dist/client/assets/editorThemeExtension-BWtZV1Af.js.gz +0 -0
- package/dist/client/assets/generatedParser-CZa2vsK6.js +1 -0
- package/dist/client/assets/generatedParser-CZa2vsK6.js.br +0 -0
- package/dist/client/assets/generatedParser-CZa2vsK6.js.gz +0 -0
- package/dist/client/assets/git-compare-arrows-158rS_vn.js +1 -0
- package/dist/client/assets/i18n-Wn96VbWM.js +13 -0
- package/dist/client/assets/i18n-Wn96VbWM.js.br +0 -0
- package/dist/client/assets/i18n-Wn96VbWM.js.gz +0 -0
- package/dist/client/assets/index-CemLYDYL.js +2 -0
- package/dist/client/assets/index-CemLYDYL.js.br +0 -0
- package/dist/client/assets/index-CemLYDYL.js.gz +0 -0
- package/dist/client/assets/index-DSF5eT29.css +1 -0
- package/dist/client/assets/index-DSF5eT29.css.br +0 -0
- package/dist/client/assets/index-DSF5eT29.css.gz +0 -0
- package/dist/client/assets/katex-Ca9qmXPj.js +257 -0
- package/dist/client/assets/katex-Ca9qmXPj.js.br +0 -0
- package/dist/client/assets/katex-Ca9qmXPj.js.gz +0 -0
- package/dist/client/assets/katex.min-VLoWtPY0.js +1 -0
- package/dist/client/assets/{latexFormatterWorker-BIDCSZPd.js → latexFormatterWorker-BWiogBYE.js} +1 -1
- package/dist/client/assets/latexFormatterWorker-BWiogBYE.js.br +0 -0
- package/dist/client/assets/latexFormatterWorker-BWiogBYE.js.gz +0 -0
- package/dist/client/assets/latexScanner-D9bMX44Y.js +6 -0
- package/dist/client/assets/latexScanner-D9bMX44Y.js.br +0 -0
- package/dist/client/assets/latexScanner-D9bMX44Y.js.gz +0 -0
- package/dist/client/assets/palette-8_-Y5XON.js +1 -0
- package/dist/client/assets/relativeTime-C-GTw3lA.js +1 -0
- package/dist/client/assets/relativeTime-C-GTw3lA.js.br +0 -0
- package/dist/client/assets/relativeTime-C-GTw3lA.js.gz +0 -0
- package/dist/client/assets/sourceCursorStore-Dpoi7PAL.js +1 -0
- package/dist/client/assets/sourceCursorStore-Dpoi7PAL.js.br +0 -0
- package/dist/client/assets/sourceCursorStore-Dpoi7PAL.js.gz +0 -0
- package/dist/client/assets/{spellCheck-D-tYd_ac.js → spellCheck-kxvnxrvw.js} +1 -1
- package/dist/client/assets/spellCheck-kxvnxrvw.js.br +0 -0
- package/dist/client/assets/spellCheck-kxvnxrvw.js.gz +0 -0
- package/dist/client/assets/{textLanguageSupport-Kz9ESEVW.js → textLanguageSupport-Ck8lMOWz.js} +1 -1
- package/dist/client/assets/{textLanguages-Dac6mieP.js → textLanguages-CwWstpJ5.js} +5 -5
- package/dist/client/assets/textLanguages-CwWstpJ5.js.br +0 -0
- package/dist/client/assets/textLanguages-CwWstpJ5.js.gz +0 -0
- package/dist/client/assets/useDeletionTransitions-Xlq7HabP.js +1 -0
- package/dist/client/assets/useDeletionTransitions-Xlq7HabP.js.br +0 -0
- package/dist/client/assets/useDeletionTransitions-Xlq7HabP.js.gz +0 -0
- package/dist/client/assets/{vimSupport-DWYaSMuX.js → vimSupport-C-WiMLjc.js} +6 -6
- package/dist/client/assets/vimSupport-C-WiMLjc.js.br +0 -0
- package/dist/client/assets/{vimSupport-DWYaSMuX.js.gz → vimSupport-C-WiMLjc.js.gz} +0 -0
- package/dist/client/index.html +3 -3
- package/dist/server/agentChanges.js +149 -0
- package/dist/server/agents/sessions.js +1 -1
- package/dist/server/agents/workspaces.js +21 -28
- package/dist/server/app.js +15 -6
- package/dist/server/boundedExpiringCache.js +69 -0
- package/dist/server/citationFolderTransfer.js +5 -5
- package/dist/server/citationInput.js +1 -0
- package/dist/server/cli.js +12 -1
- package/dist/server/collaboration.js +8 -4
- package/dist/server/config.js +10 -0
- package/dist/server/db.js +23 -0
- package/dist/server/editHistory.js +71 -12
- package/dist/server/git.js +58 -7
- package/dist/server/history.js +58 -9
- package/dist/server/i18n.js +12 -0
- package/dist/server/locales/zh-Hant.js +6 -0
- package/dist/server/projectReferences.js +110 -9
- package/dist/server/routes/auth.js +3 -0
- package/dist/server/routes/citations.js +28 -61
- package/dist/server/routes/comments.js +8 -3
- package/dist/server/routes/compile.js +56 -4
- package/dist/server/routes/projectGit.js +10 -0
- package/dist/server/routes/projectHistory.js +42 -0
- package/dist/server/routes/system.js +1 -0
- package/dist/server/routes/tikzGallery.js +38 -0
- package/dist/server/routes/users.js +2 -2
- package/dist/server/tikzEditorAddon.js +115 -0
- package/dist/server/tikzEditorRelease.js +9 -0
- package/dist/server/tikzGallery.js +63 -0
- package/dist/shared/bibtexBraces.js +20 -0
- package/dist/shared/bibtexNames.js +82 -0
- package/dist/shared/bibtexReferences.js +52 -12
- package/dist/shared/bibtexText.js +175 -0
- package/dist/shared/gitProtocol.js +2 -0
- package/dist/shared/historyProtocol.js +5 -0
- package/dist/shared/textDiff.js +36 -1
- package/dist/shared/tikzStandalone.js +15 -0
- package/package.json +2 -1
- package/templates/agents/AGENTS.md +12 -0
- package/texlite.config.example.json +4 -0
- package/dist/client/assets/AdminUsers-Cpj29JD6.js +0 -1
- package/dist/client/assets/AdminUsers-Cpj29JD6.js.br +0 -0
- package/dist/client/assets/AdminUsers-Cpj29JD6.js.gz +0 -0
- package/dist/client/assets/AgentIcon-dCMgWJG-.css.br +0 -0
- package/dist/client/assets/AgentIcon-dCMgWJG-.css.gz +0 -0
- package/dist/client/assets/AgentManagement-0n1UkKZ5.js.br +0 -0
- package/dist/client/assets/AgentManagement-0n1UkKZ5.js.gz +0 -0
- package/dist/client/assets/AgentTerminal-BbGH5iPx.js +0 -2
- package/dist/client/assets/AgentTerminal-BbGH5iPx.js.br +0 -0
- package/dist/client/assets/AgentTerminal-BbGH5iPx.js.gz +0 -0
- package/dist/client/assets/AgentTerminalSurface-CIouKd-C.js +0 -16
- package/dist/client/assets/AgentTerminalSurface-CIouKd-C.js.br +0 -0
- package/dist/client/assets/AgentTerminalSurface-CIouKd-C.js.gz +0 -0
- package/dist/client/assets/AvatarSettingsDialog-BjTx2yjQ.js +0 -1
- package/dist/client/assets/AvatarSettingsDialog-BjTx2yjQ.js.br +0 -0
- package/dist/client/assets/AvatarSettingsDialog-BjTx2yjQ.js.gz +0 -0
- package/dist/client/assets/CitationBibtexEditor-B4ITqbxl.js +0 -1
- package/dist/client/assets/CitationLibraryDialog-DDP3gXNt.js +0 -3
- package/dist/client/assets/CitationLibraryDialog-DDP3gXNt.js.br +0 -0
- package/dist/client/assets/CitationLibraryDialog-DDP3gXNt.js.gz +0 -0
- package/dist/client/assets/CitationNotesPreview-BjbIDOCl.js +0 -36
- package/dist/client/assets/CitationNotesPreview-BjbIDOCl.js.br +0 -0
- package/dist/client/assets/CitationNotesPreview-BjbIDOCl.js.gz +0 -0
- package/dist/client/assets/Dashboard-Dc3ANXhG.js +0 -5
- package/dist/client/assets/Dashboard-Dc3ANXhG.js.br +0 -0
- package/dist/client/assets/Dashboard-Dc3ANXhG.js.gz +0 -0
- package/dist/client/assets/GitDialog-CzLmo9Z_.js +0 -3
- package/dist/client/assets/GitDialog-CzLmo9Z_.js.br +0 -0
- package/dist/client/assets/GitDialog-CzLmo9Z_.js.gz +0 -0
- package/dist/client/assets/GitHubAccountDialog-DsQgHv-Z.js +0 -1
- package/dist/client/assets/GitHubAccountDialog-DsQgHv-Z.js.br +0 -0
- package/dist/client/assets/GitHubAccountDialog-DsQgHv-Z.js.gz +0 -0
- package/dist/client/assets/HistoryDialog-C4zmnE1s.js +0 -8
- package/dist/client/assets/HistoryDialog-C4zmnE1s.js.br +0 -0
- package/dist/client/assets/HistoryDialog-C4zmnE1s.js.gz +0 -0
- package/dist/client/assets/InfoPopover-Dkz742vJ.js +0 -1
- package/dist/client/assets/LatexEditor-BRPiyMbH.js +0 -25
- package/dist/client/assets/LatexEditor-BRPiyMbH.js.br +0 -0
- package/dist/client/assets/LatexEditor-BRPiyMbH.js.gz +0 -0
- package/dist/client/assets/ProjectIconPickerDialog-DAiP7wVe.js.br +0 -0
- package/dist/client/assets/ProjectIconPickerDialog-DAiP7wVe.js.gz +0 -0
- package/dist/client/assets/ProjectSearchDialog-B5a5mHXl.js +0 -1
- package/dist/client/assets/ProjectSearchDialog-B5a5mHXl.js.br +0 -0
- package/dist/client/assets/ProjectSearchDialog-B5a5mHXl.js.gz +0 -0
- package/dist/client/assets/ProjectSettings-CARW1k8M.js +0 -4
- package/dist/client/assets/ProjectSettings-CARW1k8M.js.br +0 -0
- package/dist/client/assets/ProjectSettings-CARW1k8M.js.gz +0 -0
- package/dist/client/assets/ProjectWorkspace-BQ3QGBVy.js +0 -31
- package/dist/client/assets/ProjectWorkspace-BQ3QGBVy.js.br +0 -0
- package/dist/client/assets/ProjectWorkspace-BQ3QGBVy.js.gz +0 -0
- package/dist/client/assets/QuickOpenDialog-kW-97LBY.js.br +0 -0
- package/dist/client/assets/QuickOpenDialog-kW-97LBY.js.gz +0 -0
- package/dist/client/assets/SelectionHistoryDialog-CmHcjD4T.js +0 -3
- package/dist/client/assets/SelectionHistoryDialog-CmHcjD4T.js.br +0 -0
- package/dist/client/assets/SelectionHistoryDialog-CmHcjD4T.js.gz +0 -0
- package/dist/client/assets/SharedProjectPage-BjhT-js7.js +0 -2
- package/dist/client/assets/SharedProjectPage-BjhT-js7.js.br +0 -0
- package/dist/client/assets/SharedProjectPage-BjhT-js7.js.gz +0 -0
- package/dist/client/assets/SystemMetricsDialog-Dz_zxjfR.js.br +0 -0
- package/dist/client/assets/SystemMetricsDialog-Dz_zxjfR.js.gz +0 -0
- package/dist/client/assets/TagManagementDialog-BIsAi9rh.js +0 -1
- package/dist/client/assets/TagManagementDialog-BIsAi9rh.js.br +0 -0
- package/dist/client/assets/TagManagementDialog-BIsAi9rh.js.gz +0 -0
- package/dist/client/assets/ThemeSwitcher-dp0oKTtC.js +0 -1
- package/dist/client/assets/ThemeSwitcher-dp0oKTtC.js.br +0 -0
- package/dist/client/assets/ThemeSwitcher-dp0oKTtC.js.gz +0 -0
- package/dist/client/assets/WordCountDialog-CJb1b8cD.js +0 -1
- package/dist/client/assets/WordCountDialog-CJb1b8cD.js.br +0 -0
- package/dist/client/assets/WordCountDialog-CJb1b8cD.js.gz +0 -0
- package/dist/client/assets/bibtexFormatterWorker-B_jvobIv.js.br +0 -0
- package/dist/client/assets/bibtexFormatterWorker-B_jvobIv.js.gz +0 -0
- package/dist/client/assets/citationLibrary-BzlqZiFU.js +0 -26
- package/dist/client/assets/citationLibrary-BzlqZiFU.js.br +0 -0
- package/dist/client/assets/citationLibrary-BzlqZiFU.js.gz +0 -0
- package/dist/client/assets/clipboard-CslquMx4.js +0 -1
- package/dist/client/assets/editor-fyrvjoqA.js +0 -14
- package/dist/client/assets/editor-fyrvjoqA.js.br +0 -0
- package/dist/client/assets/editor-fyrvjoqA.js.gz +0 -0
- package/dist/client/assets/editor-languages-D1a-K8dK.js +0 -36
- package/dist/client/assets/editor-languages-D1a-K8dK.js.br +0 -0
- package/dist/client/assets/editor-languages-D1a-K8dK.js.gz +0 -0
- package/dist/client/assets/editorThemeExtension-BpJbXyCP.js +0 -1
- package/dist/client/assets/editorThemeExtension-BpJbXyCP.js.br +0 -0
- package/dist/client/assets/editorThemeExtension-BpJbXyCP.js.gz +0 -0
- package/dist/client/assets/eye-BnslGpqB.js +0 -1
- package/dist/client/assets/i18n-DNTfpttY.js +0 -13
- package/dist/client/assets/i18n-DNTfpttY.js.br +0 -0
- package/dist/client/assets/i18n-DNTfpttY.js.gz +0 -0
- package/dist/client/assets/index-CfSDaTd4.js +0 -2
- package/dist/client/assets/index-CfSDaTd4.js.br +0 -0
- package/dist/client/assets/index-CfSDaTd4.js.gz +0 -0
- package/dist/client/assets/index-PNFHDg2W.css +0 -1
- package/dist/client/assets/index-PNFHDg2W.css.br +0 -0
- package/dist/client/assets/index-PNFHDg2W.css.gz +0 -0
- package/dist/client/assets/katex-CBRBI6nR.js +0 -257
- package/dist/client/assets/katex-CBRBI6nR.js.br +0 -0
- package/dist/client/assets/katex-CBRBI6nR.js.gz +0 -0
- package/dist/client/assets/latexFormatterWorker-BIDCSZPd.js.br +0 -0
- package/dist/client/assets/latexFormatterWorker-BIDCSZPd.js.gz +0 -0
- package/dist/client/assets/relativeTime-DKEihsTa.js +0 -1
- package/dist/client/assets/relativeTime-DKEihsTa.js.br +0 -0
- package/dist/client/assets/relativeTime-DKEihsTa.js.gz +0 -0
- package/dist/client/assets/sourceCursorStore-QnrFw3Ft.js +0 -1
- package/dist/client/assets/sourceCursorStore-QnrFw3Ft.js.br +0 -0
- package/dist/client/assets/sourceCursorStore-QnrFw3Ft.js.gz +0 -0
- package/dist/client/assets/spellCheck-D-tYd_ac.js.br +0 -0
- package/dist/client/assets/spellCheck-D-tYd_ac.js.gz +0 -0
- package/dist/client/assets/textLanguages-Dac6mieP.js.br +0 -0
- package/dist/client/assets/textLanguages-Dac6mieP.js.gz +0 -0
- package/dist/client/assets/useDeletionTransitions-TAZINdHX.js +0 -1
- package/dist/client/assets/useDeletionTransitions-TAZINdHX.js.br +0 -0
- package/dist/client/assets/useDeletionTransitions-TAZINdHX.js.gz +0 -0
- package/dist/client/assets/vimSupport-DWYaSMuX.js.br +0 -0
- /package/dist/client/assets/{AgentIcon-DsoMeMA8.js → AgentIcon-qmglBc3M.js} +0 -0
- /package/dist/client/assets/{AgentIcon-DsoMeMA8.js.br → AgentIcon-qmglBc3M.js.br} +0 -0
- /package/dist/client/assets/{AgentIcon-DsoMeMA8.js.gz → AgentIcon-qmglBc3M.js.gz} +0 -0
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./spellCheck-D-tYd_ac.js","./index-CfSDaTd4.js","./rolldown-runtime-XKyaHtl9.js","./react-DUEFWlB7.js","./useTranslation-DwkoADSz.js","./i18nInstance-CIMFwH0l.js","./i18n-DNTfpttY.js","./basePath-B5-c90eh.js","./vite-runtime-CRzLMJPS.js","./loader-circle-DKGyi5EK.js","./createLucideIcon-CDYIzuiB.js","./dist-DdUqlCPw.js","./es2015-D2UDOM09.js","./index-PNFHDg2W.css","./chktex-CCcr_9m7.js","./LatexEditor-BRPiyMbH.js","./useDeletionTransitions-TAZINdHX.js","./dist-B_WjsTVV.js","./editor-fyrvjoqA.js","./editorThemeExtension-BpJbXyCP.js","./textLanguages-Dac6mieP.js","./CitationLibraryDialog-DDP3gXNt.js","./relativeTime-DKEihsTa.js","./check-Dw16EqG-.js","./chevron-up-BHaMUEEA.js","./eye-BnslGpqB.js","./TagMarquee-BLmCTTCt.js","./InfoPopover-Dkz742vJ.js","./library-big-B8e_Fiql.js","./plus-Cei21TlT.js","./refresh-cw-IqExWG6S.js","./SaveButton-wiTpGLho.js","./circle-check-CunlnBPw.js","./search-DjOWqLig.js","./dist-C9O-A_C4.js","./clipboard-CslquMx4.js","./citationLibrary-BzlqZiFU.js","./SuccessNotice-ubBtzzi_.js","./TagColorSelect-e-Tq5V3H.js","./GitDialog-CzLmo9Z_.js","./GitHubIcon-CExJn0AV.js","./minimize-2-CkBmeGXp.js","./minus-DrpwqY8Y.js","./HistoryDialog-C4zmnE1s.js","./clock-3-DztJubz_.js","./sourceCursorStore-QnrFw3Ft.js","./hard-drive-CXlummIE.js","./SelectionHistoryDialog-CmHcjD4T.js","./QuickOpenDialog-kW-97LBY.js","./ProjectSearchDialog-B5a5mHXl.js","./ProjectSettings-CARW1k8M.js","./terminal-DD9WJ56e.js","./type-CKe1tHHo.js","./AgentTerminal-BbGH5iPx.js","./AgentIcon-DsoMeMA8.js","./AgentIcon-dCMgWJG-.css","./WordCountDialog-CJb1b8cD.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{n as e,r as t}from"./rolldown-runtime-XKyaHtl9.js";import{i as n,r,t as i}from"./react-DUEFWlB7.js";import{_ as a,b as o,g as s,h as c,i as l,m as u,n as d,p as f,t as p,u as m,v as h,x as g,y as _}from"./relativeTime-DKEihsTa.js";import{t as v}from"./useTranslation-DwkoADSz.js";import{t as y}from"./i18n-DNTfpttY.js";import{r as b,t as x}from"./basePath-B5-c90eh.js";import{t as S}from"./vite-runtime-CRzLMJPS.js";import{t as C}from"./createLucideIcon-CDYIzuiB.js";import{t as w}from"./arrow-down-C_4f1E-E.js";import{B as T,D as E,E as D,H as O,P as k,R as A,S as j,T as M,U as ee,_ as N,b as P,c as te,d as F,h as I,j as L,k as ne,m as re,o as ie,p as R,s as z,u as ae,v as B,w as oe,x as V,y as se,z as H}from"./useDeletionTransitions-TAZINdHX.js";import{t as U}from"./check-Dw16EqG-.js";import{o as W}from"./dist-B_WjsTVV.js";import{t as ce}from"./chevron-up-BHaMUEEA.js";import{t as le}from"./circle-check-CunlnBPw.js";import{C as ue,D as de,E as fe,O as pe,S as me,_ as he,b as ge,c as _e,d as ve,f as G,g as ye,h as be,l as xe,m as Se,n as Ce,o as we,p as Te,r as Ee,s as De,t as Oe,u as ke,v as Ae,w as je,x as Me,y as Ne}from"./sourceCursorStore-QnrFw3Ft.js";import{t as Pe}from"./InfoPopover-Dkz742vJ.js";import{t as Fe}from"./loader-circle-DKGyi5EK.js";import{t as Ie}from"./plus-Cei21TlT.js";import{t as Le}from"./refresh-cw-IqExWG6S.js";import{t as Re}from"./SaveButton-wiTpGLho.js";import{t as ze}from"./user-plus-NNBQOWDP.js";import{_ as Be,a as Ve,c as He,f as K,h as q,l as Ue,m as We,p as J,s as Ge,v as Ke,y as qe}from"./index-CfSDaTd4.js";import{a as Je,l as Ye,n as Xe,r as Ze,t as Qe}from"./dist-C9O-A_C4.js";import{t as $e}from"./clipboard-CslquMx4.js";var et={name:`arrow-right`,size:24,node:[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]};et.node;var tt=C(et),nt={name:`arrow-up`,size:24,node:[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]};nt.node;var rt=C(nt),it={name:`circle-question-mark`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`,key:`1u773s`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]],aliases:[`help-circle`,`circle-help`]};it.node;var at=C(it),ot={name:`circle-x`,size:24,node:[[`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`}]],aliases:[`x-circle`]};ot.node;var st=C(ot),ct={name:`eraser`,size:24,node:[[`path`,{d:`M21 21H8a2 2 0 0 1-1.42-.587l-3.994-3.999a2 2 0 0 1 0-2.828l10-10a2 2 0 0 1 2.829 0l5.999 6a2 2 0 0 1 0 2.828L12.834 21`,key:`g5wo59`}],[`path`,{d:`m5.082 11.09 8.828 8.828`,key:`1wx5vj`}]]};ct.node;var lt=C(ct),ut={name:`keyboard`,size:24,node:[[`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`}]]};ut.node;var dt=C(ut),ft={name:`link`,size:24,node:[[`path`,{d:`M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71`,key:`1cjeqo`}],[`path`,{d:`M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71`,key:`19qd67`}]]};ft.node;var pt=C(ft),mt={name:`logs`,size:24,node:[[`path`,{d:`M3 5h1`,key:`1mv5vm`}],[`path`,{d:`M3 12h1`,key:`lp3yf2`}],[`path`,{d:`M3 19h1`,key:`w6f3n9`}],[`path`,{d:`M8 5h1`,key:`1nxr5w`}],[`path`,{d:`M8 12h1`,key:`1con00`}],[`path`,{d:`M8 19h1`,key:`k7p10e`}],[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}]]};mt.node;var ht=C(mt),gt={name:`messages-square`,size:24,node:[[`path`,{d:`M16 10a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 14.286V4a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z`,key:`1n2ejm`}],[`path`,{d:`M20 9a2 2 0 0 1 2 2v10.286a.71.71 0 0 1-1.212.502l-2.202-2.202A2 2 0 0 0 17.172 19H10a2 2 0 0 1-2-2v-1`,key:`1qfcsi`}]]};gt.node;var _t=C(gt),vt={name:`package-open`,size:24,node:[[`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`}]]};vt.node;var yt=C(vt),bt={name:`rotate-ccw`,size:24,node:[[`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`}]]};bt.node;var xt=C(bt),St={name:`send`,size:24,node:[[`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`}]]};St.node;var Ct=C(St),Y=t(n(),1),wt=t(r(),1),X=i();function Tt(e){let[t,n]=e;return[t,n]}function Et(e,t){let n=e,r=t,i=n.length,a=r.length;if(i===0||a===0)return 0;i>a?n=n.substring(i-a):i<a&&(r=r.substring(0,i));let o=Math.min(i,a);if(n===r)return o;let s=0,c=1;for(let e=0;e!==-1;){let t=n.substring(o-c);if(e=r.indexOf(t),e===-1)return s;c+=e,(e===0||n.substring(o-c)===r.substring(0,c))&&(s=c,c++)}return s}function Dt(e,t){if(!e||!t||e[0]!==t[0])return 0;let n=0,r=Math.min(e.length,t.length),i=r,a=0;for(;n<i;)e.substring(a,i)===t.substring(a,i)?(n=i,a=n):r=i,i=Math.floor((r-n)/2+n);return i}function Ot(e,t){if(!e||!t||e[e.length-1]!==t[t.length-1])return 0;let n=0,r=Math.min(e.length,t.length),i=r,a=0;for(;n<i;)e.substring(e.length-i,e.length-a)===t.substring(t.length-i,t.length-a)?(n=i,a=n):r=i,i=Math.floor((r-n)/2+n);return i}function kt(e){let t=e.charCodeAt(0);return t>=55296&&t<=56319}function At(e){let t=e.charCodeAt(0);return t>=56320&&t<=57343}function jt(e,t,n){let r=e.length,i=t.length,a=Math.ceil((r+i)/2),o=a,s=2*a,c=Array(s),l=Array(s);for(let e=0;e<s;e++)c[e]=-1,l[e]=-1;c[o+1]=0,l[o+1]=0;let u=r-i,d=u%2!=0,f=0,p=0,m=0,h=0;for(let g=0;g<a&&!(Date.now()>n);g++){for(let a=-g+f;a<=g-p;a+=2){let m=o+a,h;h=a===-g||a!==g&&c[m-1]<c[m+1]?c[m+1]:c[m-1]+1;let _=h-a;for(;h<r&&_<i&&e.charAt(h)===t.charAt(_);)h++,_++;if(c[m]=h,h>r)p+=2;else if(_>i)f+=2;else if(d){let i=o+u-a;if(i>=0&&i<s&&l[i]!==-1){let a=r-l[i];if(h>=a)return Mt(e,t,h,_,n)}}}for(let a=-g+m;a<=g-h;a+=2){let f=o+a,p;p=a===-g||a!==g&&l[f-1]<l[f+1]?l[f+1]:l[f-1]+1;let _=p-a;for(;p<r&&_<i&&e.charAt(r-p-1)===t.charAt(i-_-1);)p++,_++;if(l[f]=p,p>r)h+=2;else if(_>i)m+=2;else if(!d){let i=o+u-a;if(i>=0&&i<s&&c[i]!==-1){let a=c[i],s=o+a-i;if(p=r-p,a>=p)return Mt(e,t,a,s,n)}}}}return[[-1,e],[1,t]]}function Mt(e,t,n,r,i){let a=e.substring(0,n),o=t.substring(0,r),s=e.substring(n),c=t.substring(r),l=Kt(a,o,{checkLines:!1,deadline:i}),u=Kt(s,c,{checkLines:!1,deadline:i});return l.concat(u)}function Nt(e,t,n=1){if(n<=0)return null;let r=e.length>t.length?e:t,i=e.length>t.length?t:e;if(r.length<4||i.length*2<r.length)return null;let a=Pt(r,i,Math.ceil(r.length/4)),o=Pt(r,i,Math.ceil(r.length/2)),s;if(a&&o)s=a[4].length>o[4].length?a:o;else{if(!a&&!o)return null;o?a||(s=o):s=a}if(!s)throw Error(`Unable to find a half match.`);let c,l,u,d;e.length>t.length?(c=s[0],l=s[1],u=s[2],d=s[3]):(u=s[0],d=s[1],c=s[2],l=s[3]);let f=s[4];return[c,l,u,d,f]}function Pt(e,t,n){let r=e.slice(n,n+Math.floor(e.length/4)),i=-1,a=``,o,s,c,l;for(;(i=t.indexOf(r,i+1))!==-1;){let r=Dt(e.slice(n),t.slice(i)),u=Ot(e.slice(0,n),t.slice(0,i));a.length<u+r&&(a=t.slice(i-u,i)+t.slice(i,i+r),o=e.slice(0,n-u),s=e.slice(n+r),c=t.slice(0,i-u),l=t.slice(i+r))}return a.length*2>=e.length?[o||``,s||``,c||``,l||``,a||``]:null}function Ft(e,t){for(let n=0;n<e.length;n++){let r=e[n][1],i=[];for(let e=0;e<r.length;e++)i[e]=t[r.charCodeAt(e)];e[n][1]=i.join(``)}}function It(e,t){let n=[],r={};n[0]=``;function i(e){let t=``,i=0,o=-1,s=n.length;for(;o<e.length-1;){o=e.indexOf(`
|
|
3
|
-
`,i),o===-1&&(o=e.length-1);let c=e.slice(i,o+1);(r.hasOwnProperty?r.hasOwnProperty(c):r[c]!==void 0)?t+=String.fromCharCode(r[c]):(s===a&&(c=e.slice(i),o=e.length),t+=String.fromCharCode(s),r[c]=s,n[s++]=c),i=o+1}return t}let a=4e4,o=i(e);return a=65535,{chars1:o,chars2:i(t),lineArray:n}}function Lt(e,t,n){let r=e,i=t,a=It(r,i);r=a.chars1,i=a.chars2;let o=a.lineArray,s=Kt(r,i,{checkLines:!1,deadline:n.deadline});Ft(s,o),s=en(s),s.push([0,``]);let c=0,l=0,u=0,d=``,f=``;for(;c<s.length;){switch(s[c][0]){case 1:u++,f+=s[c][1];break;case-1:l++,d+=s[c][1];break;case 0:if(l>=1&&u>=1){s.splice(c-l-u,l+u),c=c-l-u;let e=Kt(d,f,{checkLines:!1,deadline:n.deadline});for(let t=e.length-1;t>=0;t--)s.splice(c,0,e[t]);c+=e.length}u=0,l=0,d=``,f=``;break;default:throw Error(`Unknown diff operation.`)}c++}return s.pop(),s}function Rt(e,t,n){let r;if(!e)return[[1,t]];if(!t)return[[-1,e]];let i=e.length>t.length?e:t,a=e.length>t.length?t:e,o=i.indexOf(a);if(o!==-1)return r=[[1,i.substring(0,o)],[0,a],[1,i.substring(o+a.length)]],e.length>t.length&&(r[0][0]=-1,r[2][0]=-1),r;if(a.length===1)return[[-1,e],[1,t]];let s=Nt(e,t);if(s){let e=s[0],t=s[1],r=s[2],i=s[3],a=s[4],o=Kt(e,r,n),c=Kt(t,i,n);return o.concat([[0,a]],c)}return n.checkLines&&e.length>100&&t.length>100?Lt(e,t,n):jt(e,t,n.deadline)}var zt=Object.defineProperty,Bt=Object.getOwnPropertySymbols,Vt=Object.prototype.hasOwnProperty,Ht=Object.prototype.propertyIsEnumerable,Ut=(e,t,n)=>t in e?zt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Wt=(e,t)=>{for(var n in t||={})Vt.call(t,n)&&Ut(e,n,t[n]);if(Bt)for(var n of Bt(t))Ht.call(t,n)&&Ut(e,n,t[n]);return e};function Gt(e,t,n){if(e===null||t===null)throw Error(`Null input. (diff)`);let r=Kt(e,t,Jt(n||{}));return $t(r),r}function Kt(e,t,n){let r=e,i=t;if(r===i)return r?[[0,r]]:[];let a=Dt(r,i),o=r.substring(0,a);r=r.substring(a),i=i.substring(a),a=Ot(r,i);let s=r.substring(r.length-a);r=r.substring(0,r.length-a),i=i.substring(0,i.length-a);let c=Rt(r,i,n);return o&&c.unshift([0,o]),s&&c.push([0,s]),c=cn(c),c}function qt(e){let t=1;return typeof e<`u`&&(t=e<=0?Number.MAX_VALUE:e),Date.now()+t*1e3}function Jt(e){return Wt({checkLines:!0,deadline:qt(e.timeout||1)},e)}function Yt(e,t,n){return n===1?e+t:t+e}function Xt(e,t){return t===1?[e.substring(0,e.length-1),e[e.length-1]]:[e.substring(1),e[0]]}function Zt(e,t,n,r){return r===1?e[t][1][e[t][1].length-1]===e[n][1][e[n][1].length-1]:e[t][1][0]===e[n][1][0]}function Qt(e,t,n){let r=n===1?-1:1,i=null,a=null,o=t+n;for(;o>=0&&o<e.length&&(i===null||a===null);o+=n){let[s,c]=e[o];if(c.length!==0){if(s===1){i===null&&(i=o);continue}if(s===-1){a===null&&(a=o);continue}if(s===0){if(i===null&&a===null){let[i,a]=Xt(e[t][1],n);e[t][1]=i,e[o][1]=Yt(e[o][1],a,r);return}break}}}if(i!==null&&a!==null&&Zt(e,i,a,n)){let[o,s]=Xt(e[i][1],r),[c]=Xt(e[a][1],r);e[i][1]=o,e[a][1]=c,e[t][1]=Yt(e[t][1],s,n);return}let[s,c]=Xt(e[t][1],n);e[t][1]=s,i===null?(e.splice(o,0,[1,c]),a!==null&&a>=o&&a++):e[i][1]=Yt(e[i][1],c,r),a===null?e.splice(o,0,[-1,c]):e[a][1]=Yt(e[a][1],c,r)}function $t(e){for(let t=0;t<e.length;t++){let[n,r]=e[t];if(r.length===0)continue;let i=r[0],a=r[r.length-1];kt(a)&&n===0&&Qt(e,t,1),At(i)&&n===0&&Qt(e,t,-1)}for(let t=0;t<e.length;t++)e[t][1].length===0&&e.splice(t,1)}function en(e){let t=e.map(e=>Tt(e)),n=!1,r=[],i=0,a=null,o=0,s=0,c=0,l=0,u=0;for(;o<t.length;)t[o][0]===0?(r[i++]=o,s=l,c=u,l=0,u=0,a=t[o][1]):(t[o][0]===1?l+=t[o][1].length:u+=t[o][1].length,a&&a.length<=Math.max(s,c)&&a.length<=Math.max(l,u)&&(t.splice(r[i-1],0,[-1,a]),t[r[i-1]+1][0]=1,i--,i--,o=i>0?r[i-1]:-1,s=0,c=0,l=0,u=0,a=null,n=!0)),o++;for(n&&(t=cn(t)),t=sn(t),o=1;o<t.length;){if(t[o-1][0]===-1&&t[o][0]===1){let e=t[o-1][1],n=t[o][1],r=Et(e,n),i=Et(n,e);r>=i?(r>=e.length/2||r>=n.length/2)&&(t.splice(o,0,[0,n.substring(0,r)]),t[o-1][1]=e.substring(0,e.length-r),t[o+1][1]=n.substring(r),o++):(i>=e.length/2||i>=n.length/2)&&(t.splice(o,0,[0,e.substring(0,i)]),t[o-1][0]=1,t[o-1][1]=n.substring(0,n.length-i),t[o+1][0]=-1,t[o+1][1]=e.substring(i),o++),o++}o++}return t}var tn=/[^a-zA-Z0-9]/,nn=/\s/,rn=/[\r\n]/,an=/\n\r?\n$/,on=/^\r?\n\r?\n/;function sn(e){let t=e.map(e=>Tt(e));function n(e,t){if(!e||!t)return 6;let n=e.charAt(e.length-1),r=t.charAt(0),i=n.match(tn),a=r.match(tn),o=i&&n.match(nn),s=a&&r.match(nn),c=o&&n.match(rn),l=s&&r.match(rn),u=c&&e.match(an),d=l&&t.match(on);return u||d?5:c||l?4:i&&!o&&s?3:o||s?2:i||a?1:0}let r=1;for(;r<t.length-1;){if(t[r-1][0]===0&&t[r+1][0]===0){let e=t[r-1][1],i=t[r][1],a=t[r+1][1],o=Ot(e,i);if(o){let t=i.substring(i.length-o);e=e.substring(0,e.length-o),i=t+i.substring(0,i.length-o),a=t+a}let s=e,c=i,l=a,u=n(e,i)+n(i,a);for(;i.charAt(0)===a.charAt(0);){e+=i.charAt(0),i=i.substring(1)+a.charAt(0),a=a.substring(1);let t=n(e,i)+n(i,a);t>=u&&(u=t,s=e,c=i,l=a)}t[r-1][1]!==s&&(s?t[r-1][1]=s:(t.splice(r-1,1),r--),t[r][1]=c,l?t[r+1][1]=l:(t.splice(r+1,1),r--))}r++}return t}function cn(e){let t=e.map(e=>Tt(e));t.push([0,``]);let n=0,r=0,i=0,a=``,o=``,s;for(;n<t.length;)switch(t[n][0]){case 1:i++,o+=t[n][1],n++;break;case-1:r++,a+=t[n][1],n++;break;case 0:r+i>1?(r!==0&&i!==0&&(s=Dt(o,a),s!==0&&(n-r-i>0&&t[n-r-i-1][0]===0?t[n-r-i-1][1]+=o.substring(0,s):(t.splice(0,0,[0,o.substring(0,s)]),n++),o=o.substring(s),a=a.substring(s)),s=Ot(o,a),s!==0&&(t[n][1]=o.substring(o.length-s)+t[n][1],o=o.substring(0,o.length-s),a=a.substring(0,a.length-s))),n-=r+i,t.splice(n,r+i),a.length&&(t.splice(n,0,[-1,a]),n++),o.length&&(t.splice(n,0,[1,o]),n++),n++):n!==0&&t[n-1][0]===0?(t[n-1][1]+=t[n][1],t.splice(n,1)):n++,i=0,r=0,a=``,o=``;break;default:throw Error(`Unknown diff operation`)}t[t.length-1][1]===``&&t.pop();let c=!1;for(n=1;n<t.length-1;)t[n-1][0]===0&&t[n+1][0]===0&&(t[n][1].substring(t[n][1].length-t[n-1][1].length)===t[n-1][1]?(t[n][1]=t[n-1][1]+t[n][1].substring(0,t[n][1].length-t[n-1][1].length),t[n+1][1]=t[n-1][1]+t[n+1][1],t.splice(n-1,1),c=!0):t[n][1].substring(0,t[n+1][1].length)===t[n+1][1]&&(t[n-1][1]+=t[n+1][1],t[n][1]=t[n][1].substring(t[n+1][1].length)+t[n+1][1],t.splice(n+1,1),c=!0)),n++;return c&&(t=cn(t)),t}function ln(...e){return e.reduce((e,t)=>e+ +!!t,0)}function un(e,t=4){let n=e.map(e=>Tt(e)),r=!1,i=[],a=0,o=null,s=0,c=!1,l=!1,u=!1,d=!1;for(;s<n.length;)n[s][0]===0?(n[s][1].length<t&&(u||d)?(i[a++]=s,c=u,l=d,o=n[s][1]):(a=0,o=null),u=!1,d=!1):(n[s][0]===-1?d=!0:u=!0,o&&(c&&l&&u&&d||o.length<t/2&&ln(c,l,u,d)===3)&&(n.splice(i[a-1],0,[-1,o]),n[i[a-1]+1][0]=1,a--,o=null,c&&l?(u=!0,d=!0,a=0):(a--,s=a>0?i[a-1]:-1,u=!1,d=!1),r=!0)),s++;return r&&(n=cn(n)),n}var dn=()=>new Map,fn=e=>{let t=dn();return e.forEach((e,n)=>{t.set(n,e)}),t},pn=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},mn=(e,t)=>{let n=[];for(let[r,i]of e)n.push(t(i,r));return n},hn=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},gn=()=>new Set,_n=e=>e[e.length-1],vn=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},yn=Array.from,bn=(e,t)=>{for(let n=0;n<e.length;n++)if(!t(e[n],n,e))return!1;return!0},xn=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},Sn=(e,t)=>{let n=Array(e);for(let r=0;r<e;r++)n[r]=t(r,n);return n},Cn=Array.isArray,wn=class{constructor(){this._observers=dn()}on(e,t){return pn(this._observers,e,gn).add(t),t}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return yn((this._observers.get(e)||dn()).values()).forEach(e=>e(...t))}destroy(){this._observers=dn()}},Tn=class{constructor(){this._observers=dn()}on(e,t){pn(this._observers,e,gn).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return yn((this._observers.get(e)||dn()).values()).forEach(e=>e(...t))}destroy(){this._observers=dn()}},En=Math.floor,Dn=Math.abs,On=(e,t)=>e<t?e:t,kn=(e,t)=>e>t?e:t;Number.isNaN;var An=Math.pow,jn=e=>e===0?1/e<0:e<0,Mn=1<<29,Nn=2**53-1,Pn=-(2**53-1),Fn=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&En(e)===e);Number.isNaN,Number.parseInt;var In=String.fromCharCode;String.fromCodePoint,In(65535);var Ln=e=>e.toLowerCase(),Rn=/^\s*/g,zn=e=>e.replace(Rn,``),Bn=/([A-Z])/g,Vn=(e,t)=>zn(e.replace(Bn,e=>`${t}${Ln(e)}`)),Hn=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},Un=typeof TextEncoder<`u`?new TextEncoder:null,Wn=Un?e=>Un.encode(e):Hn,Gn=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});Gn&&Gn.decode(new Uint8Array).length===1&&(Gn=null);var Kn=(e,t)=>Sn(t,()=>e).join(``),qn=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}},Jn=()=>new qn,Yn=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},Xn=e=>{let t=new Uint8Array(Yn(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},Zn=(e,t)=>{let n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(kn(n,t)*2),e.cpos=0)},Qn=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},$n=Qn,Z=(e,t)=>{for(;t>127;)Qn(e,128|127&t),t=En(t/128);Qn(e,127&t)},er=(e,t)=>{let n=jn(t);for(n&&(t=-t),Qn(e,(t>63?128:0)|(n?64:0)|63&t),t=En(t/64);t>0;)Qn(e,(t>127?128:0)|127&t),t=En(t/128)},tr=new Uint8Array(3e4),nr=tr.length/3,rr=Un&&Un.encodeInto?(e,t)=>{if(t.length<nr){let n=Un.encodeInto(t,tr).written||0;Z(e,n);for(let t=0;t<n;t++)Qn(e,tr[t])}else ar(e,Wn(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Z(e,r);for(let t=0;t<r;t++)Qn(e,n.codePointAt(t))},ir=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=On(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(kn(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},ar=(e,t)=>{Z(e,t.byteLength),ir(e,t)},or=(e,t)=>{Zn(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},sr=(e,t)=>or(e,4).setFloat32(0,t,!1),cr=(e,t)=>or(e,8).setFloat64(0,t,!1),lr=(e,t)=>or(e,8).setBigInt64(0,t,!1),ur=new DataView(new ArrayBuffer(4)),dr=e=>(ur.setFloat32(0,e),ur.getFloat32(0)===e),fr=(e,t)=>{switch(typeof t){case`string`:Qn(e,119),rr(e,t);break;case`number`:Fn(t)&&Dn(t)<=2147483647?(Qn(e,125),er(e,t)):dr(t)?(Qn(e,124),sr(e,t)):(Qn(e,123),cr(e,t));break;case`bigint`:Qn(e,122),lr(e,t);break;case`object`:if(t===null)Qn(e,126);else if(Cn(t)){Qn(e,117),Z(e,t.length);for(let n=0;n<t.length;n++)fr(e,t[n])}else if(t instanceof Uint8Array)Qn(e,116),ar(e,t);else{Qn(e,118);let n=Object.keys(t);Z(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];rr(e,i),fr(e,t[i])}}break;case`boolean`:Qn(e,t?120:121);break;default:Qn(e,127)}},pr=class extends qn{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&Z(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}},mr=e=>{e.count>0&&(er(e.encoder,e.count===1?e.s:-e.s),e.count>1&&Z(e.encoder,e.count-2))},hr=class{constructor(){this.encoder=new qn,this.s=0,this.count=0}write(e){this.s===e?this.count++:(mr(this),this.count=1,this.s=e)}toUint8Array(){return mr(this),Xn(this.encoder)}},gr=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);er(e.encoder,t),e.count>1&&Z(e.encoder,e.count-2)}},_r=class{constructor(){this.encoder=new qn,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(gr(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return gr(this),Xn(this.encoder)}},vr=class{constructor(){this.sarr=[],this.s=``,this.lensE=new hr}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(e.length)}toUint8Array(){let e=new qn;return this.sarr.push(this.s),this.s=``,rr(e,this.sarr.join(``)),ir(e,this.lensE.toUint8Array()),Xn(e)}},yr=e=>Error(e),br=()=>{throw yr(`Method unimplemented`)},xr=()=>{throw yr(`Unexpected case`)},Sr=yr(`Unexpected end of array`),Cr=yr(`Integer out of Range`),wr=class{constructor(e){this.arr=e,this.pos=0}},Tr=e=>new wr(e),Er=e=>e.pos!==e.arr.length,Dr=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Or=e=>Dr(e,Q(e)),kr=e=>e.arr[e.pos++],Q=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>Nn)throw Cr}throw Sr},Ar=e=>{let t=e.arr[e.pos++],n=t&63,r=64,i=(t&64)>0?-1:1;if(!(t&128))return i*n;let a=e.arr.length;for(;e.pos<a;){if(t=e.arr[e.pos++],n+=(t&127)*r,r*=128,t<128)return i*n;if(n>Nn)throw Cr}throw Sr},jr=Gn?e=>Gn.decode(Or(e)):e=>{let t=Q(e);if(t===0)return``;{let n=String.fromCodePoint(kr(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(kr(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},Mr=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Nr=[e=>void 0,e=>null,Ar,e=>Mr(e,4).getFloat32(0,!1),e=>Mr(e,8).getFloat64(0,!1),e=>Mr(e,8).getBigInt64(0,!1),e=>!1,e=>!0,jr,e=>{let t=Q(e),n={};for(let r=0;r<t;r++){let t=jr(e);n[t]=Pr(e)}return n},e=>{let t=Q(e),n=[];for(let r=0;r<t;r++)n.push(Pr(e));return n},Or],Pr=e=>Nr[127-kr(e)](e),Fr=class extends wr{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),this.count=Er(this)?Q(this)+1:-1),this.count--,this.s}},Ir=class extends wr{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Ar(this);let e=jn(this.s);this.count=1,e&&(this.s=-this.s,this.count=Q(this)+2)}return this.count--,this.s}},Lr=class extends wr{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=Ar(this),t=e&1;this.diff=En(e/2),this.count=1,t&&(this.count=Q(this)+2)}return this.s+=this.diff,this.count--,this.s}},Rr=class{constructor(e){this.decoder=new Ir(e),this.str=jr(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}};crypto.subtle;var zr=crypto.getRandomValues.bind(crypto),Br=()=>zr(new Uint32Array(1))[0],Vr=`10000000-1000-4000-8000-100000000000`,Hr=()=>Vr.replace(/[018]/g,e=>(e^Br()&15>>e/4).toString(16)),Ur=Date.now,Wr=e=>new Promise(e);Promise.all.bind(Promise);var Gr=e=>e===void 0?null:e,Kr=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},qr=!0;try{typeof localStorage<`u`&&localStorage&&(Kr=localStorage,qr=!1)}catch{}var Jr=Kr,Yr=e=>qr||addEventListener(`storage`,e),Xr=e=>qr||removeEventListener(`storage`,e),Zr=Symbol(`Equality`),Qr=(e,t)=>e===t||!!e?.[Zr]?.(t)||!1,$r=e=>typeof e==`object`,ei=Object.assign,ti=Object.keys,ni=(e,t)=>{for(let n in e)t(e[n],n)},ri=(e,t)=>{let n=[];for(let r in e)n.push(t(e[r],r));return n},ii=e=>ti(e).length,ai=e=>{for(let t in e)return!1;return!0},oi=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},si=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ci=(e,t)=>e===t||ii(e)===ii(t)&&oi(e,(e,n)=>(e!==void 0||si(t,n))&&Qr(t[n],e)),li=Object.freeze,ui=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&ui(e[t])}return li(e)},di=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&di(e,t,n+1)}},fi=e=>e,pi=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Zr]!=null)return e[Zr](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!pi(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(ii(e)!==ii(t))return!1;for(let n in e)if(!si(e,n)||!pi(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!pi(e[n],t[n]))return!1;break;default:return!1}return!0},mi=(e,t)=>t.includes(e),hi=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,gi=typeof window<`u`&&typeof document<`u`&&!hi;typeof navigator<`u`&&/Mac/.test(navigator.platform);var _i,vi=[],yi=()=>{if(_i===void 0){if(hi){_i=dn();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&_i.set(t,``),t=r):t===null?vi.push(r):(_i.set(t,r),t=null)}t!==null&&_i.set(t,``)}else typeof location==`object`?(_i=dn(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);_i.set(`--${Vn(t,`-`)}`,n),_i.set(`-${Vn(t,`-`)}`,n)}})):_i=dn()}return _i},bi=e=>yi().has(e),xi=e=>Gr(hi?{}[e.toUpperCase().replaceAll(`-`,`_`)]:Jr.getItem(e)),Si=e=>bi(`--`+e)||xi(e)!==null,Ci=Si(`production`),wi=hi&&mi({}.FORCE_COLOR,[`true`,`1`,`2`])||!bi(`--no-colors`)&&!Si(`no-color`)&&(!hi||process.stdout.isTTY)&&(!hi||bi(`--color`)||xi(`COLORTERM`)!==null||(xi(`TERM`)||``).includes(`color`)),Ti=e=>new Uint8Array(e),Ei=(e,t,n)=>new Uint8Array(e,t,n),Di=e=>new Uint8Array(e),Oi=e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=In(e[n]);return btoa(t)},ki=e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),Ai=e=>{let t=atob(e),n=Ti(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},ji=e=>{let t=Buffer.from(e,`base64`);return Ei(t.buffer,t.byteOffset,t.byteLength)},Mi=gi?Oi:ki,Ni=gi?Ai:ji,Pi=e=>{let t=Ti(e.byteLength);return t.set(e),t},Fi=class{constructor(e,t){this.left=e,this.right=t}},Ii=(e,t)=>new Fi(e,t),Li=(e,t)=>e.forEach(e=>t(e.left,e.right)),Ri=e=>e.next()>=.5,zi=(e,t,n)=>En(e.next()*(n+1-t)+t),Bi=(e,t,n)=>En(e.next()*(n+1-t)+t),Vi=(e,t,n)=>Bi(e,t,n),Hi=e=>In(Vi(e,97,122)),Ui=(e,t=0,n=20)=>{let r=Vi(e,t,n),i=``;for(let t=0;t<r;t++)i+=Hi(e);return i},Wi=(e,t)=>t[Vi(e,0,t.length-1)],Gi=Symbol(`0schema`),Ki=class{constructor(){this._rerrs=[]}extend(e,t,n,r=null){this._rerrs.push({path:e,expected:t,has:n,message:r})}toString(){let e=[];for(let t=this._rerrs.length-1;t>0;t--){let n=this._rerrs[t];e.push(Kn(` `,(this._rerrs.length-t)*2)+`${n.path==null?``:`[${n.path}] `}${n.has} doesn't match ${n.expected}. ${n.message}`)}return e.join(`
|
|
4
|
-
`)}},qi=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Zr]?Qr(e,t):Cn(e)?bn(e,e=>xn(t,t=>qi(e,t))):$r(e)?oi(e,(e,n)=>qi(e,t[n])):!1,Ji=class{static _dilutes=!1;extends(e){let[t,n]=[this.shape,e.shape];return this.constructor._dilutes&&([n,t]=[t,n]),qi(t,n)}equals(e){return this.constructor===e.constructor&&pi(this.shape,e.shape)}[Gi](){return!0}[Zr](e){return this.equals(e)}validate(e){return this.check(e)}check(e,t){br()}get nullable(){return Da(this,Ha)}get optional(){return new aa(this)}cast(e){return Ka(e,this),e}expect(e){return Ka(e,this),e}},Yi=class extends Ji{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t=void 0){let n=e?.constructor===this.shape&&(this._c==null||this._c(e));return!n&&t?.extend(null,this.shape.name,e?.constructor.name,e?.constructor===this.shape?`Check failed`:`Constructor match failed`),n}},Xi=(e,t=null)=>new Yi(e,t);Xi(Yi);var Zi=class extends Ji{constructor(e){super(),this.shape=e}check(e,t){let n=this.shape(e);return!n&&t?.extend(null,`custom prop`,e?.constructor.name,`failed to check custom prop`),n}},Qi=e=>new Zi(e);Xi(Zi);var $i=class extends Ji{constructor(e){super(),this.shape=e}check(e,t){let n=this.shape.some(t=>t===e);return!n&&t?.extend(null,this.shape.join(` | `),e.toString()),n}},ea=(...e)=>new $i(e),ta=Xi($i),na=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,e=>`\\`+e)),ra=e=>{if(La.check(e))return[na(e)];if(ta.check(e))return e.shape.map(e=>e+``);if(Ia.check(e))return[`[+-]?\\d+.?\\d*`];if(Ra.check(e))return[`.*`];if(Oa.check(e))return e.shape.map(ra).flat(1);xr()};Xi(class extends Ji{constructor(e){super(),this.shape=e,this._r=RegExp(`^`+e.map(ra).map(e=>`(${e.join(`|`)})`).join(``)+`$`)}check(e,t){let n=this._r.exec(e)!=null;return!n&&t?.extend(null,this._r.toString(),e.toString(),`String doesn't match string template.`),n}});var ia=Symbol(`optional`),aa=class extends Ji{constructor(e){super(),this.shape=e}check(e,t){let n=e===void 0||this.shape.check(e);return!n&&t?.extend(null,`undefined (optional)`,`()`),n}get[ia](){return!0}},oa=Xi(aa),sa=class extends Ji{check(e,t){return t?.extend(null,`never`,typeof e),!1}};new sa,Xi(sa);var ca=class e extends Ji{constructor(e,t=!1){super(),this.shape=e,this._isPartial=t}static _dilutes=!0;get partial(){return new e(this.shape,!0)}check(e,t){return e==null?(t?.extend(null,`object`,`null`),!1):oi(this.shape,(n,r)=>{let i=this._isPartial&&!si(e,r)||n.check(e[r],t);return!i&&t?.extend(r.toString(),n.toString(),typeof e[r],`Object property does not match`),i})}},la=e=>new ca(e),ua=Xi(ca),da=Qi(e=>e!=null&&(e.constructor===Object||e.constructor==null)),fa=class extends Ji{constructor(e,t){super(),this.shape={keys:e,values:t}}check(e,t){return e!=null&&oi(e,(n,r)=>{let i=this.shape.keys.check(r,t);return!i&&t?.extend(r+``,`Record`,typeof e,i?`Key doesn't match schema`:`Value doesn't match value`),i&&this.shape.values.check(n,t)})}},pa=(e,t)=>new fa(e,t),ma=Xi(fa),ha=class extends Ji{constructor(e){super(),this.shape=e}check(e,t){return e!=null&&oi(this.shape,(n,r)=>{let i=n.check(e[r],t);return!i&&t?.extend(r.toString(),`Tuple`,typeof n),i})}},ga=(...e)=>new ha(e);Xi(ha);var _a=class extends Ji{constructor(e){super(),this.shape=e.length===1?e[0]:new Ea(e)}check(e,t){let n=Cn(e)&&bn(e,e=>this.shape.check(e));return!n&&t?.extend(null,`Array`,``),n}},va=(...e)=>new _a(e),ya=Xi(_a),ba=Qi(e=>Cn(e)),xa=class extends Ji{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t){let n=e instanceof this.shape&&(this._c==null||this._c(e));return!n&&t?.extend(null,this.shape.name,e?.constructor.name),n}},Sa=(e,t=null)=>new xa(e,t);Xi(xa);var Ca=Sa(Ji),wa=Xi(class extends Ji{constructor(e){super(),this.len=e.length-1,this.args=ga(...e.slice(-1)),this.res=e[this.len]}check(e,t){let n=e.constructor===Function&&e.length<=this.len;return!n&&t?.extend(null,`function`,typeof e),n}}),Ta=Qi(e=>typeof e==`function`);Xi(class extends Ji{constructor(e){super(),this.shape=e}check(e,t){let n=bn(this.shape,n=>n.check(e,t));return!n&&t?.extend(null,`Intersectinon`,typeof e),n}},e=>e.shape.length>0);var Ea=class extends Ji{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,t){let n=xn(this.shape,n=>n.check(e,t));return t?.extend(null,`Union`,typeof e),n}},Da=(...e)=>e.findIndex(e=>Oa.check(e))>=0?Da(...e.map(e=>Ga(e)).map(e=>Oa.check(e)?e.shape:[e]).flat(1)):e.length===1?e[0]:new Ea(e),Oa=Xi(Ea),ka=()=>!0,Aa=Qi(ka),ja=Xi(Zi,e=>e.shape===ka),Ma=Qi(e=>typeof e==`bigint`),Na=Qi(e=>e===Ma),Pa=Qi(e=>typeof e==`symbol`);Qi(e=>e===Pa);var Fa=Qi(e=>typeof e==`number`),Ia=Qi(e=>e===Fa),La=Qi(e=>typeof e==`string`),Ra=Qi(e=>e===La),za=Qi(e=>typeof e==`boolean`),Ba=Qi(e=>e===za),Va=ea(void 0);Xi($i,e=>e.shape.length===1&&e.shape[0]===void 0),ea(void 0);var Ha=ea(null),Ua=Xi($i,e=>e.shape.length===1&&e.shape[0]===null);Xi(Uint8Array),Xi(Yi,e=>e.shape===Uint8Array);var Wa=Da(Fa,La,Ha,Va,Ma,za,Pa);(()=>{let e=va(Aa),t=pa(La,Aa),n=Da(Fa,La,Ha,za,e,t);return e.shape=n,t.shape.values=n,n})();var Ga=e=>{if(Ca.check(e))return e;if(da.check(e)){let t={};for(let n in e)t[n]=Ga(e[n]);return la(t)}if(ba.check(e))return Da(...e.map(Ga));if(Wa.check(e))return ea(e);if(Ta.check(e))return Xi(e);xr()},Ka=Ci?()=>{}:(e,t)=>{let n=new Ki;if(!t.check(e,n))throw yr(`Expected value to be of type ${t.constructor.name}.\n${n.toString()}`)},qa=class{constructor(e){this.patterns=[],this.$state=e}if(e,t){return this.patterns.push({if:Ga(e),h:t}),this}else(e){return this.if(Aa,e)}done(){return(e,t)=>{for(let n=0;n<this.patterns.length;n++){let r=this.patterns[n];if(r.if.check(e))return r.h(e,t)}throw yr(`Unhandled pattern`)}}},Ja=(e=>new qa(e))(Aa).if(Ia,(e,t)=>zi(t,Pn,Nn)).if(Ra,(e,t)=>Ui(t)).if(Ba,(e,t)=>Ri(t)).if(Na,(e,t)=>BigInt(zi(t,Pn,Nn))).if(Oa,(e,t)=>Ya(t,Wi(t,e.shape))).if(ua,(e,t)=>{let n={};for(let r in e.shape){let i=e.shape[r];if(oa.check(i)){if(Ri(t))continue;i=i.shape}n[r]=Ja(i,t)}return n}).if(ya,(e,t)=>{let n=[],r=Bi(t,0,42);for(let i=0;i<r;i++)n.push(Ya(t,e.shape));return n}).if(ta,(e,t)=>Wi(t,e.shape)).if(Ua,(e,t)=>null).if(wa,(e,t)=>{let n=Ya(t,e.res);return()=>n}).if(ja,(e,t)=>Ya(t,Wi(t,[Fa,La,Ha,Va,Ma,za,va(Fa),pa(Da(`a`,`b`,`c`),Fa)]))).if(ma,(e,t)=>{let n={},r=zi(t,0,3);for(let i=0;i<r;i++){let r=Ya(t,e.shape.keys);n[r]=Ya(t,e.shape.values)}return n}).done(),Ya=(e,t)=>Ja(Ga(t),e),Xa=typeof document<`u`?document:{},Za=e=>Xa.createElement(e),Qa=()=>Xa.createDocumentFragment();Qi(e=>e.nodeType===uo);var $a=e=>Xa.createTextNode(e);typeof DOMParser<`u`&&new DOMParser;var eo=(e,t)=>(Li(t,(t,n)=>{n===!1?e.removeAttribute(t):n===!0?e.setAttribute(t,``):e.setAttribute(t,n)}),e),to=e=>{let t=Qa();for(let n=0;n<e.length;n++)oo(t,e[n]);return t},no=(e,t)=>(oo(e,to(t)),e),ro=(e,t=[],n=[])=>no(eo(Za(e),t),n);Qi(e=>e.nodeType===so);var io=$a;Qi(e=>e.nodeType===co);var ao=e=>mn(e,(e,t)=>`${t}:${e};`).join(``),oo=(e,t)=>e.appendChild(t),so=Xa.ELEMENT_NODE,co=Xa.TEXT_NODE;Xa.CDATA_SECTION_NODE,Xa.COMMENT_NODE;var lo=Xa.DOCUMENT_NODE;Xa.DOCUMENT_TYPE_NODE;var uo=Xa.DOCUMENT_FRAGMENT_NODE;Qi(e=>e.nodeType===lo);var fo=Symbol,po=fo(),mo=fo(),ho=fo(),go=fo(),_o=fo(),vo=fo(),yo=fo(),bo=fo(),xo=fo(),So=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=0;for(;r<e.length;r++){let n=e[r];if(n===void 0)break;if(n.constructor===String||n.constructor===Number)t.push(n);else if(n.constructor===Object)break}for(r>0&&n.push(t.join(``));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n};Ur();var Co={[po]:Ii(`font-weight`,`bold`),[mo]:Ii(`font-weight`,`normal`),[ho]:Ii(`color`,`blue`),[_o]:Ii(`color`,`green`),[go]:Ii(`color`,`grey`),[vo]:Ii(`color`,`red`),[yo]:Ii(`color`,`purple`),[bo]:Ii(`color`,`orange`),[xo]:Ii(`color`,`black`)},wo=wi?e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=dn(),i=[],a=0;for(;a<e.length;a++){let i=e[a],o=Co[i];if(o!==void 0)r.set(o.left,o.right);else{if(i===void 0)break;if(i.constructor===String||i.constructor===Number){let e=ao(r);a>0||e.length>0?(t.push(`%c`+i),n.push(e)):t.push(i)}else break}}for(a>0&&(i=n,i.unshift(t.join(``)));a<e.length;a++){let t=e[a];t instanceof Symbol||i.push(t)}return i}:So,To=(...e)=>{console.log(...wo(e)),Do.forEach(t=>t.print(e))},Eo=(...e)=>{console.warn(...wo(e)),e.unshift(bo),Do.forEach(t=>t.print(e))},Do=gn(),Oo=e=>({[Symbol.iterator](){return this},next:e}),ko=(e,t)=>Oo(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),Ao=(e,t)=>Oo(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}}),jo=class{constructor(e,t){this.clock=e,this.len=t}},Mo=class{constructor(){this.clients=new Map}},No=(e,t,n)=>t.clients.forEach((t,r)=>{let i=e.doc.store.clients.get(r);if(i!=null){let r=i[i.length-1],a=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<a;o=t[++r])Ys(e,i,o.clock,o.len,n)}}),Po=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=En((n+r)/2),a=e[i],o=a.clock;if(o<=t){if(t<o+a.len)return i;n=i+1}else r=i-1}return null},Fo=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&Po(n,t.clock)!==null},Io=e=>{e.clients.forEach(e=>{e.sort((e,t)=>e.clock-t.clock);let t,n;for(t=1,n=1;t<e.length;t++){let r=e[n-1],i=e[t];r.clock+r.len>=i.clock?e[n-1]=new jo(r.clock,kn(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},Lo=e=>{let t=new Mo;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){let a=r.slice();for(let t=n+1;t<e.length;t++)vn(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return Io(t),t},Ro=(e,t,n,r)=>{pn(e.clients,t,()=>[]).push(new jo(n,r))},zo=()=>new Mo,Bo=e=>{let t=zo();return e.clients.forEach((e,n)=>{let r=[];for(let t=0;t<e.length;t++){let n=e[t];if(n.deleted){let i=n.id.clock,a=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[++t+1])a+=n.length;r.push(new jo(i,a))}}r.length>0&&t.clients.set(n,r)}),t},Vo=(e,t)=>{Z(e.restEncoder,t.clients.size),yn(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),Z(e.restEncoder,t);let r=n.length;Z(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},Ho=e=>{let t=new Mo,n=Q(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=Q(e.restDecoder),r=Q(e.restDecoder);if(r>0){let i=pn(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new jo(e.readDsClock(),e.readDsLen()))}}return t},Uo=(e,t,n)=>{let r=new Mo,i=Q(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=Q(e.restDecoder),a=Q(e.restDecoder),o=n.clients.get(i)||[],s=Vs(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&Ro(r,i,s,a-s);let e=Us(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,du(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<a);)c.deleted||(a<c.id.clock+c.length&&o.splice(e,0,du(t,c,a-c.id.clock)),c.delete(t))}else Ro(r,i,n,a-n)}}if(r.clients.size>0){let e=new $o;return Z(e.restEncoder,0),Vo(e,r),e.toUint8Array()}return null},Wo=Br,Go=class e extends wn{constructor({guid:e=Hr(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:a=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=Wo(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new zs,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=a,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Wr(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>Wr(e=>{let t=n=>{(n===void 0||n===!0)&&(this.off(`sync`,t),e())};this.on(`sync`,t)});this.on(`sync`,e=>{e===!1&&this.isSynced&&(this.whenSynced=s()),this.isSynced=e===void 0||e===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=s()}load(){let e=this._item;e!==null&&!this.shouldLoad&&rc(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(yn(this.subdocs).map(e=>e.guid))}transact(e,t=null){return rc(this,e,t)}get(e,t=Nc){let n=pn(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==Nc&&r!==t){if(r===Nc){let r=new t;r._map=n._map,n._map.forEach(e=>{for(;e!==null;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;e!==null;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}throw Error(`Type with the name ${e} has already been defined with a different constructor`)}return n}getArray(e=``){return this.get(e,$c)}getText(e=``){return this.get(e,bl)}getMap(e=``){return this.get(e,nl)}getXmlElement(e=``){return this.get(e,Tl)}getXmlFragment(e=``){return this.get(e,Cl)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,yn(this.subdocs).forEach(e=>e.destroy());let t=this._item;if(t!==null){this._item=null;let n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,rc(t.parent.doc,e=>{let r=n.doc;t.deleted||e.subdocsAdded.add(r),e.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}},Ko=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Q(this.restDecoder)}readDsLen(){return Q(this.restDecoder)}},qo=class extends Ko{readLeftID(){return $(Q(this.restDecoder),Q(this.restDecoder))}readRightID(){return $(Q(this.restDecoder),Q(this.restDecoder))}readClient(){return Q(this.restDecoder)}readInfo(){return kr(this.restDecoder)}readString(){return jr(this.restDecoder)}readParentInfo(){return Q(this.restDecoder)===1}readTypeRef(){return Q(this.restDecoder)}readLen(){return Q(this.restDecoder)}readAny(){return Pr(this.restDecoder)}readBuf(){return Pi(Or(this.restDecoder))}readJSON(){return JSON.parse(jr(this.restDecoder))}readKey(){return jr(this.restDecoder)}},Jo=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Q(this.restDecoder),this.dsCurrVal}readDsLen(){let e=Q(this.restDecoder)+1;return this.dsCurrVal+=e,e}},Yo=class extends Jo{constructor(e){super(e),this.keys=[],Q(e),this.keyClockDecoder=new Lr(Or(e)),this.clientDecoder=new Ir(Or(e)),this.leftClockDecoder=new Lr(Or(e)),this.rightClockDecoder=new Lr(Or(e)),this.infoDecoder=new Fr(Or(e),kr),this.stringDecoder=new Rr(Or(e)),this.parentInfoDecoder=new Fr(Or(e),kr),this.typeRefDecoder=new Ir(Or(e)),this.lenDecoder=new Ir(Or(e))}readLeftID(){return new Ss(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Ss(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 Pr(this.restDecoder)}readBuf(){return Or(this.restDecoder)}readJSON(){return Pr(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{let e=this.stringDecoder.read();return this.keys.push(e),e}}},Xo=class{constructor(){this.restEncoder=Jn()}toUint8Array(){return Xn(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){Z(this.restEncoder,e)}writeDsLen(e){Z(this.restEncoder,e)}},Zo=class extends Xo{writeLeftID(e){Z(this.restEncoder,e.client),Z(this.restEncoder,e.clock)}writeRightID(e){Z(this.restEncoder,e.client),Z(this.restEncoder,e.clock)}writeClient(e){Z(this.restEncoder,e)}writeInfo(e){$n(this.restEncoder,e)}writeString(e){rr(this.restEncoder,e)}writeParentInfo(e){Z(this.restEncoder,+!!e)}writeTypeRef(e){Z(this.restEncoder,e)}writeLen(e){Z(this.restEncoder,e)}writeAny(e){fr(this.restEncoder,e)}writeBuf(e){ar(this.restEncoder,e)}writeJSON(e){rr(this.restEncoder,JSON.stringify(e))}writeKey(e){rr(this.restEncoder,e)}},Qo=class{constructor(){this.restEncoder=Jn(),this.dsCurrVal=0}toUint8Array(){return Xn(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,Z(this.restEncoder,t)}writeDsLen(e){e===0&&xr(),Z(this.restEncoder,e-1),this.dsCurrVal+=e}},$o=class extends Qo{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new _r,this.clientEncoder=new hr,this.leftClockEncoder=new _r,this.rightClockEncoder=new _r,this.infoEncoder=new pr($n),this.stringEncoder=new vr,this.parentInfoEncoder=new pr($n),this.typeRefEncoder=new hr,this.lenEncoder=new hr}toUint8Array(){let e=Jn();return Z(e,0),ar(e,this.keyClockEncoder.toUint8Array()),ar(e,this.clientEncoder.toUint8Array()),ar(e,this.leftClockEncoder.toUint8Array()),ar(e,this.rightClockEncoder.toUint8Array()),ar(e,Xn(this.infoEncoder)),ar(e,this.stringEncoder.toUint8Array()),ar(e,Xn(this.parentInfoEncoder)),ar(e,this.typeRefEncoder.toUint8Array()),ar(e,this.lenEncoder.toUint8Array()),ir(e,Xn(this.restEncoder)),Xn(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)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){fr(this.restEncoder,e)}writeBuf(e){ar(this.restEncoder,e)}writeJSON(e){fr(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}},es=(e,t,n,r)=>{r=kn(r,t[0].id.clock);let i=Us(t,r);Z(e.restEncoder,t.length-i),e.writeClient(n),Z(e.restEncoder,r);let a=t[i];a.write(e,r-a.id.clock);for(let n=i+1;n<t.length;n++)t[n].write(e,0)},ts=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{Vs(t,n)>e&&r.set(n,e)}),Bs(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),Z(e.restEncoder,r.size),yn(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{es(e,t.clients.get(n),n,r)})},ns=(e,t)=>{let n=dn(),r=Q(e.restDecoder);for(let i=0;i<r;i++){let r=Q(e.restDecoder),i=Array(r),a=e.readClient(),o=Q(e.restDecoder);n.set(a,{i:0,refs:i});for(let n=0;n<r;n++){let r=e.readInfo();switch(31&r){case 0:{let t=e.readLen();i[n]=new Pl($(a,o),t),o+=t;break}case 10:{let t=Q(e.restDecoder);i[n]=new vu($(a,o),t),o+=t;break}default:{let s=!(r&192),c=new mu($(a,o),null,(r&128)==128?e.readLeftID():null,null,(r&64)==64?e.readRightID():null,s?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,s&&(r&32)==32?e.readString():null,hu(e,r));i[n]=c,o+=c.length}}}}return n},rs=(e,t,n)=>{let r=[],i=yn(n.keys()).sort((e,t)=>e-t);if(i.length===0)return null;let a=()=>{if(i.length===0)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;)if(i.pop(),i.length>0)e=n.get(i[i.length-1]);else return null;return e},o=a();if(o===null)return null;let s=new zs,c=new Map,l=(e,t)=>{let n=c.get(e);(n==null||n>t)&&c.set(e,t)},u=o.refs[o.i++],d=new Map,f=()=>{for(let e of r){let t=e.id.client,r=n.get(t);r?(r.i--,s.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):s.clients.set(t,[e]),i=i.filter(e=>e!==t)}r.length=0};for(;;){if(u.constructor!==vu){let i=pn(d,u.id.client,()=>Vs(t,u.id.client))-u.id.clock;if(i<0)r.push(u),l(u.id.client,u.id.clock-1),f();else{let a=u.getMissing(e,t);if(a!==null){r.push(u);let e=n.get(a)||{refs:[],i:0};if(e.refs.length===e.i)l(a,Vs(t,a)),f();else{u=e.refs[e.i++];continue}}else(i===0||i<u.length)&&(u.integrate(e,i),d.set(u.id.client,u.id.clock+u.length))}}if(r.length>0)u=r.pop();else if(o!==null&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=a(),o===null)break;u=o.refs[o.i++]}}if(s.clients.size>0){let e=new $o;return ts(e,s,new Map),Z(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},is=(e,t)=>ts(e,t.doc.store,t.beforeState),as=(e,t,n,r=new Yo(e))=>rc(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=rs(e,i,ns(r,n)),o=i.pendingStructs;if(o){for(let[e,n]of o.missing)if(n<Vs(i,e)){t=!0;break}if(a){for(let[e,t]of a.missing){let n=o.missing.get(e);(n==null||n>t)&&o.missing.set(e,t)}o.update=pc([o.update,a.update])}}else i.pendingStructs=a;let s=Uo(r,e,i);if(i.pendingDs){let t=new Yo(Tr(i.pendingDs));Q(t.restDecoder);let n=Uo(t,e,i);i.pendingDs=s&&n?pc([s,n]):s||n}else i.pendingDs=s;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,os(e.doc,t)}},n,!1),os=(e,t,n,r=Yo)=>{let i=Tr(t);as(i,e,n,new r(i))},ss=(e,t,n)=>os(e,t,n,qo),cs=(e,t,n=new Map)=>{ts(e,t.store,n),Vo(e,Bo(t.store))},ls=(e,t=new Uint8Array([0]),n=new $o)=>{cs(n,e,fs(t));let r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(mc(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===Zo)return dc(r.map((e,t)=>t===0?e:yc(e)));if(n.constructor===$o)return pc(r)}return r[0]},us=(e,t)=>ls(e,t,new Zo),ds=e=>{let t=new Map,n=Q(e.restDecoder);for(let r=0;r<n;r++){let n=Q(e.restDecoder),r=Q(e.restDecoder);t.set(n,r)}return t},fs=e=>ds(new Ko(Tr(e))),ps=(e,t)=>(Z(e.restEncoder,t.size),yn(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{Z(e.restEncoder,t),Z(e.restEncoder,n)}),e),ms=(e,t)=>ps(e,Bs(t.store)),hs=(e,t=new Qo)=>(e instanceof Map?ps(t,e):ms(t,e),t.toUint8Array()),gs=e=>hs(e,new Xo),_s=class{constructor(){this.l=[]}},vs=()=>new _s,ys=(e,t)=>e.l.push(t),bs=(e,t)=>{let n=e.l,r=n.length;e.l=n.filter(e=>t!==e),r===e.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},xs=(e,t,n)=>di(e.l,[t,n]),Ss=class{constructor(e,t){this.client=e,this.clock=t}},Cs=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,$=(e,t)=>new Ss(e,t),ws=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw xr()},Ts=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1},Es=class{constructor(e,t,n,r=0){this.type=e,this.tname=t,this.item=n,this.assoc=r}},Ds=e=>{let t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},Os=e=>new Es(e.type==null?null:$(e.type.client,e.type.clock),e.tname??null,e.item==null?null:$(e.item.client,e.item.clock),e.assoc==null?0:e.assoc),ks=class{constructor(e,t,n=0){this.type=e,this.index=t,this.assoc=n}},As=(e,t,n=0)=>new ks(e,t,n),js=(e,t,n)=>{let r=null,i=null;return e._item===null?i=ws(e):r=$(e._item.id.client,e._item.id.clock),new Es(r,i,t,n)},Ms=(e,t,n=0)=>{let r=e._start;if(n<0){if(t===0)return js(e,null,n);t--}for(;r!==null;){if(!r.deleted&&r.countable){if(r.length>t)return js(e,$(r.id.client,r.id.clock+t),n);t-=r.length}if(r.right===null&&n<0)return js(e,r.lastId,n);r=r.right}return js(e,null,n)},Ns=(e,t)=>{let n=Ws(e,t);return{item:n,diff:t.clock-n.id.clock}},Ps=(e,t,n=!0)=>{let r=t.store,i=e.item,a=e.type,o=e.tname,s=e.assoc,c=null,l=0;if(i!==null){if(Vs(r,i.client)<=i.clock)return null;let e=n?lu(r,i):Ns(r,i),t=e.item;if(!(t instanceof mu))return null;if(c=t.parent,c._item===null||!c._item.deleted){l=t.deleted||!t.countable?0:e.diff+(s>=0?0:1);let n=t.left;for(;n!==null;)!n.deleted&&n.countable&&(l+=n.length),n=n.left}}else{if(o!==null)c=t.get(o);else if(a!==null){if(Vs(r,a.client)<=a.clock)return null;let{item:e}=n?lu(r,a):{item:Ws(r,a)};if(e instanceof mu&&e.content instanceof su)c=e.content.type;else return null}else throw xr();l=s>=0?c._length:0}return As(c,l,e.assoc)},Fs=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&Cs(e.item,t.item)&&Cs(e.type,t.type)&&e.assoc===t.assoc,Is=class{constructor(e,t){this.ds=e,this.sv=t}};((e,t)=>new Is(e,t))(zo(),new Map);var Ls=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Fo(t.ds,e.id),Rs=(e,t)=>{let n=pn(e.meta,Rs,gn),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<Vs(r,n)&&Ks(e,$(n,t))}),No(e,t.ds,e=>{}),n.add(t))},zs=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}},Bs=e=>{let t=new Map;return e.clients.forEach((e,n)=>{let r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},Vs=(e,t)=>{let n=e.clients.get(t);if(n===void 0)return 0;let r=n[n.length-1];return r.id.clock+r.length},Hs=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{let e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw xr()}n.push(t)},Us=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=En(t/(a+i.length-1)*r);for(;n<=r;){if(i=e[o],a=i.id.clock,a<=t){if(t<a+i.length)return o;n=o+1}else r=o-1;o=En((n+r)/2)}throw xr()},Ws=(e,t)=>{let n=e.clients.get(t.client);return n[Us(n,t.clock)]},Gs=(e,t,n)=>{let r=Us(t,n),i=t[r];return i.id.clock<n&&i instanceof mu?(t.splice(r+1,0,du(e,i,n-i.id.clock)),r+1):r},Ks=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[Gs(e,n,t.clock)]},qs=(e,t,n)=>{let r=t.clients.get(n.client),i=Us(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==Pl&&r.splice(i+1,0,du(e,a,n.clock-a.id.clock+1)),a},Js=(e,t,n)=>{let r=e.clients.get(t.id.client);r[Us(r,t.id.clock)]=n},Ys=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=Gs(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&Gs(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)},Xs=class{constructor(e,t,n){this.doc=e,this.deleteSet=new Mo,this.beforeState=Bs(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}},Zs=(e,t)=>t.deleteSet.clients.size===0&&!hn(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(Io(t.deleteSet),is(e,t),Vo(e,t.deleteSet),!0),Qs=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&pn(e.changed,t,gn).add(n)},$s=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0&&r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n);n=r,r=e[--i-1])n instanceof mu&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);let a=t-i;return a&&e.splice(t+1-a,a),a},ec=(e,t,n)=>{for(let[r,i]of e.clients.entries()){let e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){let a=i[r],o=a.clock+a.len;for(let r=Us(e,a.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){let i=e[r];if(a.clock+a.len<=i.id.clock)break;i instanceof mu&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},tc=(e,t)=>{e.clients.forEach((e,n)=>{let r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){let n=e[t],i=On(r.length-1,1+Us(r,n.clock+n.len-1));for(let e=i,t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+$s(r,e)}})},nc=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{Io(a),n.afterState=Bs(n.doc.store),r.emit(`beforeObserverCalls`,[n,r]);let e=[];n.changed.forEach((t,r)=>e.push(()=>{(r._item===null||!r._item.deleted)&&r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(r._item===null||!r._item.deleted)&&(t=t.filter(e=>e.target._item===null||!e.target._item.deleted),t.forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{xs(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&_l(n)})}),di(e,[])}finally{r.gc&&ec(a,i,r.gcFilter),tc(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=kn(Us(e,r),1);for(let t=e.length-1;t>=n;)t-=1+$s(e,t)}});for(let e=o.length-1;e>=0;e--){let{client:t,clock:n}=o[e].id,r=i.clients.get(t),a=Us(r,n);a+1<r.length&&$s(r,a+1)>1||a>0&&$s(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(To(bo,po,`[yjs] `,mo,vo,`Changed the client-id because another client seems to be using it.`),r.clientID=Wo()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new Zo;Zs(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new $o;Zs(e,n)&&r.emit(`updateV2`,[e.toUint8Array(),n.origin,r,n])}let{subdocsAdded:s,subdocsLoaded:c,subdocsRemoved:l}=n;(s.size>0||l.size>0||c.size>0)&&(s.forEach(e=>{e.clientID=r.clientID,e.collectionid??=r.collectionid,r.subdocs.add(e)}),l.forEach(e=>r.subdocs.delete(e)),r.emit(`subdocs`,[{loaded:c,added:s,removed:l},r,n]),l.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit(`afterAllTransactions`,[r,e])):nc(e,t+1)}}},rc=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new Xs(e,n,r),i.push(e._transaction),i.length===1&&e.emit(`beforeAllTransactions`,[e]),e.emit(`beforeTransaction`,[e._transaction,e]));try{o=t(e._transaction)}finally{if(a){let t=e._transaction===i[0];e._transaction=null,t&&nc(i,0)}}return o},ic=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}},ac=(e,t,n)=>{No(e,n.deletions,n=>{n instanceof mu&&t.scope.some(t=>t===e.doc||Ts(t,n))&&uu(n,!1)})},oc=(e,t,n)=>{let r=null,i=e.doc,a=e.scope;rc(i,n=>{for(;t.length>0&&e.currStackItem===null;){let r=i.store,o=t.pop(),s=new Set,c=[],l=!1;No(n,o.insertions,e=>{if(e instanceof mu){if(e.redone!==null){let{item:t,diff:i}=lu(r,e.id);i>0&&(t=Ks(n,$(t.id.client,t.id.clock+i))),e=t}!e.deleted&&a.some(t=>t===n.doc||Ts(t,e))&&c.push(e)}}),No(n,o.deletions,e=>{e instanceof mu&&a.some(t=>t===n.doc||Ts(t,e))&&!Fo(o.insertions,e.id)&&s.add(e)}),s.forEach(t=>{l=pu(n,t,s,o.insertions,e.ignoreRemoteMapChanges,e)!==null||l});for(let t=c.length-1;t>=0;t--){let r=c[t];e.deleteFilter(r)&&(r.delete(n),l=!0)}e.currStackItem=l?o:null}n.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),r=n},e);let o=e.currStackItem;if(o!=null){let t=r.changedParentTypes;e.emit(`stack-item-popped`,[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o},sc=class extends wn{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:o=Cn(e)?e[0].doc:e instanceof Go?e:e.doc}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=a,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!this.captureTransaction(e)||!this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)||!this.trackedOrigins.has(e.origin)&&(!e.origin||!this.trackedOrigins.has(e.origin.constructor)))return;let t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);let i=new Mo;e.afterState.forEach((t,n)=>{let r=e.beforeState.get(n)||0,a=t-r;a>0&&Ro(i,n,r,a)});let a=Ur(),o=!1;if(this.lastChange>0&&a-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){let t=r[r.length-1];t.deletions=Lo([t.deletions,e.deleteSet]),t.insertions=Lo([t.insertions,i])}else r.push(new ic(e.deleteSet,i)),o=!0;!t&&!n&&(this.lastChange=a),No(e,e.deleteSet,t=>{t instanceof mu&&this.scope.some(n=>n===e.doc||Ts(n,t))&&uu(t,!0)});let s=[{stackItem:r[r.length-1],origin:e.origin,type:t?`redo`:`undo`,changedParentTypes:e.changedParentTypes},this];o?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){let t=new Set(this.scope);e=Cn(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof Nc?e.doc!==this.doc:e!==this.doc)&&Eo(`[yjs#509] Not same Y.Doc`),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(n=>{e&&(this.undoStack.forEach(e=>ac(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>ac(n,this,e)),this.redoStack=[]),this.emit(`stack-cleared`,[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=oc(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=oc(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*cc(e){let t=Q(e.restDecoder);for(let n=0;n<t;n++){let t=Q(e.restDecoder),n=e.readClient(),r=Q(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=Q(e.restDecoder);yield new vu($(n,r),t),r+=t}else if(31&t){let i=!(t&192),a=new mu($(n,r),null,(t&128)==128?e.readLeftID():null,null,(t&64)==64?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&(t&32)==32?e.readString():null,hu(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new Pl($(n,r),t),r+=t}}}}var lc=class{constructor(e,t){this.gen=cc(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===vu);return this.curr}},uc=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}},dc=e=>pc(e,qo,Zo),fc=(e,t)=>{if(e.constructor===Pl){let{client:n,clock:r}=e.id;return new Pl($(n,r+t),e.length-t)}if(e.constructor===vu){let{client:n,clock:r}=e.id;return new vu($(n,r+t),e.length-t)}{let n=e,{client:r,clock:i}=n.id;return new mu($(r,i+t),null,$(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},pc=(e,t=Yo,n=$o)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(Tr(e))),i=r.map(e=>new lc(e,!0)),a=null,o=new n,s=new uc(o);for(;i=i.filter(e=>e.curr!==null),i.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){let n=e.curr.id.clock-t.curr.id.clock;return n===0?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===vu?1:-1:n}return t.curr.id.client-e.curr.id.client}),i.length!==0;){let e=i[0],t=e.curr.id.client;if(a!==null){let n=e.curr,r=!1;for(;n!==null&&n.id.clock+n.length<=a.struct.id.clock+a.struct.length&&n.id.client>=a.struct.id.client;)n=e.next(),r=!0;if(n===null||n.id.client!==t||r&&n.id.clock>a.struct.id.clock+a.struct.length)continue;if(t!==a.struct.id.client)gc(s,a.struct,a.offset),a={struct:n,offset:0},e.next();else if(a.struct.id.clock+a.struct.length<n.id.clock){if(a.struct.constructor===vu)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{gc(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new vu($(t,a.struct.id.clock+a.struct.length),e),offset:0}}}else{let t=a.struct.id.clock+a.struct.length-n.id.clock;t>0&&(a.struct.constructor===vu?a.struct.length-=t:n=fc(n,t)),a.struct.mergeWith(n)||(gc(s,a.struct,a.offset),a={struct:n,offset:0},e.next())}}else a={struct:e.curr,offset:0},e.next();for(let n=e.curr;n!==null&&n.id.client===t&&n.id.clock===a.struct.id.clock+a.struct.length&&n.constructor!==vu;n=e.next())gc(s,a.struct,a.offset),a={struct:n,offset:0}}return a!==null&&(gc(s,a.struct,a.offset),a=null),_c(s),Vo(o,Lo(r.map(e=>Ho(e)))),o.toUint8Array()},mc=(e,t,n=Yo,r=$o)=>{let i=fs(t),a=new r,o=new uc(a),s=new n(Tr(e)),c=new lc(s,!1);for(;c.curr;){let e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor===vu)c.next();else if(e.id.clock+e.length>n)for(gc(o,e,kn(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)gc(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===t&&c.curr.id.clock+c.curr.length<=n;)c.next()}return _c(o),Vo(a,Ho(s)),a.toUint8Array()},hc=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Xn(e.encoder.restEncoder)}),e.encoder.restEncoder=Jn(),e.written=0)},gc=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&hc(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),Z(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},_c=e=>{hc(e);let t=e.encoder.restEncoder;Z(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];Z(t,r.written),ir(t,r.restEncoder)}},vc=(e,t,n,r)=>{let i=new n(Tr(e)),a=new lc(i,!1),o=new r,s=new uc(o);for(let e=a.curr;e!==null;e=a.next())gc(s,t(e),0);return _c(s),Vo(o,Ho(i)),o.toUint8Array()},yc=e=>vc(e,fi,Yo,Zo),bc=`You must not compute changes after the event-handler fired.`,xc=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||=Sc(this.currentTarget,this.target)}deletes(e){return Fo(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw yr(bc);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(n!==null){let r=t._map.get(n),i,a;if(this.adds(r)){let e=r.left;for(;e!==null&&this.adds(e);)e=e.left;if(this.deletes(r)){if(e!==null&&this.deletes(e))i=`delete`,a=_n(e.content.getContent());else return}else e!==null&&this.deletes(e)?(i=`update`,a=_n(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=_n(r.content.getContent());else return;e.set(n,{action:i,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 yr(bc);let t=this.target,n=gn(),r=gn(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null,a=()=>{e&&i.push(e)};for(let i=t._start;i!==null;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&((e===null||e.delete===void 0)&&(a(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?((e===null||e.insert===void 0)&&(a(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):((e===null||e.retain===void 0)&&(a(),e={retain:0}),e.retain+=i.length);e!==null&&e.retain===void 0&&a()}this._changes=e}return e}},Sc=(e,t)=>{let n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},Cc=()=>{Eo(`Invalid access: Add Yjs type to a document before reading data.`)},wc=80,Tc=0,Ec=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Tc++}},Dc=e=>{e.timestamp=Tc++},Oc=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Tc++},kc=(e,t,n)=>{if(e.length>=wc){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return Oc(r,t,n),r}{let r=new Ec(t,n);return e.push(r),r}},Ac=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;let n=e._searchMarker.length===0?null:e._searchMarker.reduce((e,n)=>Dn(t-e.index)<Dn(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,Dc(n));r.right!==null&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;r.left!==null&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&Dn(n.index-i)<r.parent.length/wc?(Oc(n,r,i),n):kc(e._searchMarker,r,i)},jc=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){let i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(t===null||t.marker===!0){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=kn(t,i.index+n))}},Mc=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;pn(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;xs(r._eH,n,t)},Nc=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=vs(),this._dEH=vs(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw br()}clone(){throw br()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){ys(this._eH,e)}observeDeep(e){ys(this._dEH,e)}unobserve(e){bs(this._eH,e)}unobserveDeep(e){bs(this._dEH,e)}toJSON(){}},Pc=(e,t,n)=>{e.doc??Cc(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t,i=[],a=e._start;for(;a!==null&&r>0;){if(a.countable&&!a.deleted){let e=a.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}a=a.right}return i},Fc=e=>{e.doc??Cc();let t=[],n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){let e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},Ic=(e,t)=>{let n=0,r=e._start;for(e.doc??Cc();r!==null;){if(r.countable&&!r.deleted){let i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},Lc=(e,t)=>{let n=[];return Ic(e,(r,i)=>{n.push(t(r,i,e))}),n},Rc=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}let e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},zc=(e,t)=>{e.doc??Cc();let n=Ac(e,t),r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},Bc=(e,t,n,r)=>{let i=n,a=e.doc,o=a.clientID,s=a.store,c=n===null?t._start:n.right,l=[],u=()=>{l.length>0&&(i=new mu($(o,Vs(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Yl(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(n===null)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(u(),n.constructor){case Uint8Array:case ArrayBuffer:i=new mu($(o,Vs(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Fl(new Uint8Array(n))),i.integrate(e,0);break;case Go:i=new mu($(o,Vs(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Bl(n)),i.integrate(e,0);break;default:if(n instanceof Nc)i=new mu($(o,Vs(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new su(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},Vc=()=>yr(`Length exceeded!`),Hc=(e,t,n,r)=>{if(n>t._length)throw Vc();if(n===0)return t._searchMarker&&jc(t._searchMarker,n,r.length),Bc(e,t,null,r);let i=n,a=Ac(t,n),o=t._start;for(a!==null&&(o=a.p,n-=a.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&Ks(e,$(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&jc(t._searchMarker,i,r.length),Bc(e,t,o,r)},Uc=(e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Bc(e,t,r,n)},Wc=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=Ac(t,n),s=t._start;for(o!==null&&(s=o.p,n-=o.index);s!==null&&n>0;s=s.right)!s.deleted&&s.countable&&(n<s.length&&Ks(e,$(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&Ks(e,$(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw Vc();t._searchMarker&&jc(t._searchMarker,i,-a+r)},Gc=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},Kc=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new Yl([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new Yl([r]);break;case Uint8Array:s=new Fl(r);break;case Go:s=new Bl(r);break;default:if(r instanceof Nc)s=new su(r);else throw Error(`Unexpected content type`)}new mu($(o,Vs(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},qc=(e,t)=>{e.doc??Cc();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Jc=e=>{let t={};return e.doc??Cc(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},Yc=(e,t)=>{e.doc??Cc();let n=e._map.get(t);return n!==void 0&&!n.deleted},Xc=(e,t)=>{let n={};return e._map.forEach((e,r)=>{let i=e;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&Ls(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Zc=e=>(e.doc??Cc(),ko(e._map.entries(),e=>!e[1].deleted)),Qc=class extends xc{},$c=class e extends Nc{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let n=new e;return n.push(t),n}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof Nc?e.clone():e)),t}get length(){return this.doc??Cc(),this._length}_callObserver(e,t){super._callObserver(e,t),Mc(this,e,new Qc(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):rc(this.doc,n=>{Hc(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):rc(this.doc,t=>{Uc(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):rc(this.doc,n=>{Wc(n,this,e,t)})}get(e){return zc(this,e)}toArray(){return Fc(this)}slice(e=0,t=this.length){return Pc(this,e,t)}toJSON(){return this.map(e=>e instanceof Nc?e.toJSON():e)}map(e){return Lc(this,e)}forEach(e){Ic(this,e)}[Symbol.iterator](){return Rc(this)}_write(e){e.writeTypeRef(eu)}},el=e=>new $c,tl=class extends xc{constructor(e,t,n){super(e,t),this.keysChanged=n}},nl=class e extends Nc{constructor(e){super(),this._prelimContent=null,this._prelimContent=e===void 0?new Map:new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof Nc?e.clone():e)}),t}_callObserver(e,t){Mc(this,e,new tl(this,e,t))}toJSON(){this.doc??Cc();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof Nc?r.toJSON():r}}),e}get size(){return[...Zc(this)].length}keys(){return Ao(Zc(this),e=>e[0])}values(){return Ao(Zc(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return Ao(Zc(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Cc(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc===null?this._prelimContent.delete(e):rc(this.doc,t=>{Gc(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):rc(this.doc,n=>{Kc(n,this,e,t)}),t}get(e){return qc(this,e)}has(e){return Yc(this,e)}clear(){this.doc===null?this._prelimContent.clear():rc(this.doc,e=>{this.forEach(function(t,n,r){Gc(e,r,n)})})}_write(e){e.writeTypeRef(tu)}},rl=e=>new nl,il=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&ci(e,t),al=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&xr(),this.right.content.constructor){case Wl:this.right.deleted||ll(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length)}this.left=this.right,this.right=this.right.right}},ol=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case Wl:t.right.deleted||ll(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&Ks(e,$(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length)}t.left=t.right,t.right=t.right.right}return t},sl=(e,t,n,r)=>{let i=new Map,a=r?Ac(t,n):null;return a?ol(e,new al(a.p.left,a.p,a.index,i),n-a.index):ol(e,new al(null,t._start,0,i),n)},cl=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Wl&&il(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();let i=e.doc,a=i.clientID;r.forEach((r,o)=>{let s=n.left,c=n.right,l=new mu($(a,Vs(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new Wl(o,r));l.integrate(e,0),n.right=l,n.forward()})},ll=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},ul=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===Wl&&il(t[e.right.content.key]??null,e.right.content.value));)e.forward()},dl=(e,t,n,r)=>{let i=e.doc,a=i.clientID,o=new Map;for(let s in r){let c=r[s],l=n.currentAttributes.get(s)??null;if(!il(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new mu($(a,Vs(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new Wl(s,c)),n.right.integrate(e,0),n.forward()}}return o},fl=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;ul(n,i);let s=dl(e,t,n,i),c=r.constructor===String?new Zl(r):r instanceof Nc?new su(r):new Hl(r),{left:l,right:u,index:d}=n;t._searchMarker&&jc(t._searchMarker,n.index,c.getLength()),u=new mu($(o,Vs(a.store,o)),l,l&&l.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=d,n.forward(),cl(e,t,n,s)},pl=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;ul(n,i);let s=dl(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===Wl));){if(!n.right.deleted)switch(n.right.content.constructor){case Wl:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(il(o,a))s.delete(t);else{if(r===0)break iterationLoop;s.set(t,a)}n.right.delete(e)}else n.currentAttributes.set(t,a);break}default:r<n.right.length&&Ks(e,$(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let i=``;for(;r>0;r--)i+=`
|
|
5
|
-
`;n.right=new mu($(o,Vs(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Zl(i)),n.right.integrate(e,0),n.forward()}cl(e,t,n,s)},ml=(e,t,n,r,i)=>{let a=t,o=dn();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===Wl){let e=a.content;o.set(e.key,e)}a=a.right}let s=0,c=!1;for(;t!==a;){if(n===t&&(c=!0),!t.deleted){let n=t.content;switch(n.constructor){case Wl:{let{key:a,value:l}=n,u=r.get(a)??null;(o.get(a)!==n||u===l)&&(t.delete(e),s++,!c&&(i.get(a)??null)===l&&u!==l&&(u===null?i.delete(a):i.set(a,u))),!c&&!t.deleted&&ll(i,n);break}}}t=t.right}return s},hl=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Wl){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},gl=e=>{let t=0;return rc(e.doc,n=>{let r=e._start,i=e._start,a=dn(),o=fn(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Wl:ll(o,i.content);break;default:t+=ml(n,r,i,a,o),a=fn(o),r=i}i=i.right}}),t},_l=e=>{let t=new Set,n=e.doc;for(let[r,i]of e.afterState.entries()){let a=e.beforeState.get(r)||0;i!==a&&Ys(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===Wl&&e.constructor!==Pl&&t.add(e.parent)})}rc(n,n=>{No(e,e.deleteSet,e=>{if(e instanceof Pl||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===Wl?t.add(r):hl(n,e)});for(let e of t)gl(e)})},vl=(e,t,n)=>{let r=n,i=fn(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case su:case Hl:case Zl:n<t.right.length&&Ks(e,$(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}a&&ml(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&jc(o._searchMarker,t.index,-r+n),t},yl=class extends xc{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{e===null?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(this._changes===null){let 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){let e=this.target.doc,t=[];rc(e,e=>{let n=new Map,r=new Map,i=this.target._start,a=null,o={},s=``,c=0,l=0,u=()=>{if(a!==null){let e=null;switch(a){case`delete`:l>0&&(e={delete:l}),l=0;break;case`insert`:(typeof s==`object`||s.length>0)&&(e={insert:s},n.size>0&&(e.attributes={},n.forEach((t,n)=>{t!==null&&(e.attributes[n]=t)}))),s=``;break;case`retain`:c>0&&(e={retain:c},ai(o)||(e.attributes=ei({},o))),c=0}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case su:case Hl:this.adds(i)?this.deletes(i)||(u(),a=`insert`,s=i.content.getContent()[0],u()):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=1):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=1);break;case Zl:this.adds(i)?this.deletes(i)||(a!==`insert`&&(u(),a=`insert`),s+=i.content.str):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=i.length):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=i.length);break;case Wl:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(il(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),il(s,r.get(t)??null)?delete o[t]:o[t]=s));else if(this.deletes(i)){r.set(t,s);let e=n.get(t)??null;il(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(il(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),ll(n,i.content));break}}i=i.right}for(u();t.length>0;){let e=t[t.length-1];if(e.retain!==void 0&&e.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},bl=class e extends Nc{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Cc(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){console.error(e)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);let n=new yl(this,e,t);Mc(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Cc();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===Zl&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc===null?this._pending.push(()=>this.applyDelta(e)):rc(this.doc,n=>{let r=new al(null,this._start,0,new Map);for(let i=0;i<e.length;i++){let a=e[i];if(a.insert!==void 0){let o=!t&&typeof a.insert==`string`&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
|
|
6
|
-
`?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&fl(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&vl(n,r,a.delete):pl(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??Cc();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(Ls(s,e)||t!==void 0&&Ls(s,t))switch(s.content.constructor){case Zl:{let r=i.get(`ychange`);e!==void 0&&!Ls(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!Ls(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case su:case Hl:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case Wl:Ls(s,e)&&(c(),ll(i,s.content))}s=s.right}c()};return e||t?rc(a,n=>{e&&Rs(n,e),t&&Rs(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):rc(r,r=>{let i=sl(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),fl(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):rc(r,r=>{let i=sl(r,this,e,!n);fl(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):rc(n,n=>{vl(n,sl(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):rc(r,r=>{let i=sl(r,this,e,!1);i.right!==null&&pl(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):rc(this.doc,t=>{Gc(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):rc(this.doc,n=>{Kc(n,this,e,t)})}getAttribute(e){return qc(this,e)}getAttributes(){return Jc(this)}_write(e){e.writeTypeRef(nu)}},xl=e=>new bl,Sl=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Cc()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===Tl||t.constructor===Cl)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}e=e.parent===this._root?null: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})}},Cl=class e extends Nc{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof Nc?e.clone():e)),t}get length(){return this.doc??Cc(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Sl(this,e)}querySelector(e){e=e.toUpperCase();let t=new Sl(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),yn(new Sl(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Mc(this,e,new Dl(this,t,e))}toString(){return Lc(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),Ic(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):rc(this.doc,n=>{Hc(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)rc(this.doc,n=>{let r=e&&e instanceof Nc?e._item:e;Bc(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw yr(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):rc(this.doc,n=>{Wc(n,this,e,t)})}toArray(){return Fc(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return zc(this,e)}slice(e=0,t=this.length){return Pc(this,e,t)}forEach(e){Ic(this,e)}_write(e){e.writeTypeRef(iu)}},wl=e=>new Cl,Tl=class e extends Cl{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return ni(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof Nc?e.clone():e)),t}toString(){let e=this.getAttributes(),t=[],n=[];for(let t in e)n.push(t);n.sort();let r=n.length;for(let i=0;i<r;i++){let r=n[i];t.push(r+`="`+e[r]+`"`)}let i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?` `+t.join(` `):``}>${super.toString()}</${i}>`}removeAttribute(e){this.doc===null?this._prelimAttrs.delete(e):rc(this.doc,t=>{Gc(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):rc(this.doc,n=>{Kc(n,this,e,t)})}getAttribute(e){return qc(this,e)}hasAttribute(e){return Yc(this,e)}getAttributes(e){return e?Xc(this,e):Jc(this)}toDOM(e=document,t={},n){let r=e.createElement(this.nodeName),i=this.getAttributes();for(let e in i){let t=i[e];typeof t==`string`&&r.setAttribute(e,t)}return Ic(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(ru),e.writeKey(this.nodeName)}},El=e=>new Tl(e.readKey()),Dl=class extends xc{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{e===null?this.childListChanged=!0:this.attributesChanged.add(e)})}},Ol=class e extends nl{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){let t=new e(this.hookName);return this.forEach((e,n)=>{t.set(n,e)}),t}toDOM(e=document,t={},n){let r=t[this.hookName],i;return i=r===void 0?document.createElement(this.hookName):r.createDom(this),i.setAttribute(`data-yjs-hook`,this.hookName),n!==void 0&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(au),e.writeKey(this.hookName)}},kl=e=>new Ol(e.readKey()),Al=class e extends bl{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,n){let r=e.createTextNode(this.toString());return n!==void 0&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{let t=[];for(let n in e.attributes){let r=[];for(let t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:n,attrs:r})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n=``;for(let e=0;e<t.length;e++){let r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){let t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=`>`}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n}).join(``)}toJSON(){return this.toString()}_write(e){e.writeTypeRef(ou)}},jl=e=>new Al,Ml=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw br()}mergeWith(e){return!1}write(e,t,n){throw br()}integrate(e,t){throw br()}},Nl=0,Pl=class extends Ml{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Hs(e.doc.store,this)}write(e,t){e.writeInfo(Nl),e.writeLen(this.length-t)}getMissing(e,t){return null}},Fl=class e{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(e){throw br()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}},Il=e=>new Fl(e.readBuf()),Ll=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){let n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Ro(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}},Rl=e=>new Ll(e.readLen()),zl=(e,t)=>new Go({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1}),Bl=class e{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;let t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(zl(this.doc.guid,this.opts))}splice(e){throw br()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,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,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}},Vl=e=>new Bl(zl(e.readString(),e.readAny())),Hl=class e{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(e){throw br()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}},Ul=e=>new Hl(e.readJSON()),Wl=class e{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(e){throw br()}mergeWith(e){return!1}integrate(e,t){let n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}},Gl=e=>new Wl(e.readKey(),e.readJSON()),Kl=class e{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeString(t===void 0?`undefined`:JSON.stringify(t))}}getRef(){return 2}},ql=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++){let t=e.readString();t===`undefined`?n.push(void 0):n.push(JSON.parse(t))}return new Kl(n)},Jl=xi(`node_env`)===`development`,Yl=class e{constructor(e){this.arr=e,Jl&&ui(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeAny(t)}}getRef(){return 8}},Xl=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Yl(n)},Zl=class e{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split(``)}isCountable(){return!0}copy(){return new e(this.str)}splice(t){let n=new e(this.str.slice(t));this.str=this.str.slice(0,t);let r=this.str.charCodeAt(t-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+`�`,n.str=`�`+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}},Ql=e=>new Zl(e.readString()),$l=[el,rl,xl,El,wl,kl,jl],eu=0,tu=1,nu=2,ru=3,iu=4,au=5,ou=6,su=class e{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(e){throw br()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;t!==null;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}},cu=e=>new su($l[e.readTypeRef()](e)),lu=(e,t)=>{let n=t,r=0,i;do r>0&&(n=$(n.client,n.clock+r)),i=Ws(e,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof mu);return{item:i,diff:r}},uu=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},du=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new mu($(r,i+n),t,$(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&a.markDeleted(),t.keep&&(a.keep=!0),t.redone!==null&&(a.redone=$(t.redone.client,t.redone.clock+n)),t.right=a,a.right!==null&&(a.right.left=a),e._mergeStructs.push(a),a.parentSub!==null&&a.right===null&&a.parent._map.set(a.parentSub,a),t.length=n,a},fu=(e,t)=>xn(e,e=>Fo(e.deletions,t)),pu=(e,t,n,r,i,a)=>{let o=e.doc,s=o.store,c=o.clientID,l=t.redone;if(l!==null)return Ks(e,l);let u=t.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||pu(e,u,n,r,i,a)===null))return null;for(;u.redone!==null;)u=Ks(e,u.redone)}let p=u===null?t.parent:u.content.type;if(t.parentSub===null){for(d=t.left,f=t;d!==null;){let t=d;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Ks(e,t.redone);if(t!==null&&t.parent._item===u){d=t;break}d=d.left}for(;f!==null;){let t=f;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Ks(e,t.redone);if(t!==null&&t.parent._item===u){f=t;break}f=f.right}}else{if(f=null,t.right&&!i){for(d=t;d!==null&&d.right!==null&&(d.right.redone||Fo(r,d.right.id)||fu(a.undoStack,d.right.id)||fu(a.redoStack,d.right.id));)for(d=d.right;d.redone;)d=Ks(e,d.redone);if(d&&d.right!==null)return null}else d=p._map.get(t.parentSub)||null;d!==null&&d.parent._item!==u&&(d=p._map.get(t.parentSub)||null)}let m=$(c,Vs(s,c)),h=new mu(m,d,d&&d.lastId,f,f&&f.id,p,t.parentSub,t.content.copy());return t.redone=m,uu(h,!0),h.integrate(e,0),h},mu=class e extends Ml{constructor(e,t,n,r,i,a,o,s){super(e,s.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=a,this.parentSub=o,this.redone=null,this.content=s,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Vs(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Vs(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Ss&&this.id.client!==this.parent.client&&this.parent.clock>=Vs(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=qs(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=Ks(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===Pl||this.right&&this.right.constructor===Pl)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Ss){let e=Ws(n,this.parent);this.parent=e.constructor===Pl?null:e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=qs(e,e.doc.store,$(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let t=this.left,n;if(t!==null)n=t.right;else if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start;let r=new Set,i=new Set;for(;n!==null&&n!==this.right;){if(i.add(n),r.add(n),Cs(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(Cs(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(Ws(e.doc.store,n.origin)))r.has(Ws(e.doc.store,n.origin))||(t=n,r.clear());else break;n=n.right}this.left=t}if(this.left!==null){let e=this.left.right;this.right=e,this.left.right=this}else{let e;if(this.parentSub!==null)for(e=this.parent._map.get(this.parentSub)||null;e!==null&&e.left!==null;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}this.right===null?this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)):this.right.left=this,this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Hs(e.doc.store,this),this.content.integrate(e,this),Qs(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new Pl(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:$(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Cs(e.origin,this.lastId)&&this.right===e&&Cs(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)){let t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.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){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),Ro(e.deleteSet,this.id.client,this.id.clock,this.length),Qs(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw xr();this.content.gc(e),t?Js(e,this,new Pl(this.id,this.length)):this.content=new Ll(this.length)}write(e,t){let n=t>0?$(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,a=this.content.getRef()&31|(n===null?0:128)|(r===null?0:64)|(i===null?0:32);if(e.writeInfo(a),n!==null&&e.writeLeftID(n),r!==null&&e.writeRightID(r),n===null&&r===null){let t=this.parent;if(t._item!==void 0){let n=t._item;if(n===null){let n=ws(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===Ss?(e.writeParentInfo(!1),e.writeLeftID(t)):xr();i!==null&&e.writeString(i)}this.content.write(e,t)}},hu=(e,t)=>gu[t&31](e),gu=[()=>{xr()},Rl,ql,Il,Ql,Ul,Gl,cu,Xl,Vl,()=>{xr()}],_u=10,vu=class extends Ml{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){xr()}write(e,t){e.writeInfo(_u),Z(e.restEncoder,this.length-t)}getMissing(e,t){return null}},yu=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},bu=`__ $YJS$ __`;yu[bu]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),yu[bu]=!0;var xu=`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`.split(`.`),Su=new Set(xu);function Cu(e){return Su.has(e)}function wu(e,t,n){if(e[t]!==`[`)return t;let r=1;for(let i=t+1;i<n;i+=1)if(e[i]===`\\`)i+=1;else if(e[i]===`[`&&(r+=1),e[i]===`]`&&(--r,r===0))return i+1;return null}function Tu(e,t,n){if(e[t]!==`{`)return null;let r=1;for(let i=t+1;i<n;i+=1)if(e[i]===`\\`)i+=1;else if(e[i]===`{`&&(r+=1),e[i]===`}`&&(--r,r===0))return i+1;return null}function Eu(e,t,n=e.length){let r=e.indexOf(`
|
|
7
|
-
`,t);r>=0&&(n=Math.min(n,r));let i=/^\\(verb\*?|Verb\*?|lstinline\*?|mintinline\*?)(?![A-Za-z@])/.exec(e.slice(t,n));if(!i)return null;let a=i[1].replace(/\*$/,``),o=t+i[0].length;if(a!==`verb`){let t=wu(e,o,n);if(t===null)return null;o=t}if(a===`mintinline`){let t=Tu(e,o,n);if(t===null)return null;o=t}let s=e[o];if(!s||/\s/.test(s))return null;if(s===`{`&&a!==`verb`){let t=Tu(e,o,n);return{end:t??n,closed:t!==null}}let c=e.indexOf(s,o+1);return c<0||c>=n?{end:n,closed:!1}:{end:c+1,closed:!0}}function Du(e,t,n=e.length){return Eu(e,t,n)?.end??null}function Ou(e,t,n){let r=n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),i=new RegExp(String.raw`\\end\s*\{\s*${r}\s*\}`,`g`);i.lastIndex=t;let a=i.exec(e);return a?{from:a.index,to:a.index+a[0].length}:null}function ku(e,t){let n=0;for(let r=t-1;r>=0&&e[r]===`\\`;--r)n+=1;return n%2==1}function Au(e,t){let n=t+1;if(/[A-Za-z@]/.test(e[n]??``)){for(;/[A-Za-z@]/.test(e[n]??``);)n+=1;return e[n]===`*`&&(n+=1),n}return Math.min(e.length,n+1)}function ju(e,t){let n=/^\\begin\s*\{\s*([A-Za-z0-9@:_*.\-]+)\s*\}/.exec(e.slice(t));return!n||!Cu(n[1])?null:{name:n[1],to:t+n[0].length}}function Mu(e,t){let n=Math.max(0,Math.min(e.length,t));for(let t=0;t<n;){if(e[t]===`%`&&!ku(e,t)){let r=e.indexOf(`
|
|
8
|
-
`,t),i=r<0?e.length:r;if(n<=i)return`comment`;t=i+1;continue}if(e[t]!==`\\`||ku(e,t)){t+=1;continue}let r=Eu(e,t);if(r!==null){if(n<r.end||!r.closed&&n<=r.end)return`literal`;t=r.end;continue}let i=ju(e,t);if(i){let r=Ou(e,i.to,i.name),a=r?.to??e.length;if(n<a||!r&&n<=a)return`literal`;t=a}else t=Au(e,t)}return null}function Nu(e,t,n){return e.slice(t,n).replace(/[^\r\n]/g,` `)}function Pu(e){let t=e.split(``);for(let n=0;n<e.length;n+=1){if(e[n]!==`%`||ku(e,n))continue;let r=e.indexOf(`
|
|
9
|
-
`,n),i=r<0?e.length:r;for(let e=n;e<i;e+=1)t[e]=` `;n=i}return t.join(``)}function Fu(e){let t=``,n=0;for(;n<e.length;){if(e[n]===`%`&&!ku(e,n)){let r=e.indexOf(`
|
|
10
|
-
`,n),i=r<0?e.length:r;t+=e.slice(n,i),n=i;continue}if(e[n]!==`\\`||ku(e,n)){t+=e[n],n+=1;continue}let r=Du(e,n);if(r!==null){t+=Nu(e,n,r),n=r;continue}let i=ju(e,n);if(i){let r=Ou(e,i.to,i.name)?.to??e.length;t+=Nu(e,n,r),n=r}else t+=e[n],n+=1}return t}var Iu=new Set(xu);function Lu(e){return/[A-Za-z@0-9:_-]/.test(e)}function Ru(e,t){let n=0;for(let r=t-1;r>=0&&e[r]===`\\`;--r)n+=1;return n%2==1}function zu(e,t){return e[t]===`%`&&!Ru(e,t)}function Bu(e,t){let n=e.indexOf(`
|
|
11
|
-
`,t);return n===-1?e.length:n}function Vu(e,t){let n=t;for(;n<e.length;)if(/\s/.test(e[n]))n+=1;else if(zu(e,n))n=Bu(e,n);else break;return n}function Hu(e,t,n,r){if(e[t]!==n)return null;let i=0,a=0;for(let o=t;o<e.length;o+=1){let s=e[o];if(s===`\\`&&o+1<e.length)o+=1;else if(zu(e,o))o=Bu(e,o)-1;else{if(n===`[`){if(s===`{`){a+=1;continue}if(s===`}`&&a>0){--a;continue}if(a>0)continue}if(s===n)i+=1;else if(s===r&&(--i,i===0))return{from:t,to:o+1,contentFrom:t+1,contentTo:o}}}return null}function Uu(e,t,n){let r=[],i=t;for(;r.length<n;){for(i=Vu(e,i);e[i]===`[`;){let t=Hu(e,i,`[`,`]`);if(!t)return r;i=Vu(e,t.to)}if(e[i]!==`{`)break;let t=Hu(e,i,`{`,`}`);if(!t)break;r.push(t),i=t.to}return r}function Wu(e,t,n){let r=[],i=t;for(;r.length<n&&(i=Vu(e,i),e[i]===`[`);){let t=Hu(e,i,`[`,`]`);if(!t)break;r.push(t),i=t.to}return r}function Gu(e,t){if(e[t]!==`\\`||t+1>=e.length)return null;let n=t+1;if(!/[A-Za-z@]/.test(e[n]))return{name:e[n],from:t,to:n+1};for(;n<e.length&&Lu(e[n]);)n+=1;let r=e.slice(t+1,n);return e[n]===`*`&&(n+=1),{name:r,from:t,to:n}}function Ku(e,t){if(t.name!==`begin`)return t.to;let n=Uu(e,t.to,1)[0];if(!n)return t.to;let r=e.slice(n.contentFrom,n.contentTo).trim();return Iu.has(r)?Ou(e,n.to,r)?.to??e.length:t.to}function qu(e,t){let n=0;for(;n<e.length;){if(zu(e,n)){n=Bu(e,n);continue}if(e[n]!==`\\`){n+=1;continue}let r=Gu(e,n);if(!r){n+=1;continue}let i=Du(e,r.from);if(i!==null&&i>r.to){n=i;continue}let a=Ku(e,r);a>r.to?n=a:(t(r),n=r.to)}}function Ju(e,t,n){let r=[],i=t.contentFrom,a=t.contentFrom;for(;a<=t.contentTo;){if(a<t.contentTo&&zu(e,a)){a=Bu(e,a),e[a]===`
|
|
12
|
-
`&&(a+=1);continue}if(a!==t.contentTo&&(!n||e[a]!==`,`)){a+=1;continue}let o=Yu(e,i,a);o&&r.push(o),i=a+1,a+=1}return r}function Yu(e,t,n){let r=[],i=t;for(;i<n;)zu(e,i)?(i=Bu(e,i),e[i]===`
|
|
13
|
-
`&&(i+=1)):(r.push({character:e[i],index:i}),i+=1);let a=0,o=r.length;for(;a<o&&/\s/.test(r[a].character);)a+=1;for(;o>a&&/\s/.test(r[o-1].character);)--o;return a===o?null:{path:r.slice(a,o).map(e=>e.character).join(``),command:``,from:r[a].index,to:r[o-1].index+1}}function Xu(e,t){let n=Vu(e,t);if(n>=e.length||/[\\{}\[\]#~]/.test(e[n]))return null;let r=n;for(;r<e.length&&!/\s/.test(e[r])&&!zu(e,r)&&!/[\\{}\[\]#~]/.test(e[r]);)r+=1;return r===n?null:{path:e.slice(n,r),command:``,from:n,to:r}}function Zu(e){let t=[];return qu(e,n=>{let r=n.name.toLowerCase();if(r===`input`||r===`include`||r===`subfile`){let i=Uu(e,n.to,1)[0];if(i)for(let r of Ju(e,i,!1))t.push({...r,command:n.name});else if(r===`input`){let r=Xu(e,n.to);r&&t.push({...r,command:n.name})}return}if(r!==`import`&&r!==`subimport`&&r!==`includefrom`&&r!==`inputfrom`&&r!==`subinputfrom`&&r!==`subincludefrom`)return;let i=Uu(e,n.to,2);if(i.length!==2)return;let a=Ju(e,i[0],!1)[0]?.path??``,o=Ju(e,i[1],!1)[0];if(!o)return;let s=a&&!a.endsWith(`/`)?`/`:``;t.push({path:a+s+o.path,command:n.name,from:o.from,to:o.to,directory:a})}),t}var Qu=(e,t)=>e>>>t|e<<32-t,$u=e=>Qu(e,2)^Qu(e,13)^Qu(e,22),ed=e=>Qu(e,6)^Qu(e,11)^Qu(e,25),td=e=>Qu(e,7)^Qu(e,18)^e>>>3,nd=e=>Qu(e,17)^Qu(e,19)^e>>>10,rd=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]),id=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ad=class{constructor(){let e=new ArrayBuffer(320);this._H=new Uint32Array(e,0,8),this._H.set(id),this._W=new Uint32Array(e,64,64)}_updateHash(){let e=this._H,t=this._W;for(let e=16;e<64;e++)t[e]=nd(t[e-2])+t[e-7]+td(t[e-15])+t[e-16];let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7];for(let e=0,u,d;e<64;e++)u=l+ed(o)+(o&s^~o&c)+rd[e]+t[e]>>>0,d=$u(n)+(n&r^n&i^r&i)>>>0,l=c,c=s,s=o,o=a+u>>>0,a=i,i=r,r=n,n=u+d>>>0;e[0]+=n,e[1]+=r,e[2]+=i,e[3]+=a,e[4]+=o,e[5]+=s,e[6]+=c,e[7]+=l}digest(e){let t=0;for(;t+56<=e.length;){let n=0;for(;n<16&&t+3<e.length;n++)this._W[n]=e[t++]<<24|e[t++]<<16|e[t++]<<8|e[t++];if(t%64!=0){for(this._W.fill(0,n,16);t<e.length;)this._W[n]|=e[t]<<(3-t%4)*8,t++;this._W[n]|=128<<(3-t%4)*8}this._updateHash()}let n=t%64!=0;this._W.fill(0,0,16);let r=0;for(;t<e.length;r++)for(let n=3;n>=0&&t<e.length;n--)this._W[r]|=e[t++]<<n*8;n||(this._W[r-(t%4==0?0:1)]|=128<<(3-t%4)*8),this._W[14]=e.byteLength/Mn,this._W[15]=e.byteLength*8,this._updateHash();let i=new Uint8Array(32);for(let e=0;e<this._H.length;e++)for(let t=0;t<4;t++)i[e*4+t]=this._H[e]>>>(3-t)*8;return i}},od=e=>new ad().digest(e);function sd(e){return Array.from(od(new TextEncoder().encode(e)),e=>e.toString(16).padStart(2,`0`)).join(``)}function cd(e){for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);return e}function ld(e){e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function ud(e=globalThis.crypto){if(typeof e?.randomUUID==`function`)return e.randomUUID();let t=new Uint8Array(16);return ld(typeof e?.getRandomValues==`function`?e.getRandomValues(t):cd(t))}function dd(e){return/\.(?:tex|sty|cls|ltx|dtx|ins|txt|md|markdown|rst)$/i.test(e.trim())}function fd(e){return/\.(?:tex|sty|cls)$/i.test(e.trim())}function pd(){let e={status:`loading`,error:``},t=new Set,n=(n,r=``)=>{if(e.status!==n||e.error!==r){e={status:n,error:r};for(let e of t)e()}};return{getSnapshot:()=>e,subscribe:e=>(t.add(e),()=>t.delete(e)),loading:()=>n(`loading`),working:()=>n(`working`),failed:e=>n(`error`,e instanceof Error?e.message:String(e))}}var md=pd(),hd=/\.(?:tex|bib|cls|sty)$/i,gd=3e4,_d=null,vd=!1,yd=null,bd=1,xd=new Map,Sd=[],Cd=null,wd=null,Td=class extends Error{kind;constructor(e,t){super(t),this.kind=e,this.name=`TexFmtError`}};function Ed(e){return e instanceof Td}function Dd(e){_d?.terminate(),_d=null,vd=!1,yd!==null&&window.clearTimeout(yd),yd=null,Cd=null,Sd.length=0,wd=null,md.failed(e);for(let t of xd.values())t.timeout!==null&&window.clearTimeout(t.timeout),t.reject(e);xd.clear()}function Od(){if(Cd!==null||Sd.length===0)return;let e;try{e=kd()}catch(e){Dd(e instanceof Td?e:new Td(`load`,`The bundled tex-fmt formatter could not be loaded.`));return}if(!vd)return;let t=Sd.shift();if(t===void 0)return;let n=xd.get(t);if(!n)Od();else{Cd=t,n.timeout=window.setTimeout(()=>{Cd===t&&Dd(new Td(`result`,`The formatter did not respond within 30 seconds.`))},gd);try{e.postMessage({...n.request,id:t})}catch{Dd(new Td(`load`,`The formatter worker could not receive the source.`))}}}function kd(){if(_d)return _d;if(typeof Worker>`u`){let e=new Td(`load`,`This browser does not support formatter workers.`);throw md.failed(e),e}md.loading();try{_d=new Worker(new URL(new URL(`latexFormatterWorker-BIDCSZPd.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:`texlite-latex-formatter`}),yd=window.setTimeout(()=>{vd||Dd(new Td(`load`,`The formatter did not finish loading within 30 seconds.`))},gd)}catch{let e=new Td(`load`,`The bundled tex-fmt formatter could not be loaded.`);throw md.failed(e),e}return _d.onmessage=e=>{let t=e.data;if(t&&`type`in t){t.type===`ready`&&(vd=!0,yd!==null&&window.clearTimeout(yd),yd=null,Od());return}if(!t||typeof t.id!=`number`){Dd(new Td(`result`,`The formatter worker returned an invalid response.`));return}let n=xd.get(t.id);if(n){if(xd.delete(t.id),n.timeout!==null&&window.clearTimeout(n.timeout),Cd===t.id&&(Cd=null),t.ok)md.working(),n.resolve(t.result),Od();else{let e=new Td(t.kind,t.message);t.kind===`format`?(md.working(),n.reject(e),Od()):(n.reject(e),Dd(e))}}},_d.onerror=()=>{Dd(new Td(`load`,`The bundled tex-fmt formatter could not be loaded.`))},_d.onmessageerror=()=>{Dd(new Td(`result`,`The formatter worker returned an unreadable response.`))},_d}function Ad(e){let t=bd++;return new Promise((n,r)=>{xd.set(t,{request:e,resolve:n,reject:r,timeout:null}),Sd.push(t),Od()})}function jd(e,t=``){return Ad({action:`format`,source:e,config:t})}async function Md(){_d&&md.getSnapshot().status===`working`||(wd||=Ad({action:`probe`}).then(()=>void 0).finally(()=>{wd=null}),await wd)}async function Nd(){(_d||xd.size)&&Dd(new Td(`load`,`The formatter runtime was reloaded.`)),md.loading(),await Md()}function Pd(e){return hd.test(e)}function Fd(e){return e.match(/(?:\r?\n)+$/)?.[0]??``}function Id(e,t){let n=Fd(e),r=(n?e.slice(0,-n.length):e).split(/\r?\n/).find(e=>e.trim())?.match(/^[\t ]*/)?.[0]??``,i=t.replace(/(?:\r?\n)+$/,``);return`${r?i.split(`
|
|
14
|
-
`).map(e=>e&&`${r}${e}`).join(`
|
|
15
|
-
`):i}${n}`}async function Ld(e,t,n=0){return Ad({action:`diff`,source:e,formatted:t,baseOffset:n})}var Rd=null,zd=1,Bd=new Map,Vd=class extends Error{kind;constructor(e){super(`BibTeX formatter: ${e}`),this.kind=e,this.name=`BibtexFormatterError`}};function Hd(e){Rd?.terminate(),Rd=null;for(let t of Bd.values())clearTimeout(t.timeout),t.reject(new Vd(e));Bd.clear()}function Ud(){if(Rd)return Rd;let e=new Worker(new URL(new URL(`bibtexFormatterWorker-B_jvobIv.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:`texlite-bibtex-formatter`});return Rd=e,e.onmessage=({data:t})=>{if(Rd!==e)return;if(!t||typeof t.id!=`number`||typeof t.ok!=`boolean`){Hd(`unavailable`);return}let n=Bd.get(t.id);n&&(t.ok&&(t.action!==n.action||(t.action===`format`?typeof t.result!=`string`:!Wd(t.result)))?Hd(`unavailable`):(clearTimeout(n.timeout),Bd.delete(t.id),t.ok?n.resolve(t.result):t.kind===`too-large`||t.kind===`invalid`?n.reject(new Vd(t.kind)):(n.reject(new Vd(`unavailable`)),Hd(`unavailable`))))},e.onerror=e.onmessageerror=()=>{Rd===e&&Hd(`unavailable`)},e}function Wd(e){if(!Array.isArray(e))return!1;let t=0;return e.every(e=>!e||!Number.isSafeInteger(e.from)||!Number.isSafeInteger(e.to)||e.from<t||e.to<e.from||typeof e.replacement!=`string`?!1:(t=e.to,!0))}function Gd(e){return new Promise((t,n)=>{let r;try{r=Ud()}catch{n(new Vd(`unavailable`));return}let i=zd++,a=setTimeout(()=>Hd(`timeout`),3e4);Bd.set(i,{action:e.action,resolve:t,reject:n,timeout:a});try{r.postMessage({...e,id:i})}catch{Hd(`unavailable`)}})}function Kd(e,t){return Gd({action:`format`,source:e,maxBytes:t})}function qd(e,t,n=0){return Gd({action:`diff`,source:e,formatted:t,baseOffset:n})}function Jd(e,t=null){let n=Yd(e),r=t===`succeeded`||t===null&&Qd(e)?[]:Xd(n.filter($d));return{warnings:Xd(Yd(Zd(e)).filter(e=>!$d(e)&&ef(e))),errors:r}}function Yd(e){return e.split(`
|
|
16
|
-
`).map(e=>e.trim()).filter(Boolean)}function Xd(e){return[...new Set(e)]}function Zd(e){let t=/^Running ['"][^\n]*(?:pdf|xe|lua)latex(?:\s|['"])[^\n]*$/gim,n=-1;for(let r of e.matchAll(t))n=r.index;return n>=0?e.slice(n):e}function Qd(e){return/Latexmk: All targets .* are up-to-date/i.test(e)&&/Output written on .*\.pdf/i.test(e)}function $d(e){return/^!\s/.test(e)||/(?:^|:\s)(?:LaTeX|Package|Class|pdfTeX|XeTeX|LuaTeX)?\s*Error:/i.test(e)||/^Latexmk:.*(?:\bErrors?,|did not complete making targets|failure)/i.test(e)||/^Collected error summary/i.test(e)||/\b(?:fatal error|emergency stop|undefined control sequence|no output pdf|no pages of output)\b/i.test(e)||/\b(?:bibtex|biber) errors?:/i.test(e)||/^error, and then rerun latexmk/i.test(e)}function ef(e){return/\bwarnings?\b|overfull|underfull|badness/i.test(e)}var tf=Object.freeze({}),nf=class{threads=new Map;listeners=new Map;newComments=new Map;getThread(e){return this.threads.get(e)??tf}subscribe(e,t){let n=this.listeners.get(e)??new Set;return n.add(t),this.listeners.set(e,n),()=>{n.delete(t),n.size||this.listeners.delete(e)}}publish(e,t){Object.keys(t).length?this.threads.set(e,t):this.threads.delete(e);for(let t of this.listeners.get(e)??[])t()}isPending(e){return Object.values(this.getThread(e)).some(e=>e?.pending)}open(e,t,n=``){if(this.isPending(e))return;let r={...this.getThread(e)};if(t.startsWith(`edit-reply:`))for(let[e,t]of Object.entries(r))e.startsWith(`edit-reply:`)&&t?.open&&(r[e]={...t,open:!1});r[t]={content:n,pending:!1,error:``,...r[t],open:!0},this.publish(e,r)}change(e,t,n){let r=this.getThread(e)[t];r&&!this.isPending(e)&&this.publish(e,{...this.getThread(e),[t]:{...r,content:n}})}discard(e,t){let n={...this.getThread(e)};t===void 0?this.publish(e,tf):(delete n[t],this.publish(e,n))}async submit(e,t,n,r){let i=this.getThread(e)[t];if(!i||!i.content.trim()||this.isPending(e))return!1;let a={...i,pending:!0,error:``};this.publish(e,{...this.getThread(e),[t]:a});let o=r;try{if(await n(i.content))return this.getThread(e)[t]===a&&this.discard(e,t),!0}catch(e){o=K(e)}return this.getThread(e)[t]===a&&this.publish(e,{...this.getThread(e),[t]:{...i,pending:!1,error:o}}),!1}getNew(e){return this.newComments.get(e)}setNew(e){this.newComments.set(e.filePath,{...e,selection:{...e.selection},suggestion:e.suggestion?{...e.suggestion}:e.suggestion})}discardNew(e){this.newComments.delete(e)}},rf=Y.createContext(void 0),af=e=>{let t=Y.useContext(rf);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},of=({client:e,children:t})=>(Y.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,X.jsx)(rf.Provider,{value:e,children:t})),sf={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},cf=new class{#e=sf;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function lf(e){setTimeout(e,0)}var uf=typeof window>`u`||`Deno`in globalThis;function df(){}function ff(e,t){return typeof e==`function`?e(t):e}function pf(e){return typeof e==`number`&&e>=0&&e!==1/0}function mf(e,t){return Math.max(e+(t||0)-Date.now(),0)}function hf(e,t){return typeof e==`function`?e(t):e}function gf(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==vf(o,t.options))return!1}else if(!bf(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function _f(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(yf(t.options.mutationKey)!==yf(a))return!1}else if(!bf(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function vf(e,t){return(t?.queryKeyHashFn||yf)(e)}function yf(e){return JSON.stringify(e,(e,t)=>Tf(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function bf(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!bf(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!bf(e[r],t[r]))return!1;return!0}return!1}var xf=Object.prototype.hasOwnProperty;function Sf(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=wf(e)&&wf(t);if(!r&&!(Tf(e)&&Tf(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:xf.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=Sf(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function Cf(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function wf(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Tf(e){if(!Ef(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!Ef(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function Ef(e){return Object.prototype.toString.call(e)===`[object Object]`}function Df(e){return new Promise(t=>{cf.setTimeout(t,e)})}function Of(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:Sf(e,t)}function kf(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Af(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var jf=Symbol();function Mf(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===jf?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Nf(e,t){return typeof e==`function`?e(...t):!!e}function Pf(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0})),i)}),e}var Ff=()=>uf,If=()=>Ff(),Lf=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Rf=new class extends Lf{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},zf=lf;function Bf(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=zf,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var Vf=Bf(),Hf=new class extends Lf{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function Uf(e){return Math.min(1e3*2**e,3e4)}function Wf(e){return(e??`online`)!==`online`||Hf.isOnline()}var Gf=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function Kf(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(df);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new Gf(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>Rf.isFocused()&&(e.networkMode===`always`||Hf.isOnline())&&e.canRun(),p=()=>Wf(e.networkMode)&&e.canRun(),m=e=>{c()||(r?.(),i=`resolved`,a(e))},h=e=>{c()||(r?.(),i=`rejected`,o(e))},g=t=>new Promise(n=>{r=e=>{(c()||t())&&n(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),_=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(m).catch(r=>{if(c())return;let i=e.retry??(If()?0:3),a=e.retryDelay??Uf,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);t||!s?h(r):(n++,e.onFail?.(n,r),Df(o).then(()=>f()?void 0:g(f)).then(()=>{t?h(r):_()}))})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?_():g(p).then(_),s)}}var qf=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),pf(this.gcTime)&&(this.#e=cf.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(If()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(cf.clearTimeout(this.#e),this.#e=void 0)}};function Jf(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{Pf(e,()=>t.signal,()=>n=!0)},u=Mf(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?Af:kf;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Xf:Yf,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]===void 0?r.initialPageParam:o[0]:Yf(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function Yf(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Xf(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var Zf=class extends qf{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=ep(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=ep(this.options);e.data!==void 0&&(this.setState($f(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=Of(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(df).catch(df):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>hf(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===jf||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>hf(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!mf(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=Mf(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?Jf(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=Kf({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof Gf&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof Gf){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Qf(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...$f(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),Vf.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Qf(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Wf(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function $f(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function ep(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var tp=class extends Lf{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),rp(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ip(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ip(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof hf(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!Cf(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&ap(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||hf(this.options.enabled,this.#t)!==hf(t.enabled,this.#t)||hf(this.options.staleTime,this.#t)!==hf(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||hf(this.options.enabled,this.#t)!==hf(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Cf(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch(t).then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(df)),t}#h(e){return!If()&&hf(this.options.enabled,this.#t)!==!1&&pf(e)}#g(){this.#b();let e=hf(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=mf(this.#r.dataUpdatedAt,e)+1;this.#u=cf.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return hf(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=cf.setInterval(()=>{(this.options.refetchIntervalInBackground||Rf.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(cf.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(cf.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&rp(e,t),o=i&&ap(e,n,t,r);(a||o)&&(l={...l,...Qf(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=Of(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=Of(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:op(e,t),refetch:this.refetch,isEnabled:hf(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),Cf(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})();Vf.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function np(e,t){return hf(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||hf(t.retryOnMount,e)!==!1)}function rp(e,t){return np(e,t)||e.state.data!==void 0&&ip(e,t,t.refetchOnMount)}function ip(e,t,n){if(hf(t.enabled,e)!==!1&&hf(t.staleTime,e)!==`static`){let r=hf(n,e);return r===`always`||r!==!1&&op(e,t)}return!1}function ap(e,t,n,r){return(e!==t||hf(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&op(e,n)}function op(e,t){return hf(t.enabled,e)!==!1&&e.isStaleByTime(hf(t.staleTime,e))}var sp=class extends qf{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||cp(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=Kf({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),Vf.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function cp(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var lp=class extends Lf{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new sp({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=up(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=up(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=up(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=up(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){Vf.batch(()=>{let e=this.getAll();this.#e.clear(),this.#t.clear(),e.forEach(e=>{this.notify({type:`removed`,mutation:e})})})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>_f(t,e))}findAll(e={}){return this.getAll().filter(t=>_f(e,t))}notify(e){Vf.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return Vf.batch(()=>Promise.all(e.map(e=>e.continue().catch(df))))}};function up(e){return e.options.scope?.id}var dp=class extends Lf{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),Cf(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&yf(t.mutationKey)!==yf(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??cp();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){Vf.batch(()=>{let t=this.#r;if(t&&this.hasListeners()){let n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{t.onSuccess?.(e.data,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(e.data,null,n,r,i)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{t.onError?.(e.error,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(void 0,e.error,n,r,i)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},fp=class extends Lf{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??vf(r,t),a=this.get(i);return a||(a=new Zf({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){this.#e.get(e.queryHash)===e&&(e.destroy(),this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){Vf.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>gf(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>gf(e,t)):t}notify(e){Vf.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Vf.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Vf.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},pp=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new fp,this.#t=e.mutationCache||new lp,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=Rf.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=Hf.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(hf(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=ff(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return Vf.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;Vf.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return Vf.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=Vf.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(df).catch(df)}invalidateQueries(e,t={}){return Vf.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=Vf.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(df)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(df)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(hf(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(hf(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(df).catch(df)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(df).catch(df)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return Hf.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(yf(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{bf(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(yf(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{bf(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=vf(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===jf&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},mp=Y.createContext(!1),hp=()=>Y.useContext(mp);mp.Provider;function gp(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var _p=Y.createContext(gp()),vp=()=>Y.useContext(_p),yp=(e,t,n)=>{let r=n?.state.status===`error`&&typeof e.throwOnError==`function`?Nf(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},bp=e=>{Y.useEffect(()=>{e.clearReset()},[e])},xp=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Nf(n,[e.error,r])),Sp=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},Cp=(e,t)=>e?.suspense&&t.isPending,wp=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Tp(e,t,n){let r=hp(),i=vp(),a=af(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,Sp(o),yp(o,i,s),bp(i);let[l]=Y.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&c;if(Y.useSyncExternalStore(Y.useCallback(e=>{let t=d?l.subscribe(Vf.batchCalls(e)):df;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Y.useEffect(()=>{l.setOptions(o)},[o,l]),Cp(o,u))throw wp(o,l,i);if(xp({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function Ep(e,t){return Tp(e,tp,t)}function Dp(e,t){let n=af(t),[r]=Y.useState(()=>new dp(n,e));Y.useEffect(()=>{r.setOptions(e)},[r,e]);let i=Y.useSyncExternalStore(Y.useCallback(e=>r.subscribe(Vf.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=Y.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(df)},[r]);if(i.error&&Nf(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var Op={lists:e=>[`discussion`,e,`comments`],file:(e,t)=>[`discussion`,e,`comments`,`file`,t],all:e=>[`discussion`,e,`comments`,`project`],summary:e=>[`discussion`,e,`summary`],mentions:e=>[`discussion`,e,`mentions`],candidates:e=>[`discussion`,e,`candidates`]},kp=[],Ap=[],jp=e=>e instanceof We&&[401,403,404].includes(e.status);function Mp(){return new pp({defaultOptions:{queries:{staleTime:3e4,gcTime:3e5,retry:(e,t)=>!jp(t)&&e<2&&(!(t instanceof We)||t.status===0||t.status>=500||t.code===`INVALID_RESPONSE`),retryDelay:e=>Math.min(500*2**e,2e3),refetchOnReconnect:`always`},mutations:{retry:!1}}})}var Np=new WeakMap;function Pp(e){let t=Np.get(e);return t||(t={next:0,summaries:new Map},Np.set(e,t)),++t.next}function Fp(e,t,n,r){let i=Np.get(e);!n||!i||r<(i.summaries.get(t)??0)||(i.summaries.set(t,r),e.setQueryData(Op.summary(t),n))}function Ip(e,t){if(t.kind===`created`)return e.some(e=>e.id===t.comment.id)?e:[...e,t.comment];let n=t.kind===`edited`?t.comment.id:t.kind===`resolved`?t.resolution.id:t.commentId;return t.kind===`deleted`?e.filter(e=>e.id!==n):e.map(e=>{if(e.id!==n)return e;if(t.kind===`suggestion`)return{...e,suggestion:t.suggestion};if(t.kind===`edited`)return{...e,...t.comment};if(t.kind===`resolved`)return{...e,...t.resolution};if(t.kind===`reply-deleted`)return{...e,replies:e.replies.filter(e=>e.id!==t.replyId)};let r=e.replies.some(e=>e.id===t.reply.id);return{...e,replies:r?e.replies.map(e=>e.id===t.reply.id?t.reply:e):[...e.replies,t.reply]}})}async function Lp(e,t,n){await Promise.all([e.cancelQueries({queryKey:Op.lists(t)}),e.cancelQueries({queryKey:Op.mentions(t)})]);let r=n.change,i=r.kind===`created`||r.kind===`edited`?r.comment.filePath:r.kind===`resolved`?r.resolution.filePath:r.filePath;if(e.setQueriesData({queryKey:Op.lists(t)},e=>{if(!e)return e;let t=e.comments;return r.kind===`created`?e:{...e,comments:Ip(t,r),summary:n.summary}}),r.kind===`created`)for(let a of[Op.file(t,i),Op.all(t)])e.setQueryData(a,e=>e&&{...e,comments:Ip(e.comments,r),summary:n.summary});Fp(e,t,n.summary,Pp(e)),e.setQueryData(Op.mentions(t),e=>e&&{mentions:e.mentions.filter(e=>r.kind===`deleted`?e.commentId!==r.commentId:r.kind===`resolved`&&r.resolution.resolved?e.commentId!==r.resolution.id:r.kind===`suggestion`&&e.kind===`review`&&e.commentId===r.commentId?r.suggestion.status===`pending`&&e.readAt===null:r.kind!==`reply-deleted`||e.replyId!==r.replyId)})}async function Rp(e,t){await Promise.all([Op.lists(t),Op.mentions(t)].map(async t=>{await e.cancelQueries({queryKey:t}),await e.invalidateQueries({queryKey:t})}))}function zp(e,t,n,r,i){let a=af(),o=async(t,n)=>{let r=Pp(a),i=await q(t,{signal:n});return n.aborted||Fp(a,e,i.summary,r),i},s=Ep({queryKey:Op.file(e,t),enabled:!!t,queryFn:({signal:n})=>o(`/api/projects/${e}/comments?path=${encodeURIComponent(t)}`,n)}),c=Ep({queryKey:Op.all(e),enabled:n===`project`,queryFn:({signal:t})=>o(`/api/projects/${e}/comments?scope=project`,t)}),l=Ep({queryKey:Op.summary(e),enabled:!1}),u=(0,Y.useRef)({projectId:e,revision:r,sourceOrderRevision:i});(0,Y.useEffect)(()=>{let t=u.current;if(u.current={projectId:e,revision:r,sourceOrderRevision:i},t.projectId!==e)return;let n=t.revision===r?t.sourceOrderRevision===i?null:Op.all(e):Op.lists(e);n&&a.cancelQueries({queryKey:n}).then(()=>a.invalidateQueries({queryKey:n}))},[a,e,r,i]);let d=n===`project`?c:s,f=s.error?K(s.error):``;return{comments:jp(s.error)?kp:s.data?.comments??kp,commentsFilePath:t&&(s.data||s.error)?t:``,commentsReady:!(!t||!s.data||s.isFetching||s.error),fileCommentsLoading:!!(t&&s.isFetching),fileCommentsError:f,reviewComments:jp(d.error)?kp:d.data?.comments??kp,reviewCommentsLoading:!(n!==`project`&&!t||!d.isFetching),reviewCommentsError:d.error?K(d.error):``,projectCommentSummary:jp(s.error)||jp(c.error)?null:l.data??null,refreshComments:()=>Rp(a,e)}}function Bp(e){let t=af(),n=Dp({retry:!1,mutationFn:async({id:e,path:n,options:r})=>{let i=await q(`/api/projects/${e}/comments${n}`,r);return await Lp(t,e,i),Rp(t,e),i},onError:(e,{id:n})=>{e instanceof We&&[`SUGGESTION_UPDATED`,`SUGGESTION_DECIDED`,`SUGGESTION_APPLYING`].includes(e.code??``)&&Rp(t,n)}});return(t,r)=>n.mutateAsync({id:e,path:t,options:r})}function Vp(e,t,n,r){let i=!!e.trim(),a=n&&t&&n.replacementText!==t?n:null;return{hasComment:i,edit:a,issue:!i&&!a?`empty`:a?.reviewerId&&a.reviewerId===r?`selfReview`:a&&!a.reviewerId?`reviewer`:null,kind:a?i?`commentAndEdit`:`editOnly`:`commentOnly`}}function Hp({projectId:e,activeFile:t,content:n,permission:r,revision:i,sourceOrderRevision:a,selection:o,save:s,saveFailureMessage:c,onError:l,onAdded:u}){let d=(0,Y.useMemo)(()=>new nf,[e]),f=(0,Y.useMemo)(()=>({active:!1}),[e]);(0,Y.useEffect)(()=>(f.active=!0,()=>{f.active=!1}),[f]);let[p,m]=(0,Y.useState)(`file`),h=zp(e,t,p,i,a),g=Bp(e),[_,v]=(0,Y.useState)(null),[b,x]=(0,Y.useState)(!1),[S,C]=(0,Y.useState)(``),[w,T]=(0,Y.useState)(null),E=(0,Y.useRef)(w);E.current=w;let[D,O]=(0,Y.useState)(null),[k,A]=(0,Y.useState)(null),[j,M]=(0,Y.useState)(!1),[ee,N]=(0,Y.useState)(!1),[P,te]=(0,Y.useState)(``),F=(0,Y.useRef)(!1),I=(0,Y.useRef)(t),L=(0,Y.useRef)(s),ne=(0,Y.useRef)(l),re=(0,Y.useRef)(u),ie=(0,Y.useRef)(D),R=(0,Y.useRef)(S);ie.current=D,R.current=S,I.current=t,L.current=s,ne.current=l,re.current=u,(0,Y.useEffect)(()=>{v(null),m(`file`),x(!1),O(null),A(null),C(``),T(null),M(!1),te(``)},[e]),(0,Y.useEffect)(()=>{x(!1),O(null),A(null),C(``),T(null),M(!1),te(``)},[t]);let z=(e,r)=>{if(!t)return;te(``);let i={filePath:t,selection:{...e??o},sourceHash:sd(r??n)},a=d.getNew(t);O(a??i),C(a?.content??``),T(a?.suggestion??null),A(i),M(!!a),x(!0)},ae=e=>{C(e),D&&(e||w?d.setNew({...D,content:e,suggestion:w}):d.discardNew(D.filePath))},B=e=>{T(e),D&&(S||e?d.setNew({...D,content:S,suggestion:e}):d.discardNew(D.filePath))},oe=()=>{F.current||(x(!1),te(``))},V=()=>{F.current||(D&&d.discardNew(D.filePath),C(``),T(null),O(null),A(null),M(!1),oe())},se=()=>{!F.current&&k&&k.filePath===I.current&&(O(k),(S||w)&&d.setNew({...k,content:S,suggestion:w}),M(!1),te(``))},H=async()=>{let e=D,t=S,n=w;if(!e||F.current)return;let i=Vp(t,e.selection.selectedText,n);if(i.issue)return;let a=i.edit,o=()=>{let r=ie.current;return r?.filePath===e.filePath&&r.sourceHash===e.sourceHash&&r.selection.startOffset===e.selection.startOffset&&r.selection.endOffset===e.selection.endOffset&&R.current===t&&E.current===n};F.current=!0,N(!0),te(``);try{if(r!==`read`&&!await L.current()){o()&&te(c);return}await g(``,{method:`POST`,body:JSON.stringify({path:e.filePath,content:t.trim()||(a?y.t(`suggestions.defaultComment`):t),...e.selection,sourceHash:e.sourceHash,...a?{suggestion:a}:{}})});let i=d.getNew(e.filePath);if(i?.content===t&&JSON.stringify(i.suggestion??null)===JSON.stringify(n)&&i.sourceHash===e.sourceHash&&i.selection.startOffset===e.selection.startOffset&&i.selection.endOffset===e.selection.endOffset&&d.discardNew(e.filePath),!f.active)return;o()&&(x(!1),O(null),C(``),T(null),M(!1)),re.current()}catch(e){o()&&te(K(e))}finally{F.current=!1,N(!1)}},U=async e=>{try{await g(`/${e.id}`,{method:`PATCH`,body:JSON.stringify({resolved:!e.resolved})})}catch(e){f.active&&ne.current(K(e))}},W=async(e,t)=>(await g(`/${e.id}/replies`,{method:`POST`,body:JSON.stringify({content:t})}),!0),ce=async(e,t)=>(await g(`/${e.id}`,{method:`PATCH`,body:JSON.stringify({content:t})}),!0),le=async e=>(await g(`/${e.id}`,{method:`DELETE`}),f.active&&(v(t=>t?.id===e.id?null:t),d.discard(e.id)),!0),ue=async(e,t,n)=>(await g(`/${e.id}/replies/${t}`,{method:`PATCH`,body:JSON.stringify({content:n})}),!0),de=async(e,t)=>(await g(`/${e.id}/replies/${t}`,{method:`DELETE`}),d.discard(e.id,`edit-reply:${t}`),!0);return{commentDraftStore:d,...h,retryFileComments:h.refreshComments,retryReviewComments:h.refreshComments,commentScope:p,setCommentScope:m,focusComment:_,setFocusComment:v,commentOpen:b,openComment:z,closeComment:oe,cancelComment:V,commentDraftRestored:j,commentDraftCanRetarget:!(!D||!k||D.sourceHash===k.sourceHash&&D.selection.startOffset===k.selection.startOffset&&D.selection.endOffset===k.selection.endOffset),useCurrentCommentSelection:se,commentText:S,commentSuggestion:w,setCommentSuggestion:B,setCommentText:ae,commentSelection:D?.selection??o,commentSubmitting:ee,commentError:P,addComment:H,toggleComment:U,replyToComment:W,editComment:ce,deleteComment:le,editCommentReply:ue,deleteCommentReply:de}}function Up(e){let t=new Map;for(let n of e)for(let e of[n,...n.replies])t.has(e.authorId)||t.set(e.authorId,{authorId:e.authorId,authorUsername:e.authorUsername,authorDisplayName:e.authorDisplayName,authorAvatarStyle:e.authorAvatarStyle});return[...t.values()].sort((e,t)=>(e.authorDisplayName??e.authorUsername??``).localeCompare(t.authorDisplayName??t.authorUsername??``))}function Wp(e,t){let n=t.participantIds;return!n?.size||n.has(e.authorId)||!t.topLevelOnly&&e.replies.some(e=>n.has(e.authorId))}function Gp(e,t=`source`){return[...e].sort((e,n)=>{if(t===`time`)return Date.parse(n.createdAt)-Date.parse(e.createdAt);let r=e.sourceOrder??1/0,i=n.sourceOrder??1/0;return r===i?e.filePath.localeCompare(n.filePath,`en`,{numeric:!0})||e.startLine-n.startLine||e.startOffset-n.startOffset:r-i})}function Kp(e,t){return t.scope===`project`||e.filePath===t.activeFile}function qp(e,t){return t===`unresolved`?!e.resolved:e.resolved}function Jp(e,t){return t.some(t=>t.commentId===e.id&&t.readAt===null)}function Yp(e,t){return e.filter(e=>Kp(e,t)&&Wp(e,t)&&qp(e,t.filter)&&(!t.unreadMentionsOnly||Jp(e,t.unreadMentions)))}function Xp(e,t,n=[]){let r=new Set(n.filter(e=>!!e));return Gp(e.filter(e=>Kp(e,t)?r.has(e.id)||Wp(e,t)&&qp(e,t.filter)&&(!t.unreadMentionsOnly||Jp(e,t.unreadMentions)):!1),t.sort)}function Zp(e,t,n){let r=e.find(e=>e.id===t&&e.filePath===n&&!e.resolved);return r?[r]:[]}function Qp(e,t){return e.filter(e=>e.filePath===t)}function $p(e,t,n){return!e||e.filePath!==t||n!==t?null:e}function em(e,t,n,r,i,a){return!e||e.filePath!==t||n!==t||r!==t||!i?null:a.find(n=>n.id===e.id&&n.filePath===t)??null}function tm(e,t){if(!t)return 0;let n=e.findIndex(e=>e.id===t);return n<0?0:n+1}function nm(e,t,n){if(!e.length)return null;let r=t?e.findIndex(e=>e.id===t):-1;if(r<0)return n===1?e[0]:null;let i=r+n;return i>=0&&i<e.length?e[i]:null}function rm(e,t,n,r){let i=af(),a=Op.mentions(e),o=Ep({queryKey:a,queryFn:({signal:t})=>q(`/api/projects/${e}/mentions?unread=1&limit=100`,{signal:t})}),s=jp(o.error)?Ap:o.data?.mentions??Ap,c=(0,Y.useRef)({onError:n,onRead:r});c.current={onError:n,onRead:r};let l=(0,Y.useMemo)(()=>({active:!1,pending:new Map}),[e]);(0,Y.useEffect)(()=>(l.active=!0,()=>{l.active=!1}),[l]);let u=(0,Y.useRef)({projectId:e,revision:t}),d=async(e=!1)=>{if(!l.active)return;await i.cancelQueries({queryKey:a});let t=await o.refetch();e&&t.error&&l.active&&c.current.onError(K(t.error))};(0,Y.useEffect)(()=>{let n=u.current;u.current={projectId:e,revision:t},n.projectId===e&&n.revision!==t&&d()},[e,t]);let f=t=>{let n=t??`all`,r=l.pending.get(n);if(r)return r;let o=(async()=>{try{let n=await q(`/api/projects/${e}/mentions/${t?`${encodeURIComponent(t)}/read`:`read-all`}`,{method:`POST`});if(!l.active||(await i.cancelQueries({queryKey:a}),!l.active))return!1;i.setQueryData(a,e=>e&&{mentions:t?e.mentions.filter(e=>e.id!==t):[]});let r=Number(n.changed)||0;return(r||!t)&&c.current.onRead?.(r,!t),i.invalidateQueries({queryKey:a}),!0}catch(e){return l.active&&c.current.onError(K(e)),!1}finally{l.pending.delete(n)}})();return l.pending.set(n,o),o};return{unreadMentions:s,mentionsError:o.error?K(o.error):``,refresh:d,markMentionRead:e=>f(e),markAllMentionsRead:()=>f()}}function im({children:e}){let[t]=(0,Y.useState)(Mp);return(0,X.jsx)(of,{client:t,children:e})}function am(e){if(!e||typeof e!=`object`)return!1;let t=e;return(t.kind===`update`||t.kind===`move`||t.kind===`delete`)&&typeof t.revision==`string`}function om(e,t,n,r){let[i,a]=(0,Y.useState)(`connecting`),[o,s]=(0,Y.useState)(!1),[c,l]=(0,Y.useState)([]),[u,d]=(0,Y.useState)(null),[f,p]=(0,Y.useState)(null),[m,h]=(0,Y.useState)(``),[g,_]=(0,Y.useState)(!1),[v,y]=(0,Y.useState)(``),[b,x]=(0,Y.useState)(``),[S,C]=(0,Y.useState)([]),[w,T]=(0,Y.useState)(!1),[E,D]=(0,Y.useState)(n),[O,k]=(0,Y.useState)(null),[A,j]=(0,Y.useState)(!1),M=(0,Y.useRef)(t),ee=(0,Y.useRef)(r);M.current=t,ee.current=r,(0,Y.useEffect)(()=>{let n=e.compileStates();d(n[t]??null)},[t,e]),(0,Y.useEffect)(()=>{let t=()=>l(e.sessions()),n=()=>{s(!1),l([]),d(null),p(null),h(``),_(!1),y(``),x(``),C([])},r=({status:t})=>{a(t),t===`connected`?s(e.synced):n()},i=e=>{s(e),e&&(t(),c())},o=()=>{a(`disconnected`),n()},c=()=>{_(e.meta.get(`historyWarning`)===!0);let t=e.meta.get(`filesEvent`);am(t)&&p(t);let n=e.meta.get(`commentsRevision`);typeof n==`string`&&h(n);let r=e.meta.get(`dictionaryRevision`);typeof r==`string`&&y(r);let i=e.meta.get(`chktexSettingsRevision`);typeof i==`string`&&x(i);let a=e.compileStates();d(a[M.current]??null)},u=()=>{let t=e.compileStates();d(t[M.current]??null)};e.awareness.on(`change`,t),e.provider.on(`status`,r),e.provider.on(`sync`,i),e.provider.on(`connection-close`,o),e.provider.on(`connection-error`,o),e.meta.observe(c);let f=e.onCompileStates(u),m=e.onProtocolUpgrade(()=>{j(!0),a(`disconnected`),n()}),g=e.onFormatLeaseState(()=>C(e.formatLeaseStates())),v=()=>{if(!ee.current||e.currentPermission!==`read`)return;let t=e.hasWritableDraft,n=e.hasOtherWritableDraft;(t||n)&&k({previous:`edit`,localDraftReady:t,otherTabDraft:n})},b=e.onDraftReady(()=>{T(!0),v()}),S=e.onPermissionChanged((t,r)=>{t===`revoked`?(a(`disconnected`),n()):(D(t),t===`read`&&r!==`read`?k({previous:r,localDraftReady:e.hasWritableDraft,otherTabDraft:e.hasOtherWritableDraft}):t!==`read`&&k(null))});return t(),c(),a(e.connected?`connected`:`connecting`),s(e.synced),()=>{e.awareness.off(`change`,t),e.provider.off(`status`,r),e.provider.off(`sync`,i),e.provider.off(`connection-close`,o),e.provider.off(`connection-error`,o),e.meta.unobserve(c),f(),m(),g(),b(),S()}},[e]),(0,Y.useEffect)(()=>{e.setPermission(n),D(n),r&&n===`read`&&(e.hasWritableDraft||e.hasOtherWritableDraft)?k({previous:`edit`,localDraftReady:e.hasWritableDraft,otherTabDraft:e.hasOtherWritableDraft}):n!==`read`&&k(null)},[e,n,r]),(0,Y.useEffect)(()=>{r&&e.connect()},[e,r]);let N=O!==null;return(0,Y.useEffect)(()=>{if(!N)return;let t=()=>{if(e.currentPermission!==`read`)return;let t=e.hasWritableDraft,n=e.hasOtherWritableDraft;k(e=>!e||e.localDraftReady===t&&e.otherTabDraft===n?e:{...e,localDraftReady:t,otherTabDraft:n})};t();let n=window.setInterval(t,2e3);return()=>window.clearInterval(n)},[e,N]),{collaboration:e,status:i===`connected`&&!o?`syncing`:i,synced:i===`connected`&&o,activeSessions:c,compileState:u,setCompileState:d,formatLeaseStates:S,filesEvent:f,commentsRevision:m,historyWarning:g,dictionaryRevision:v,chktexSettingsRevision:b,localDraftReady:w,permission:E,protocolUpgradeRequired:A,reconnect:()=>{A||(a(`connecting`),s(!1),l([]),d(null),C([]),e.reconnect())},permissionDowngrade:O,dismissPermissionDowngrade:()=>k(null),discardLocalDraft:async()=>await e.discardLocalDraft()?(k(null),window.location.reload(),!0):(k(e=>e&&{...e,otherTabDraft:!0}),!1)}}var sm=new Map,cm=class{constructor(e){this.room=e,this.onmessage=null,this._onChange=t=>t.key===e&&this.onmessage!==null&&this.onmessage({data:Ni(t.newValue||``)}),Yr(this._onChange)}postMessage(e){Jr.setItem(this.room,Mi(Di(e)))}close(){Xr(this._onChange)}},lm=typeof BroadcastChannel>`u`?cm:BroadcastChannel,um=e=>pn(sm,e,()=>{let t=gn(),n=new lm(e);return n.onmessage=e=>t.forEach(t=>t(e.data,`broadcastchannel`)),{bc:n,subs:t}}),dm=(e,t)=>(um(e).subs.add(t),t),fm=(e,t)=>{let n=um(e),r=n.subs.delete(t);return r&&n.subs.size===0&&(n.bc.close(),sm.delete(e)),r},pm=(e,t,n=null)=>{let r=um(e);r.bc.postMessage(t),r.subs.forEach(e=>e(t,n))},mm=(e,t)=>{Z(e,0),ar(e,gs(t))},hm=(e,t,n)=>{Z(e,1),ar(e,us(t,n))},gm=(e,t,n)=>hm(t,n,Or(e)),_m=(e,t,n,r)=>{try{ss(t,Or(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},vm=(e,t)=>{Z(e,2),ar(e,t)},ym=_m,bm=(e,t,n,r,i)=>{let a=Q(e);switch(a){case 0:gm(e,t,n);break;case 1:_m(e,n,r,i);break;case 2:ym(e,n,r,i);break;default:throw Error(`Unknown message type`)}return a},xm=(e,t,n)=>{Q(e)===0&&n(t,jr(e))},Sm=3e4,Cm=class extends Tn{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=Ur();this.getLocalState()!==null&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&wm(this,t,`timeout`)},En(Sm/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){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:Ur()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),pi(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},wm=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:Ur()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},Tm=(e,t,n=e.states)=>{let r=t.length,i=Jn();Z(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;Z(i,r),Z(i,s),rr(i,JSON.stringify(o))}return Xn(i)},Em=(e,t,n)=>{let r=Tr(t),i=Ur(),a=[],o=[],s=[],c=[],l=Q(r);for(let t=0;t<l;t++){let t=Q(r),n=Q(r),l=JSON.parse(jr(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(pi(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},Dm=e=>ri(e,(e,t)=>`${encodeURIComponent(t)}=${encodeURIComponent(e)}`).join(`&`),Om=[];Om[0]=(e,t,n,r,i)=>{Z(e,0);let a=bm(t,e,n.doc,n);r&&a===1&&!n.synced&&(n.synced=!0)},Om[3]=(e,t,n,r,i)=>{Z(e,1),ar(e,Tm(n.awareness,Array.from(n.awareness.getStates().keys())))},Om[1]=(e,t,n,r,i)=>{Em(n.awareness,Or(t),n)},Om[2]=(e,t,n,r,i)=>{xm(t,n.doc,(e,t)=>Am(n,t))};var km=3e4,Am=(e,t)=>console.warn(`Permission denied to access ${e.url}.\n${t}`),jm=(e,t,n)=>{let r=Tr(t),i=Jn(),a=Q(r),o=e.messageHandlers[a];return o?o(i,r,e,n,a):console.error(`Unable to compute message`),i},Mm=(e,t,n)=>{t===e.ws&&(e.emit(`connection-close`,[n,e]),e.ws=null,t.close(),e.wsconnecting=!1,e.wsconnected?(e.wsconnected=!1,e.synced=!1,wm(e.awareness,Array.from(e.awareness.getStates().keys()).filter(t=>t!==e.doc.clientID),e),e.emit(`status`,[{status:`disconnected`}])):e.wsUnsuccessfulReconnects++,setTimeout(Nm,On(An(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e))},Nm=e=>{if(e.shouldConnect&&e.ws===null){let t=new e._WS(e.url,e.protocols);t.binaryType=`arraybuffer`,e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{e.wsLastMessageReceived=Ur();let r=jm(e,new Uint8Array(n.data),!0);Yn(r)>1&&t.send(Xn(r))},t.onerror=t=>{e.emit(`connection-error`,[t,e])},t.onclose=n=>{Mm(e,t,n)},t.onopen=()=>{e.wsLastMessageReceived=Ur(),e.wsconnecting=!1,e.wsconnected=!0,e.wsUnsuccessfulReconnects=0,e.emit(`status`,[{status:`connected`}]);let n=Jn();if(Z(n,0),mm(n,e.doc),t.send(Xn(n)),e.awareness.getLocalState()!==null){let n=Jn();Z(n,1),ar(n,Tm(e.awareness,[e.doc.clientID])),t.send(Xn(n))}},e.emit(`status`,[{status:`connecting`}])}},Pm=(e,t)=>{let n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&pm(e.bcChannel,t,e)},Fm=class extends wn{constructor(e,t,n,{connect:r=!0,awareness:i=new Cm(n),params:a={},protocols:o=[],WebSocketPolyfill:s=WebSocket,resyncInterval:c=-1,maxBackoffTime:l=2500,disableBc:u=!1}={}){for(super();e[e.length-1]===`/`;)e=e.slice(0,e.length-1);this.serverUrl=e,this.bcChannel=e+`/`+t,this.maxBackoffTime=l,this.params=a,this.protocols=o,this.roomname=t,this.doc=n,this._WS=s,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=Om.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,c>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){let e=Jn();Z(e,0),mm(e,n),this.ws.send(Xn(e))}},c)),this._bcSubscriber=(e,t)=>{if(t!==this){let t=jm(this,new Uint8Array(e),!1);Yn(t)>1&&pm(this.bcChannel,Xn(t),this)}},this._updateHandler=(e,t)=>{if(t!==this){let t=Jn();Z(t,0),vm(t,e),Pm(this,Xn(t))}},this.doc.on(`update`,this._updateHandler),this._awarenessUpdateHandler=({added:e,updated:t,removed:n},r)=>{let a=e.concat(t).concat(n),o=Jn();Z(o,1),ar(o,Tm(i,a)),Pm(this,Xn(o))},this._exitHandler=()=>{wm(this.awareness,[n.clientID],`app closed`)},hi&&typeof process<`u`&&process.on(`exit`,this._exitHandler),i.on(`update`,this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&km<Ur()-this.wsLastMessageReceived&&Mm(this,this.ws,null)},km/10),r&&this.connect()}get url(){let e=Dm(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(),hi&&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||=(dm(this.bcChannel,this._bcSubscriber),!0);let e=Jn();Z(e,0),mm(e,this.doc),pm(this.bcChannel,Xn(e),this);let t=Jn();Z(t,0),hm(t,this.doc),pm(this.bcChannel,Xn(t),this);let n=Jn();Z(n,3),pm(this.bcChannel,Xn(n),this);let r=Jn();Z(r,1),ar(r,Tm(this.awareness,[this.doc.clientID])),pm(this.bcChannel,Xn(r),this)}disconnectBc(){let e=Jn();Z(e,1),ar(e,Tm(this.awareness,[this.doc.clientID],new Map)),Pm(this,Xn(e)),this.bcconnected&&=(fm(this.bcChannel,this._bcSubscriber),!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&Mm(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(Nm(this),this.connectBc())}},Im=e=>Wr((t,n)=>{e.onerror=e=>n(Error(e.target.error)),e.onsuccess=e=>t(e.target.result)}),Lm=(e,t)=>Wr((n,r)=>{let i=indexedDB.open(e);i.onupgradeneeded=e=>t(e.target.result),i.onerror=e=>r(yr(e.target.error)),i.onsuccess=e=>{let t=e.target.result;t.onversionchange=()=>{t.close()},n(t)}}),Rm=e=>Im(indexedDB.deleteDatabase(e)),zm=(e,t)=>t.forEach(t=>e.createObjectStore.apply(e,t)),Bm=(e,t,n=`readwrite`)=>{let r=e.transaction(t,n);return t.map(e=>Zm(r,e))},Vm=(e,t)=>Im(e.count(t)),Hm=(e,t)=>Im(e.get(t)),Um=(e,t)=>Im(e.delete(t)),Wm=(e,t,n)=>Im(e.put(t,n)),Gm=(e,t)=>Im(e.add(t)),Km=(e,t,n)=>Im(e.getAll(t,n)),qm=(e,t,n)=>{let r=null;return Xm(e,t,e=>(r=e,!1),n).then(()=>r)},Jm=(e,t=null)=>qm(e,t,`prev`),Ym=(e,t)=>Wr((n,r)=>{e.onerror=r,e.onsuccess=async e=>{let r=e.target.result;if(r===null||await t(r)===!1)return n();r.continue()}}),Xm=(e,t,n,r=`next`)=>Ym(e.openKeyCursor(t,r),e=>n(e.key)),Zm=(e,t)=>e.objectStore(t),Qm=(e,t)=>IDBKeyRange.upperBound(e,t),$m=(e,t)=>IDBKeyRange.lowerBound(e,t),eh=`custom`,th=`updates`,nh=(e,t=()=>{},n=()=>{})=>{let[r]=Bm(e.db,[th]);return Km(r,$m(e._dbref,!1)).then(i=>{e._destroyed||(t(r),rc(e.doc,()=>{i.forEach(t=>ss(e.doc,t))},e,!1),n(r))}).then(()=>Jm(r).then(t=>{e._dbref=t+1})).then(()=>Vm(r).then(t=>{e._dbsize=t})).then(()=>r)},rh=(e,t=!0)=>nh(e).then(n=>{(t||e._dbsize>=500)&&Gm(n,us(e.doc)).then(()=>Um(n,Qm(e._dbref,!0))).then(()=>Vm(n).then(t=>{e._dbsize=t}))}),ih=class extends Tn{constructor(e,t){super(),this.doc=t,this.name=e,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=Lm(e,e=>zm(e,[[`updates`,{autoIncrement:!0}],[`custom`]])),this.whenSynced=Wr(e=>this.on(`synced`,()=>e(this))),this._db.then(e=>{this.db=e,nh(this,e=>Gm(e,us(t)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit(`synced`,[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(e,t)=>{if(this.db&&t!==this){let[t]=Bm(this.db,[th]);Gm(t,e),++this._dbsize>=500&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{rh(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},t.on(`update`,this._storeUpdate),this.destroy=this.destroy.bind(this),t.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(()=>{Rm(this.name)})}get(e){return this._db.then(t=>{let[n]=Bm(t,[eh],`readonly`);return Hm(n,e)})}set(e,t){return this._db.then(n=>{let[r]=Bm(n,[eh]);return Wm(r,t,e)})}del(e){return this._db.then(t=>{let[n]=Bm(t,[eh]);return Um(n,e)})}},ah={Sync:0,Awareness:1,QueryAwareness:3,Flush:4,Protocol:5,Maintenance:6,Permission:7,CompileStates:8,FormatLease:9},oh=[`queued`,`running`,`succeeded`,`failed`,`cleaned`],sh=[`cache`,`artifacts`];function ch(e){return typeof e==`string`&&oh.includes(e)}function lh(e){return typeof e==`string`&&sh.includes(e)}var uh=[[`#1677c8`,`#1677c833`],[`#d65745`,`#d6574533`],[`#16866a`,`#16866a33`],[`#9a58b5`,`#9a58b533`],[`#d27b18`,`#d27b1833`],[`#3f7d20`,`#3f7d2033`],[`#be3e7b`,`#be3e7b33`],[`#4964c6`,`#4964c633`],[`#8a6a14`,`#8a6a1433`],[`#087f8c`,`#087f8c33`]],{Sync:dh,Awareness:fh,Flush:ph,Protocol:mh,Maintenance:hh,Permission:gh,CompileStates:_h,FormatLease:vh}=ah,yh=6e4,bh=2592e6,xh=15e3,Sh=3e5;function Ch(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.requestedBy;return typeof t.mainFile!=`string`||typeof t.runId!=`string`||!ch(t.status)||t.status===`cleaned`&&!lh(t.cleanMode)||t.stale!==void 0&&typeof t.stale!=`boolean`||typeof t.updatedAt!=`string`||!n||typeof n.id!=`string`||typeof n.username!=`string`||typeof n.name!=`string`?null:t}function wh(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e)){let e=Ch(r);e&&e.mainFile===n&&(t[n]=e)}return t}function Th(e,t,n){return e<=n&&t<=n}function Eh(e,t,n){let r=e=>e>0&&n-e<=Sh;return{recoverable:e.some(e=>e.tabId===t||!r(e.activeAt)),otherActive:e.some(e=>e.tabId!==t&&r(e.activeAt))}}var Dh=class{projectId;user;doc=new Go;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;constructor(e,t){this.projectId=e,this.user=t;let n=window.location.protocol===`https:`?`wss:`:`ws:`;this.draftTabId=Ph(b(`texlite:collaboration-tab:${t.id}:${e}`));let 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 ih(b(`texlite:${t.id}:${e}`),this.doc),this.localDraftTransactionObserver=e=>{if(e.local){for(let[t,n]of this.doc.share)if(t.startsWith(`source:`)&&(e.changed.has(n)||e.changedParentTypes.has(n))){this.markWritableDraft();return}}},this.doc.on(`afterTransaction`,this.localDraftTransactionObserver),this.persistence.on(`synced`,()=>{this.localDraftReady=!0;for(let e of this.draftListeners)e()}),this.provider=new Fm(`${n}//${window.location.host}${x(`/api/collaboration`)}`,e,this.doc,{connect:!1,disableBc:!0,maxBackoffTime:2500}),this.awareness=this.provider.awareness;let i=this.doc.getMap(`texlite:meta`);this.metaObserver=(e,t)=>{t.origin===this.provider&&e.keysChanged.has(`compileStates`)&&(this.authoritativeCompileStates=null,this.notifyCompileStateListeners())},i.observe(this.metaObserver),this.provider.messageHandlers[ph]=(e,t)=>{let n=jr(t),r=this.flushRequests.get(n);if(!r)return;let i=Q(t)===1,a=Q(t),o=jr(t),s=Q(t),c=[];for(let e=0;e<s;e++)c.push(jr(t));if(window.clearTimeout(r.timer),this.flushRequests.delete(n),i)this.clearOwnWritableDraftMarker(r.draftGeneration),r.resolve({revision:a,persistedAt:o,ok:!0,failedPaths:[]});else{let e=Object.assign(Error(c.length?`保存失败:${c.join(`, `)}`:`源码保存到服务器磁盘失败`),{failedPaths:c});r.reject(e)}},this.provider.messageHandlers[mh]=(e,t)=>{let n=jr(t),r=this.epochStorageKey(),i=Oh(r),a=/^([0-9]+):/.exec(n)?.[1]??null,o=i?/^([0-9]+):/.exec(i)?.[1]??null:null,s=!this.epoch&&a===`3`&&o!==null&&o!==a;if((this.epoch&&this.epoch!==n||i&&i!==n)&&!s){this.provider.disconnect(),this.rejectFlushes(Error(`Collaboration state changed`));let e=n.endsWith(`:reload`)||a!==null&&a!==`3`,t=()=>{kh(r,n.replace(/:reload$/,``)),window.location.reload()};if(e)for(let e of this.protocolUpgradeListeners)e();else this.persistence.clearData().then(()=>{this.clearWritableDraftMarkers(),t()});return}this.epoch=n,kh(r,n);let c=this.provider.ws;if(!c||c.readyState!==WebSocket.OPEN)return;let l=Jn();Z(l,mh),rr(l,n),Z(l,3),c.send(Xn(l));let u=Jn();Z(u,dh),mm(u,this.doc),c.send(Xn(u));let d=Jn();Z(d,fh),ar(d,Tm(this.awareness,[this.doc.clientID])),c.send(Xn(d))},this.provider.messageHandlers[gh]=(e,t)=>{let n=jr(t),r=jr(t);if(n!==this.user.id)return;if(r===`revoked`){this.rejectFlushes(Error(`Project access revoked`)),this.provider.disconnect();for(let e of this.permissionListeners)e(`revoked`,this.permission);return}if(r!==`read`&&r!==`edit`&&r!==`owner`)return;let i=this.permission;if(this.setPermission(r),i!==r){r===`read`&&this.rejectFlushes(Error(`Project permission changed to read-only`));for(let e of this.permissionListeners)e(r,i)}},this.provider.messageHandlers[hh]=(e,t)=>{jr(t)},this.provider.messageHandlers[_h]=(e,t)=>{let n={};try{n=wh(JSON.parse(jr(t)))}catch{}this.authoritativeCompileStates=n,this.notifyCompileStateListeners()},this.provider.messageHandlers[vh]=(e,t)=>{let n=jr(t),r=jr(t),i=jr(t),a=jr(t),o=jr(t),s=jr(t);if(n===`state`){let e=Er(t)?jr(t):``,n=Er(t)?jr(t):``,r=Number(o);if(!e||!Number.isFinite(r)||r<=Date.now())this.removeFormatLeaseState(i),this.notifyFormatLeaseListeners(null);else{let t={path:i,holderUserId:e,holderName:n,expiresAt:r};this.formatLeaseStatesByPath.set(i,t);let a=this.formatLeaseExpiryTimers.get(i);a!==void 0&&window.clearTimeout(a);let o=window.setTimeout(()=>{let e=this.formatLeaseStatesByPath.get(i);!e||e.expiresAt>Date.now()||(this.removeFormatLeaseState(i),this.notifyFormatLeaseListeners(null))},Math.max(0,r-Date.now())+25);this.formatLeaseExpiryTimers.set(i,o),this.notifyFormatLeaseListeners(t)}return}let c=this.formatLeaseRequests.get(r);c&&(window.clearTimeout(c.timer),this.formatLeaseRequests.delete(r),n===`denied`?c.reject(Error(s||`Format lease request was denied`)):c.resolve({status:n,filePath:i,token:a,expiresAt:Number(o)}))},this.provider.on(`status`,({status:e})=>{e===`disconnected`&&(this.authoritativeCompileStates=null,this.notifyCompileStateListeners(),this.rejectFlushes(Error(`Collaboration connection closed`)),this.rejectFormatLeaseRequests(Error(`Collaboration connection closed`)),this.clearFormatLeaseStates())}),this.updateLocalAwareness()}connect(){this.destroyed||(this.provider.connect(),this.updateLocalAwareness())}getText(e){return this.doc.getText(`source:${e}`)}getUndoManager(e){let t=this.undoManagers.get(e);if(t)return t;let n=new sc(this.getText(e));return this.undoManagers.set(e,n),n}applyTextEdits(e,t){if(this.permission===`read`)throw Error(`Read-only collaborators cannot edit source files`);let n=this.getText(e),r=0;for(let e of t){if(!Number.isInteger(e.from)||!Number.isInteger(e.to)||e.from<r||e.to<e.from||e.to>n.length)throw RangeError(`Invalid collaborative text edits`);r=e.to}this.doc.transact(()=>{for(let e=t.length-1;e>=0;--e){let r=t[e];r.to>r.from&&n.delete(r.from,r.to-r.from),r.replacement&&n.insert(r.from,r.replacement)}})}get meta(){return this.doc.getMap(`texlite:meta`)}compileStates(){return this.authoritativeCompileStates??wh(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 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&&(await this.persistence.clearData(),this.localDraftReady=!1,this.clearWritableDraftMarkers(),!0)}get hasWritableDraft(){return Eh(this.readWritableDraftMarkers().map(({tabId:e,marker:t})=>({tabId:e,activeAt:t.activeAt})),this.draftTabId,Date.now()).recoverable}get hasOtherWritableDraft(){return Eh(this.readWritableDraftMarkers().map(({tabId:e,marker:t})=>({tabId:e,activeAt:t.activeAt})),this.draftTabId,Date.now()).otherActive}setPermission(e,t=!1){let n=this.permission;if(this.permission=e,e===`read`&&(n!==`read`&&this.rejectFlushes(Error(`Project permission changed to read-only`)),this.destroyUndoManagers(),this.clearFormatLeaseStates()),this.updateLocalAwareness(),t&&n!==e)for(let t of this.permissionListeners)t(e,n)}setActiveFile(e){this.activeFile!==e&&(this.activeFile=e,this.awareness.setLocalStateField(`cursor`,null),this.updateLocalAwareness())}sessions(){let e=[];return this.awareness.getStates().forEach((t,n)=>{let r=t?.user;r&&typeof r.id==`string`&&typeof r.name==`string`&&e.push({clientId:n,userId:r.id,username:typeof r.username==`string`?r.username:r.name,name:r.name,avatarStyle:R(r.avatarStyle)?r.avatarStyle:null,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 t.filePath==`string`?t.filePath:``,editing:!!t.cursor,local:n===this.doc.clientID})}),e.sort((e,t)=>Number(t.local)-Number(e.local)||e.name.localeCompare(t.name))}flush(){let e=this.provider.ws;if(!this.provider.synced||!e||e.readyState!==WebSocket.OPEN)return Promise.reject(Error(`Collaboration connection is unavailable`));let t=ud(),n=this.draftGeneration,r=Jn();return Z(r,ph),rr(r,t),new Promise((i,a)=>{let o=window.setTimeout(()=>{this.flushRequests.delete(t),a(Error(`Collaboration save timed out`))},5e3);this.flushRequests.set(t,{resolve:i,reject:a,timer:o,draftGeneration:n}),e.send(Xn(r))})}onFormatLeaseState(e){this.formatLeaseListeners.add(e);for(let t of this.formatLeaseStatesByPath.values())e(t);return()=>this.formatLeaseListeners.delete(e)}formatLeaseStates(){let e=Date.now();for(let[t,n]of this.formatLeaseStatesByPath)n.expiresAt<=e&&this.removeFormatLeaseState(t);return[...this.formatLeaseStatesByPath.values()]}async acquireFormatLease(e){if(this.permission===`read`)throw Error(`Formatting requires write permission`);let t=await this.requestFormatLease(`acquire`,e);if(t.status!==`grant`||!t.token||!Number.isFinite(t.expiresAt))throw Error(`Format lease was not granted`);let n=t.token,r=t.expiresAt,i=!1,a=async()=>{if(i)throw Error(`Format lease has already been released`);let t=await this.requestFormatLease(`renew`,e,n);if(t.status!==`renewed`||!Number.isFinite(t.expiresAt))throw Error(`Format lease renewal failed`);n=t.token||n,r=t.expiresAt};return{path:e,get token(){return n},get expiresAt(){return r},confirm:a,renew:a,release:async()=>{if(i)return;i=!0;let t=this.provider.ws;if(t&&t.readyState===WebSocket.OPEN)try{await this.requestFormatLease(`release`,e,n)}catch{}}}}reconnect(){this.destroyed||(this.rejectFlushes(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(Error(`Collaboration connection closed`)),this.provider.destroy(),this.persistence.destroy(),this.draftListeners.clear(),this.protocolUpgradeListeners.clear(),this.compileStateListeners.clear(),this.rejectFormatLeaseRequests(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(let e of this.undoManagers.values())e.destroy();this.undoManagers.clear()}notifyCompileStateListeners(){for(let e of this.compileStateListeners)e()}rejectFlushes(e){for(let t of this.flushRequests.values())window.clearTimeout(t.timer),t.reject(e);this.flushRequests.clear()}requestFormatLease(e,t,n=``){let r=this.provider.ws;if(!this.provider.synced||!r||r.readyState!==WebSocket.OPEN)return Promise.reject(Error(`Collaboration connection is unavailable`));let i=ud(),a=Jn();return Z(a,vh),rr(a,e),rr(a,i),rr(a,t),rr(a,n),new Promise((n,o)=>{let s=window.setTimeout(()=>{if(this.formatLeaseRequests.delete(i),e===`acquire`){let e=this.provider.ws;if(e?.readyState===WebSocket.OPEN){let n=Jn();Z(n,vh),rr(n,`cancel`),rr(n,i),rr(n,t),rr(n,``),e.send(Xn(n))}}o(Error(`Format lease request timed out`))},e===`acquire`?yh:5e3);this.formatLeaseRequests.set(i,{resolve:n,reject:o,timer:s}),r.send(Xn(a))})}rejectFormatLeaseRequests(e){for(let t of this.formatLeaseRequests.values())window.clearTimeout(t.timer),t.reject(e);this.formatLeaseRequests.clear()}clearFormatLeaseStates(){for(let e of this.formatLeaseExpiryTimers.values())window.clearTimeout(e);this.formatLeaseExpiryTimers.clear(),this.formatLeaseStatesByPath.size&&(this.formatLeaseStatesByPath.clear(),this.notifyFormatLeaseListeners(null))}removeFormatLeaseState(e){let t=this.formatLeaseExpiryTimers.get(e);t!==void 0&&window.clearTimeout(t),this.formatLeaseExpiryTimers.delete(e),this.formatLeaseStatesByPath.delete(e)}notifyFormatLeaseListeners(e){for(let t of this.formatLeaseListeners)t(e)}updateLocalAwareness(){let[e,t]=uh[Math.abs(this.doc.clientID)%uh.length],n=this.awareness.getLocalState()?.user,r=n&&Object.hasOwn(n,`avatarStyle`)?n.avatarStyle:this.user.avatarStyle;this.awareness.setLocalStateField(`user`,{id:this.user.id,username:this.user.username,name:this.user.displayName,avatarStyle:R(r)?r:null,color:e,colorLight:t,permission:this.permission,sessionId:String(this.doc.clientID)}),this.awareness.setLocalStateField(`filePath`,this.activeFile)}epochStorageKey(){return b(`texlite:collaboration-epoch:${this.user.id}:${this.projectId}`)}writableDraftStoragePrefix(){return`${b(`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(let{key:e}of this.readWritableDraftMarkers())Ah(e);this.draftMarkerPresent=!1,this.stopDraftHeartbeat(),Ah(this.writableDraftStoragePrefix().slice(0,-1))}clearOwnWritableDraftMarker(e){let t=this.readOwnWritableDraftMarker();t&&Th(t.generation,this.draftGeneration,e)&&(Ah(this.ownWritableDraftStorageKey()),this.draftMarkerPresent=!1,this.stopDraftHeartbeat())}readOwnWritableDraftMarker(){return this.readWritableDraftMarker(this.ownWritableDraftStorageKey())}readWritableDraftMarkers(){let e=this.writableDraftStoragePrefix(),t=[];for(let n of jh()){if(!n.startsWith(e))continue;let r=this.readWritableDraftMarker(n);r&&t.push({key:n,tabId:n.slice(e.length),marker:r})}return t}readWritableDraftMarker(e){let t=Oh(e);if(!t)return null;try{let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=n,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>bh)return Ah(e),null;let a=typeof r.activeAt==`number`&&Number.isFinite(r.activeAt)?Math.max(0,r.activeAt):0;return{generation:r.generation,updatedAt:r.updatedAt,activeAt:a}}catch{return Ah(e),null}}writeOwnWritableDraftMarker(e){if(!this.draftMarkerPresent&&this.draftUpdatedAt<=0)return;let t={generation:this.draftGeneration,updatedAt:this.draftUpdatedAt||Date.now(),activeAt:e?Date.now():0};kh(this.ownWritableDraftStorageKey(),JSON.stringify(t)),this.draftMarkerPresent=!0}setOwnDraftActivity(e){this.draftMarkerPresent&&(this.writeOwnWritableDraftMarker(e),e?this.startDraftHeartbeat():this.stopDraftHeartbeat())}resumeOwnDraftActivity(){let e=this.readOwnWritableDraftMarker();e?(this.draftGeneration=Math.max(this.draftGeneration,e.generation),this.draftUpdatedAt=e.updatedAt,this.draftMarkerPresent=!0,this.setOwnDraftActivity(!0)):(this.draftMarkerPresent=!1,this.stopDraftHeartbeat())}startDraftHeartbeat(){this.draftHeartbeatTimer===null&&this.draftMarkerPresent&&(this.draftHeartbeatTimer=window.setInterval(()=>{this.writeOwnWritableDraftMarker(!0)},xh))}stopDraftHeartbeat(){this.draftHeartbeatTimer!==null&&(window.clearInterval(this.draftHeartbeatTimer),this.draftHeartbeatTimer=null)}};function Oh(e){try{return window.localStorage.getItem(e)}catch{return null}}function kh(e,t){try{window.localStorage.setItem(e,t)}catch{}}function Ah(e){try{window.localStorage.removeItem(e)}catch{}}function jh(){try{let e=[];for(let t=0;t<window.localStorage.length;t+=1){let n=window.localStorage.key(t);n&&e.push(n)}return e}catch{return[]}}function Mh(e){try{return window.sessionStorage.getItem(e)}catch{return null}}function Nh(e,t){try{window.sessionStorage.setItem(e,t)}catch{}}function Ph(e){let t=Mh(e);if(t)return t;let n=ud();return Nh(e,n),n}function Fh({projectId:e,user:t,children:n}){let{t:r}=v(),i=(0,Y.useRef)(t);i.current=t;let[a,o]=(0,Y.useState)(null),s=(0,Y.useRef)(null),c=(0,Y.useRef)(null),l=t.id;return(0,Y.useEffect)(()=>{c.current=null;let t=s.current;return(!t||t.projectId!==e||t.userId!==l)&&(t?.collaboration.destroy(),t={projectId:e,userId:l,collaboration:new Dh(e,i.current)},s.current=t),o(t),()=>{let e={};c.current=e,queueMicrotask(()=>{c.current===e&&s.current===t&&(c.current=null,s.current=null,t.collaboration.destroy())})}},[e,l]),!a||a.projectId!==e||a.userId!==l?(0,X.jsx)(`div`,{className:`center-card`,role:`status`,children:r(`common.loading`)}):(0,X.jsx)(Y.Fragment,{children:n(a.collaboration)},a.collaboration.doc.guid)}var Ih=class{selection;restoreRetained;value;sharedAllowed;initialAllowed;constructor(e,t){this.selection=e,this.restoreRetained=t,this.value={selection:e,run:null,pdf:null},this.sharedAllowed=t,this.initialAllowed=t}get snapshot(){return this.value}get sharedCompletionAllowed(){return this.sharedAllowed}observeRunning(){this.sharedAllowed=!0}hasRun(e){return this.snapshot.run?.identity.runId===e&&this.snapshot.run.outcome!==null}beginCompile(){this.initialAllowed=!1,this.sharedAllowed=!0,this.value={...this.snapshot,run:null}}clean(e){this.initialAllowed=!1,e===`artifacts`&&(this.value={selection:this.selection,run:null,pdf:null})}receiveLatest(e,t){if(e.mainFile!==this.selection.mainFile||(t===`initial`?!this.initialAllowed:!this.sharedCompletionAllowed)||t===`shared`&&(!e.latestRun||this.hasRun(e.latestRun.id)))return null;let n=e.latestRun,r=n?.status===`succeeded`?`succeeded`:n?.log.includes(`Compilation was cancelled.`)?`cancelled`:n?.status===`failed`?`failed`:null;return this.receive(e,n?{identity:{...this.selection,runId:n.id},log:n.log,diagnostics:n.diagnostics,outcome:r}:null,t!==`initial`)}receiveLocal(e){return e.mainFile===this.selection.mainFile?this.receive(e,{identity:{...this.selection,runId:e.runId},log:e.log,diagnostics:e.diagnostics,outcome:e.cancelled?`cancelled`:e.ok?`succeeded`:`failed`},!0,e.skipped):null}receive(e,t,n,r=!1){let i=this.snapshot,a=t?this.hasRun(t.identity.runId):!1,o=i.pdf;if(e.pdfUrl){let t=new URL(e.pdfUrl,`https://texlite.invalid/`).searchParams.get(`run`);if(!t)throw Error(`PDF response is missing its compile run identity`);o={identity:{...this.selection,runId:t},url:e.pdfUrl,compiledAt:e.pdfCompiledAt,sizeBytes:e.pdfSizeBytes,loadingMode:e.pdfLoadingMode??`full`}}else n||(o=null);return this.initialAllowed=!1,this.value={selection:this.selection,run:t,pdf:o},{snapshot:this.snapshot,pdfChanged:i.pdf?.url!==o?.url,focusPdf:n&&t?.outcome===`succeeded`&&!!e.pdfUrl&&(r||!a)}}},Lh=(e,t)=>`${e}\0${t}`,Rh=e=>e instanceof Error&&e.name===`AbortError`;function zh(e,t){e.current&&(!t||e.current.owner===t)&&(e.current.controller.abort(),e.current=null)}function Bh(e){return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof Element&&!!e.closest(`[role="dialog"], [role="alertdialog"], [data-agent-terminal]`)}function Vh(e){let{projectId:t,project:n,mainFile:r,initialLatest:i,collaborationSynced:a,pdfVisible:o,sharedState:s}=e,{t:c}=v(),l=(0,Y.useRef)({...e,t:c});l.current={...e,t:c};let u=(0,Y.useRef)(!1),d=(0,Y.useRef)(null),f=d.current;(!f||f.selection.projectId!==t||f.selection.mainFile!==r)&&(d.current=new Ih({projectId:t,mainFile:r},!f||f.selection.projectId!==t||!f.selection.mainFile));let p=d.current,[m,h]=(0,Y.useState)(p.snapshot),[g,_]=(0,Y.useState)(null),[y,b]=(0,Y.useState)(null),[x,S]=(0,Y.useState)([]),[C,w]=(0,Y.useState)(null),[T,E]=(0,Y.useState)(!1),[D,O]=(0,Y.useState)(null),[k,A]=(0,Y.useState)(()=>new Set),[j,M]=(0,Y.useState)(()=>new Set),[ee,N]=(0,Y.useState)(``),P=(0,Y.useRef)(null),te=(0,Y.useRef)(null),F=(0,Y.useRef)(null),I=(0,Y.useRef)(null),L=(0,Y.useRef)(null),ne=(0,Y.useRef)(new Map),re=(0,Y.useRef)(new Map),ie=(0,Y.useRef)(new Set),R=(0,Y.useRef)({projectId:t,promise:i});R.current.projectId!==t&&(R.current={projectId:t,promise:i});let z=(0,Y.useRef)(null),ae=(0,Y.useRef)(null),B=(0,Y.useRef)(()=>void 0),oe=()=>l.current.getCurrentMainFile?.()||d.current.selection.mainFile,V=(e,t)=>u.current&&!t?.aborted&&d.current===e&&oe()===e.selection.mainFile,se=Lh(t,r),H=m.selection===p.selection,U=k.has(se),W=D===p,ce=e=>{for(let t of[P,te,F,I])zh(t,e);for(let t of ie.current)t.owner===e&&(t.controller.abort(),ie.current.delete(t));_(t=>t?.owner===e?null:t),b(t=>t?.owner===e?null:t),E(!1)},le=()=>{ae.current=null,z.current=null,S([]),w(null),E(!1),N(``),l.current.onPdfChanged()},ue=async(e,t)=>{if(!V(e))return;let n=t??{owner:e,controller:new AbortController};t||(zh(F),F.current=n);let r=e.snapshot.pdf?.url,i=()=>V(e,n.controller.signal)&&e.snapshot.pdf?.url===r;try{let t=await q(`/api/projects/${e.selection.projectId}/compile/artifacts?mainFile=${encodeURIComponent(e.selection.mainFile)}`,{signal:n.controller.signal});i()&&(S(t.artifacts),w(null))}catch(e){!Rh(e)&&i()&&(S([]),w(null))}finally{F.current===n&&(F.current=null)}},de=()=>{let e=ae.current;e&&(ae.current=null,V(e.owner)&&e.owner.snapshot.pdf?.url===e.url&&ue(e.owner))},fe=e=>{let t=e.snapshot.pdf?.url;t&&(ae.current={owner:e,url:t},(!l.current.pdfVisible||z.current?.owner===e&&z.current.url===t)&&de())},pe=e=>{V(p)&&p.snapshot.pdf?.url===e&&(z.current={owner:p,url:e},ae.current?.owner===p&&ae.current.url===e&&de())},me=(e,t)=>!t||!V(e)?!1:(h(t.snapshot),t.pdfChanged&&l.current.onPdfChanged(),t.focusPdf&&l.current.onCompileSuccess(),!0),he=(e,t)=>{ce(e),ae.current=null,e.clean(t),h(e.snapshot),t===`artifacts`&&(le(),l.current.onPreviewTab(`pdf`)),N(l.current.t(t===`cache`?`editor.cleanCacheComplete`:`editor.cleanArtifactsComplete`))};(0,Y.useEffect)(()=>(u.current=!0,()=>{u.current=!1;for(let e of[P,te,F,I,L])zh(e);for(let e of[...ie.current,...re.current.values(),...ne.current.values()])e.controller.abort();ie.current.clear(),re.current.clear(),ne.current.clear()}),[]),(0,Y.useEffect)(()=>{o||de()},[o]),(0,Y.useEffect)(()=>{h(p.snapshot),le();for(let e of[re.current,ne.current])for(let[n,r]of e)r.owner.selection.projectId!==t&&(r.controller.abort(),e.delete(n));let e=Lh(t,``),n=t=>{let n=new Set([...t].filter(t=>t.startsWith(e)));return n.size===t.size?t:n};if(A(n),M(n),L.current?.owner!==p&&zh(L),!r)return;if(!p.restoreRetained){l.current.onPreviewTab(`pdf`);let e={owner:p,controller:new AbortController};return l.current.loadOutline(e.controller.signal,r).catch(()=>void 0),()=>{e.controller.abort(),ce(p)}}let i={owner:p,controller:new AbortController};P.current=i,_(i);let a=null,o,s=()=>(o=l.current.sharedState,q(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(r)}`,{signal:i.controller.signal})),c=R.current.promise;return R.current.promise=null,(c?c.then(e=>V(p,i.controller.signal)?e.mainFile===r?e:s():null,()=>V(p,i.controller.signal)?s():null):s()).then(e=>{if(e&&V(p,i.controller.signal)&&me(p,p.receiveLatest(e,`initial`))){if(e.latestRun?.requestedBy&&(e.latestRun.status===`queued`||e.latestRun.status===`running`)){let t={mainFile:r,runId:e.latestRun.id,status:e.latestRun.status,requestedBy:e.latestRun.requestedBy,updatedAt:new Date().toISOString()};l.current.onSharedState(e=>!V(p,i.controller.signal)||e?.mainFile===r&&(e!==o||e.runId===t.runId&&(e.status!==`queued`||t.status===`queued`))?e:t)}e.pdfUrl&&l.current.onPreviewTab(`pdf`)}}).catch(e=>{!Rh(e)&&V(p,i.controller.signal)&&l.current.onError(K(e))}).finally(()=>{P.current===i&&(P.current=null),_(e=>e===i?null:e),V(p,i.controller.signal)&&(ie.current.add(i),a=window.setTimeout(()=>{V(p,i.controller.signal)?Promise.all([ue(p,i),l.current.loadOutline(i.controller.signal,r).catch(()=>void 0)]).finally(()=>ie.current.delete(i)):ie.current.delete(i)},0))}),()=>{a!==null&&window.clearTimeout(a),i.controller.abort(),ce(p)}},[p]),(0,Y.useEffect)(()=>{s&&s.mainFile===r&&s.status===`cleaned`&&s.cleanMode&&he(p,s.cleanMode)},[p,s?.runId,s?.status,s?.cleanMode,s?.mainFile]),(0,Y.useEffect)(()=>{s?.mainFile===r&&(s.status===`queued`||s.status===`running`)?p.observeRunning():M(e=>{if(!e.has(se))return e;let t=new Set(e);return t.delete(se),t})},[p,s?.mainFile,s?.status,s?.runId]),(0,Y.useEffect)(()=>{if(!s||s.mainFile!==r||s.status!==`succeeded`&&s.status!==`failed`||P.current?.owner===p||L.current?.owner===p||W||U||!p.sharedCompletionAllowed||p.hasRun(s.runId))return;let e={owner:p,controller:new AbortController};return zh(te),zh(I),E(!1),te.current=e,b(e),q(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(r)}`,{signal:e.controller.signal}).then(t=>{V(p,e.controller.signal)&&t.latestRun?.id===s.runId&&me(p,p.receiveLatest(t,`shared`))&&(s.status===`succeeded`&&s.stale&&N(l.current.t(`editor.compileSnapshotStale`)),s.status===`succeeded`&&t.pdfUrl?(l.current.onPreviewTab(`pdf`),fe(p)):s.status===`failed`&&l.current.onPreviewTab(t.latestRun.diagnostics.errors.length?`errors`:`log`))}).catch(t=>{!Rh(t)&&V(p,e.controller.signal)&&l.current.onError(K(t))}).finally(()=>{te.current===e&&(te.current=null),b(t=>t===e?null:t)}),()=>{e.controller.abort(),te.current===e&&(te.current=null)}},[p,s?.runId,s?.status,s?.mainFile,s?.stale,U,g,W]);let ge=async()=>{if(!n||n.permission===`read`||!a)return;let e=l.current.resolveCompileMainFile?.()||oe(),r=Lh(t,e),i=l.current.sharedState;if(!e||re.current.has(r)||i?.mainFile===e&&(i.status===`queued`||i.status===`running`))return;let o=d.current;o.selection.mainFile!==e&&(ce(o),o=new Ih({projectId:t,mainFile:e},!1),d.current=o,le()),ce(o),N(``),l.current.onCompileStart(),l.current.onPreviewTab(o.snapshot.pdf?`pdf`:`log`);let s={owner:o,controller:new AbortController};re.current.set(r,s),A(e=>new Set([...e,r]));try{if(!await l.current.save()||!V(o,s.controller.signal))return;o.beginCompile(),h(o.snapshot);let n=await q(`/api/projects/${t}/compile`,{method:`POST`,signal:s.controller.signal,body:JSON.stringify({mainFile:e})});if(!V(o,s.controller.signal)||!me(o,o.receiveLocal(n)))return;n.cancelled&&N(l.current.t(`compileControls.cancelled`)),n.skipped&&N(l.current.t(`editor.upToDate`)),n.ok&&n.stale&&N(l.current.t(`editor.compileSnapshotStale`)),n.pdfUrl?(fe(o),l.current.onPreviewTab(`pdf`)):l.current.onPreviewTab(n.diagnostics.errors.length?`errors`:`log`)}catch(e){!Rh(e)&&V(o,s.controller.signal)&&l.current.onError(K(e))}finally{re.current.get(r)===s&&(re.current.delete(r),A(e=>{let t=new Set(e);return t.delete(r),t}),M(e=>{let t=new Set(e);return t.delete(r),t}))}},_e=async()=>{if(!n||n.permission===`read`||!a||!V(p))return;let e=Lh(t,r);if(!r||ne.current.has(e))return;let i={owner:p,controller:new AbortController};ne.current.set(e,i),M(t=>new Set([...t,e]));try{!(await q(`/api/projects/${t}/compile/cancel`,{method:`POST`,signal:i.controller.signal,body:JSON.stringify({mainFile:r})})).cancelled&&V(p,i.controller.signal)&&M(t=>{let n=new Set(t);return n.delete(e),n})}catch(t){V(p,i.controller.signal)&&(M(t=>{let n=new Set(t);return n.delete(e),n}),Rh(t)||l.current.onError(K(t)))}finally{ne.current.get(e)===i&&ne.current.delete(e)}},ve=async e=>{if(!n||n.permission===`read`||!a||!V(p)||!r||L.current||re.current.has(se)||s?.mainFile===r&&(s.status===`queued`||s.status===`running`))return;let i={owner:p,controller:new AbortController},o=l.current.sharedState;L.current=i,O(p),ce(p);try{let n=await q(`/api/projects/${t}/compile/clean`,{method:`POST`,signal:i.controller.signal,body:JSON.stringify({mainFile:r,mode:e})});if(!V(p,i.controller.signal)||n.mainFile!==r)return;l.current.sharedState===o&&l.current.onSharedState(null),he(p,e)}catch(e){!Rh(e)&&V(p,i.controller.signal)&&l.current.onError(K(e))}finally{L.current===i&&(L.current=null),O(e=>e===p?null:e)}},G=async e=>{if(!e.viewable||!V(p))return;zh(I);let n={owner:p,controller:new AbortController},i=p.snapshot.pdf?.url;I.current=n,E(!0);try{let a=await q(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(r)}&path=${encodeURIComponent(e.path)}`,{signal:n.controller.signal});V(p,n.controller.signal)&&p.snapshot.pdf?.url===i&&w(a)}catch(e){!Rh(e)&&V(p,n.controller.signal)&&p.snapshot.pdf?.url===i&&l.current.onError(K(e))}finally{I.current===n&&(I.current=null,E(!1))}};B.current=()=>void ge(),(0,Y.useEffect)(()=>{if(!ee)return;let e=window.setTimeout(()=>N(``),3e3);return()=>window.clearTimeout(e)},[ee,p]),(0,Y.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&e.key.toLocaleLowerCase()===`s`&&(e.preventDefault(),!Bh(e.target)&&(e.stopPropagation(),e.repeat||B.current()))};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[]);let ye=H?m:null;return{pdfUrl:ye?.pdf?.url??``,pdfCompiledAt:ye?.pdf?.compiledAt??null,pdfSizeBytes:ye?.pdf?.sizeBytes??null,pdfLoadingMode:ye?.pdf?.loadingMode??`full`,pdfLoading:g?.owner===p&&!g.controller.signal.aborted||y?.owner===p&&!y.controller.signal.aborted,compileLog:ye?.run?.log??``,compileDiagnostics:ye?.run?.diagnostics??null,compileOutcome:ye?.run?.outcome??null,artifacts:H?x:[],artifactPreview:H?C:null,artifactLoading:H&&T,editorNotice:H?ee:``,localCompiling:U,cancelling:j.has(se),cleaning:W,pdfDisplayed:pe,compile:ge,cancelCompile:_e,cleanCompile:ve,viewArtifact:G}}var Hh=10485760;function Uh(e){return e instanceof Error&&e.name===`AbortError`}function Wh(e){let t=e.split(`/`).filter(Boolean);return t.pop(),t.map((e,n)=>t.slice(0,n+1).join(`/`))}function Gh(e,t){return!!(e&&t)&&(t===e||t.startsWith(`${e}/`))}function Kh(e,t){let n=ge(e);return n===`binary`||n===`other`||n===`text`&&t===!1?`unsupported`:n}function qh(e,t){let n=Kh(e.path,e.textContent);return n===`unsupported`?n:(e.size??0)>10485760||n===`text`&&(e.size??0)>t?`large`:n===`text`?`editor`:n}function Jh(e,t){return x(`/api/projects/${e}/file/raw?path=${encodeURIComponent(t)}`)}function Yh({projectId:e,site:t,activeFile:n,dirty:r,save:i,onError:a,onProject:o,onActiveFile:s,onActiveMainFile:c}){let{t:l}=v(),[u,d]=(0,Y.useState)([]),[f,p]=(0,Y.useState)(!1),[m,h]=(0,Y.useState)(``),[g,_]=(0,Y.useState)(null),[y,b]=(0,Y.useState)(!1),[x,S]=(0,Y.useState)(!1),[C,w]=(0,Y.useState)(``),[T,E]=(0,Y.useState)(``),[D,O]=(0,Y.useState)(null),[k,A]=(0,Y.useState)(``),[j,M]=(0,Y.useState)(new Set),[ee,N]=(0,Y.useState)(null),[P,te]=(0,Y.useState)(``),[F,I]=(0,Y.useState)(``),[L,ne]=(0,Y.useState)(null),[re,ie]=(0,Y.useState)(!1),[R,z]=(0,Y.useState)(null),[ae,B]=(0,Y.useState)(!1),[oe,V]=(0,Y.useState)(null),se=(0,Y.useRef)(!1),H=(0,Y.useRef)(null),U=(0,Y.useRef)(null),W=(0,Y.useRef)(null),ce=async(t={})=>{U.current?.abort(),U.current=null;let n=t.signal?null:new AbortController;n&&(U.current=n);try{let r=await q(`/api/projects/${e}/files`,{signal:t.signal??n?.signal});return(!t.isCurrent||t.isCurrent())&&d(r.files),r.files}catch(e){if(!Uh(e))throw e;return}finally{n&&U.current===n&&(U.current=null)}},le=async()=>{if(m.trim()&&!m.trim().endsWith(`/`)){E(``);try{await q(`/api/projects/${e}/file`,{method:`POST`,body:JSON.stringify({path:m,content:``})});let t=(await ce())?.find(e=>e.path===m);t&&await he(t),O(null),M(e=>new Set([...e,...Wh(m)])),p(!1),h(``)}catch(e){E(K(e))}}},ue=async()=>{if(!C.trim())return;E(``);let t=D?`${D}/${C.trim()}`:C.trim();try{let n=await q(`/api/projects/${e}/folders`,{method:`POST`,body:JSON.stringify({path:t})});await ce(),M(e=>new Set([...e,...Wh(n.path),n.path])),O(n.path),S(!1),w(``)}catch(e){E(K(e))}},de=async(n,r=new Set,i=D)=>{if(!n.length||se.current)return;let a=t.maxUploadSizeMB;if(n.find(e=>e.size>a*1024*1024)){V({kind:`error`,message:l(`errors.fileTooLarge`,{size:a})});return}let o=i??``,s=n.map(e=>o?`${o}/${e.name}`:e.name),c=new Map;for(let e of s)c.set(e,(c.get(e)??0)+1);let d=[...c.entries()].filter(([,e])=>e>1).map(([e])=>e);if(d.length){V({kind:`error`,message:l(`errors.duplicateUploadNames`,{files:d.join(`, `)})});return}let f=new Set(u.map(e=>e.path)),p=[...new Set(s.filter(e=>f.has(e)&&!r.has(e)))];if(p.length){V(null),z({files:n,directory:o,collisions:p});return}z(null),H.current!==null&&window.clearTimeout(H.current),H.current=null,V(null),se.current=!0,B(!0);let m=0;try{let i=new URLSearchParams;o&&i.set(`directory`,o);let a=``;for(let[t,c]of n.entries()){let l=s[t];i.delete(`overwrite`),r.has(l)&&i.set(`overwrite`,`1`);let u=i.toString()?`?${i.toString()}`:``,d=new FormData;d.append(`file`,c);try{V({kind:`uploading`,fileName:c.name,current:t+1,total:n.length});let r=await q(`/api/projects/${e}/upload${u}`,{method:`POST`,body:d});m+=1,typeof r.path==`string`&&Ae(r.path)&&(a=r.path)}catch(e){if(e instanceof We&&e.status===409&&!r.has(l)&&e.code===`FILE_EXISTS`){if(V(null),t>0)try{await ce()}catch{}z({files:n.slice(t),directory:o,collisions:[l]});return}throw e}}let c;try{c=(await ce())?.find(e=>e.path===a&&Ae(e.path,e.textContent)&&(e.size??0)<=t.maxCollaborativeFileSizeMB*1024*1024)}catch(e){V({kind:`error`,message:l(`editor.uploadSucceededRefreshFailed`,{message:K(e)})});return}c&&await he(c),V({kind:`success`,count:m}),H.current=window.setTimeout(()=>{V(e=>e?.kind===`success`?null:e),H.current=null},3e3)}catch(e){try{await ce()}catch{}let t=m>0?l(`editor.uploadFailedPartial`,{count:n.length,uploaded:m,total:n.length,message:K(e)}):l(`editor.uploadFailed`,{message:K(e)});V({kind:`error`,message:t})}finally{se.current=!1,B(!1)}},fe=()=>{H.current!==null&&window.clearTimeout(H.current),H.current=null,V(null)},pe=async e=>{await de(Array.from(e.target.files??[])),e.target.value=``},me=async n=>{W.current?.abort(),W.current=null,b(!1);let r=Jh(e,n.path);if(qh(n,t.maxCollaborativeFileSizeMB*1024*1024)===`large`){let e=Ae(n.path,n.textContent)?Math.min(Hh,t.maxCollaborativeFileSizeMB*1024*1024):Hh;_({path:n.path,kind:`large`,size:n.size??0,url:r,limitBytes:e});return}let i=Kh(n.path,n.textContent);if(i!==`text`){_({path:n.path,kind:i,size:n.size??0,url:r});return}_({path:n.path,kind:i,size:n.size??0,url:r,content:``}),b(!0);let o=new AbortController;W.current=o;try{let e;try{e=await fetch(r,{signal:o.signal})}catch(e){throw Ke(e)}let t=e.headers.get(`content-type`)??``;if(!e.ok){let n=null;try{n=t.includes(`application/json`)?await e.json():await e.text()}catch{}throw new We(Be(n,e.status),e.status,qe(n))}let i=new Uint8Array(await e.arrayBuffer());if(!Ne(i)){_(e=>e?.path===n.path?{...e,kind:`unsupported`,content:void 0}:e);return}let a=new TextDecoder().decode(i);_(e=>e?.path===n.path?{...e,content:a}:e)}catch(e){Uh(e)||(_(null),a(K(e)))}finally{W.current===o&&(W.current=null,b(!1))}},he=async n=>{if(W.current?.abort(),W.current=null,b(!1),O(null),A(n.path),qh(n,t.maxCollaborativeFileSizeMB*1024*1024)!==`editor`){await me(n);return}let r=new AbortController;W.current=r;try{if(await q(`/api/projects/${e}/file?path=${encodeURIComponent(n.path)}&validate=1`,{signal:r.signal}),r.signal.aborted||W.current!==r)return;s(n.path)}catch(t){if(r.signal.aborted||W.current!==r||Uh(t))return;t instanceof We&&t.code===`FILE_CONTENT_INVALID`?(d(e=>e.map(e=>e.path===n.path?{...e,textContent:!1}:e)),_({path:n.path,kind:`unsupported`,size:n.size??0,url:Jh(e,n.path)})):a(K(t))}finally{W.current===r&&(W.current=null)}},ge=async(t,n,r)=>{if(!await i())return null;let a=await q(`/api/projects/${e}/path`,{method:`PATCH`,body:JSON.stringify({source:t.path,destinationDirectory:n,destinationName:r})}),l=e=>e===t.path?a.path:e.startsWith(`${t.path}/`)?`${a.path}${e.slice(t.path.length)}`:e;s(e=>l(e)),c(e=>l(e)),O(e=>e&&l(e)),A(e=>e&&l(e));let[u,f]=await Promise.all([q(`/api/projects/${e}/files`),q(`/api/projects/${e}`)]);return d(u.files),o(f.project),M(e=>new Set([...e,...Wh(a.path),n].filter(Boolean))),a.path};return(0,Y.useEffect)(()=>()=>{U.current?.abort(),W.current?.abort(),H.current!==null&&window.clearTimeout(H.current)},[]),(0,Y.useEffect)(()=>{W.current?.abort(),W.current=null,b(!1)},[n]),(0,Y.useEffect)(()=>{D!==null&&(W.current?.abort(),W.current=null,b(!1))},[D]),(0,Y.useEffect)(()=>{n&&A(n)},[n]),{files:u,setFiles:d,loadFiles:ce,newFileOpen:f,setNewFileOpen:p,newFilePath:m,setNewFilePath:h,resourcePreview:g,setResourcePreview:_,resourcePreviewLoading:y,setResourcePreviewLoading:b,newFolderOpen:x,setNewFolderOpen:S,newFolderName:C,setNewFolderName:w,fileDialogError:T,setFileDialogError:E,selectedFolder:D,setSelectedFolder:O,selectedFile:k,setSelectedFile:A,expandedFolders:j,setExpandedFolders:M,moveEntry:ee,setMoveEntry:N,moveName:P,setMoveName:te,moveDestination:F,setMoveDestination:I,deleteEntry:L,setDeleteEntry:ne,fileDragActive:re,setFileDragActive:ie,uploadConflict:R,setUploadConflict:z,uploadingFiles:ae,uploadFeedback:oe,dismissUploadFeedback:fe,directoryEntries:u.filter(e=>e.type===`directory`),visibleEntries:u.filter(e=>Wh(e.path).every(e=>j.has(e))),createFile:le,createFolder:ue,uploadFiles:de,upload:pe,openFile:he,movePath:async()=>{if(!ee)return;let e=P.trim();if(e){E(``);try{if(!await ge(ee,F,e))return;N(null),te(``),I(``)}catch(e){E(K(e))}}},movePathToFolder:async(e,t)=>{if(Xh(e.path)!==t&&(e.type!==`directory`||t!==e.path&&!t.startsWith(`${e.path}/`)))try{await ge(e,t,e.path.split(`/`).at(-1)??e.path)}catch(e){a(K(e))}},removePath:async()=>{if(L){E(``);try{if(r&&!await i())return;await q(`/api/projects/${e}/file?path=${encodeURIComponent(L.path)}`,{method:`DELETE`}),ne(null)}catch(e){E(K(e))}}}}}function Xh(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function Zh({active:e,harperEnabled:t=!0,projectId:n,activeFile:r,content:i,dictionaryWords:a,additionalIssues:o=[],additionalIssuesReady:s=!0}){let[c,l]=(0,Y.useState)([]),[u,d]=(0,Y.useState)(``),[f,p]=(0,Y.useState)(``),[m,h]=(0,Y.useState)(0),[g,_]=(0,Y.useState)(null),[v,y]=(0,Y.useState)(null),[b,x]=(0,Y.useState)(!1),[C,w]=(0,Y.useState)(0),T=(0,Y.useRef)(0),E=(0,Y.useRef)(!1),D=(0,Y.useRef)(!1),O=(0,Y.useRef)(i),k=(0,Y.useRef)(r),A=(0,Y.useRef)(0);O.current=i,k.current=r,D.current=b,(0,Y.useEffect)(()=>{l([]),d(``),p(``),_(null),y(null),x(!1)},[r,a,t]),(0,Y.useEffect)(()=>{y(null),x(!1)},[n]),(0,Y.useEffect)(()=>{let o=++T.current;if(!e||!r){l([]),d(``),p(``),_(null);return}if(!t||v){l([]),d(``),p(``);return}let s=i,c=r,u=!1,f=window.setTimeout(()=>{y(null),(async()=>{try{let{lintLatex:e,isHarperLintSupersededError:t}=await S(async()=>{let{lintLatex:e,isHarperLintSupersededError:t}=await import(`./spellCheck-D-tYd_ac.js`);return{lintLatex:e,isHarperLintSupersededError:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url);if(u||o!==T.current||O.current!==s||k.current!==c)return;let r;try{r=await e(n,c,s,a)}catch(e){if(t(e))return;throw e}if(u||o!==T.current||O.current!==s||k.current!==c)return;E.current=!1,x(!1),l(r),d(s),p(c),h(0),_(null)}catch(e){if(u||o!==T.current||O.current!==s||k.current!==c)return;l([]),d(``),p(``),y(e instanceof Error?e.message:String(e));let t=E.current;E.current=!1,x(t?D.current:!1)}})()},700);return()=>{u=!0,window.clearTimeout(f)}},[e,t,n,r,i,a,C,v]),(0,Y.useEffect)(()=>{if(!v||!e||!t)return;let n=!1,r=()=>{n||(n=!0,E.current=!0,y(null),w(e=>e+1))},i=window.setTimeout(r,15e3);return window.addEventListener(`online`,r,{once:!0}),()=>{window.clearTimeout(i),window.removeEventListener(`online`,r)}},[v,e,t]);let j=t&&e&&f===r&&u===i,M=(0,Y.useMemo)(()=>{if(!e)return[];let t=[...j?c:[],...o].sort((e,t)=>e.from-t.from||e.to-t.to),n=new Set;return t.filter(e=>{let t=`${e.from}:${e.to}:${e.kind}:${e.message}`;return!n.has(t)&&(n.add(t),!0)})},[e,o,j,c]),ee=(0,Y.useMemo)(()=>e&&(!t||j)&&s?{total:M.length,unique:new Set(M.map(e=>`${e.kind}:${e.word.toLocaleLowerCase(`en-US`)}`)).size}:null,[e,s,t,j,M]);return(0,Y.useEffect)(()=>{h(e=>M.length?Math.min(e,M.length-1):0)},[M]),{issues:M,jump:e?g:null,index:m,summary:ee,jumpToIssue:e=>{if(!M.length)return;let t=Math.max(0,Math.min(e,M.length-1)),n=M[t];h(t),_({from:n.from,to:n.to,nonce:++A.current})},error:e&&t&&!b?v:null,nativeFallback:e&&t&&!!v,retry:()=>{E.current=!1,y(null),x(!1),w(e=>e+1)},dismissError:()=>{E.current=!1,x(!0)}}}function Qh({active:e,projectId:t,activeFile:n,content:r}){let[i,a]=(0,Y.useState)([]),[o,s]=(0,Y.useState)(``),[c,l]=(0,Y.useState)(``),[u,d]=(0,Y.useState)(null),[f,p]=(0,Y.useState)(!1),[m,h]=(0,Y.useState)(0),g=(0,Y.useRef)(0),_=(0,Y.useRef)(r),v=(0,Y.useRef)(n);_.current=r,v.current=n,(0,Y.useEffect)(()=>{a([]),s(``),l(``),d(null),p(!1)},[t,n]),(0,Y.useEffect)(()=>{let i=++g.current;if(!e||!n){a([]),s(``),l(``);return}let o=r,c=n,u=!1,f=window.setTimeout(()=>{(async()=>{try{let{lintChktex:e,isChktexLintSupersededError:n}=await S(async()=>{let{lintChktex:e,isChktexLintSupersededError:t}=await import(`./chktex-CCcr_9m7.js`);return{lintChktex:e,isChktexLintSupersededError:t}},__vite__mapDeps([14,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url);if(u||i!==g.current||_.current!==o||v.current!==c)return;let r;try{r=await e(t,c,o)}catch(e){if(n(e))return;throw e}if(u||i!==g.current||_.current!==o||v.current!==c)return;a(r),s(o),l(c),d(null),p(!1)}catch(e){if(u||i!==g.current||_.current!==o||v.current!==c)return;a([]),s(``),l(``),d(e instanceof Error?e.message:String(e))}})()},2e3);return()=>{u=!0,window.clearTimeout(f)}},[e,t,n,r,m]);let y=e&&c===n&&o===r;return{issues:y?i:[],checked:y,error:e&&!f?u:null,retry:()=>{d(null),p(!1),h(e=>e+1)},dismissError:()=>p(!0)}}function $h(e){return e instanceof Error&&e.name===`AbortError`}function eg(e,t){return/\.tex$/i.test(e)&&/\.tex$/i.test(t)}function tg({projectId:e,mainFile:t,activeFile:n,onOpenSourceFile:r,onError:i,onShowPdf:a,onShowEditor:o}){let[s,c]=(0,Y.useState)(null),[l,u]=(0,Y.useState)(null),[d,f]=(0,Y.useState)(null),p=(0,Y.useRef)(null),m=(0,Y.useRef)(0),h=(0,Y.useRef)(n),g=(0,Y.useRef)(r),_=(0,Y.useRef)(i),v=(0,Y.useRef)(a),y=(0,Y.useRef)(o);h.current=n,g.current=r,_.current=i,v.current=a,y.current=o,(0,Y.useEffect)(()=>(p.current?.abort(),p.current=null,c(null),u(null),f(null),()=>p.current?.abort()),[e,t]);let b=(e,t,n)=>{f({path:e,line:t,column:n,nonce:++m.current}),g.current(e)},x=async(n,r,i,a={})=>{if(!eg(n,t))return;p.current?.abort();let o=new AbortController;p.current=o;try{let a=await q(`/api/projects/${e}/sync/pdf?mainFile=${encodeURIComponent(t)}&path=${encodeURIComponent(n)}&line=${r}&column=${i}`,{signal:o.signal});if(p.current!==o||!a)return;c({...a,nonce:++m.current}),v.current()}catch(e){!$h(e)&&!a.silent&&_.current(K(e))}finally{p.current===o&&(p.current=null)}},S=async(n,r,i)=>{let a=h.current;p.current?.abort();let o=new AbortController;p.current=o;try{let s=await q(`/api/projects/${e}/sync/source?mainFile=${encodeURIComponent(t)}&page=${n}&x=${r}&y=${i}`,{signal:o.signal});if(p.current!==o||h.current!==a)return;y.current(),b(s.path,s.line,s.column)}catch(e){$h(e)||_.current(K(e))}finally{p.current===o&&(p.current=null)}};return{pdfTarget:s,pdfViewport:l,sourceJump:d,setPdfViewport:u,resetPdfViewport:()=>u(null),clearPdfViewport:()=>{p.current?.abort(),p.current=null,u(null),c(null)},jumpToSource:b,syncSourceToPdf:x,syncPdfToSource:S,syncVisiblePdfToSource:()=>l?S(l.page,l.x,l.y):Promise.resolve()}}function ng(e,t,n){return b(`texlite.workspaceLayout:${encodeURIComponent(e)}:${encodeURIComponent(t)}${n?`:phone`:``}`)}function rg(e,t,n){try{let r=window.localStorage.getItem(ng(e,t,n));if(r===`editor-only`||r===`pdf-only`||!n&&r===`editor-pdf`)return r}catch{}return n?`editor-only`:`editor-pdf`}function ig(e,t){let n=ve(),[r,i]=(0,Y.useState)(()=>rg(e,t,n));return(0,Y.useEffect)(()=>{i(rg(e,t,n))},[e,t,n]),{workspaceLayout:n&&r===`editor-pdf`?`editor-only`:r,setWorkspaceLayout:r=>{let a=n&&r===`editor-pdf`?`editor-only`:r;i(a);try{window.localStorage.setItem(ng(e,t,n),a)}catch{}},phone:n}}function ag(e,t){let n=0;for(let r=t-1;r>=0&&e[r]===`\\`;--r)n+=1;return n%2==1}function og(e){let t=Pu(Fu(e));for(let e of t.matchAll(/\\documentclass(?![A-Za-z@])\s*(?:\[[^\]]*\]\s*)?\{/g))if(e.index!==void 0&&!ag(t,e.index))return!0;return!1}function sg({site:e,project:t,activeFile:n,saveStateLabel:r,editorPreferences:i,activeSessions:a,collaborationStatus:o,reconnectCollaboration:s,protocolUpgradeRequired:c,showEditor:l,filesCollapsed:u,toggleFilesPanel:d,workspaceLayout:f,changeWorkspaceLayout:p,onBack:h,onShare:g,showCitationLibrary:y,citationLibraryOpen:b,onCitationLibrary:x,onHistory:S,onGit:C,canManageGit:w,formatting:T,readOnly:E,collaborationSynced:O,onToggleComments:k,commentsOpen:A,unresolvedCommentCount:M,onToggleSettings:ee,settingsOpen:N,compileBusy:P,sharedCompiling:te,localCompiling:F,cancelling:I,onCompile:re,onCancelCompile:ie,agentTerminal:R}){let{t:z}=v(),{showExecutionReminder:ae}=m();return(0,X.jsxs)(De,{siteName:e.siteName,projectName:t.name,subtitle:(0,X.jsxs)(X.Fragment,{children:[n,` · `,r]}),onBack:h,accessory:(0,X.jsxs)(X.Fragment,{children:[i.vimMode&&(0,X.jsxs)(`span`,{className:`vim-status-badge`,title:z(`editor.vimOnHint`),children:[(0,X.jsx)(dt,{size:14}),z(`editor.vimOn`)]}),(0,X.jsx)(_e,{sessions:a,status:o}),o===`disconnected`&&!c&&(0,X.jsxs)(`div`,{className:`collaboration-recovery`,role:`status`,children:[(0,X.jsx)(`span`,{children:z(`editor.collaboration.disconnected`)}),(0,X.jsx)(`button`,{type:`button`,onClick:s,children:z(`editor.collaboration.reconnect`)})]})]}),children:[l&&(0,X.jsxs)(`button`,{className:`files-action${u?``:` active`}`,"aria-label":z(`common.files`),title:z(`common.files`),"aria-expanded":!u,onClick:d,children:[u?(0,X.jsx)(ue,{size:15}):(0,X.jsx)(je,{size:15}),(0,X.jsx)(`span`,{className:`workspace-action-label`,children:z(`common.files`)})]}),(0,X.jsx)(xe,{value:f,onChange:p,workspacePrimary:!0}),(0,X.jsxs)(`button`,{type:`button`,className:`share-action`,title:z(`projectSettings.share`),"aria-label":t.sharedMemberCount?`${z(`projectSettings.share`)} (${t.sharedMemberCount})`:z(`projectSettings.share`),onClick:g,children:[(0,X.jsx)(j,{size:15}),(0,X.jsx)(`span`,{className:`workspace-action-label`,children:z(`projectSettings.share`)}),(t.sharedMemberCount??0)>0&&(0,X.jsx)(`sup`,{className:`share-action-count`,children:t.sharedMemberCount})]}),y&&(0,X.jsxs)(`button`,{className:`citation-action${b?` active`:``}`,"aria-label":z(`citationProject.button`),title:z(`citationProject.button`),onClick:x,children:[(0,X.jsx)(_,{size:15}),(0,X.jsx)(`span`,{className:`workspace-action-label`,children:z(`citationProject.button`)})]}),(0,X.jsxs)(`button`,{type:`button`,className:`snapshots-action`,"aria-label":z(`history.projectSnapshots`),title:z(`history.projectSnapshots`),onClick:S,children:[(0,X.jsx)(pe,{size:15}),(0,X.jsx)(`span`,{className:`workspace-action-label`,children:z(`history.projectSnapshotsButton`)})]}),(0,X.jsxs)(`button`,{type:`button`,className:`comments-action${A?` active`:``}`,title:z(`editor.commentsAll`),"aria-label":M>0?`${z(`common.comments`)} (${M})`:z(`common.comments`),onClick:k,children:[(0,X.jsx)(ne,{size:15}),(0,X.jsx)(`span`,{className:`workspace-action-label`,children:z(`common.comments`)}),M>0&&(0,X.jsx)(`sup`,{className:`comments-action-count`,children:M})]}),(0,X.jsxs)(`button`,{className:`git-action`,"aria-label":z(`git.title`),title:z(w?`git.title`:`git.ownerOnly`),disabled:!w,onClick:C,children:[(0,X.jsx)(L,{size:15}),(0,X.jsx)(`span`,{className:`workspace-action-label`,children:`Git`})]}),R&&(0,X.jsxs)(`button`,{type:`button`,className:R.open?`active`:``,"aria-expanded":R.open,"aria-label":ae&&R.activeCount>0?`${z(`agents.terminal`)}: ${z(`agents.activeCount`,{count:R.activeCount})}`:z(`agents.terminal`),title:z(`agents.terminal`),onClick:R.toggle,children:[(0,X.jsx)(D,{size:15}),(0,X.jsx)(`span`,{className:`workspace-action-label`,children:z(`agents.terminal`)}),ae&&R.activeCount>0&&(0,X.jsx)(`sup`,{className:`agent-active-count`,"aria-label":z(`agents.activeCount`,{count:R.activeCount}),children:R.activeCount})]}),(0,X.jsxs)(`button`,{className:N?`active`:``,"aria-label":z(`common.settings`),title:z(`common.settings`),onClick:ee,children:[(0,X.jsx)(Me,{size:15}),(0,X.jsx)(`span`,{className:`workspace-action-label workspace-action-label-persistent`,children:z(`common.settings`)})]}),te||F?(0,X.jsxs)(`button`,{className:`compile cancel-compile`,"aria-label":z(I?`compileControls.cancelling`:`compileControls.cancel`),title:z(`compileControls.cancel`),onClick:ie,disabled:I||T||E||!O,children:[I?(0,X.jsx)(Fe,{className:`spin`,size:15}):(0,X.jsx)(V,{size:15}),(0,X.jsx)(`span`,{className:`workspace-action-label workspace-action-label-persistent`,children:z(I?`compileControls.cancelling`:`compileControls.cancel`)})]}):(0,X.jsxs)(`button`,{className:`compile`,"aria-label":z(`editor.compile`,{engine:t.engine}),title:z(`editor.compileShortcut`),onClick:re,disabled:P||T||E||!O,children:[P?(0,X.jsx)(Fe,{className:`spin`,size:15}):(0,X.jsx)(me,{size:15}),(0,X.jsxs)(`span`,{className:`workspace-action-label workspace-action-label-persistent`,children:[z(`editor.compileShort`),(0,X.jsxs)(`span`,{className:`compile-engine-label`,children:[` · `,t.engine]})]})]})]})}function cg(e,t,n){return e===`connected`?t:e===`disconnected`&&n?`editor.offlineDraft`:`editor.collaboration.${e}`}function lg({children:e,tabs:t,terminal:n}){let{t:r}=v(),i=be(),[a,o]=(0,Y.useState)(!1),s=!!n,c=(0,Y.useRef)(s),l=s&&a;return(0,Y.useLayoutEffect)(()=>{c.current&&!s&&i.current?.resize(`100%`),c.current=s},[i,s]),(0,X.jsx)(`main`,{className:`source-panel`,children:(0,X.jsxs)(Se,{orientation:`vertical`,className:`agent-editor-group`,children:[(0,X.jsx)(G,{id:`source-editor`,panelRef:i,minSize:`20%`,collapsible:!!n,collapsedSize:`0%`,onResize:e=>o(e.asPercentage===0),children:(0,X.jsxs)(`div`,{className:`source-editor-pane`,inert:l,children:[t,e]})}),n&&(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Te,{className:`agent-terminal-resizer`,"aria-label":r(`agents.resizeTerminal`)}),(0,X.jsx)(G,{id:`agent-terminal`,defaultSize:`35%`,minSize:`20%`,children:n({maximized:l,toggleMaximized:()=>{let e=i.current;e?.isCollapsed()?e.expand():e?.collapse()}})})]})]})})}function ug({direction:e,disabled:t,onClick:n}){let{t:r}=v(),[i,a]=(0,Y.useState)(!1),o=e===`pdf`?tt:ee,s=r(e===`pdf`?`editor.showInPdf`:`editor.showInSource`);return(0,X.jsx)(`button`,{type:`button`,className:`workspace-mobile-sync workspace-mobile-sync-${e}`,title:s,"aria-label":s,"aria-busy":i,disabled:t||i,onClick:async()=>{a(!0);try{await n()}finally{a(!1)}},children:i?(0,X.jsx)(Fe,{className:`spin`,size:18,"aria-hidden":`true`}):(0,X.jsx)(o,{size:18,"aria-hidden":`true`})})}var dg=(0,Y.lazy)(()=>S(()=>import(`./LatexEditor-BRPiyMbH.js`).then(e=>({default:e.LatexEditor})),__vite__mapDeps([15,2,3,4,5,8,16,7,10,17,12,1,6,9,11,13,18,19,20]),import.meta.url));function fg({project:e,activeFile:t,openTabs:n,content:r,loadedFile:i,readOnly:a,comments:o,focusComment:s,editorPreferences:c,completionIndex:l,nativeSpellCheck:u,spellCheckIssues:d,spellCheckJump:f,sourceJump:p,collaborativeText:m,collaborationAwareness:g,undoManager:_,editorNotice:y,activateTab:b,closeTab:x,handleTabKeyDown:S,updateEditorContent:C,setSelection:w,onAddComment:T,onSelectionHistory:E,onCommentClick:D,onSpellCheckReplace:O,onReferenceNavigate:A,onCursor:j,terminal:M,mobileSync:ee}){let{t:N}=v(),P=Qp(o,t),te=$p(s,t,i);return(0,X.jsx)(G,{id:`source`,minSize:`22%`,children:(0,X.jsx)(lg,{terminal:M,tabs:c.openFilesInTabs&&n.length>0&&(0,X.jsx)(`div`,{className:`editor-tabs-bar`,role:`tablist`,"aria-label":N(`editor.openFiles`),children:(0,X.jsx)(`div`,{className:`editor-tabs-scroll`,children:n.map((n,r)=>{let i=n===t,a=n===e.mainFile,o=n.split(`/`).at(-1)||n;return(0,X.jsxs)(`div`,{className:`editor-tab-item${i?` active`:``}`,role:`presentation`,children:[(0,X.jsxs)(`button`,{id:`editor-tab-${encodeURIComponent(n)}`,type:`button`,role:`tab`,"aria-selected":i,"aria-controls":`editor-source-content`,tabIndex:i?0:-1,className:`editor-tab${i?` active`:``}${a?` main-tab`:``}`,onClick:()=>b(n),onKeyDown:e=>S(e,r),title:n,children:[(0,X.jsx)(`span`,{className:`editor-tab-icon`,children:a?(0,X.jsx)(h,{size:13}):(0,X.jsx)(k,{size:13})}),(0,X.jsx)(`span`,{className:`editor-tab-title`,children:o}),a&&(0,X.jsx)(`small`,{className:`editor-tab-badge`,children:N(`editor.currentMainShort`)})]}),(0,X.jsx)(`button`,{type:`button`,className:`editor-tab-close`,title:N(`common.close`),"aria-label":`${N(`common.close`)} ${o}`,onClick:()=>x(n),children:(0,X.jsx)(V,{size:12})})]},n)})})}),children:(0,X.jsxs)(`div`,{id:`editor-source-content`,className:`editor-content-container`,children:[(0,X.jsx)(Y.Suspense,{fallback:(0,X.jsxs)(`div`,{className:`preview-empty`,children:[(0,X.jsx)(Fe,{className:`spin`,size:22}),(0,X.jsx)(`span`,{children:N(`common.loading`)})]}),children:(0,X.jsx)(dg,{value:r,filePath:t,readOnly:a,comments:P,focusComment:te,preferences:c,nativeSpellCheck:u,completionIndex:l,spellCheckIssues:d,spellCheckJump:f,jumpTo:i===t&&p?.path===t?p:null,searchRequest:0,collaboration:m?{text:m,awareness:g,undoManager:a?void 0:_}:void 0,onChange:C,onSelection:w,onAddComment:T,onSelectionHistory:E,onCommentClick:D,onSpellCheckReplace:O,onReferenceNavigate:A,onCursor:j},t)}),y&&(0,X.jsx)(`div`,{className:`editor-centered-notice`,role:`status`,"aria-live":`polite`,children:y}),ee&&(0,X.jsx)(ug,{direction:`pdf`,...ee})]})})})}function pg({children:e,showControls:t=!0}){let[n,r]=(0,Y.useState)(null),[i,a]=(0,Y.useState)(null);return(0,Y.useLayoutEffect)(()=>{if(!n||!t)return;let e=()=>{let e=n.getBoundingClientRect(),t=e.left+e.width/2,r=e.top+e.height/2;a(e=>e?.left===t&&e.top===r?e:{left:t,top:r})},r=new ResizeObserver(e);r.observe(n);let i=n.parentElement;if(i){r.observe(i);for(let e of i.children)e.hasAttribute(`data-panel`)&&r.observe(e)}return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),e(),()=>{r.disconnect(),window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[n,t]),(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Te,{className:`resize-handle sync-resize-handle`,elementRef:r,children:(0,X.jsx)(fe,{className:`resize-grip`,size:12})}),t&&i&&(0,wt.createPortal)((0,X.jsx)(`span`,{className:`sync-direction-buttons`,style:{position:`fixed`,...i},children:e}),document.body)]})}var mg=360,hg=280,gg=640,_g=()=>b(`texlite-comments-width`);function vg(){try{let e=Number(window.localStorage.getItem(_g()));if(Number.isFinite(e)&&e>=hg&&e<=gg)return e}catch{}return mg}var yg=(e,{min:t,max:n})=>Math.min(n,Math.max(t,Math.round(e)));function bg({open:e,onHost:t}){let{t:n}=v(),r=(0,Y.useId)(),i=(0,Y.useRef)(null),a=(0,Y.useRef)(null),o=(0,Y.useRef)(null),[s,c]=(0,Y.useState)(vg),l=(0,Y.useRef)(s),[u,d]=(0,Y.useState)(!1),[f,p]=(0,Y.useState)({now:s,min:hg,max:gg}),m=(0,Y.useCallback)(e=>{i.current=e,t?.(e)},[t]),h=()=>{let e=i.current,t=Number.parseFloat(getComputedStyle(e).getPropertyValue(`--comments-preview-reserve`))||0,n=Math.max(0,Math.min(gg,Math.floor(e.parentElement.getBoundingClientRect().width-t)));return{min:Math.min(hg,n),max:n}},g=e=>{l.current=e,c(e)},_=e=>{try{window.localStorage.setItem(_g(),String(Math.max(hg,e)))}catch{}};(0,Y.useEffect)(()=>{if(!e){d(!1);return}let t=i.current,n=a.current,r=()=>{let e={now:Math.round(t.getBoundingClientRect().width),...h()};p(t=>t.now===e.now&&t.min===e.min&&t.max===e.max?t:e)};r();let s=new ResizeObserver(r);return s.observe(t),s.observe(t.parentElement),()=>{s.disconnect();let e=o.current;o.current=null,e&&n.hasPointerCapture(e.pointerId)&&n.releasePointerCapture(e.pointerId)}},[e]);let y=e=>{e.button!==0||o.current||(e.preventDefault(),e.stopPropagation(),o.current={pointerId:e.pointerId,x:e.clientX,width:i.current.getBoundingClientRect().width,preferred:l.current},e.currentTarget.setPointerCapture(e.pointerId),d(!0))},b=e=>{let t=o.current;t&&t.pointerId===e.pointerId&&(e.preventDefault(),e.stopPropagation(),g(yg(t.width+e.clientX-t.x,h())))},x=(e,t=!1)=>{let n=o.current;n&&n.pointerId===e.pointerId&&(o.current=null,t?g(n.preferred):l.current!==n.preferred&&_(l.current),d(!1),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))};return(0,X.jsx)(`div`,{ref:m,id:r,className:`workspace-comments-slot`,hidden:!e,"data-resizing":u||void 0,style:{"--workspace-comments-width":`${s}px`},children:e&&(0,X.jsx)(`div`,{ref:a,className:`comments-resize-handle`,role:`separator`,tabIndex:0,"aria-orientation":`vertical`,"aria-label":n(`editor.resizeComments`),"aria-controls":r,"aria-valuemin":f.min,"aria-valuemax":f.max,"aria-valuenow":f.now,"aria-valuetext":`${f.now} px`,onPointerDown:y,onPointerMove:b,onPointerUp:x,onPointerCancel:e=>x(e,!0),onLostPointerCapture:e=>x(e,!0),onKeyDown:e=>{let t=h(),n=i.current.getBoundingClientRect().width,r=e.shiftKey?48:16,a=e.key===`ArrowLeft`?n-r:e.key===`ArrowRight`?n+r:e.key===`Home`?t.min:e.key===`End`?t.max:null;if(a===null)return;e.preventDefault(),e.stopPropagation();let o=yg(a,t);g(o),_(o)},onDoubleClick:e=>{e.preventDefault(),e.stopPropagation(),g(mg),_(mg)}})})}function xg({diagnostics:e,files:t,empty:n,tone:r,onJump:i}){let{t:a}=v(),o=r===`error`?st:oe;return e.length?(0,X.jsx)(`div`,{className:`compile-diagnostic-list compile-${r}`,children:e.map((e,n)=>{let r=Tg(e.file,t),s=!!(r&&e.line);return(0,X.jsxs)(`button`,{type:`button`,disabled:!s,className:`compile-diagnostic-row`,onClick:()=>{r&&e.line&&i(r,e.line,e.column??1)},children:[(0,X.jsx)(o,{size:15}),(0,X.jsxs)(`span`,{children:[(0,X.jsx)(`strong`,{children:e.message}),(0,X.jsxs)(`small`,{children:[e.phase,r?` · ${r}${e.line?`:${e.line}`:``}`:e.line?` · ${a(`editor.lineNumber`,{line:e.line})}`:``]})]})]},`${e.phase}-${e.file??``}-${e.line??0}-${n}`)})}):(0,X.jsxs)(`div`,{className:`compile-empty compile-${r}`,children:[(0,X.jsx)(o,{size:26}),(0,X.jsx)(`span`,{children:n})]})}function Sg({lines:e,empty:t,tone:n=`log`}){let r=n===`error`?st:n===`warning`?oe:E;return e.length?(0,X.jsx)(`pre`,{className:`compile-output compile-${n}`,children:e.join(`
|
|
17
|
-
`)}):(0,X.jsxs)(`div`,{className:`compile-empty compile-${n}`,children:[(0,X.jsx)(r,{size:26}),(0,X.jsx)(`span`,{children:t})]})}function Cg({projectId:e,mainFile:t,artifacts:n,preview:r,loading:i,onView:a}){let{t:o}=v(),s=n=>x(`/api/projects/${e}/compile/artifacts?mainFile=${encodeURIComponent(t)}&path=${encodeURIComponent(n)}&download=1`);return n.length?(0,X.jsxs)(`div`,{className:`artifact-browser`,children:[(0,X.jsx)(`div`,{className:`artifact-list`,children:n.map(e=>(0,X.jsxs)(`div`,{className:`artifact-row${r?.path===e.path?` active`:``}`,children:[(0,X.jsxs)(`button`,{type:`button`,disabled:!e.viewable,title:e.viewable?o(`editor.viewArtifact`):o(`editor.downloadToView`),onClick:()=>a(e),children:[(0,X.jsx)(ye,{path:e.path,size:14}),(0,X.jsxs)(`span`,{children:[(0,X.jsx)(`strong`,{children:e.path}),(0,X.jsx)(`small`,{children:ae(e.size,{maximumUnit:`MB`})})]})]}),(0,X.jsx)(`a`,{href:s(e.path),title:o(`editor.downloadArtifact`),"aria-label":o(`editor.downloadArtifact`),children:(0,X.jsx)(T,{size:14})})]},e.path))}),(0,X.jsx)(`div`,{className:`artifact-preview`,children:i?(0,X.jsxs)(`div`,{className:`compile-empty`,children:[(0,X.jsx)(Fe,{className:`spin`,size:24}),(0,X.jsx)(`span`,{children:o(`common.loading`)})]}):r?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`header`,{children:[(0,X.jsx)(`strong`,{children:r.path}),(0,X.jsxs)(`a`,{href:s(r.path),children:[(0,X.jsx)(T,{size:13}),o(`projects.download`)]})]}),(0,X.jsx)(`pre`,{children:r.content})]}):(0,X.jsxs)(`div`,{className:`compile-empty`,children:[(0,X.jsx)(k,{size:24}),(0,X.jsx)(`span`,{children:o(`editor.selectArtifact`)})]})})]}):(0,X.jsxs)(`div`,{className:`compile-empty`,children:[(0,X.jsx)(yt,{size:26}),(0,X.jsx)(`span`,{children:o(`editor.noArtifacts`)})]})}function wg({mainFile:e,disabled:t,cleaning:n,onCleanCache:r,onCleanArtifacts:i}){let{t:a}=v();return(0,X.jsxs)(`div`,{className:`compile-clean-panel`,children:[(0,X.jsxs)(`div`,{className:`compile-clean-intro`,children:[(0,X.jsx)(oe,{size:28}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`strong`,{children:a(`editor.cleanTitle`)}),(0,X.jsx)(`p`,{children:a(`editor.cleanDescription`,{file:e})})]})]}),(0,X.jsxs)(`div`,{className:`compile-clean-actions`,children:[(0,X.jsxs)(`article`,{children:[(0,X.jsx)(`div`,{className:`compile-clean-action-icon`,children:(0,X.jsx)(lt,{size:19})}),(0,X.jsxs)(`div`,{children:[(0,X.jsxs)(`div`,{className:`compile-clean-action-heading`,children:[(0,X.jsx)(`strong`,{children:a(`editor.cleanCache`)}),(0,X.jsx)(Pe,{className:`compile-clean-help`,content:a(`editor.cleanCacheDescription`),icon:at,size:13})]}),(0,X.jsxs)(`button`,{type:`button`,className:`compile-clean-operation`,disabled:t||n,onClick:r,children:[n?(0,X.jsx)(Fe,{className:`spin`,size:14}):(0,X.jsx)(lt,{size:14}),a(`editor.cleanCache`)]})]})]}),(0,X.jsxs)(`article`,{className:`danger`,children:[(0,X.jsx)(`div`,{className:`compile-clean-action-icon`,children:(0,X.jsx)(M,{size:19})}),(0,X.jsxs)(`div`,{children:[(0,X.jsxs)(`div`,{className:`compile-clean-action-heading`,children:[(0,X.jsx)(`strong`,{children:a(`editor.cleanArtifacts`)}),(0,X.jsx)(Pe,{className:`compile-clean-help`,content:a(`editor.cleanArtifactsDescription`),icon:at,size:13})]}),(0,X.jsxs)(`button`,{type:`button`,className:`compile-clean-operation danger`,disabled:t||n,onClick:i,children:[n?(0,X.jsx)(Fe,{className:`spin`,size:14}):(0,X.jsx)(M,{size:14}),a(`editor.cleanArtifacts`)]})]})]})]})]})}function Tg(e,t){if(!e)return null;let n=t.filter(e=>e.type===`file`).map(e=>e.path),r=e.replaceAll(`\\`,`/`).replace(/^\.\//,``);if(n.includes(r))return r;let i=n.filter(e=>r.endsWith(`/${e}`));if(i.length===1)return i[0];let a=r.split(`/`).at(-1),o=n.filter(e=>e.split(`/`).at(-1)===a);return o.length===1?o[0]:null}var Eg=(0,Y.lazy)(()=>J().then(e=>({default:e.PdfPreview})));function Dg({commentsOpen:e=!1,onCommentsHost:t,mobileSync:n=!1,projectId:r,activeMainFile:i,previewTab:a,diagnosticTab:o,pdfUrl:s,pdfLoadingMode:c,pdfLoading:l,pdfCompiledAt:u,pdfSizeBytes:d,pdfCompiledLabel:f,pdfTargetLabel:p,pdfDownloadUrl:m,pdfTarget:h,pdfViewport:g,activeFile:_,compileBusy:y,compileLog:b,compileDiagnostics:x,compileMessages:S,artifacts:C,artifactPreview:w,artifactLoading:T,cleaning:E,readOnly:D,collaborationSynced:O,workspaceLayout:k,showSyncResize:A,diagnosticCount:j,selectPreviewTab:M,changeWorkspaceLayout:ee,onSetPdfViewport:N,onResetPdfViewport:P,onPdfDisplayed:te,syncVisiblePdfToSource:F,syncCurrentSourceToPdf:I,syncPdfToSource:L,canSyncWithPdf:ne,canSyncPdfToSource:re,files:ie,jumpToSource:R,onSetCleanMode:z,viewArtifact:ae}){let{t:B}=v(),[V,se]=(0,Y.useState)(``),H=(0,Y.useRef)(``),U=e=>{H.current!==e&&(H.current=e,se(e),P(),te(e))},W=re&&!!s&&V===s;return(0,X.jsxs)(X.Fragment,{children:[A&&(0,X.jsxs)(pg,{showControls:!e,children:[(0,X.jsx)(`button`,{disabled:!s||!g||!W,title:B(re?W?`editor.showInSource`:`editor.syncTexWaitingForPdf`:`editor.syncTexOnlyForMain`),"aria-label":B(`editor.showInSource`),onClick:e=>{e.stopPropagation(),W&&F()},children:(0,X.jsx)(`span`,{"aria-hidden":!0,children:`←`})}),(0,X.jsx)(`button`,{disabled:!_||!s||!ne,title:B(ne?`editor.showInPdf`:`editor.syncTexOnlyForTex`),"aria-label":B(`editor.showInPdf`),onClick:e=>{e.stopPropagation(),_&&s&&ne&&I()},children:(0,X.jsx)(`span`,{"aria-hidden":!0,children:`→`})})]}),(0,X.jsx)(G,{id:`preview`,minSize:`22%`,children:(0,X.jsx)(`div`,{className:`workspace-preview-region`,children:(0,X.jsxs)(`div`,{className:`workspace-output-layout${e?` has-comments`:``}`,children:[n&&!e&&a===`pdf`&&(0,X.jsx)(ug,{direction:`source`,disabled:!g||!W,onClick:F}),(0,X.jsx)(bg,{open:e,onHost:t}),(0,X.jsxs)(`section`,{className:`preview-panel`,children:[(0,X.jsx)(Ce,{mainFile:i,targetLabel:p,compiledAt:u,compiledLabel:f,sizeBytes:d,downloadUrl:m,activeSurface:a,onSelect:M,diagnosticCount:j}),a===`diagnostics`&&(0,X.jsxs)(`div`,{className:`preview-subtabs`,role:`tablist`,"aria-label":B(`editor.outputTabs`),children:[(0,X.jsxs)(`button`,{role:`tab`,"aria-selected":o===`log`,className:o===`log`?`active`:``,onClick:()=>M(`log`),children:[(0,X.jsx)(ht,{size:13}),B(`editor.log`)]}),(0,X.jsxs)(`button`,{role:`tab`,"aria-selected":o===`warnings`,className:o===`warnings`?`active`:``,onClick:()=>M(`warnings`),children:[(0,X.jsx)(oe,{size:13}),B(`editor.warnings`),(0,X.jsx)(`span`,{children:S.warnings.length})]}),(0,X.jsxs)(`button`,{role:`tab`,"aria-selected":o===`errors`,className:o===`errors`?`active`:``,onClick:()=>M(`errors`),children:[(0,X.jsx)(st,{size:13}),B(`editor.errors`),(0,X.jsx)(`span`,{children:S.errors.length})]}),(0,X.jsxs)(`button`,{role:`tab`,"aria-selected":o===`artifacts`,className:o===`artifacts`?`active`:``,onClick:()=>M(`artifacts`),children:[(0,X.jsx)(yt,{size:13}),B(`editor.artifacts`),(0,X.jsx)(`span`,{children:C.length})]}),(0,X.jsxs)(`button`,{role:`tab`,"aria-selected":o===`clean`,className:o===`clean`?`active`:``,onClick:()=>M(`clean`),children:[(0,X.jsx)(lt,{size:13}),B(`editor.clean`)]})]}),(0,X.jsxs)(`div`,{className:`preview-content preview-${a} ${a===`diagnostics`?`preview-${o}`:``}`,children:[a===`pdf`&&(s?(0,X.jsx)(Y.Suspense,{fallback:(0,X.jsxs)(`div`,{className:`pdf-loading-state`,role:`status`,"aria-live":`polite`,children:[(0,X.jsx)(Fe,{className:`spin`,size:24}),(0,X.jsx)(`span`,{children:B(`editor.loadingPdf`)})]}),children:(0,X.jsx)(Eg,{url:s,loadingMode:c,target:h,compiling:y,onDisplayedUrlChange:U,onViewportLocation:(e,t,n)=>{H.current===s&&N({page:e,x:t,y:n})},onDoubleClickLocation:(e,t,n)=>{H.current===s&&W&&(N({page:e,x:t,y:n}),L(e,t,n))}})}):l?(0,X.jsxs)(`div`,{className:`pdf-loading-state`,role:`status`,"aria-live":`polite`,children:[(0,X.jsx)(Fe,{className:`spin`,size:24}),(0,X.jsx)(`span`,{children:B(`editor.loadingPdf`)})]}):(0,X.jsxs)(`div`,{className:`preview-empty preview-empty-uncompiled`,role:`status`,"aria-live":`polite`,children:[(0,X.jsx)(`span`,{className:`preview-empty-icon`,"aria-hidden":`true`,children:y?(0,X.jsx)(Fe,{className:`spin`,size:26}):(0,X.jsx)(he,{size:32})}),(0,X.jsx)(`strong`,{children:B(y?`editor.compiling`:`editor.previewEmptyTitle`)}),(0,X.jsx)(`p`,{children:B(y?`editor.previewCompilingHint`:`editor.previewHint`)})]})),a===`diagnostics`&&o===`log`&&(0,X.jsx)(Sg,{lines:b?b.split(`
|
|
18
|
-
`):[],empty:B(y?`editor.compiling`:`editor.noLog`)}),a===`diagnostics`&&o===`warnings`&&(x?(0,X.jsx)(xg,{tone:`warning`,diagnostics:x.warnings,files:ie,empty:B(`editor.noWarnings`),onJump:(e,t,n)=>{k===`pdf-only`&&ee(`editor-pdf`),R(e,t,n)}}):(0,X.jsx)(Sg,{tone:`warning`,lines:S.warnings,empty:B(`editor.noWarnings`)})),a===`diagnostics`&&o===`errors`&&(x?(0,X.jsx)(xg,{tone:`error`,diagnostics:x.errors,files:ie,empty:B(`editor.noErrors`),onJump:(e,t,n)=>{k===`pdf-only`&&ee(`editor-pdf`),R(e,t,n)}}):(0,X.jsx)(Sg,{tone:`error`,lines:S.errors,empty:B(`editor.noErrors`)})),a===`diagnostics`&&o===`artifacts`&&(0,X.jsx)(Cg,{projectId:r,mainFile:i,artifacts:C,preview:w,loading:T,onView:e=>void ae(e)}),a===`diagnostics`&&o===`clean`&&(0,X.jsx)(wg,{mainFile:i,disabled:D||!O||y,cleaning:E,onCleanCache:()=>z(`cache`),onCleanArtifacts:()=>z(`artifacts`)})]})]})]})})})]})}function Og({kind:e,onEdit:t,onDelete:n,onSuggest:r,disabled:i=!1}){let{t:a}=v(),o=(0,Y.useRef)(!1);return(0,X.jsx)(`span`,{className:`comment-actions-menu`,onClick:e=>e.stopPropagation(),children:(0,X.jsxs)(Qe,{modal:!1,children:[(0,X.jsx)(Ye,{asChild:!0,children:(0,X.jsx)(`button`,{type:`button`,disabled:i,className:`comment-actions-menu-trigger`,"aria-label":a(e===`comment`?`editor.commentActions`:`editor.replyActions`),children:(0,X.jsx)(H,{size:16,"aria-hidden":!0})})}),(0,X.jsx)(Je,{children:(0,X.jsxs)(Xe,{className:`comment-actions-menu-content`,align:`end`,sideOffset:4,collisionPadding:8,onCloseAutoFocus:e=>{o.current&&e.preventDefault(),o.current=!1},children:[(0,X.jsxs)(Ze,{onSelect:()=>{o.current=!0,t()},children:[(0,X.jsx)(u,{size:13,"aria-hidden":!0}),a(e===`comment`?`editor.editComment`:`editor.editReply`)]}),e===`comment`&&r&&(0,X.jsxs)(Ze,{onSelect:()=>{o.current=!0,r()},children:[(0,X.jsx)(c,{size:13,"aria-hidden":!0}),a(`suggestions.attach`)]}),(0,X.jsxs)(Ze,{className:`danger-text`,onSelect:()=>{o.current=!0,n()},children:[(0,X.jsx)(M,{size:13,"aria-hidden":!0}),a(e===`comment`?`editor.deleteComment`:`editor.deleteReply`)]})]})})]})})}function kg(e,t){let n=e.slice(0,t),r=/(^|[^\p{L}\p{N}_.-])@([\p{L}\p{N}_.-]*)$/u.exec(n);return r?{start:t-r[2].length-1,end:t,query:r[2]}:null}function Ag({projectId:e,value:t,onChange:n,onKeyDown:r,onFocus:i,...a}){let{t:s}=v(),c=(0,Y.useRef)(null),[l,u]=(0,Y.useState)(null),d=Ep({queryKey:Op.candidates(e),enabled:!!l,queryFn:({signal:t})=>q(`/api/projects/${e}/mention-candidates`,{signal:t})}),f=jp(d.error)?void 0:d.data?.users,[p,m]=(0,Y.useState)(0),h=(0,Y.useMemo)(()=>{if(!l||!f)return[];let e=l.query.toLocaleLowerCase();return(e?f.filter(t=>t.username.toLocaleLowerCase().includes(e)||t.displayName.toLocaleLowerCase().includes(e)):f).slice(0,8)},[f,l]),g=!!(l&&h.length),_=(e,t)=>{let n=kg(e,t);u(n),m(0),n&&!d.isFetching&&(d.isError||d.isStale)&&d.refetch()},y=e=>{if(!l)return;let r=`@${e.username} `,i=`${t.slice(0,l.start)}${r}${t.slice(l.end)}`,a=l.start+r.length;n(i),u(null),m(0),window.requestAnimationFrame(()=>{c.current?.focus(),c.current?.setSelectionRange(a,a)})},b=e=>{if(!e.nativeEvent.isComposing&&g){if(e.key===`ArrowDown`){e.preventDefault(),m(e=>(e+1)%h.length);return}if(e.key===`ArrowUp`){e.preventDefault(),m(e=>(e-1+h.length)%h.length);return}if(e.key===`Enter`&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey){e.preventDefault(),y(h[p]??h[0]);return}if(e.key===`Escape`){u(null);return}}r?.(e)};return(0,X.jsxs)(`span`,{className:`mention-textarea`,children:[(0,X.jsx)(`textarea`,{...a,ref:c,value:t,onFocus:e=>{i?.(e),_(t,e.currentTarget.selectionStart??t.length)},onClick:e=>_(t,e.currentTarget.selectionStart??t.length),onChange:e=>{let t=e.currentTarget.value;n(t),_(t,e.currentTarget.selectionStart??t.length)},onKeyDown:b}),g&&(0,X.jsx)(`span`,{className:`mention-menu`,role:`listbox`,"aria-label":s(`editor.mentionUsers`),children:h.map((e,t)=>(0,X.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":t===p,className:t===p?`active`:``,onMouseDown:e=>e.preventDefault(),onClick:()=>y(e),children:[(0,X.jsx)(o,{"aria-hidden":!0,size:13}),(0,X.jsxs)(`span`,{children:[(0,X.jsx)(`strong`,{children:e.displayName}),(0,X.jsxs)(`small`,{children:[`(`,e.username,`)`]})]})]},e.id))})]})}function jg({projectId:e,value:t,onChange:n,onSubmit:r,onCancel:i,pending:a=!1,error:o=``,label:s,editing:c=!1,originalValue:l,disabled:u=!1,autoFocus:d=!0}){let{t:f}=v(),p=(0,Y.useId)(),m=a||u,h=!!t.trim()&&(!c||l===void 0||t.trim()!==l.trim()),g=e=>{e?.preventDefault(),!m&&h&&r()};return(0,X.jsxs)(`form`,{className:`comment-reply-form${c?` comment-edit-form`:``}`,"aria-busy":a,onSubmit:e=>void g(e),onClick:e=>e.stopPropagation(),children:[(0,X.jsx)(Ag,{projectId:e,autoFocus:d,rows:c?4:3,value:t,onChange:n,disabled:m,"aria-label":s,"aria-invalid":!!o,"aria-describedby":o?p:void 0,placeholder:c?void 0:f(`editor.replyPlaceholder`),onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&!e.nativeEvent.isComposing&&(e.preventDefault(),e.stopPropagation(),g())}}),o&&(0,X.jsx)(`p`,{id:p,className:`comment-form-error`,role:`alert`,children:o}),(0,X.jsxs)(`div`,{className:`comment-form-actions`,children:[(0,X.jsx)(`button`,{type:`button`,disabled:m,onClick:i,children:f(`common.cancel`)}),c?(0,X.jsx)(Re,{type:`submit`,saving:a,disabled:u||!h,iconSize:13,children:f(`common.save`)}):(0,X.jsxs)(`button`,{className:`primary`,type:`submit`,disabled:m||!h,children:[a?(0,X.jsx)(Fe,{className:`spin`,"aria-hidden":!0,size:13}):(0,X.jsx)(Ct,{"aria-hidden":!0,size:13}),f(a?`editor.commentSending`:`editor.sendReply`)]})]})]})}var Mg=5e4,Ng=new Intl.Segmenter(void 0,{granularity:`word`}),Pg=55296,Fg=2048,Ig=63487;function Lg(e,t){if(e===t)return e?[[0,e]]:[];let n=[``],r=new Map,i=e=>{let t=[];for(let{segment:i}of Ng.segment(e)){let e=r.get(i);if(e===void 0){let t=n.length;if(t>Ig)return null;e=String.fromCharCode(t<Pg?t:t+Fg),n.push(i),r.set(i,e)}t.push(e)}return t.join(``)},a=i(e),o=i(t);return a===null||o===null?[[-1,e],[1,t]].filter(([,e])=>e!==``):Gt(a,o,{checkLines:!1,timeout:1}).map(([e,t])=>[e,Array.from(t,e=>{let t=e.charCodeAt(0);return n[t<Pg?t:t-Fg]}).join(``)])}function Rg({original:e,replacement:t}){let{t:n}=v(),[r,i]=(0,Y.useState)(!1),a=(0,Y.useMemo)(()=>Lg(e,t),[e,t]),o=!r&&a.some(([e,t])=>e===0&&t.length>192);return(0,X.jsxs)(`div`,{className:`suggestion-diff-view`,children:[(0,X.jsx)(`pre`,{className:`suggestion-diff`,"aria-label":n(`suggestions.diff`),children:a.map(([e,t],n)=>e<0?(0,X.jsx)(`del`,{children:t},n):e>0?(0,X.jsx)(`ins`,{children:t},n):(0,X.jsx)(`span`,{children:r||t.length<=192?t:n===0?`…${t.slice(-96)}`:n===a.length-1?`${t.slice(0,96)}…`:`${t.slice(0,48)}…${t.slice(-48)}`},n))}),(o||r)&&(0,X.jsx)(`button`,{type:`button`,className:`suggestion-text-action`,onClick:()=>i(!r),children:n(r?`suggestions.collapse`:`suggestions.showFull`)})]})}function zg({projectId:e,authorId:t,commentId:n,value:r,onChange:i,disabled:a=!1}){let{t:o}=v(),[s,c]=(0,Y.useState)([]),[l,u]=(0,Y.useState)(``),[d,f]=(0,Y.useState)(!1),[p,m]=(0,Y.useState)(0);return(0,Y.useEffect)(()=>{let r=new AbortController;u(``),c([]),f(!1);let i=n?`?${new URLSearchParams({commentId:n})}`:``;return q(`/api/projects/${e}/suggestion-reviewers${i}`,{signal:r.signal}).then(e=>{r.signal.aborted||(c(e.users.filter(e=>e.id!==t)),f(!0))}).catch(e=>{r.signal.aborted||u(K(e))}),()=>r.abort()},[e,t,n,p]),(0,X.jsxs)(`div`,{className:`suggestion-reviewer-picker`,children:[(0,X.jsxs)(`label`,{className:`form-field`,children:[o(`suggestions.reviewer`),(0,X.jsxs)(`select`,{value:r===t?``:r,disabled:a||s.length===0,onChange:e=>i(e.target.value),children:[(0,X.jsx)(`option`,{value:``,children:o(`suggestions.chooseReviewer`)}),s.map(e=>(0,X.jsxs)(`option`,{value:e.id,children:[e.displayName,` (@`,e.username,`)`]},e.id))]})]}),d&&s.length===0&&(0,X.jsx)(`p`,{className:`field-hint`,children:o(`suggestions.noReviewers`)}),l&&(0,X.jsxs)(`p`,{className:`comment-form-error`,role:`alert`,children:[l,` `,(0,X.jsx)(`button`,{type:`button`,disabled:a,onClick:()=>m(e=>e+1),children:o(`common.retry`)})]})]})}function Bg({projectId:e,authorId:t,commentId:n,original:r,value:i,onChange:a,disabled:o=!1,autoFocus:s=!1}){let{t:l}=v();return(0,X.jsxs)(`section`,{className:`suggestion-editor`,"aria-label":l(`suggestions.title`),children:[(0,X.jsxs)(`header`,{children:[(0,X.jsxs)(`strong`,{children:[(0,X.jsx)(c,{size:14}),l(`suggestions.title`)]}),(0,X.jsx)(`button`,{type:`button`,disabled:o,"aria-label":l(`suggestions.removeAttachment`),onClick:()=>a(null),children:(0,X.jsx)(V,{size:14})})]}),(0,X.jsx)(Vg,{original:r,replacement:i.replacementText,onChange:e=>a({...i,replacementText:e}),disabled:o,autoFocus:s}),(0,X.jsx)(zg,{projectId:e,authorId:t,commentId:n,value:i.reviewerId,disabled:o,onChange:e=>a({...i,reviewerId:e})})]})}function Vg({original:e,replacement:t,onChange:n,disabled:r=!1,autoFocus:i=!1}){let{t:a}=v();return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`label`,{className:`form-field`,children:[a(`suggestions.replacement`),(0,X.jsx)(`textarea`,{autoFocus:i,rows:4,maxLength:Mg,spellCheck:!1,disabled:r,value:t,onChange:e=>n(e.target.value)})]}),t===``&&(0,X.jsx)(`p`,{className:`field-hint`,children:a(`suggestions.deletionHint`)}),t!==e&&(0,X.jsxs)(`details`,{className:`suggestion-preview`,children:[(0,X.jsx)(`summary`,{children:a(`suggestions.preview`)}),(0,X.jsx)(Rg,{original:e,replacement:t})]})]})}function Hg(e,t){return!e.suggestion&&e.authorId===t&&!e.resolved&&!e.orphaned&&!!e.anchorSourceHash&&e.selectedText.length>0&&e.selectedText.length<=5e4}function Ug({projectId:e,ownerId:t,currentUserId:n,canEdit:r,comment:i,draftTarget:a,onCloseComposer:o}){let{t:s,i18n:c}=v(),l=Bp(e),[d,f]=(0,Y.useState)(!1),[p,m]=(0,Y.useState)(()=>a?{replacementText:a.original,reviewerId:t===n?``:t}:null),[h,_]=(0,Y.useState)(null),[y,b]=(0,Y.useState)(null),[x,S]=(0,Y.useState)(!1),C=(0,Y.useRef)(!1),[w,T]=(0,Y.useState)(``),E=i.suggestion,D=async(e,t,n)=>{if(!C.current){C.current=!0,S(!0),T(``);try{let r=await l(`/${i.id}/suggestion${e}`,{method:t,body:JSON.stringify(n)});m(null),_(null),t===`PATCH`&&r.change.kind===`suggestion`&&b(r.change.suggestion.replacementText),t===`POST`&&e===``&&o?.()}catch(e){T(K(e))}finally{C.current=!1,S(!1)}}};if(!E)return!a||!p||i.authorId!==n||i.resolved?null:(0,X.jsxs)(`div`,{className:`suggestion-new`,onClick:e=>e.stopPropagation(),children:[(0,X.jsx)(Bg,{projectId:e,authorId:n,commentId:i.id,original:a.original,value:p,disabled:x,autoFocus:!0,onChange:e=>{m(e),e||o?.()}}),w&&(0,X.jsx)(`p`,{className:`comment-form-error`,role:`alert`,children:w}),(0,X.jsxs)(`button`,{type:`button`,className:`suggestion-submit`,disabled:x||!p.reviewerId||p.reviewerId===i.authorId||p.replacementText===a.original,onClick:()=>void D(``,`POST`,{...p,sourceHash:a.sourceHash}),children:[x&&(0,X.jsx)(Fe,{size:13,className:`spin`}),s(p.replacementText===``?`suggestions.submitDeletion`:`suggestions.submit`)]})]});let k=E.status===`pending`,A=E.reviewerDisplayName??E.reviewerUsername??s(`editor.deletedUser`),j=E.reviewerId!==null&&E.reviewerId===i.authorId,M=r&&!j&&E.reviewerId===n&&E.reviewerAvailable,ee=k&&!E.applying&&i.authorId===n,N=!!(h&&h.expectedReplacementText!==E.replacementText&&h.replacementText!==E.replacementText),P=k?M?s(`suggestions.awaitingYou`):(0,X.jsx)(g,{i18nKey:`suggestions.awaiting`,values:{name:A},components:{reviewer:(0,X.jsx)(`strong`,{className:`suggestion-reviewer-name`,"data-tooltip":E.reviewerUsername?`@${E.reviewerUsername}`:void 0,"data-texlite-tooltip-always":!0})}}):s(`suggestions.${E.status}`);return(0,X.jsxs)(`section`,{className:`comment-suggestion ${E.status}`,onClick:e=>e.stopPropagation(),children:[(0,X.jsxs)(`button`,{type:`button`,className:`suggestion-toggle`,"aria-expanded":d,onClick:()=>f(!d),children:[d?(0,X.jsx)(W,{size:13}):(0,X.jsx)(O,{size:13}),(0,X.jsx)(`strong`,{children:s(`suggestions.title`)}),(0,X.jsx)(`span`,{children:P})]}),d&&(0,X.jsxs)(`div`,{className:`suggestion-details`,children:[ee&&h?(0,X.jsxs)(`section`,{className:`suggestion-editor suggestion-revision-editor`,"aria-label":s(`suggestions.edit`),children:[(0,X.jsx)(Vg,{original:E.originalText,replacement:h.replacementText,autoFocus:!0,disabled:x,onChange:e=>_({...h,replacementText:e})}),N&&(0,X.jsx)(`p`,{className:`suggestion-warning`,role:`alert`,children:s(`suggestions.updatedWhileEditing`)}),(0,X.jsxs)(`div`,{className:`suggestion-actions comment-form-actions`,children:[(0,X.jsx)(`button`,{type:`button`,disabled:x,onClick:()=>{_(null),T(``)},children:s(`common.cancel`)}),(0,X.jsx)(Re,{saving:x,iconSize:13,disabled:N||h.replacementText===E.originalText||h.replacementText===h.expectedReplacementText,onClick:()=>void D(``,`PATCH`,h),children:s(`common.save`)})]})]}):(0,X.jsx)(Rg,{original:E.originalText,replacement:E.replacementText}),k&&!E.applicable&&!E.applying&&(0,X.jsx)(`p`,{className:`suggestion-warning`,children:s(`suggestions.sourceChanged`)}),k&&(j||!E.reviewerAvailable)&&(0,X.jsx)(`p`,{className:`suggestion-warning`,children:s(j?`errors.codes.SUGGESTION_SELF_REVIEW`:`suggestions.reviewerUnavailable`)}),E.applying&&(0,X.jsx)(`p`,{className:`suggestion-warning`,children:s(`suggestions.saving`)}),!k&&(0,X.jsxs)(`p`,{className:`suggestion-decision`,children:[(0,X.jsx)(`span`,{children:(0,X.jsx)(g,{i18nKey:`suggestions.decidedBy`,values:{name:E.decidedByDisplayName??E.decidedByUsername??s(`editor.deletedUser`)},components:{reviewer:(0,X.jsx)(`strong`,{className:`suggestion-reviewer-name`,"data-tooltip":E.decidedByUsername?`@${E.decidedByUsername}`:void 0,"data-texlite-tooltip-always":!0})}})}),E.decidedAt&&(0,X.jsx)(`time`,{dateTime:E.decidedAt,children:te(E.decidedAt,c.resolvedLanguage)})]}),w&&(0,X.jsx)(`p`,{className:`comment-form-error`,role:`alert`,children:w}),k&&M&&(0,X.jsxs)(`div`,{className:`suggestion-actions`,children:[(0,X.jsxs)(`button`,{type:`button`,className:`primary`,disabled:x||!E.applicable&&!E.applying,onClick:()=>void D(`/review`,`POST`,{action:`accept`,expectedReplacementText:E.replacementText}),children:[x?(0,X.jsx)(Fe,{className:`spin`,size:13}):(0,X.jsx)(U,{size:13}),s(`suggestions.accept`)]}),(0,X.jsxs)(`button`,{type:`button`,disabled:x||E.applying,onClick:()=>void D(`/review`,`POST`,{action:`reject`,expectedReplacementText:E.replacementText}),children:[(0,X.jsx)(V,{size:13}),s(`suggestions.reject`)]})]}),ee&&!h&&(0,X.jsxs)(`div`,{className:`suggestion-revision-action`,children:[(0,X.jsxs)(`button`,{type:`button`,className:`suggestion-text-action`,disabled:x,onClick:()=>{_({replacementText:E.replacementText,expectedReplacementText:E.replacementText}),b(null),T(``)},children:[(0,X.jsx)(u,{size:12,"aria-hidden":!0}),s(`suggestions.edit`)]}),y===E.replacementText&&(0,X.jsxs)(`span`,{className:`suggestion-edit-saved`,role:`status`,children:[(0,X.jsx)(U,{size:12,"aria-hidden":!0}),s(`suggestions.saved`)]})]})]})]})}function Wg(e,t={}){let n=e.slice(0,Math.max(0,e.length-2)),r=!!(t.activeDraft||t.targetReplyId&&e.some(e=>e.id===t.targetReplyId)||n.some(e=>t.unreadReplyMentionIds?.has(e.id)||t.highlightReplyParticipants&&t.selectedParticipantIds?.has(e.authorId))),i=r||(t.expansion??!!t.current),a=i?0:n.length;return{replies:a?e.slice(-2):e,hiddenCount:a,expanded:i,canToggle:n.length>0&&!r}}var Gg=1100;function Kg(e){let t=()=>{};if(!e||window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches)return t;let n=e.closest(`.comments`)??e.parentElement,r=e.getBoundingClientRect(),i=e.closest(`.context-panel`)?.getBoundingClientRect(),a=Math.max(0,r.left,i?.left??0),o=Math.max(0,r.top,i?.top??0),s=Math.min(window.innerWidth,r.right,i?.right??window.innerWidth)-a,c=Math.min(180,Math.min(window.innerHeight,r.bottom,i?.bottom??window.innerHeight)-o);if(!n||s<=0||c<=0)return t;let l=!1;return()=>{if(l||!n.isConnected||window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches)return;l=!0;let e=document.createElement(`div`);e.className=`comment-paper-shred`,e.setAttribute(`aria-hidden`,`true`),e.inert=!0,Object.assign(e.style,{left:`${a}px`,top:`${o}px`,width:`${s}px`,height:`${c}px`}),e.style.setProperty(`--shred-duration`,`${Gg}ms`),e.style.setProperty(`--shred-height`,`${c}px`);let t=Math.min(12,Math.max(8,Math.round(s/22))),r=c<96?1:2;for(let n=0;n<t*r;n++){let i=document.createElement(`span`),a=n%t,o=Math.floor(n/t),s=a/(t-1)*2-1,l=n*37;i.style.left=`${a/t*100}%`,i.style.top=`${o/r*100}%`,i.style.width=`${100/t}%`,i.style.height=`${c/r}px`,i.style.setProperty(`--shred-x`,`${s*14+l%7-3}px`),i.style.setProperty(`--shred-y`,`${48+o*16+l%31}px`),i.style.setProperty(`--shred-angle`,`${s*12+l%13-6}deg`),i.style.setProperty(`--shred-flip`,`${(n%2?1:-1)*(18+l%23)}deg`),i.style.setProperty(`--shred-line-offset`,`${-o*c/r}px`),i.style.animationDuration=`${780+l%4*25}ms`,i.style.animationDelay=`${80+a*7+o*35+l%3*9}ms`,e.append(i)}let i=()=>{window.clearTimeout(d),u.disconnect(),window.removeEventListener(`resize`,i),e.remove()},u=new MutationObserver(()=>{n.isConnected||i()}),d=window.setTimeout(i,1300);e.addEventListener(`animationend`,t=>{t.target===e&&!t.pseudoElement&&i()}),window.addEventListener(`resize`,i),u.observe(document.body,{childList:!0,subtree:!0}),document.body.append(e)}}var qg=e=>`${e.displayName?.trim()||e.username} (@${e.username})`;function Jg({users:e,value:t,onChange:n,disabled:r=!1}){let{t:i}=v(),a=(0,Y.useId)(),[o,s]=(0,Y.useState)(``),[c,l]=(0,Y.useState)(!1),[u,d]=(0,Y.useState)(0),f=(0,Y.useRef)(null),p=(0,Y.useRef)(null),m=(0,Y.useRef)(null),h=e.find(e=>e.id===t),g=h?``:o.trim().replace(/^@/,``).toLowerCase(),_=g?e.filter(e=>e.username.toLowerCase().includes(g)||(e.displayName??``).toLowerCase().includes(g)):e,y=Math.min(u,Math.max(0,_.length-1)),b=c&&!r;(0,Y.useEffect)(()=>{b&&m.current?.querySelector(`[data-index="${y}"]`)?.scrollIntoView?.({block:`nearest`})},[y,b,o]);let x=e=>{let t=_[e];t&&!r&&(n(t.id),s(``),l(!1))},S=()=>{d(Math.max(0,_.findIndex(e=>e.id===t))),l(!0)},C=`${a}-user`;return(0,X.jsxs)(`div`,{className:`share-user-picker`,children:[(0,X.jsx)(`label`,{htmlFor:C,children:i(`common.user`)}),(0,X.jsxs)(re,{open:b,onOpenChange:l,children:[(0,X.jsx)(I,{asChild:!0,children:(0,X.jsxs)(`div`,{className:`share-user-search`,ref:p,onClick:()=>{r||(f.current?.focus(),S())},children:[(0,X.jsx)(`input`,{id:C,ref:f,role:`combobox`,value:h?qg(h):o,disabled:r,placeholder:i(`projectSettings.searchUsersPlaceholder`),autoComplete:`off`,spellCheck:!1,"aria-autocomplete":`list`,"aria-expanded":b,"aria-controls":b?`${a}-list`:void 0,"aria-activedescendant":b&&_[y]?`${a}-user-${_[y].id}`:void 0,onClick:e=>{h&&e.currentTarget.select()},onFocus:e=>{S(),h&&e.currentTarget.select()},onChange:e=>{s(e.target.value),n(``),d(0),l(!0)},onKeyDown:e=>{if(!e.nativeEvent.isComposing){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),l(!0);let n=e.key===`ArrowDown`?1:-1;if(b)d(e=>_.length?(e+n+_.length)%_.length:0);else{let e=_.findIndex(e=>e.id===t);d(e>=0?e:n===1?0:Math.max(0,_.length-1))}}else e.key===`Enter`?(e.preventDefault(),b&&x(y)):e.key===`Escape`&&b&&(e.preventDefault(),e.stopPropagation(),l(!1))}}}),(0,X.jsx)(W,{className:`share-user-chevron`,size:14,"aria-hidden":!0})]})}),(0,X.jsx)(B,{container:f.current?.closest(`[role="dialog"]`),children:(0,X.jsxs)(N,{className:`share-user-popover`,"aria-label":i(`projectSettings.chooseUser`),align:`start`,side:`bottom`,sideOffset:5,collisionPadding:12,avoidCollisions:!1,collisionBoundary:f.current?.closest(`[role="dialog"]`)??void 0,onOpenAutoFocus:e=>e.preventDefault(),onCloseAutoFocus:e=>e.preventDefault(),onInteractOutside:e=>{p.current?.contains(e.target)&&e.preventDefault()},onEscapeKeyDown:e=>{e.preventDefault(),e.stopPropagation(),l(!1)},children:[(0,X.jsx)(`div`,{id:`${a}-list`,ref:m,role:`listbox`,"aria-label":i(`projectSettings.chooseUser`),children:_.map((e,n)=>(0,X.jsxs)(`button`,{type:`button`,role:`option`,tabIndex:-1,id:`${a}-user-${e.id}`,"data-index":n,"data-active":n===y||void 0,"aria-selected":e.id===t,onMouseDown:e=>e.preventDefault(),onMouseMove:()=>d(n),onClick:()=>x(n),children:[(0,X.jsxs)(`span`,{children:[(0,X.jsx)(`strong`,{children:e.displayName?.trim()||e.username}),(0,X.jsxs)(`small`,{children:[`@`,e.username]})]}),e.id===t&&(0,X.jsx)(U,{size:14,"aria-hidden":!0})]},e.id))}),_.length===0&&(0,X.jsx)(`p`,{className:`share-user-no-results`,role:`status`,children:i(e.length?`projectSettings.noMatchingUsers`:`projectSettings.noAvailableUsers`)})]})})]})]})}function Yg({projectId:e,onBusyChange:t}){let{t:n,i18n:r}=v(),[i,a]=(0,Y.useState)([]),[o,c]=(0,Y.useState)(``),[l,u]=(0,Y.useState)(`168`),[d,p]=(0,Y.useState)(null),[m,h]=(0,Y.useState)(null),[g,_]=(0,Y.useState)(``),[y,b]=(0,Y.useState)(!0),[x,S]=(0,Y.useState)(!1),[C,w]=(0,Y.useState)(null),[T,E]=(0,Y.useState)(Date.now),D=(0,Y.useRef)(null),O=(0,Y.useRef)(null),k=(0,Y.useRef)(!1),A=(0,Y.useRef)(!1),j=(0,Y.useRef)(void 0),ee=(0,Y.useRef)(t);ee.current=t,(0,Y.useEffect)(()=>{let t=new AbortController;return O.current=t,b(!0),a([]),_(``),w(null),p(null),E(Date.now()),q(`/api/projects/${e}/view-links`,{signal:t.signal}).then(e=>{t.signal.aborted||a(e.links)}).catch(e=>{t.signal.aborted||_(K(e))}).finally(()=>{t.signal.aborted||b(!1)}),()=>{t.abort(),clearTimeout(j.current),ee.current(!1)}},[e]),(0,Y.useEffect)(()=>{let e=i.flatMap(e=>e.expiresAt&&Date.parse(e.expiresAt)>T?[Date.parse(e.expiresAt)]:[]);if(!e.length)return;let t=setTimeout(()=>E(Date.now()),Math.min(Math.max(1,Math.min(...e)-Date.now()),2147483647));return()=>clearTimeout(t)},[i,T]);let N=i.some(e=>!e.expiresAt||Date.parse(e.expiresAt)>T),P=async e=>{let t=O.current;if(!(!t||t.signal.aborted||k.current||A.current)){k.current=!0,S(!0),ee.current(!0),_(``);try{await e(t.signal)}catch(e){t.signal.aborted||_(K(e))}finally{k.current=!1,t.signal.aborted||(S(!1),ee.current(!1))}}},F=()=>P(async t=>{if(!N)try{let n=await q(`/api/projects/${e}/view-links`,{method:`POST`,signal:t,body:JSON.stringify({label:o,expiresAt:l===`never`?null:new Date(Date.now()+Number(l)*36e5).toISOString()})});t.aborted||(a(e=>[n.link,...e]),c(``))}catch(n){if(n instanceof We&&n.code===`VIEW_LINK_EXISTS`){let n=await q(`/api/projects/${e}/view-links`,{signal:t});t.aborted||a(n.links)}throw n}}),I=()=>{if(!C)return;let t=C;P(async n=>{await q(`/api/projects/${e}/view-links/${t.id}`,{method:`DELETE`,signal:n}),n.aborted||a(e=>e.filter(e=>e.id!==t.id)),n.aborted||w(null)})},L=async e=>{let t=O.current;if(!(!t||t.signal.aborted||k.current||A.current)&&e.path){A.current=!0,h(e.id),p(null),_(``),clearTimeout(j.current);try{await $e(new URL(e.path,window.location.origin).href,()=>D.current),t.signal.aborted||(p(e.id),j.current=setTimeout(()=>p(null),2e3))}catch{t.signal.aborted||_(n(`viewLinks.copyFailed`))}finally{A.current=!1,t.signal.aborted||h(null)}}};return(0,X.jsxs)(`div`,{className:`view-link-manager`,ref:D,"aria-busy":y||x,children:[(0,X.jsxs)(`p`,{className:`view-link-description`,children:[(0,X.jsx)(f,{size:17,"aria-hidden":!0}),n(`viewLinks.description`)]}),!y&&!N&&(0,X.jsxs)(`div`,{className:`view-link-create`,children:[(0,X.jsxs)(`label`,{className:`form-field`,children:[n(`viewLinks.label`),(0,X.jsx)(`input`,{maxLength:80,value:o,disabled:x,onChange:e=>c(e.target.value)})]}),(0,X.jsxs)(`label`,{className:`form-field`,children:[n(`viewLinks.expiry`),(0,X.jsx)(`select`,{value:l,disabled:x,onChange:e=>u(e.target.value),children:[[`1`,`hour`],[`24`,`day`],[`168`,`week`],[`720`,`month`],[`never`,`never`]].map(([e,t])=>(0,X.jsx)(`option`,{value:e,children:n(`viewLinks.${t}`)},e))})]}),(0,X.jsxs)(`button`,{className:`primary icon-button`,disabled:x||y||m!==null,onClick:()=>void F(),children:[(0,X.jsx)(Ie,{size:15}),n(`viewLinks.create`)]})]}),g&&(0,X.jsx)(`p`,{className:`error`,role:`alert`,children:g}),y?(0,X.jsxs)(`div`,{className:`share-empty`,role:`status`,children:[(0,X.jsx)(Fe,{size:20,className:`spin`}),n(`common.loading`)]}):(0,X.jsxs)(`div`,{className:`view-link-list`,children:[i.map(e=>{let t=e.expiresAt&&Date.parse(e.expiresAt)<=T?`expired`:`active`,i=e.path?new URL(e.path,window.location.origin).href:``;return(0,X.jsxs)(`div`,{className:`view-link-item ${t}`,children:[(0,X.jsxs)(`div`,{className:`view-link-heading`,children:[(0,X.jsx)(pt,{size:16,"aria-hidden":!0}),(0,X.jsxs)(`div`,{className:`view-link-identity`,children:[(0,X.jsx)(`strong`,{children:e.label||n(`viewLinks.untitled`)}),(0,X.jsx)(`small`,{children:e.expiresAt?n(`viewLinks.expires`,{time:te(e.expiresAt,r.resolvedLanguage)}):n(`viewLinks.never`)})]}),(0,X.jsx)(`span`,{className:`view-link-status`,children:n(`viewLinks.${t}`)}),(0,X.jsx)(`div`,{className:`view-link-actions`,children:(0,X.jsx)(`button`,{className:`icon-only danger-text`,disabled:x||m!==null,"aria-label":n(`viewLinks.delete`),"data-tooltip":n(`viewLinks.delete`),onClick:()=>{_(``),w(e)},children:(0,X.jsx)(M,{size:15})})})]}),(0,X.jsxs)(`div`,{className:`view-link-address`,children:[(0,X.jsx)(`input`,{readOnly:!0,spellCheck:!1,autoComplete:`off`,"aria-label":n(`viewLinks.address`,{name:e.label||n(`viewLinks.untitled`)}),value:i,placeholder:n(`viewLinks.addressUnavailable`),onFocus:e=>e.target.select()}),(0,X.jsxs)(`button`,{type:`button`,className:`save-button view-link-copy`,disabled:x||m!==null||t!==`active`||!e.path,"aria-busy":m===e.id,onClick:()=>void L(e),children:[m===e.id?(0,X.jsx)(Fe,{className:`spin`,size:14}):d===e.id?(0,X.jsx)(U,{className:`save-button-confirmation`,size:14}):(0,X.jsx)(s,{size:14}),(0,X.jsx)(`span`,{role:`status`,"aria-live":`polite`,children:n(d===e.id?`viewLinks.copied`:`viewLinks.copy`)})]})]})]},e.id)}),i.length===0&&(0,X.jsxs)(`div`,{className:`share-empty`,children:[(0,X.jsx)(pt,{size:24}),(0,X.jsx)(`span`,{children:n(`viewLinks.empty`)})]})]}),(0,X.jsx)(He,{open:!!C,title:n(`viewLinks.delete`),description:n(`viewLinks.deleteConfirm`),confirmLabel:n(`viewLinks.delete`),danger:!0,busy:x,error:g,onCancel:()=>{x||(w(null),_(``))},onConfirm:I})]})}function Xg(e){let t=/(^|\s)(@[\p{L}\p{N}_.-]+)/gu,n=[],r=0;for(let i of e.matchAll(t)){let t=i.index??0,a=i[1],o=i[2],s=t+a.length;s>r&&n.push(e.slice(r,s)),n.push((0,X.jsx)(`span`,{className:`comment-inline-mention`,children:o},`${s}:${o}`)),r=s+o.length}return n.length?(r<e.length&&n.push(e.slice(r)),n):e}function Zg({userId:e,avatarStyle:t,name:n,username:r,highlighted:i,children:a}){return(0,X.jsxs)(`span`,{className:`comment-identity`,children:[(0,X.jsx)(F,{userId:e,name:n,username:r,avatarStyle:t,className:`comment-avatar`}),(0,X.jsxs)(`span`,{className:`comment-author-details`,children:[(0,X.jsx)(`span`,{className:`comment-author${i?` participant-match`:``}`,children:(0,X.jsx)(`strong`,{"data-tooltip":r?`@${r}`:void 0,"data-texlite-tooltip-always":!0,children:n})}),a]})]})}function Qg({projectOwnerId:e=``,canEditSource:t=!1,unreadCommentMentionKind:n,projectId:r,comment:i,draftStore:a,currentUserId:s,unreadCommentMentionId:c,unreadReplyMentionIds:l,highlightedComment:u,highlightedReplyId:f,currentComment:m,showFilePath:h,onMarkMentionRead:_,onFocus:y,onActivate:b,onToggle:x,onReply:S,onEdit:C,onDelete:w,onEditReply:T,onDeleteReply:E,selectedParticipantIds:D,highlightReplyParticipants:k,replyExpansion:A,onReplyExpansionChange:j}){let{t:M,i18n:ee}=v(),N=d(),[P,F]=(0,Y.useState)(!1),[I,L]=(0,Y.useState)(null),ne=(0,Y.useCallback)(e=>a.subscribe(i.id,e),[a,i.id]),re=(0,Y.useCallback)(()=>a.getThread(i.id),[a,i.id]),ie=(0,Y.useSyncExternalStore)(ne,re,re),R=ie.reply,z=ie[`edit-comment`],ae=(0,Y.useId)(),B=Wg(i.replies,{expansion:A,current:m,targetReplyId:f,unreadReplyMentionIds:l,selectedParticipantIds:D,highlightReplyParticipants:k,activeDraft:!!(R?.open||R?.pending||i.authorId===s&&z?.open||i.replies.some(e=>e.authorId===s&&ie[`edit-reply:${e.id}`]?.open))}),oe=a.isPending(i.id),[V,se]=(0,Y.useState)(null),[H,W]=(0,Y.useState)(!1),[ue,de]=(0,Y.useState)(null),[fe,pe]=(0,Y.useState)(``),me=(0,Y.useRef)(null),he=(0,Y.useRef)(!1),[ge,_e]=(0,Y.useState)(!1),ve=async e=>{if(he.current)return;he.current=!0,_e(!0),pe(``);let t=Kg(e?me.current?.querySelector(`[data-comment-reply-id="${e}"]`)??null:me.current);try{if(!(e?await E(e):await w())){pe(M(`editor.commentDeleteFailed`));return}e?de(null):W(!1),t()}catch(e){pe(K(e))}finally{he.current=!1,_e(!1)}},G=(e,t=``)=>{b(),j(!0),se(e),a.open(i.id,e,t)},ye=(e,t,n,o)=>{let s=ie[e];return s?.open?(0,X.jsx)(jg,{projectId:r,editing:e!==`reply`,originalValue:o,label:t,value:s.content,pending:s.pending,error:s.error,disabled:oe||P,autoFocus:V===e,onChange:t=>a.change(i.id,e,t),onSubmit:()=>a.submit(i.id,e,n,M(`editor.commentSubmitFailed`)),onCancel:()=>a.discard(i.id,e)},e):null},be=i.authorUsername,xe=e=>p(e,ee.resolvedLanguage??`en`,N,(e,t)=>M(e,t)),Se=e=>te(e,ee.resolvedLanguage,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),Ce=e=>(0,X.jsx)(`time`,{dateTime:e,"data-tooltip":Se(e),"data-texlite-tooltip-always":!0,children:xe(e)}),we=(e,t)=>(0,X.jsxs)(`span`,{className:`comment-times`,children:[Ce(e),t&&(0,X.jsx)(`small`,{"data-tooltip":M(`editor.editedAt`,{time:Se(t)}),"data-texlite-tooltip-always":!0,children:M(`editor.commentEdited`)})]}),Te=async(e,t)=>{t.stopPropagation(),j(!0),await _(e)};return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`article`,{ref:me,"data-comment-id":i.id,className:`comment-thread${i.resolved?` resolved`:``}${i.orphaned?` orphaned`:``}${u?` mention-target`:``}${m?` review-current`:``}`,onFocusCapture:b,onClick:()=>{window.getSelection()?.toString()||y()},children:[(0,X.jsxs)(`header`,{className:`comment-header`,children:[(0,X.jsx)(Zg,{userId:i.authorId,avatarStyle:i.authorAvatarStyle,name:i.authorDisplayName??be??M(`editor.deletedUser`),username:be,highlighted:D?.has(i.authorId),children:we(i.createdAt,i.editedAt)}),(0,X.jsxs)(`span`,{className:`comment-header-actions`,children:[(0,X.jsx)(`button`,{type:`button`,className:`resolve`,disabled:P||oe||i.suggestion?.status===`pending`,"aria-busy":P,"aria-label":M(i.resolved?`editor.reopen`:`editor.resolve`),"data-tooltip":M(i.suggestion?.status===`pending`?`suggestions.reviewBeforeResolve`:i.resolved?`editor.reopen`:`editor.resolve`),"data-texlite-tooltip-always":!0,onClick:e=>{e.stopPropagation(),!P&&(F(!0),x().finally(()=>F(!1)))},children:P?(0,X.jsx)(Fe,{className:`spin`,size:15,"aria-hidden":!0}):i.resolved?(0,X.jsx)(xt,{size:15,"aria-hidden":!0}):(0,X.jsx)(U,{size:16,"aria-hidden":!0})}),i.authorId===s&&!z?.open&&(0,X.jsx)(Og,{kind:`comment`,disabled:oe||P,onSuggest:e&&!I&&Hg(i,s)?()=>{b(),L({original:i.selectedText,sourceHash:i.anchorSourceHash})}:void 0,onEdit:()=>G(`edit-comment`,i.content),onDelete:()=>{pe(``),W(!0)}})]})]}),(0,X.jsx)(`div`,{className:`comment-location`,children:i.orphaned?M(`editor.orphaned`):h?M(`editor.commentLocation`,{path:i.filePath,line:i.startLine}):M(`editor.line`,{line:i.startLine})}),i.selectedText&&(0,X.jsx)(`blockquote`,{className:`comment-selected-text`,children:i.selectedText}),z?.open&&i.authorId===s?ye(`edit-comment`,M(`editor.editComment`),C,i.content):(0,X.jsx)(`p`,{className:`comment-content`,children:Xg(i.content)}),e&&(i.suggestion||I)&&(0,X.jsx)(Ug,{projectId:r,ownerId:e,currentUserId:s,canEdit:t,comment:i,draftTarget:I,onCloseComposer:()=>L(null)}),c&&(0,X.jsxs)(`div`,{className:`comment-mention`,children:[(0,X.jsxs)(`span`,{children:[(0,X.jsx)(o,{"aria-hidden":!0,size:12}),M(n===`review`?`suggestions.reviewRequested`:`editor.mentionedYou`)]}),(0,X.jsx)(`button`,{type:`button`,onClick:e=>void Te(c,e),children:M(`editor.markMentionRead`)})]}),i.replies.length>0&&(0,X.jsxs)(`div`,{className:`comment-replies`,children:[B.canToggle&&(0,X.jsxs)(`button`,{type:`button`,className:`comment-replies-toggle`,"aria-expanded":B.expanded,"aria-controls":ae,onClick:e=>{e.stopPropagation(),j(!B.expanded)},children:[B.expanded?(0,X.jsx)(ce,{size:12,"aria-hidden":!0}):(0,X.jsx)(O,{size:12,"aria-hidden":!0}),B.expanded?M(`editor.hideEarlierReplies`):M(`editor.showEarlierReplies`,{count:B.hiddenCount})]}),(0,X.jsx)(`div`,{className:`comment-replies-list`,id:ae,children:B.replies.map(e=>{let t=l?.get(e.id),n=`edit-reply:${e.id}`,r=ie[n]?.open&&e.authorId===s;return(0,X.jsxs)(`div`,{"data-comment-reply-id":e.id,className:`comment-reply${f===e.id?` mention-target`:``}`,children:[(0,X.jsxs)(`header`,{children:[(0,X.jsx)(Zg,{userId:e.authorId,avatarStyle:e.authorAvatarStyle,name:e.authorDisplayName??e.authorUsername??M(`editor.deletedUser`),username:e.authorUsername,highlighted:k&&D?.has(e.authorId),children:we(e.createdAt,e.editedAt)}),(0,X.jsx)(`span`,{className:`comment-header-actions`,children:e.authorId===s&&!r&&(0,X.jsx)(Og,{kind:`reply`,disabled:oe||P,onEdit:()=>G(n,e.content),onDelete:()=>{pe(``),de(e.id)}})})]}),r?ye(n,M(`editor.editReply`),t=>T(e.id,t),e.content):(0,X.jsx)(`p`,{className:`comment-content`,children:Xg(e.content)}),t&&(0,X.jsxs)(`div`,{className:`comment-mention`,children:[(0,X.jsxs)(`span`,{children:[(0,X.jsx)(o,{"aria-hidden":!0,size:12}),M(`editor.mentionedYou`)]}),(0,X.jsx)(`button`,{type:`button`,onClick:e=>void Te(t,e),children:M(`editor.markMentionRead`)})]})]},e.id)})})]}),i.resolved&&i.resolvedAt&&(0,X.jsxs)(`div`,{className:`comment-resolution`,children:[(0,X.jsx)(le,{size:12,"aria-hidden":!0}),(0,X.jsxs)(`span`,{children:[(0,X.jsx)(g,{i18nKey:`editor.resolvedBy`,values:{user:i.resolvedByDisplayName??i.resolvedByUsername??M(`editor.deletedUser`)},components:{user:(0,X.jsx)(`strong`,{className:`comment-resolution-user`,"data-tooltip":i.resolvedByUsername?`@${i.resolvedByUsername}`:void 0,"data-texlite-tooltip-always":!0})}}),` · `,Ce(i.resolvedAt)]})]}),!R?.open&&(0,X.jsx)(`button`,{type:`button`,className:`reply-action`,disabled:oe||P,onClick:e=>{e.stopPropagation(),G(`reply`)},children:M(`editor.replyPrompt`)}),ye(`reply`,M(`editor.reply`),S)]}),(0,X.jsx)(He,{open:H,title:M(`editor.deleteCommentTitle`),description:M(`editor.deleteCommentDescription`),confirmLabel:M(`common.delete`),danger:!0,busy:ge,error:fe,onCancel:()=>W(!1),onConfirm:()=>void ve(null)}),(0,X.jsx)(He,{open:!!ue,title:M(`editor.deleteReplyTitle`),description:M(`editor.deleteReplyDescription`),confirmLabel:M(`common.delete`),danger:!0,busy:ge,error:fe,onCancel:()=>de(null),onConfirm:()=>{ue&&ve(ue)}})]})}function $g({open:e,onOpenChange:t,project:n,projectId:r,onMemberCountChange:i}){let{t:a}=v(),[o,s]=(0,Y.useState)([]),[c,l]=(0,Y.useState)([]),[u,d]=(0,Y.useState)(`members`),[f,p]=(0,Y.useState)(!1),[m,h]=(0,Y.useState)(``),[g,_]=(0,Y.useState)(`read`),[y,b]=(0,Y.useState)(null),[x,S]=(0,Y.useState)(``),[C,w]=(0,Y.useState)(!1),[T,E]=(0,Y.useState)(!1),D=(0,Y.useRef)(null),O=(0,Y.useRef)(null),k=(0,Y.useRef)(null),A=n.permission===`owner`,ee=(0,Y.useCallback)(async e=>{let[t,a]=await Promise.all([q(`/api/projects/${r}/members`,{signal:e}),A?q(`/api/users`,{signal:e}):Promise.resolve({users:[]})]);if(e.aborted)return;let o=t.members.filter(e=>e.id!==n.ownerId);s(o),i?.(r,o.length),l(a.users.filter(e=>e.id!==n.ownerId))},[r,n.ownerId,A,i]);(0,Y.useEffect)(()=>{if(!e)return;let t=new AbortController;return D.current=t,h(``),_(`read`),b(null),S(``),d(`members`),l([]),s([]),E(!1),w(!0),ee(t.signal).catch(e=>{t.signal.aborted||S(K(e))}).finally(()=>{t.signal.aborted||w(!1)}),()=>{t.abort(),D.current===t&&(D.current=null)}},[e,ee]);let N=async e=>{let t=D.current;if(A&&t&&!t.signal.aborted&&O.current!==t){O.current=t,E(!0),S(``);try{await e(t.signal),t.signal.aborted||await ee(t.signal)}catch(e){t.signal.aborted||S(K(e))}finally{O.current===t&&(O.current=null),t.signal.aborted||E(!1)}}},P=c.filter(e=>!o.some(t=>t.id===e.id)),te=async()=>{P.some(e=>e.id===m)&&await N(async e=>{await q(`/api/projects/${r}/members/${m}`,{method:`PUT`,body:JSON.stringify({permission:g}),signal:e}),e.aborted||(h(``),_(`read`))})},I=async(e,t)=>{await N(n=>q(`/api/projects/${r}/members/${e.id}`,{method:`PUT`,body:JSON.stringify({permission:t}),signal:n}))},L=async()=>{y&&await N(async e=>{await q(`/api/projects/${r}/members/${y.id}`,{method:`DELETE`,signal:e}),e.aborted||b(null)})};return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Ue,{open:e,wide:!0,className:`share-dialog-modal`,title:a(`projectSettings.share`),onOpenChange:e=>{!T&&!f&&t(e)},onEscapeKeyDown:e=>{k.current?.querySelector(`[role="combobox"][aria-expanded="true"]`)&&e.preventDefault()},footer:(0,X.jsx)(`button`,{disabled:T||f,onClick:()=>t(!1),children:a(`common.close`)}),children:(0,X.jsxs)(`div`,{className:`share-dialog`,ref:k,"aria-busy":C||T,children:[A&&(0,X.jsxs)(`div`,{className:`share-scope-tabs`,role:`tablist`,"aria-label":a(`projectSettings.share`),children:[(0,X.jsx)(`button`,{role:`tab`,"aria-selected":u===`members`,disabled:T||f,onClick:()=>d(`members`),children:a(`projectSettings.members`)}),(0,X.jsx)(`button`,{role:`tab`,"aria-selected":u===`links`,disabled:T||f,onClick:()=>d(`links`),children:a(`viewLinks.tab`)})]}),u===`links`&&A?(0,X.jsx)(Yg,{projectId:r,onBusyChange:p},r):(0,X.jsxs)(X.Fragment,{children:[x&&!y&&(0,X.jsx)(`p`,{className:`error`,role:`alert`,children:x}),(0,X.jsxs)(`div`,{className:`share-owner`,children:[(0,X.jsx)(j,{size:17}),(0,X.jsxs)(`span`,{children:[(0,X.jsx)(`small`,{children:a(`projects.owner`)}),(0,X.jsx)(`strong`,{children:n.ownerDisplayName??n.ownerUsername})]})]}),A&&(0,X.jsxs)(`div`,{className:`share-add`,children:[(0,X.jsx)(Jg,{users:P,value:m,onChange:h,disabled:C||T},r),(0,X.jsxs)(`label`,{className:`form-field`,children:[a(`common.permission`),(0,X.jsxs)(`select`,{disabled:C||T,value:g,onChange:e=>_(e.target.value),children:[(0,X.jsx)(`option`,{value:`read`,children:a(`common.readOnly`)}),(0,X.jsx)(`option`,{value:`edit`,children:a(`common.readWrite`)})]})]}),(0,X.jsxs)(`button`,{className:`primary icon-button`,disabled:C||T||!P.some(e=>e.id===m),onClick:()=>void te(),children:[T?(0,X.jsx)(Fe,{className:`spin`,size:15}):(0,X.jsx)(ze,{size:15}),a(`projectSettings.addMember`)]})]}),(0,X.jsxs)(`div`,{className:`shared-members-heading`,children:[(0,X.jsx)(`strong`,{children:a(`projectSettings.members`)}),(0,X.jsx)(`span`,{children:o.length})]}),(0,X.jsxs)(`div`,{className:`shared-members`,children:[o.map(e=>(0,X.jsxs)(`div`,{className:`shared-member`,children:[(0,X.jsxs)(`span`,{className:`member-identity`,children:[(0,X.jsx)(F,{userId:e.id,name:e.displayName,username:e.username,avatarStyle:e.avatarStyle,className:`member-avatar`}),(0,X.jsxs)(`span`,{children:[(0,X.jsx)(`strong`,{children:e.displayName??e.username}),(0,X.jsxs)(`small`,{children:[`@`,e.username]})]})]}),(0,X.jsxs)(`span`,{className:`member-controls`,children:[(0,X.jsxs)(`select`,{"aria-label":a(`common.permission`),disabled:!A||T,value:e.permission,onChange:t=>void I(e,t.target.value),children:[(0,X.jsx)(`option`,{value:`read`,children:a(`common.readOnly`)}),(0,X.jsx)(`option`,{value:`edit`,children:a(`common.readWrite`)})]}),A&&(0,X.jsx)(`button`,{disabled:T,className:`icon-only danger-text`,title:a(`common.remove`),"aria-label":a(`common.remove`),onClick:()=>{S(``),b(e)},children:(0,X.jsx)(M,{size:15})})]})]},e.id)),C?(0,X.jsxs)(`div`,{className:`share-empty`,role:`status`,children:[(0,X.jsx)(Fe,{className:`spin`,size:20}),(0,X.jsx)(`span`,{children:a(`common.loading`)})]}):o.length===0&&(0,X.jsxs)(`div`,{className:`share-empty`,children:[(0,X.jsx)(j,{size:24}),(0,X.jsx)(`span`,{children:a(`projectSettings.noMembers`)})]})]})]})]})}),(0,X.jsx)(He,{open:!!y,title:a(`projectSettings.removeTitle`),description:a(`projectSettings.removeDescription`,{username:y?.username??``}),confirmLabel:a(`common.remove`),danger:!0,busy:T,error:x,onCancel:()=>{T||(b(null),S(``))},onConfirm:()=>void L()})]})}function e_({open:e,projectId:t,ownerId:n,authorId:r,selection:i,text:a,onText:o,suggestion:s,onSuggestion:l,submitting:u,error:d,onSubmit:f,onClose:p,onCancel:m,draftRestored:h,canRetarget:g,onRetarget:_}){let{t:y}=v(),b=(0,Y.useId)(),[x,S]=(0,Y.useState)(!1),[C,w]=(0,Y.useState)(!1),T=(0,Y.useRef)(null);(0,Y.useEffect)(()=>{e||(S(!1),w(!1),T.current=null)},[e]);let E=Vp(a,i.selectedText,s,r),D=!!(i.selectedText&&i.selectedText.length<=5e4),O=E.issue===`selfReview`?`errors.codes.SUGGESTION_SELF_REVIEW`:E.issue===`reviewer`?`commentComposer.chooseReviewer`:D?`commentComposer.empty`:`commentComposer.emptyComment`,k=!!(d||x&&E.issue),A=d||(E.issue?y(O):`${y(`commentComposer.${E.kind}`)}${E.edit?` · ${y(`commentComposer.reviewRequested`)}`:``}`),j=()=>{u||(S(!0),E.issue||f())};return(0,X.jsxs)(Ue,{open:e,draggable:!0,wide:!0,className:`comment-compose-modal`,title:y(`editor.addComment`),description:i.selectedText?y(`editor.commentDescription`,{count:i.endOffset-i.startOffset}):y(`editor.pointComment`),onOpenChange:e=>{!e&&!u&&p()},footer:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`p`,{className:`comment-compose-status${k?` has-error`:``}`,role:k?`alert`:`status`,"aria-live":`polite`,children:u?y(`editor.commentSending`):A}),(0,X.jsxs)(`div`,{className:`comment-compose-actions`,children:[(0,X.jsx)(`button`,{type:`button`,disabled:u,onClick:m,children:y(`common.cancel`)}),(0,X.jsxs)(`button`,{type:`button`,className:`primary`,"aria-busy":u,disabled:u,onClick:j,children:[u&&(0,X.jsx)(Fe,{className:`spin`,size:14}),y(u?`editor.commentSending`:`editor.addComment`)]})]})]}),children:[h&&(0,X.jsxs)(`p`,{className:`comment-draft-restored`,children:[(0,X.jsx)(`span`,{children:y(`editor.commentDraftRestored`)}),g&&(0,X.jsx)(`button`,{type:`button`,disabled:u,onClick:_,children:y(`editor.commentDraftUseSelection`)})]}),i.selectedText&&(0,X.jsxs)(`section`,{className:`comment-compose-original`,"aria-label":y(`commentComposer.original`),children:[(0,X.jsx)(`span`,{children:y(`commentComposer.original`)}),(0,X.jsx)(`blockquote`,{children:i.selectedText})]}),(0,X.jsxs)(`label`,{className:`form-field comment-compose-note`,children:[y(`editor.commentContent`),(0,X.jsx)(Ag,{projectId:t,autoFocus:!0,rows:3,disabled:u,value:a,placeholder:y(`commentComposer.placeholder`),onChange:o,onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&!e.nativeEvent.isComposing&&(e.preventDefault(),e.stopPropagation(),j())}})]}),D&&(0,X.jsxs)(`div`,{className:`comment-compose-edit`,children:[(0,X.jsxs)(`label`,{className:`comment-compose-edit-toggle`,children:[(0,X.jsx)(`input`,{type:`checkbox`,role:`switch`,disabled:u,checked:!!s,"aria-controls":s?`${b}-edit`:void 0,onChange:e=>{e.target.checked?(w(!0),l(T.current??{replacementText:i.selectedText,reviewerId:n===r?``:n})):(T.current=s,w(!1),l(null))}}),(0,X.jsx)(c,{size:16,"aria-hidden":!0}),(0,X.jsx)(`span`,{children:y(`commentComposer.suggestEdit`)})]}),s&&(0,X.jsx)(`div`,{className:`comment-compose-edit-fields`,id:`${b}-edit`,children:(0,X.jsx)(Vg,{original:i.selectedText,replacement:s.replacementText,onChange:e=>l({...s,replacementText:e}),disabled:u,autoFocus:C})})]}),s&&(0,X.jsx)(`div`,{className:`comment-compose-reviewer`,children:(0,X.jsx)(zg,{projectId:t,authorId:r,value:s.reviewerId,onChange:e=>l({...s,reviewerId:e}),disabled:u})})]})}var t_=(0,Y.lazy)(()=>S(()=>import(`./CitationLibraryDialog-DDP3gXNt.js`).then(e=>({default:e.CitationLibraryDialog})),__vite__mapDeps([21,2,3,22,5,4,7,10,16,17,12,1,6,8,9,11,13,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38]),import.meta.url)),n_=(0,Y.lazy)(()=>S(()=>import(`./GitDialog-CzLmo9Z_.js`).then(e=>({default:e.GitDialog})),__vite__mapDeps([39,2,3,4,5,10,16,7,17,12,40,25,9,41,42,29,1,6,8,11,13]),import.meta.url)),r_=(0,Y.lazy)(()=>S(()=>import(`./HistoryDialog-C4zmnE1s.js`).then(e=>({default:e.HistoryDialog})),__vite__mapDeps([43,2,3,4,5,10,16,7,17,12,32,44,45,23,28,9,33,11,1,6,8,13,34,46,41,42,29,31,37]),import.meta.url)),i_=(0,Y.lazy)(()=>S(()=>import(`./SelectionHistoryDialog-CmHcjD4T.js`).then(e=>({default:e.SelectionHistoryDialog})),__vite__mapDeps([47,2,3,4,5,16,7,10,17,12,44,46,9,1,6,8,11,13]),import.meta.url)),a_=(0,Y.lazy)(()=>S(()=>import(`./QuickOpenDialog-kW-97LBY.js`).then(e=>({default:e.QuickOpenDialog})),__vite__mapDeps([48,2,3,4,5,23,10,45,7,16,17,12,32,28,9,33,11,1,6,8,13,34]),import.meta.url)),o_=(0,Y.lazy)(()=>S(()=>import(`./ProjectSearchDialog-B5a5mHXl.js`).then(e=>({default:e.ProjectSearchDialog})),__vite__mapDeps([49,2,3,4,5,6,10,16,7,17,12,23,45,32,28,9,33,11,1,8,13,34]),import.meta.url));function s_({projectSearchOpen:e,setProjectSearchOpen:t,onSearchNavigate:n,commentSuggestion:r,setCommentSuggestion:i,user:a,project:o,projectId:s,activeFile:c,content:l,maxCitationBibtexBytes:u,files:d,directoryEntries:f,readOnly:p,resourcePreview:m,resourcePreviewLoading:h,setResourcePreview:g,setResourcePreviewLoading:_,uploadConflict:y,setUploadConflict:b,dismissUploadFeedback:x,uploadFiles:S,cleanMode:C,setCleanMode:w,cleanCompile:E,newFileOpen:D,setNewFileOpen:O,newFilePath:k,setNewFilePath:j,newFolderOpen:ee,setNewFolderOpen:N,newFolderName:P,setNewFolderName:te,selectedFolder:F,fileDialogError:I,setFileDialogError:L,createFile:ne,createFolder:re,moveEntry:ie,setMoveEntry:R,moveName:z,setMoveName:B,moveDestination:V,setMoveDestination:se,movePath:H,deleteEntry:U,setDeleteEntry:W,deleteActiveSessions:ce,removePath:le,commentOpen:ue,closeComment:fe,commentSelection:pe,commentText:me,setCommentText:he,commentSubmitting:ge,commentError:_e,addComment:ve,cancelComment:G,commentDraftRestored:ye,commentDraftCanRetarget:be,useCurrentCommentSelection:xe,shareOpen:Se,setShareOpen:Ce,onSharedMemberCountChange:we,citationLibraryOpen:Te,setCitationLibraryOpen:Ee,insertCitationAtCursor:De,quickOpen:Oe,setQuickOpen:ke,openFile:Ae,selectionHistoryTarget:je,closeSelectionHistory:Me,historyOpen:Ne,setHistoryOpen:Pe,gitOpen:Ie,setGitOpen:Re,save:ze,permissionDowngrade:Be,permissionDowngradeBusy:K,dismissPermissionDowngrade:q,discardPermissionDraft:We}){let{t:J}=v();return(0,X.jsxs)(X.Fragment,{children:[Be&&(0,X.jsx)(Ue,{open:!0,title:J(`editor.collaboration.permissionDowngradeTitle`),description:Be.localDraftReady&&Be.otherTabDraft?J(`editor.collaboration.permissionDowngradeMultipleDrafts`):Be.otherTabDraft?J(`editor.collaboration.permissionDowngradeOtherTab`):Be.localDraftReady?J(`editor.collaboration.permissionDowngradeDescription`,{previous:J(`common.readWrite`)}):J(`editor.collaboration.permissionDowngradeNoDraft`),onOpenChange:e=>{!e&&!K&&q()},footer:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`button`,{type:`button`,disabled:K,onClick:q,children:Be.localDraftReady?J(`editor.collaboration.permissionDowngradeKeep`):J(`common.close`)}),!Be.otherTabDraft&&(0,X.jsxs)(`button`,{type:`button`,className:`danger`,disabled:K,onClick:()=>void We(),children:[K?(0,X.jsx)(Fe,{className:`spin`,size:14}):Be.localDraftReady?(0,X.jsx)(M,{size:14}):(0,X.jsx)(Le,{size:14}),Be.localDraftReady?J(`editor.collaboration.permissionDowngradeDiscard`):J(`editor.collaboration.permissionDowngradeReload`)]})]}),children:(0,X.jsx)(`div`,{})}),(0,X.jsxs)(Ue,{open:!!m,extraWide:m?.kind===`image`||m?.kind===`pdf`||m?.kind===`text`,title:m?.path??``,description:m?.kind===`large`?J(`editor.resourceTooLarge`,{size:ae(m.size,{maximumUnit:`MB`}),limit:ae(m.limitBytes??10485760,{maximumUnit:`MB`})}):J(`editor.resourcePreview.${m?.kind??`text`}`),onOpenChange:e=>{e||(g(null),_(!1))},footer:m&&(0,X.jsxs)(`a`,{className:`primary resource-download`,href:`${m.url}&download=1`,download:!0,children:[(0,X.jsx)(T,{size:14}),J(`editor.downloadResource`)]}),children:[m?.kind===`large`&&(0,X.jsxs)(`div`,{className:`resource-preview-message`,children:[(0,X.jsx)(A,{size:34}),(0,X.jsx)(`strong`,{children:J(`editor.resourceTooLargeTitle`)}),(0,X.jsx)(`span`,{children:J(`editor.resourceTooLargeDescription`)})]}),m?.kind===`unsupported`&&(0,X.jsxs)(`div`,{className:`resource-preview-message`,children:[(0,X.jsx)(de,{size:34}),(0,X.jsx)(`strong`,{children:J(`editor.resourceUnsupportedTitle`)}),(0,X.jsx)(`span`,{children:J(`editor.resourceUnsupportedDescription`)})]}),m?.kind===`image`&&(0,X.jsx)(`div`,{className:`resource-image-wrap`,children:(0,X.jsx)(`img`,{className:`resource-image`,src:m.url,alt:m.path})}),m?.kind===`pdf`&&(0,X.jsx)(`iframe`,{className:`resource-pdf`,src:m.url,title:m.path}),m?.kind===`text`&&(h?(0,X.jsxs)(`div`,{className:`resource-preview-message`,children:[(0,X.jsx)(Fe,{className:`spin`,size:24}),(0,X.jsx)(`span`,{children:J(`common.loading`)})]}):(0,X.jsx)(`pre`,{className:`resource-text`,children:m.content}))]}),(0,X.jsx)(He,{open:!!y,title:J(`editor.uploadOverwriteTitle`),description:J(`editor.uploadOverwriteDescription`,{count:y?.collisions.length??0,files:y?.collisions.join(`, `)??``}),confirmLabel:J(`editor.uploadOverwrite`),danger:!0,onCancel:()=>{b(null),x()},onConfirm:()=>{let e=y;b(null),e&&S(e.files,new Set(e.collisions),e.directory)}}),(0,X.jsx)(He,{open:!!C,title:J(C===`cache`?`editor.cleanCacheConfirmTitle`:`editor.cleanArtifactsConfirmTitle`),description:J(C===`cache`?`editor.cleanCacheConfirmDescription`:`editor.cleanArtifactsConfirmDescription`),confirmLabel:J(`editor.cleanConfirm`),danger:C===`artifacts`,onCancel:()=>w(null),onConfirm:()=>{let e=C;w(null),e&&E(e)}}),(0,X.jsx)(Ue,{open:D,title:J(`editor.newFile`),description:J(`editor.newFileDescription`),onOpenChange:e=>{O(e),e||L(``)},footer:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`button`,{onClick:()=>O(!1),children:J(`common.cancel`)}),(0,X.jsx)(`button`,{className:`primary`,onClick:()=>void ne(),children:J(`common.create`)})]}),children:(0,X.jsxs)(X.Fragment,{children:[I&&(0,X.jsx)(`p`,{className:`error dialog-error`,children:I}),(0,X.jsxs)(`label`,{className:`form-field`,children:[J(`editor.filePath`),(0,X.jsx)(`input`,{autoFocus:!0,value:k,onChange:e=>j(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&(e.preventDefault(),ne())}})]})]})}),(0,X.jsx)(Ue,{open:ee,title:J(`editor.newFolder`),description:J(`editor.folderDestination`,{folder:F||J(`editor.projectRoot`)}),onOpenChange:e=>{N(e),e||L(``)},footer:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`button`,{onClick:()=>N(!1),children:J(`common.cancel`)}),(0,X.jsx)(`button`,{className:`primary`,onClick:()=>void re(),children:J(`common.create`)})]}),children:(0,X.jsxs)(X.Fragment,{children:[I&&(0,X.jsx)(`p`,{className:`error dialog-error`,children:I}),(0,X.jsxs)(`label`,{className:`form-field`,children:[J(`editor.folderName`),(0,X.jsx)(`input`,{autoFocus:!0,value:P,onChange:e=>te(e.target.value),onKeyDown:e=>{e.key===`Enter`&&re()}})]})]})}),(0,X.jsx)(Ue,{open:!!ie,title:J(`editor.moveTitle`,{name:ie?.path.split(`/`).at(-1)??``}),description:J(`editor.moveDescription`),onOpenChange:e=>{e||(R(null),B(``),L(``))},footer:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`button`,{onClick:()=>R(null),children:J(`common.cancel`)}),(0,X.jsx)(`button`,{className:`primary`,disabled:!z.trim(),onClick:()=>void H(),children:J(`editor.moveApply`)})]}),children:(0,X.jsxs)(X.Fragment,{children:[I&&(0,X.jsx)(`p`,{className:`error dialog-error`,children:I}),(0,X.jsxs)(`label`,{className:`form-field`,children:[J(`editor.pathName`),(0,X.jsx)(`input`,{autoFocus:!0,value:z,onChange:e=>B(e.target.value),onKeyDown:e=>{e.key===`Enter`&&H()}})]}),(0,X.jsxs)(`label`,{className:`form-field`,children:[J(`editor.destinationFolder`),(0,X.jsxs)(`select`,{value:V,onChange:e=>se(e.target.value),children:[(0,X.jsx)(`option`,{value:``,children:J(`editor.projectRoot`)}),f.filter(e=>ie?.type!==`directory`||e.path!==ie.path&&!e.path.startsWith(`${ie.path}/`)).map(e=>(0,X.jsx)(`option`,{value:e.path,children:e.path},e.path))]})]})]})}),(0,X.jsx)(Ue,{open:!!U,title:J(`editor.deletePathTitle`,{name:U?.path.split(`/`).at(-1)??``}),description:ce.length?J(`editor.deletePathActiveDescription`,{count:ce.length,path:U?.path??``,users:[...new Set(ce.map(e=>e.name))].join(`, `)}):J(`editor.deletePathDescription`,{path:U?.path??``}),onOpenChange:e=>{e||(W(null),L(``))},footer:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`button`,{onClick:()=>W(null),children:J(`common.cancel`)}),(0,X.jsx)(`button`,{className:`danger`,onClick:()=>void le(),children:J(`common.delete`)})]}),children:(0,X.jsxs)(X.Fragment,{children:[I&&(0,X.jsx)(`p`,{className:`error dialog-error`,children:I}),ce.length>0&&(0,X.jsxs)(`p`,{className:`warning`,children:[(0,X.jsx)(oe,{size:15}),J(`editor.deletePathWillClose`)]})]})}),(0,X.jsx)(e_,{open:ue,projectId:s,ownerId:o.ownerId,authorId:a.id,selection:pe,text:me,onText:he,suggestion:r,onSuggestion:i,submitting:ge,error:_e,onSubmit:ve,onClose:fe,onCancel:G,draftRestored:ye,canRetarget:be,onRetarget:xe}),(0,X.jsx)($g,{open:Se,onOpenChange:Ce,project:o,projectId:s,onMemberCountChange:we}),Te&&(0,X.jsx)(Ve,{title:J(`citationLibrary.title`),onClose:()=>Ee(!1),children:(0,X.jsx)(t_,{open:!0,onOpenChange:Ee,currentFile:c,currentSource:l,readOnly:p,currentUserId:a.id,maxBibtexBytes:u,onInsert:De})}),Oe&&(0,X.jsx)(Y.Suspense,{fallback:null,children:(0,X.jsx)(a_,{open:!0,files:d,onOpenChange:ke,onOpenFile:e=>{let t=d.find(t=>t.path===e);t&&Ae(t)}})}),e&&(0,X.jsx)(Ve,{title:J(`projectSearch.title`),onClose:()=>t(!1),children:(0,X.jsx)(o_,{projectId:s,readOnly:p,onClose:()=>t(!1),onNavigate:n})}),je&&(0,X.jsx)(Y.Suspense,{fallback:null,children:(0,X.jsx)(i_,{open:!0,onOpenChange:e=>{e||Me()},project:o,filePath:je.filePath,selection:je.selection,currentSource:je.source})}),Ne&&(0,X.jsx)(Y.Suspense,{fallback:null,children:(0,X.jsx)(r_,{open:!0,onOpenChange:Pe,project:o,onBeforeMutation:o.permission===`read`?async()=>!0:ze})}),o.ownerId===a.id&&Ie&&(0,X.jsx)(Y.Suspense,{fallback:null,children:(0,X.jsx)(n_,{open:!0,onOpenChange:Re,project:o,onBeforeMutation:ze})})]})}function c_({participants:e,selectedIds:t,topLevelOnly:n,onToggle:r,onClear:i,onTopLevelOnlyChange:a}){let{t:o}=v(),[s,c]=(0,Y.useState)(!1),l=(0,Y.useRef)(null),u=t.size>0,d=e.find(e=>t.has(e.authorId)),f=e=>e.authorDisplayName??e.authorUsername??o(`editor.deletedUser`),p=u?d?t.size===1?f(d):o(`editor.commentParticipantsSelected`,{name:f(d),count:t.size-1}):o(`editor.commentParticipantsCount`,{count:t.size}):o(`editor.commentParticipantsAll`);return(0,X.jsx)(`div`,{className:`comment-participant-filter`,children:(0,X.jsxs)(`div`,{className:`comment-participants-trigger-group${u?` active`:``}`,children:[(0,X.jsxs)(re,{open:s,onOpenChange:c,children:[(0,X.jsx)(P,{asChild:!0,children:(0,X.jsxs)(`button`,{type:`button`,className:`comment-participants-toggle`,"aria-label":`${o(`editor.commentParticipants`)}: ${p}`,children:[(0,X.jsx)(j,{size:13,"aria-hidden":!0}),(0,X.jsx)(`span`,{className:`comment-participants-summary`,children:u&&d?f(d):p}),u&&d&&t.size>1&&(0,X.jsxs)(`span`,{className:`comment-participants-extra-count`,children:[`+`,t.size-1]}),(0,X.jsx)(W,{size:12,"aria-hidden":!0,className:s?`expanded`:``})]})}),(0,X.jsx)(B,{children:(0,X.jsxs)(N,{ref:l,className:`comment-participants-popover`,side:`bottom`,align:`end`,sideOffset:6,collisionPadding:10,"aria-label":o(`editor.commentParticipants`),onOpenAutoFocus:e=>{e.preventDefault();let t=l.current?.querySelector(`input[type="checkbox"]:not(:disabled)`);t?t.focus():l.current?.focus()},children:[(0,X.jsxs)(`div`,{className:`comment-participants-heading`,children:[(0,X.jsx)(se,{children:o(`editor.commentParticipants`)}),u&&(0,X.jsx)(`button`,{type:`button`,onClick:i,children:o(`editor.commentParticipantsClear`)})]}),(0,X.jsxs)(`div`,{className:`comment-participants-list`,children:[e.map(e=>{let n=f(e),i=t.has(e.authorId);return(0,X.jsxs)(`label`,{className:`comment-participant-option${i?` selected`:``}`,children:[(0,X.jsx)(`input`,{type:`checkbox`,checked:i,onChange:()=>r(e.authorId)}),(0,X.jsx)(F,{userId:e.authorId,name:n,username:e.authorUsername,avatarStyle:e.authorAvatarStyle,className:`comment-participant-avatar`}),(0,X.jsxs)(`span`,{className:`comment-participant-identity`,children:[(0,X.jsx)(`strong`,{children:n}),e.authorUsername&&(0,X.jsxs)(`small`,{children:[`@`,e.authorUsername]})]})]},e.authorId??`deleted`)}),e.length===0&&(0,X.jsx)(`p`,{className:`comment-participants-empty`,children:o(`editor.commentNoParticipants`)})]}),(0,X.jsxs)(`label`,{className:`comment-participants-root-only`,children:[(0,X.jsx)(`input`,{type:`checkbox`,checked:n,disabled:!u,onChange:e=>a(e.target.checked)}),o(`editor.commentTopLevelOnly`)]})]})})]}),u&&(0,X.jsx)(`button`,{type:`button`,className:`comment-participants-clear`,"aria-label":o(`editor.commentParticipantsClear`),onClick:i,children:(0,X.jsx)(V,{size:12,"aria-hidden":!0})})]})})}function l_(e,t,n,r,i){let a=t.map(e=>({comment:e,exitAt:null})),o=new Set(t.map(e=>e.id)),s=new Map(n.map(e=>[e.id,e]));return e.forEach((e,t)=>{let n=s.get(e.comment.id);o.has(e.comment.id)||!n||qp(n,r)||a.splice(Math.min(t,a.length),0,{comment:n,exitAt:e.exitAt??i+280+50})}),a}function u_(e,t,n,r){let[i,a]=(0,Y.useState)(()=>({contextKey:r,visible:e,comments:t,entries:e.map(e=>({comment:e,exitAt:null}))}));(i.contextKey!==r||i.visible!==e||i.comments!==t)&&a({contextKey:r,visible:e,comments:t,entries:i.contextKey===r?l_(i.entries,e,t,n,Date.now()):e.map(e=>({comment:e,exitAt:null}))});let o=(0,Y.useCallback)(e=>{a(t=>({...t,entries:t.entries.filter(t=>t.comment.id!==e||t.exitAt===null)}))},[]);return(0,Y.useEffect)(()=>{let e=i.entries.flatMap(e=>e.exitAt===null?[]:[e.exitAt]);if(!e.length)return;let t=window.setTimeout(()=>{let e=Date.now();a(t=>({...t,entries:t.entries.filter(t=>t.exitAt===null||t.exitAt>e)}))},Math.max(0,Math.min(...e)-Date.now()));return()=>window.clearTimeout(t)},[i.entries]),{entries:i.entries,finishExit:o}}function d_(e,t,n,r){let[i,a]=(0,Y.useState)(()=>({contextKey:n,limit:50})),o=i.contextKey===n?i.limit:50;if(t)for(let t of r){if(!t)continue;let n=e.findIndex(e=>e.id===t)+1;o=Math.max(o,Math.ceil(n/50)*50)}(i.contextKey!==n||i.limit!==o)&&a({contextKey:n,limit:o});let s=(0,Y.useMemo)(()=>t?e.slice(0,o):e,[e,t,o]),c=(0,Y.useCallback)(()=>{a(e=>({contextKey:n,limit:(e.contextKey===n?e.limit:50)+50}))},[n]);return{shown:s,hasMore:s.length<e.length,loadMore:c}}var f_=(0,Y.lazy)(()=>S(()=>import(`./ProjectSettings-CARW1k8M.js`).then(e=>({default:e.ProjectSettings})),__vite__mapDeps([50,2,3,22,5,4,7,10,16,17,12,1,6,8,9,11,13,32,45,23,28,33,34,25,30,31,51,52,37]),import.meta.url));function p_({phone:e=!1,commentsHost:t,sidePanel:n,onClose:r,project:i,projectId:s,site:c,files:l,currentUserId:u,comments:d,commentDraftStore:f,commentsLoading:p,commentsError:m,onRetryComments:h,unreadMentions:g,activeFile:_,singleCommentId:y,onShowAllComments:b,hasProjectCommentsScope:x,commentScope:S,onCommentScopeChange:C,focusedCommentId:T,commentFocusNonce:E,onMarkMentionRead:D,onMarkAllMentionsRead:k,onClearFocusComment:A,targetCommentId:j,targetReplyId:M,onFocusComment:ee,onToggleComment:N,onReplyComment:P,onEditComment:te,onDeleteComment:F,onEditCommentReply:I,onDeleteCommentReply:L,dictionaryWords:ne,onDictionaryChange:re,editorPreferences:ie,onEditorPreferences:R,spellCheckCount:z,spellCheckUniqueCount:ae,spellCheckIndex:B,onSpellCheckNavigate:oe,onProject:se}){let{t:H}=v(),U=!!y,[W,ce]=(0,Y.useState)(`unresolved`),[le,ue]=(0,Y.useState)(!1),[de,fe]=(0,Y.useState)(`source`),pe=H(de===`time`?`editor.commentSortTime`:S===`project`?`editor.commentSortSourceProject`:`editor.commentSortSource`),[me,he]=(0,Y.useState)(()=>new Set),[ge,_e]=(0,Y.useState)(!0),[ve,ye]=(0,Y.useState)(()=>new Map),[be,xe]=(0,Y.useState)(null),Se=(0,Y.useRef)(new Map(d.map(e=>[e.id,e.resolved]))),Ce=(0,Y.useMemo)(()=>Up(d),[d]),Ee=(0,Y.useMemo)(()=>{let e=d.filter(e=>Kp(e,{activeFile:_,scope:S})),t=e.filter(e=>e.resolved).length;return{unresolved:e.length-t,resolved:t}},[_,S,d]),De=(0,Y.useMemo)(()=>Yp(d,{activeFile:_,scope:S,unreadMentions:g,participantIds:me,topLevelOnly:ge,filter:W,unreadMentionsOnly:!0}).length,[_,S,d,g,me,ge,W]),Oe=(0,Y.useMemo)(()=>y?Zp(d,y,_):Xp(d,{activeFile:_,scope:S,filter:W,unreadMentions:g,sort:de,participantIds:me,topLevelOnly:ge,unreadMentionsOnly:le},[j,T]),[_,y,W,S,d,T,j,g,de,me,ge,le]),ke=T&&Oe.some(e=>e.id===T)?T:j&&Oe.some(e=>e.id===j)?j:null,Ae=U?Oe[0]?.id??null:be&&Oe.some(e=>e.id===be)?be:ke;(0,Y.useEffect)(()=>{xe(null)},[T,E,j,M,_,S]),(0,Y.useEffect)(()=>{be&&!Oe.some(e=>e.id===be)&&xe(null)},[be,Oe]);let je=tm(Oe,Ae),Me=JSON.stringify([n,y,S,S===`file`?_:``,W,de,[...me].sort(),ge,le]),Ne=JSON.stringify([s,S,S===`file`?_:``,W,de,[...me].sort(),ge,le]),{shown:Pe,hasMore:Fe,loadMore:Ie}=d_(Oe,!U&&W===`resolved`,Ne,[j,T,be]),{entries:Le,finishExit:Re}=u_(Pe,d,U?`unresolved`:W,Me);(0,Y.useEffect)(()=>{let e=d.some(e=>(e.id===T||e.id===j)&&Se.current.has(e.id)&&Se.current.get(e.id)!==e.resolved);Se.current=new Map(d.map(e=>[e.id,e.resolved])),e&&A()},[d,T,j,A]),(0,Y.useEffect)(()=>{if(n!==`comments`||be)return;let e=j&&M?`.comments [data-comment-reply-id="${M}"]`:j?`.comments .comment-thread[data-comment-id="${j}"]`:ke?`.comments .comment-thread[data-comment-id="${ke}"]`:``;if(!e)return;let t=document.querySelector(e);if(!t)return;let r=window.requestAnimationFrame(()=>t.scrollIntoView({block:j?`center`:`nearest`,behavior:`smooth`}));return()=>window.cancelAnimationFrame(r)},[n,be,ke,E,j,M,Oe]);let ze=e=>{xe(null),ee(e)},Be=e=>{let t=nm(Oe,Ae,e);t?ze(t):A()},Ve=async e=>{let t=await D(e);if(!t||U||!le)return t;let n=g.find(t=>t.id===e)?.commentId;return n&&(g.some(t=>t.id!==e&&t.commentId===n)||(T===n||j===n)&&A()),t},He=async()=>{await k()&&le&&A()},K=e=>{e!==S&&(xe(null),A(),C(e))},q=e=>{e!==W&&(xe(null),A(),ce(e))},Ue=()=>{xe(null),A()},We=e=>{Ue(),me.size===1&&me.has(e)&&_e(!0),he(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};if(!n)return null;let J=(0,X.jsxs)(`aside`,{className:`context-panel`,"aria-label":H(n===`comments`?`editor.sourceComments`:`editor.projectSettings`),children:[n===`comments`&&(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{className:`drawer-title`,children:[(0,X.jsx)(`strong`,{children:H(U?`editor.currentComment`:`editor.sourceComments`)}),(0,X.jsxs)(`span`,{className:`drawer-title-actions`,children:[!U&&g.length>0&&(0,X.jsxs)(`button`,{className:`drawer-mention-read-all`,type:`button`,onClick:()=>void He(),title:H(`editor.markAllMentionsRead`),children:[(0,X.jsx)(o,{"aria-hidden":!0,size:13}),(0,X.jsx)(`span`,{children:H(`editor.markAllMentionsRead`)})]}),(0,X.jsx)(`button`,{"aria-label":H(`common.close`),onClick:r,children:(0,X.jsx)(V,{size:17})})]})]}),U?(0,X.jsx)(`div`,{className:`comment-current-controls`,children:(0,X.jsxs)(`button`,{type:`button`,onClick:b,children:[(0,X.jsx)(_t,{size:14,"aria-hidden":!0}),H(`editor.viewAllComments`)]})}):(0,X.jsxs)(`div`,{className:`comment-review-controls`,children:[(0,X.jsxs)(`div`,{className:`comment-review-queue-row`,children:[x&&(0,X.jsxs)(`div`,{className:`comment-review-group`,role:`group`,"aria-label":H(`editor.commentScope`),children:[(0,X.jsx)(`button`,{type:`button`,className:S===`file`?`active`:``,"aria-pressed":S===`file`,onClick:()=>K(`file`),children:H(`editor.commentScopeFile`)}),(0,X.jsx)(`button`,{type:`button`,className:S===`project`?`active`:``,"aria-pressed":S===`project`,onClick:()=>K(`project`),children:H(`editor.commentScopeProject`)})]}),(0,X.jsxs)(`div`,{className:`comment-review-group`,role:`group`,"aria-label":H(`editor.commentFilter`),children:[(0,X.jsx)(`button`,{type:`button`,className:W===`unresolved`?`active`:``,"aria-pressed":W===`unresolved`,onClick:()=>q(`unresolved`),children:H(`editor.commentFilterUnresolved`,{count:Ee.unresolved})}),(0,X.jsx)(`button`,{type:`button`,className:W===`resolved`?`active`:``,"aria-pressed":W===`resolved`,onClick:()=>q(`resolved`),children:H(`editor.commentFilterResolved`,{count:Ee.resolved})})]}),(0,X.jsxs)(`div`,{className:`comment-review-navigation`,children:[(0,X.jsx)(`button`,{type:`button`,disabled:je<=1,"aria-label":H(`editor.commentPrevious`),title:H(`editor.commentPrevious`),onClick:()=>Be(-1),children:(0,X.jsx)(a,{size:14})}),(0,X.jsx)(`output`,{"aria-live":`polite`,children:H(`editor.commentPosition`,{current:je,total:Oe.length})}),(0,X.jsx)(`button`,{type:`button`,disabled:Oe.length===0||je>0&&je>=Oe.length,"aria-label":H(`editor.commentNext`),title:H(`editor.commentNext`),onClick:()=>Be(1),children:(0,X.jsx)(O,{size:14})})]})]}),(0,X.jsxs)(`div`,{className:`comment-review-sort-row`,children:[(0,X.jsx)(c_,{participants:Ce,selectedIds:me,topLevelOnly:ge,onToggle:We,onClear:()=>{Ue(),he(new Set),_e(!0)},onTopLevelOnlyChange:e=>{Ue(),_e(e)}},`${S}:${S===`file`?_:`project`}`),(0,X.jsxs)(`button`,{type:`button`,className:`comment-unread-toggle${le?` active`:``}`,"aria-pressed":le,"aria-label":H(`editor.commentUnreadMentionsHint`),title:H(`editor.commentUnreadMentionsHint`),onClick:()=>{Ue(),ue(e=>!e)},children:[(0,X.jsx)(o,{size:12,"aria-hidden":!0}),H(`editor.commentUnreadMentionsOnly`),(0,X.jsx)(`span`,{children:De})]}),(0,X.jsxs)(`label`,{className:`comment-review-sort`,"data-texlite-tooltip-always":!0,"data-tooltip":pe,children:[(0,X.jsx)(`span`,{className:`sr-only`,children:H(`editor.commentSort`)}),de===`source`?(0,X.jsx)(w,{size:12,"aria-hidden":!0}):(0,X.jsx)(rt,{size:12,"aria-hidden":!0}),(0,X.jsxs)(`select`,{value:de,"aria-label":`${H(`editor.commentSort`)}: ${pe}`,onChange:e=>{Ue(),fe(e.target.value)},children:[(0,X.jsx)(`option`,{value:`source`,children:H(`editor.commentSortSourceShort`)}),(0,X.jsx)(`option`,{value:`time`,children:H(`editor.commentSortTimeShort`)})]})]})]})]}),m&&(0,X.jsxs)(`div`,{className:`comment-review-error`,role:`alert`,children:[(0,X.jsx)(`span`,{children:m}),(0,X.jsx)(`button`,{type:`button`,onClick:()=>void h(),children:H(`common.retry`)})]}),p&&(0,X.jsx)(`div`,{className:`comment-review-loading`,role:`status`,children:H(`common.loading`)}),(0,X.jsxs)(`div`,{className:`comments`,children:[Le.map(({comment:e,exitAt:t})=>{let n=g.find(t=>t.commentId===e.id&&!t.replyId)?.id,r=new Map(g.filter(t=>t.commentId===e.id&&t.replyId).map(e=>[e.replyId,e.id]));return(0,X.jsx)(`div`,{className:`comment-thread-slot${t===null?``:` is-exiting`}`,inert:t!==null||void 0,"aria-hidden":t!==null||void 0,style:{"--comment-exit-duration":`280ms`},onAnimationEnd:n=>{n.target===n.currentTarget&&t!==null&&Re(e.id)},children:(0,X.jsx)(`div`,{className:`comment-thread-slot-content`,children:(0,X.jsx)(Qg,{projectId:s,comment:e,draftStore:f,currentUserId:u,projectOwnerId:i.ownerId,canEditSource:i.permission!==`read`,unreadCommentMentionKind:g.find(e=>e.id===n)?.kind,unreadCommentMentionId:n,unreadReplyMentionIds:r,highlightedComment:j===e.id&&!M,highlightedReplyId:j===e.id?M:null,currentComment:Ae===e.id,showFilePath:!U&&S===`project`&&x,replyExpansion:ve.get(e.id),onReplyExpansionChange:t=>{ye(n=>n.get(e.id)===t?n:new Map(n).set(e.id,t))},selectedParticipantIds:U?void 0:me,highlightReplyParticipants:!U&&!ge,onMarkMentionRead:Ve,onFocus:()=>ze(e),onActivate:()=>xe(e.id),onToggle:()=>N(e),onReply:t=>P(e,t),onEdit:t=>te(e,t),onDelete:()=>F(e),onEditReply:(t,n)=>I(e,t,n),onDeleteReply:t=>L(e,t)})})},e.id)}),Le.length===0&&!p&&!m&&(0,X.jsxs)(`div`,{className:`comment-review-empty`,role:`status`,children:[(0,X.jsx)(`span`,{className:`comment-review-empty-icon`,"aria-hidden":`true`,children:(0,X.jsx)(_t,{size:23,strokeWidth:1.5})}),(0,X.jsx)(`p`,{children:U?H(d.some(e=>e.id===y&&e.resolved)?`editor.currentCommentResolved`:`editor.currentCommentUnavailable`):Ee.unresolved+Ee.resolved>0?H(`editor.commentNoMatches`):H(`editor.noComments`)})]}),!U&&W===`resolved`&&Fe&&(0,X.jsx)(`div`,{className:`comment-review-pagination`,children:(0,X.jsx)(`button`,{type:`button`,onClick:Ie,children:H(`editor.commentLoadMore`)})})]})]}),n===`settings`&&(0,X.jsx)(Ge,{onClose:r,children:(0,X.jsx)(f_,{onClose:r,project:i,projectId:s,site:c,files:l,dictionaryWords:ne,onDictionaryChange:re,editorPreferences:ie,onEditorPreferences:R,spellCheckCount:z,spellCheckUniqueCount:ae,spellCheckIndex:B,onSpellCheckNavigate:oe,onProject:se},s)})]});return e?(0,X.jsx)(we,{open:!0,title:H(n===`comments`?`editor.sourceComments`:`editor.projectSettings`),onClose:r,children:J}):n===`comments`&&t!==void 0?t?(0,wt.createPortal)(J,t):null:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Te,{className:`resize-handle`}),(0,X.jsx)(G,{id:`context`,defaultSize:`20%`,minSize:`15%`,maxSize:`38%`,children:J})]})}function m_(e,t,n){return e.mainFile===t?e.items:!t||n.filePath!==t?[]:h_(n.content).map(e=>({...e,path:t}))}function h_(e){let t=[],n=/^\s*\\(part|chapter|section|subsection|subsubsection)\*?(?:\[[^\]]*\])?\{([^}]*)\}/,r={part:0,chapter:0,section:1,subsection:2,subsubsection:3};return e.split(`
|
|
19
|
-
`).forEach((e,i)=>{let a=e.match(n);a&&t.push({level:r[a[1]],title:a[2],line:i+1})}),t}var g_=e({ProjectWorkspace:()=>C_}),__=(0,Y.lazy)(()=>S(()=>import(`./AgentTerminal-BbGH5iPx.js`).then(e=>({default:e.AgentTerminal})),__vite__mapDeps([53,2,3,22,5,4,7,10,16,17,12,1,6,8,9,11,13,23,24,54,55,45,32,28,33,34,27,29,31]),import.meta.url)),v_=(0,Y.lazy)(()=>S(()=>import(`./WordCountDialog-CJb1b8cD.js`).then(e=>({default:e.WordCountDialog})),__vite__mapDeps([56,3,2,4,5,16,7,10,17,12,45,23,32,28,9,33,11,1,6,8,13,34,52]),import.meta.url)),y_=null;function b_(){return y_||=S(()=>import(`./citationLibrary-BzlqZiFU.js`),__vite__mapDeps([36,2]),import.meta.url).catch(e=>{throw y_=null,e}),y_}function x_(e){return e instanceof Error&&e.name===`AbortError`}var S_=300;function C_(e){return(0,X.jsx)(im,{children:(0,X.jsx)(Fh,{projectId:e.projectId,user:e.user,children:t=>(0,X.jsx)(w_,{...e,collaboration:t})})},`${e.user.id}:${e.projectId}`)}function w_({site:e,user:t,projectId:n,preload:r,mentionId:i=null,onMentionTargeted:a,onMentionsRead:o,onBack:s,collaboration:c}){let{t:u}=v(),d=(0,Y.useRef)(n),f=l(t.id,n),[p,m]=(0,Y.useState)(!1);d.current=n;let[h,g]=(0,Y.useState)(null),_=(0,Y.useCallback)((e,t)=>{g(n=>n?.id===e&&n.sharedMemberCount!==t?{...n,sharedMemberCount:t}:n)},[]);(0,Y.useEffect)(()=>(document.title=h?.name?`${e.siteName} | ${h.name}`:e.siteName,()=>{document.title=e.siteName}),[h?.name,e.siteName]);let[b,x]=(0,Y.useState)([]),[S,C]=(0,Y.useState)(null),[w,T]=(0,Y.useState)({mainFile:``,items:[]}),[E,D]=(0,Y.useState)(``),[O,k]=(0,Y.useState)(``),[A,j]=(0,Y.useState)(``),[M,ee]=(0,Y.useState)({filePath:``,content:``}),[N,P]=(0,Y.useState)({path:``,hasIncludes:!1}),[F,I]=(0,Y.useState)(``),[L,ne]=(0,Y.useState)(!1),[re,R]=(0,Y.useState)(`editor.saved`),[ae,B]=(0,Y.useState)(null),se=(0,Y.useRef)(ae);se.current=ae;let H=(0,Y.useRef)(null);H.current||=Oe();let U=H.current,[W,ce]=(0,Y.useState)(`pdf`),[le,ue]=(0,Y.useState)(`log`),de=e=>{e===`pdf`?ce(`pdf`):(e===`diagnostics`||ue(e),ce(`diagnostics`))},{workspaceLayout:pe,setWorkspaceLayout:me,phone:he}=ig(t.id,n),[ge,_e]=(0,Y.useState)(!1),[ve,G]=(0,Y.useState)(``),[ye,be]=(0,Y.useState)(``),[xe,Ce]=(0,Y.useState)({selectedText:``,startOffset:0,endOffset:0}),we=(0,Y.useRef)({selectedText:``,startOffset:0,endOffset:0}),De=e=>{let t=we.current;(t.selectedText!==e.selectedText||t.startOffset!==e.startOffset||t.endOffset!==e.endOffset)&&(we.current=e,Ce(e))},[je,Me]=(0,Y.useState)(null),[Ne,Pe]=(0,Y.useState)(null),[Ie,Le]=(0,Y.useState)(null),[Re,ze]=(0,Y.useState)(null),[Be,He]=(0,Y.useState)(null),[Ue,Ge]=(0,Y.useState)(null),[Ke,qe]=(0,Y.useState)(!1),[Je,Ye]=(0,Y.useState)(!1),[Xe,Ze]=(0,Y.useState)(!1),[Qe,$e]=(0,Y.useState)(!1),[et,tt]=(0,Y.useState)(null),[nt,rt]=(0,Y.useState)(!1),[it,at]=(0,Y.useState)(null),[ot,st]=(0,Y.useState)(!1),[ct,lt]=(0,Y.useState)(!1),[ut,dt]=(0,Y.useState)(!1),[ft,pt]=(0,Y.useState)(`full`),[mt,ht]=(0,Y.useState)(``),[gt,_t]=(0,Y.useState)(!1),[vt,yt]=(0,Y.useState)(``),[bt,xt]=(0,Y.useState)(null),[St,Ct]=(0,Y.useState)(!1),[wt,Tt]=(0,Y.useState)(null),[Et,Dt]=(0,Y.useState)(!1),[Ot,kt]=(0,Y.useState)(()=>ie(t.id,n));(0,Y.useEffect)(()=>{let e=document.documentElement,t=Ot.showTooltips?`on`:`off`;return e.setAttribute(`data-texlite-tooltips`,t),()=>{e.getAttribute(`data-texlite-tooltips`)===t&&e.removeAttribute(`data-texlite-tooltips`)}},[Ot.showTooltips]);let[At,jt]=(0,Y.useState)([]),Mt=(0,Y.useRef)([]);Mt.current=At;let Nt=(0,Y.useRef)(null),Pt=(0,Y.useRef)(null),Ft=(0,Y.useRef)(0),It=(0,Y.useRef)(0),Lt=(0,Y.useRef)(``),Rt=(0,Y.useRef)(``),zt=(0,Y.useRef)(()=>void 0),Bt=(0,Y.useRef)(pe),Vt=(0,Y.useRef)(0),Ht=(0,Y.useRef)(null),Ut=(0,Y.useRef)(null),Wt=(0,Y.useRef)(null),Gt=(0,Y.useRef)(null),Kt=(0,Y.useRef)(null),qt=(0,Y.useRef)(null),Jt=(0,Y.useRef)(null),Yt=(0,Y.useRef)(null),Xt=(0,Y.useRef)(null),Zt=(0,Y.useRef)(!1),Qt=(0,Y.useRef)(null),$t=(0,Y.useRef)(s),en=(0,Y.useRef)(a),tn=(0,Y.useRef)(o);$t.current=s,en.current=a,tn.current=o,Lt.current=E,Rt.current=O,Bt.current=pe,(0,Y.useEffect)(()=>{if(!ye)return;let e=window.setTimeout(()=>be(``),3e3);return()=>window.clearTimeout(e)},[ye]);let nn=(0,Y.useCallback)((e,t,n=0)=>{U.update(e,t,n)},[U]);(0,Y.useEffect)(()=>()=>U.dispose(),[U]),(0,Y.useEffect)(()=>()=>{Yt.current?.abort(),Yt.current=null},[]);let rn=e=>{let t=Mt.current,n=e(t);n!==t&&(Mt.current=n,jt(n))};(0,Y.useEffect)(()=>{Mt.current=[],jt([]),Tt(null),tt(null),qt.current?.abort(),qt.current=null,Jt.current?.abort(),Jt.current=null,Yt.current?.abort(),Yt.current=null,Xt.current=null,ze(null),He(null),Ge(null),dt(!1),_t(!1),yt(``),xt(null)},[n]);let an=e=>{let t=Mt.current,n=t.indexOf(e);if(n<0)return;let r=t.filter(t=>t!==e);if(Mt.current=r,jt(r),Lt.current!==e)return;let i=r.length>0?r[Math.min(n,r.length-1)]:h?.mainFile??``;D(i)},{status:on,synced:sn,activeSessions:cn,formatLeaseStates:ln,compileState:un,setCompileState:dn,filesEvent:fn,commentsRevision:pn,historyWarning:mn,dictionaryRevision:hn,chktexSettingsRevision:gn,localDraftReady:_n,permission:vn,reconnect:yn,protocolUpgradeRequired:bn,permissionDowngrade:xn,dismissPermissionDowngrade:Sn,discardLocalDraft:Cn}=om(c,O,h?.permission??`read`,h?.id===n),{unreadMentions:wn,mentionsError:Tn,markMentionRead:En,markAllMentionsRead:Dn}=rm(n,pn,G,(e,t)=>tn.current?.(e,t)),{pdfTarget:On,pdfViewport:kn,sourceJump:An,setPdfViewport:jn,resetPdfViewport:Mn,clearPdfViewport:Nn,jumpToSource:Pn,syncSourceToPdf:Fn,syncPdfToSource:In,syncVisiblePdfToSource:Ln}=tg({projectId:n,mainFile:O,activeFile:E,onOpenSourceFile:e=>zt.current(e),onError:G,onShowPdf:()=>{de(`pdf`),he&&me(`pdf-only`)},onShowEditor:()=>{Bt.current===`pdf-only`&&me(`editor-pdf`)}}),Rn=!!(h&&h.chktexEnabled&&E&&sn&&fd(E)),zn=Qh({active:Rn,projectId:n,activeFile:E,content:A}),Bn=Zh({active:!!(h&&E&&sn&&dd(E)&&(Ot.spellCheck||h.chktexEnabled&&fd(E))),harperEnabled:Ot.spellCheck,projectId:n,activeFile:E,content:A,dictionaryWords:b,additionalIssues:zn.issues,additionalIssuesReady:!Rn||zn.checked});(0,Y.useEffect)(()=>{kt(ie(t.id,n))},[t.id,n]);let Vn=e=>{j(e)};(0,Y.useEffect)(()=>{if(!E||F!==E){ee(e=>e.filePath||e.content?{filePath:``,content:``}:e);return}let e=E,t=A,n=window.setTimeout(()=>{ee(n=>n.filePath===e&&n.content===t?n:{filePath:e,content:t})},S_);return()=>window.clearTimeout(n)},[E,F,A]),(0,Y.useEffect)(()=>{Lt.current=E,U.reset(),De({selectedText:``,startOffset:0,endOffset:0}),Ot.openFilesInTabs?E&&rn(e=>e.includes(E)?e:[...e,E]):Mt.current.length>0&&(Mt.current=[],jt([]))},[E,Ot.openFilesInTabs,n,U]),(0,Y.useEffect)(()=>{if(!L)return;let e=e=>{e.preventDefault(),e.returnValue=``};return window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e)},[L]),(0,Y.useEffect)(()=>{if(on!==`disconnected`)return;let e=new AbortController;return q(`/api/projects/${n}`,{signal:e.signal}).then(({project:t})=>{e.signal.aborted||(g(t),G(``))}).catch(e=>{x_(e)||(e instanceof We&&[401,403,404].includes(e.status)?(G(K(e)),$t.current()):G(u(`errors.collaborationUnavailable`)))}),()=>e.abort()},[on,n,u]);let Hn=async(e={},t=Rt.current)=>{Ht.current?.abort(),Ht.current=null;let r=e.signal?null:new AbortController;r&&(Ht.current=r);try{let i=t?`?mainFile=${encodeURIComponent(t)}`:``,a=await q(`/api/projects/${n}/completions${i}`,{signal:e.signal??r?.signal});(!e.isCurrent||e.isCurrent())&&C(a.index)}catch(t){if(x_(t))return;(!e.isCurrent||e.isCurrent())&&C(null)}finally{r&&Ht.current===r&&(Ht.current=null)}},Un=async(e={},t=Rt.current)=>{Wt.current?.abort(),Wt.current=null;let r=e.signal?null:new AbortController;r&&(Wt.current=r);try{let i=t?`?mainFile=${encodeURIComponent(t)}`:``,a=await q(`/api/projects/${n}/outline${i}`,{signal:e.signal??r?.signal});(!e.isCurrent||e.isCurrent())&&Rt.current===t&&T({mainFile:t,items:a.outline})}catch(e){if(x_(e))return}finally{r&&Wt.current===r&&(Wt.current=null)}},Wn=async(e={})=>{Gt.current?.abort(),Gt.current=null;let t=e.signal?null:new AbortController;t&&(Gt.current=t);try{let r=await q(`/api/projects/${n}/dictionary`,{signal:e.signal??t?.signal});(!e.isCurrent||e.isCurrent())&&x(r.words)}catch(t){if(x_(t))return;(!e.isCurrent||e.isCurrent())&&x([])}finally{t&&Gt.current===t&&(Gt.current=null)}};(0,Y.useEffect)(()=>{let e=!1,t=++Vt.current,i=new AbortController,a=()=>!e&&Vt.current===t,o=!1,s=``;g(null),tr([]),T({mainFile:``,items:[]}),D(``),k(``),P({path:``,hasIncludes:!1}),j(``),I(``),dn(null),Nn(),C(null),x([]),J();let c=(r?.projectId===n?r.project:q(`/api/projects/${n}`,{signal:i.signal})).then(e=>{a()&&(o=!0,s=e.project.mainFile,g(e.project),D(e.project.mainFile),Rt.current=e.project.mainFile,k(e.project.mainFile),Sr(new Set(Wh(e.project.mainFile))))}).catch(e=>{a()&&G(K(e))}),l=q(`/api/projects/${n}/files`,{signal:i.signal}).then(e=>{a()&&tr(e.files)}).catch(e=>{a()&&G(K(e))}),u=null;return Promise.allSettled([c,l]).then(()=>{a()&&o&&(u=window.setTimeout(()=>{a()&&Promise.all([Hn({signal:i.signal,isCurrent:a},Rt.current||s),Wn({signal:i.signal,isCurrent:a})])},0))}),()=>{e=!0,u!==null&&window.clearTimeout(u),i.abort(),Ht.current?.abort(),Ht.current=null,Wt.current?.abort(),Wt.current=null,Gt.current?.abort(),Gt.current=null,Kt.current?.abort(),Kt.current=null}},[n,r]),(0,Y.useEffect)(()=>{h&&O&&(Ut.current===n?Hn({},O):Ut.current=n)},[O,h?.id,n]),(0,Y.useEffect)(()=>{if(!i||!h)return;Jt.current?.abort();let e=new AbortController;return Jt.current=e,q(`/api/projects/${n}/mentions/${encodeURIComponent(i)}`,{signal:e.signal}).then(({mention:t})=>{e.signal.aborted||(ze(t),Le(null),Me(`comments`),D(t.filePath),en.current?.(t.id))}).catch(t=>{x_(t)||e.signal.aborted||(G(K(t)),en.current?.(i))}).finally(()=>{Jt.current===e&&(Jt.current=null)}),()=>e.abort()},[i,h?.id,n]),(0,Y.useEffect)(()=>{hn&&Wn()},[hn,n]),(0,Y.useEffect)(()=>{if(!gn)return;let e=new AbortController;return q(`/api/projects/${n}`,{signal:e.signal}).then(({project:t})=>{e.signal.aborted||g(e=>e?{...e,chktexEnabled:t.chktexEnabled}:t)}).catch(e=>{x_(e)||G(K(e))}),()=>e.abort()},[gn,n]),(0,Y.useEffect)(()=>{h&&on===`connected`&&vn!==h.permission&&g(e=>e&&{...e,permission:vn})},[vn,h?.permission]),(0,Y.useEffect)(()=>{if(!fn)return;let t=fn.kind===`delete`&&!!fn.path&&Gh(fn.path,Lt.current),r=fn.kind===`delete`&&!!fn.path&&Gh(fn.path,Rt.current);if(fn.kind===`move`&&fn.source&&fn.destination){let e=fn.source,t=fn.destination,n=n=>n===e?t:n.startsWith(`${e}/`)?`${t}${n.slice(e.length)}`:n;D(e=>n(e)),k(e=>n(e)),vr(e=>e&&n(e)),br(e=>e&&n(e)),rn(e=>e.map(n))}t&&(D(``),I(``),Vn(``),be(u(`editor.fileDeletedByCollaborator`,{path:fn.path}))),fn.kind===`delete`&&fn.path&&(vr(e=>e&&Gh(fn.path,e)?null:e),br(e=>Gh(fn.path,e)?``:e),cr(e=>e&&Gh(fn.path,e.path)?null:e),rn(e=>e.filter(e=>!Gh(fn.path,e)))),Kt.current?.abort();let i=new AbortController;Kt.current=i,Promise.all([nr({signal:i.signal}),q(`/api/projects/${n}`,{signal:i.signal})]).then(([n,a])=>{if(g(a.project),r&&k(a.project.mainFile),t&&n){let t=n.find(e=>e.type===`file`&&e.path===a.project.mainFile)??n.find(t=>t.type===`file`&&Ae(t.path,t.textContent)&&(t.size??0)<=e.maxCollaborativeFileSizeMB*1024*1024);D(t?.path??``)}Hn({signal:i.signal}),Un({signal:i.signal},r?a.project.mainFile:Rt.current)}).catch(e=>{x_(e)}).finally(()=>{Kt.current===i&&(Kt.current=null)})},[fn?.revision]),(0,Y.useEffect)(()=>{if(c.setActiveFile(E),!E)return;I(``),R(`editor.loading`);let e=c.getText(E),t=(t,n)=>{Vn(e.toString()),I(E),n?.local&&h?.permission!==`read`?(Ft.current+=1,ne(!0),R(`editor.pending`)):Ft.current<=It.current&&R(se.current?`editor.savedAt`:`editor.saved`)};return e.observe(t),(sn||_n)&&t(),()=>{e.unobserve(t)}},[E,c,sn,_n,h?.permission]);let Gn=async()=>{if(!sn)throw Error(`Collaboration is not synchronized`);let e=Ft.current,t=await c.flush();return It.current=Math.max(It.current,e),B(t.persistedAt),/\.tex$/i.test(Lt.current)&&Un(),Ft.current===e?(ne(!1),R(`editor.savedAt`)):R(`editor.pending`),t};(0,Y.useEffect)(()=>{if(!L||!E||!sn)return;R(`editor.pending`);let e=window.setTimeout(()=>{R(`editor.saving`),Gn().catch(()=>{R(`editor.saveFailed`)})},750);return()=>window.clearTimeout(e)},[A,L,E,sn]);let Kn=async()=>{if(!h||h.permission===`read`||!sn||!E)return!1;R(`editor.saving`);try{return await Gn(),Hn(),!0}catch(e){return R(`editor.saveFailed`),G(K(e)||u(`errors.collaborationUnavailable`)),!1}},qn=async e=>{if(!h||gt)return;let t=e===`full`?Rt.current||h.mainFile:Lt.current,r=e===`selection`?we.current.selectedText:``;if(!t)return;if(e===`selection`&&(!r.trim()||!/\.(?:tex|sty|cls)$/i.test(t))){be(u(`editor.wordCountSelectionEmpty`));return}qt.current?.abort();let i=new AbortController;qt.current=i,pt(e),ht(t),xt(null),yt(``),dt(!0),_t(!0);try{if(e===`full`&&L&&h.permission!==`read`&&!await Kn())throw Error(u(`editor.wordCountSaveRequired`));let a=e===`selection`?{mode:e,path:t,source:r}:{mode:e,mainFile:t},o=await q(`/api/projects/${n}/word-count`,{method:`POST`,body:JSON.stringify(a),signal:i.signal});if(i.signal.aborted)return;xt(o)}catch(e){if(x_(e))return;i.signal.aborted||yt(K(e))}finally{qt.current===i&&(qt.current=null,_t(!1))}},Jn=async(t,n,r=Ot.texFmtConfig)=>{if(/\.bib$/i.test(t))try{return{formatted:await Kd(n,e.maxCitationBibtexBytes)}}catch(t){throw t instanceof Vd?t.kind===`too-large`?Error(u(`citationLibrary.fileTooLarge`,{size:`${Math.round(e.maxCitationBibtexBytes/1024)} KB`})):t.kind===`invalid`?Error(u(`citationLibrary.fileInvalid`)):Error(u(t.kind===`timeout`?`editor.bibtexFormatterTimeout`:`editor.bibtexFormatterUnavailable`)):t}return{formatted:(await jd(n,r)).output}},Yn=async(e,t,n,r=0)=>{if(!/\.bib$/i.test(e))return Ld(t,n,r);try{return await qd(t,n,r)}catch(e){throw e instanceof Vd?Error(u(e.kind===`timeout`?`editor.bibtexFormatterTimeout`:`editor.bibtexFormatterUnavailable`)):e}},Xn=async e=>{if(!h||h.permission===`read`||!sn||Zt.current||!Pd(Lt.current))return;let t=Lt.current,n=c.getText(t);Zt.current=!0,Ct(!0);let r=()=>{},i=new Promise(e=>{r=e});Qt.current=i;let a=null;try{a=await c.acquireFormatLease(t);let r=n.toString(),{formatted:i}=await Jn(t,r,e);if(Lt.current!==t||n.toString()!==r){G(u(`editor.formatSourceChanged`));return}await a.confirm();let o=await Yn(t,r,i);if(Lt.current!==t||n.toString()!==r||(await a.confirm(),Lt.current!==t||n.toString()!==r)){G(u(`editor.formatSourceChanged`));return}o.length&&c.applyTextEdits(t,o),o.length&&await Gn(),Tt(null),G(``),be(u(`editor.formatFileComplete`))}catch(e){Ed(e)?(Tt({action:`file`,kind:e.kind,detail:e.message}),G(``)):G(u(`editor.formatFileFailed`,{message:K(e)}))}finally{a&&await a.release(),Zt.current=!1,Ct(!1),r(),Qt.current===i&&(Qt.current=null)}},Zn=async()=>{if(!Ot.formatOnCompile||!h||h.permission===`read`||!sn||!Pd(Lt.current)||Zt.current)return;let e=Lt.current,t=c.getText(e);Zt.current=!0,Ct(!0);let n=null;try{n=await c.acquireFormatLease(e);let r=t.toString(),{formatted:i}=await Jn(e,r);await n.confirm();let a=await Yn(e,r,i);if(Lt.current!==e||t.toString()!==r||(await n.confirm(),Lt.current!==e||t.toString()!==r))throw Error(u(`editor.formatSourceChanged`));a.length&&c.applyTextEdits(e,a),a.length&&await c.flush(),Tt(null)}catch(e){Ed(e)?(Tt({action:`file`,kind:e.kind,detail:e.message}),G(``)):G(u(`editor.formatFailedContinue`,{message:K(e)}))}finally{n&&await n.release(),Zt.current=!1,Ct(!1)}},Qn=async()=>(Qt.current&&await Qt.current,await Zn(),Kn()),$n=async e=>{if(!h||h.permission===`read`||!sn||Zt.current||!Pd(Lt.current))return;let t=we.current;if(!t.selectedText.trim()){be(u(`editor.formatSelectionRequired`));return}let n=Lt.current,{startOffset:r,endOffset:i,selectedText:a}=t,o=c.getText(n);if(o.toString().slice(r,i)!==a){G(u(`editor.formatSelectionChanged`));return}Zt.current=!0,Ct(!0);let s=()=>{},l=new Promise(e=>{s=e});Qt.current=l;let d=null;try{if(d=await c.acquireFormatLease(n),o.toString().slice(r,i)!==a){G(u(`editor.formatSelectionChanged`));return}let t=Id(a,(await Jn(n,a,e)).formatted);await d.confirm();let s=await Yn(n,a,t,r);if(Lt.current!==n||o.toString().slice(r,i)!==a||(await d.confirm(),Lt.current!==n||o.toString().slice(r,i)!==a)){G(u(`editor.formatSelectionChanged`));return}s.length&&c.applyTextEdits(n,s),s.length&&await Gn(),Tt(null),G(``),be(u(`editor.formatSelectionComplete`))}catch(e){Ed(e)?(Tt({action:`selection`,kind:e.kind,detail:e.message}),G(``)):G(u(`editor.formatFailed`,{message:K(e)}))}finally{d&&await d.release(),Zt.current=!1,Ct(!1),s(),Qt.current===l&&(Qt.current=null)}},Z=async t=>{let n=Lt.current;if(!/\.bib$/i.test(n)||h?.permission===`read`||!sn)return be(u(`citationLibrary.importRequiresWrite`)),!1;let r=c.getText(n),i;try{i=await b_()}catch(e){return G(K(e)),!1}if(Lt.current!==n||!sn)return!1;let a=r.toString(),o=i.parseBibEntriesResult(a,e.maxCitationBibtexBytes);if(o.status===`too-large`)return be(u(`citationLibrary.fileTooLarge`,{size:i.citationBibtexLimitLabel(e.maxCitationBibtexBytes)})),!1;if(o.status===`invalid`)return be(u(`citationLibrary.fileInvalid`)),!1;if(o.entries.some(e=>e.citationKey.toLowerCase()===t.citationKey.toLowerCase()))return be(u(`citationErrors.alreadyInFile`,{key:t.citationKey})),!1;let s=Math.max(0,Math.min(a.length,U.getCursor().offset)),l=a.slice(0,s),d=a.slice(s),f=l?l.endsWith(`
|
|
20
|
-
|
|
21
|
-
`)?``:l.endsWith(`
|
|
22
|
-
`)?`
|
|
23
|
-
`:`
|
|
24
|
-
|
|
25
|
-
`:``,p=d?d.startsWith(`
|
|
26
|
-
|
|
27
|
-
`)?``:d.startsWith(`
|
|
28
|
-
`)?`
|
|
29
|
-
`:`
|
|
30
|
-
|
|
31
|
-
`:``;return c.applyTextEdits(n,[{from:s,to:s,replacement:`${f}${t.bibtex.trim()}${p}`}]),be(u(`citationLibrary.imported`,{key:t.citationKey})),!0},{files:er,setFiles:tr,loadFiles:nr,newFileOpen:rr,setNewFileOpen:ir,newFilePath:ar,setNewFilePath:or,resourcePreview:sr,setResourcePreview:cr,resourcePreviewLoading:lr,setResourcePreviewLoading:ur,newFolderOpen:dr,setNewFolderOpen:fr,newFolderName:pr,setNewFolderName:mr,fileDialogError:hr,setFileDialogError:gr,selectedFolder:_r,setSelectedFolder:vr,selectedFile:yr,setSelectedFile:br,expandedFolders:xr,setExpandedFolders:Sr,moveEntry:Cr,setMoveEntry:wr,moveName:Tr,setMoveName:Er,moveDestination:Dr,setMoveDestination:Or,deleteEntry:kr,setDeleteEntry:Q,fileDragActive:Ar,setFileDragActive:jr,uploadConflict:Mr,setUploadConflict:Nr,uploadingFiles:Pr,uploadFeedback:Fr,dismissUploadFeedback:Ir,directoryEntries:Lr,visibleEntries:Rr,createFile:zr,createFolder:Br,uploadFiles:Vr,upload:Hr,openFile:Ur,movePath:Wr,movePathToFolder:Gr,removePath:Kr}=Yh({projectId:n,site:e,activeFile:E,dirty:L,save:Kn,onError:G,onProject:g,onActiveFile:D,onActiveMainFile:k});zt.current=e=>{vr(null),br(e),Sr(t=>new Set([...t,...Wh(e)])),D(e)};let qr=e=>{if(e.id!==d.current)return;let t=e.mainFile!==h?.mainFile;g(e),t&&(Rt.current=e.mainFile,Lt.current=e.mainFile,k(e.mainFile),D(e.mainFile),vr(null),br(e.mainFile),Sr(t=>new Set([...t,...Wh(e.mainFile)])))},Jr=()=>Rt.current||h?.mainFile||``,Yr=()=>{let e=Jr(),t=Lt.current;if(!t||!/\.tex$/i.test(t))return e;let n=er.filter(e=>e.type===`file`&&/\.tex$/i.test(e.path)).length;return og(c.getText(t).toString())||n===1?(e!==t&&(Rt.current=t,k(t)),t):e===t&&h?.mainFile&&h.mainFile!==t?(Rt.current=h.mainFile,k(h.mainFile),h.mainFile):e};(0,Y.useEffect)(()=>{E&&E===O&&F===E&&M.filePath===E&&E.toLocaleLowerCase().endsWith(`.tex`)&&er.filter(e=>e.type===`file`&&/\.tex$/i.test(e.path)).length!==0&&E!==h?.mainFile&&!og(M.content)&&h?.mainFile&&(Rt.current=h.mainFile,k(h.mainFile))},[E,O,F,M,er,h?.mainFile]),(0,Y.useEffect)(()=>{if(!Ot.openFilesInTabs||er.length===0)return;let t=new Set(er.filter(t=>t.type===`file`&&Ae(t.path,t.textContent)&&(t.size??0)<=e.maxCollaborativeFileSizeMB*1024*1024).map(e=>e.path));rn(e=>{let n=e.filter(e=>t.has(e));return n.length===e.length?e:n})},[er,Ot.openFilesInTabs]);let{comments:Xr,projectCommentSummary:Zr,commentsFilePath:Qr,commentsReady:$r,fileCommentsLoading:ei,fileCommentsError:ti,retryFileComments:ni,reviewComments:ri,reviewCommentsLoading:ii,reviewCommentsError:ai,retryReviewComments:oi,commentScope:si,setCommentScope:ci,focusComment:li,setFocusComment:ui,commentOpen:di,openComment:fi,closeComment:pi,commentText:mi,setCommentText:hi,commentSelection:gi,commentSuggestion:_i,setCommentSuggestion:vi,commentSubmitting:yi,commentError:bi,addComment:xi,toggleComment:Si,replyToComment:Ci,editComment:wi,deleteComment:Ti,editCommentReply:Ei,deleteCommentReply:Di,commentDraftStore:Oi,cancelComment:ki,commentDraftRestored:Ai,commentDraftCanRetarget:ji,useCurrentCommentSelection:Mi}=Hp({projectId:n,activeFile:E,content:A,permission:h?.permission,revision:pn,sourceOrderRevision:`${h?.mainFile??``}\0${fn?.revision??``}`,selection:xe,save:Kn,saveFailureMessage:u(`errors.collaborationUnavailable`),onError:G,onAdded:()=>{Le(null),Me(`comments`)}});(0,Y.useEffect)(()=>{if(!O||M.filePath!==O)return;let e=Zu(M.content).length>0;P(t=>t.path===O&&t.hasIncludes===e?t:{path:O,hasIncludes:e})},[O,M]),(0,Y.useEffect)(()=>{if(!O||!sn||E===O)return;let e=c.getText(O),t=null,n=()=>{let t=Zu(e.toString()).length>0;P(e=>e.path===O&&e.hasIncludes===t?e:{path:O,hasIncludes:t})},r=()=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,n()},S_)};return n(),e.observe(r),()=>{t!==null&&window.clearTimeout(t),e.unobserve(r)}},[E,O,c,sn]);let Ni=(0,Y.useMemo)(()=>N.path===O&&N.hasIncludes||!!Zr?.filePaths.some(e=>e!==E),[O,N,Zr,E]),Pi=e=>{Ge(null),Me(`comments`),ui(null),He(e),Lt.current!==e.filePath&&Pn(e.filePath,e.startLine,1)},Fi=(e,t=!1)=>{let n=Xr.find(t=>t.id===e&&t.filePath===E);!n||n.resolved||n.orphaned||(He(null),ui(null),ze(null),t&&je===`comments`&&Ie===n.id?(Le(null),Ge(null),Me(null)):(Le(n.id),Ge(e=>({id:n.id,filePath:n.filePath,nonce:(e?.nonce??0)+1})),Me(`comments`)))};(0,Y.useEffect)(()=>{Ge(null),Le(null)},[E]),(0,Y.useEffect)(()=>{if(!Be)return;let e=em(Be,E,F,Qr,$r,Xr);e?(ui({...e}),He(null)):Be.filePath===E&&F===E&&Qr===E&&$r&&He(null)},[E,Xr,Qr,$r,F,Be,ui]),(0,Y.useEffect)(()=>{if(!Re||E!==Re.filePath||je!==`comments`)return;let e=Xr.find(e=>e.id===Re.commentId);if(!e||Re.replyId&&!e.replies.some(e=>e.id===Re.replyId)||Xt.current===Re.id)return;Xt.current=Re.id,Pi(e);let t=window.setTimeout(()=>ze(e=>e?.id===Re.id?null:e),3e3);return()=>window.clearTimeout(t)},[E,Xr,je,Re]);let{pdfUrl:Ii,pdfCompiledAt:Li,pdfSizeBytes:Ri,pdfLoadingMode:zi,pdfLoading:Bi,compileLog:Vi,compileDiagnostics:Hi,compileOutcome:Ui,artifacts:Wi,artifactPreview:Gi,artifactLoading:Ki,editorNotice:qi,localCompiling:Ji,cancelling:Yi,cleaning:Xi,compile:Zi,cancelCompile:Qi,cleanCompile:$i,viewArtifact:ea,pdfDisplayed:ta}=Vh({projectId:n,project:h,mainFile:O,resolveCompileMainFile:Yr,getCurrentMainFile:Jr,initialLatest:r?.projectId===n?r.latestCompile:null,collaborationSynced:sn,pdfVisible:W===`pdf`&&pe!==`editor-only`,sharedState:un,onSharedState:dn,save:Qn,loadOutline:(e,t)=>Un({signal:e},t),onPreviewTab:de,onError:G,onCompileStart:()=>{G(``),be(``)},onCompileSuccess:()=>{let e=Lt.current;if(e){let t=U.getCursor();Fn(e,t.line,t.column,{silent:!0})}},onPdfChanged:Nn});(0,Y.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&!e.shiftKey&&e.key.toLocaleLowerCase()===`p`&&(e.preventDefault(),st(!0))};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[]);let na=e=>{z(t.id,n,e),kt(e)},ra=(e=!1)=>{let t=wt;if(!t)return;Tt(null),G(``),e&&na({...Ot,texFmtConfig:``});let n=e?``:void 0;t.action===`selection`?$n(n):Xn(n)},ia=async()=>{Dt(!0);try{await Cn()||(G(u(`editor.collaboration.permissionDowngradeOtherTabBlocked`)),Dt(!1))}catch(e){G(K(e)),Dt(!1)}},aa=()=>{he?_e(e=>!e):Pt.current?.isCollapsed()?Pt.current.expand():Pt.current?.collapse()},oa=(0,Y.useMemo)(()=>m_(w,O,M),[w,O,M]),sa=(0,Y.useMemo)(()=>Jd(Vi,Ui),[Vi,Ui]),ca=pe!==`pdf-only`,la=pe!==`editor-only`,ua=ke(ca,la,je===`settings`||je===`comments`&&!la,he),da=e=>{me(e),e===`pdf-only`&&de(`pdf`)},fa=(0,Y.useCallback)(e=>{Yt.current?.abort();let t=new AbortController;Yt.current=t;let r=Lt.current,i=Rt.current,a=new URLSearchParams({kind:e.kind,key:e.key,...r?{path:r}:{},...i?{mainFile:i}:{}});q(`/api/projects/${n}/references/resolve?${a}`,{signal:t.signal}).then(({target:n})=>{t.signal.aborted||Lt.current!==r||Rt.current!==i||(n?(Bt.current===`pdf-only`&&da(`editor-pdf`),Pn(n.path,n.line,n.column)):G(u(e.kind===`citation`?`editor.citationTargetNotFound`:`editor.labelTargetNotFound`,{key:e.key})))}).catch(e=>{!t.signal.aborted&&!x_(e)&&G(K(e))}).finally(()=>{Yt.current===t&&(Yt.current=null)})},[Pn,n,u]),pa=kr?cn.filter(e=>e.filePath&&Gh(kr.path,e.filePath)):[];if(!h)return(0,X.jsxs)(`div`,{className:`center-card`,children:[(0,X.jsx)(`p`,{children:ve||u(`common.loading`)}),ve&&(0,X.jsx)(`button`,{className:`primary`,onClick:s,children:u(`editor.backToProjects`)})]});let ma=h.permission===`read`||!sn,ha=ln.find(e=>e.path===E),ga=ha&&!St?ha:null,_a=(e,t)=>{if(ma)return;let n=Lt.current;if(n){if(c.getText(n).toString().slice(e.from,e.to)!==e.word)G(u(`editor.spellCheckSourceChanged`));else try{c.applyTextEdits(n,[{from:e.from,to:e.to,replacement:t}])}catch(e){G(K(e))}}},va=un?.mainFile===O&&(un.status===`queued`||un.status===`running`),ya=Ji||va||Xi,ba=E?c.getText(E):null,xa=Li?te(Li,y.resolvedLanguage,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):``,Sa=O.split(`/`).at(-1)??O,Ca=sa.warnings.length+sa.errors.length+Wi.length,wa=Ii?`${Ii}${Ii.includes(`?`)?`&`:`?`}download=1`:``,Ta=O||h.mainFile,Ea=eg(E,Ta),Da=!!(Ta&&/\.tex$/i.test(Ta)),Oa=()=>{let e=Lt.current;if(!e)return Promise.resolve();let t=U.getCursor();return Fn(e,t.line,t.column)},ka=e=>{let t=er.find(t=>t.path===e);t&&Ae(t.path,t.textContent)?Ur(t):an(e)},Aa=e=>{document.getElementById(`editor-tab-${encodeURIComponent(e)}`)?.focus()},ja=(e,t)=>{if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(e.key))return;e.preventDefault();let n=e.key===`Home`?0:e.key===`End`?At.length-1:(t+(e.key===`ArrowLeft`?-1:1)+At.length)%At.length,r=At[n];r&&(ka(r),window.requestAnimationFrame(()=>Aa(r)))},Ma=ya?va?un?.status===`queued`?u(`editor.compileQueued`):u(`editor.compilingBy`,{name:un?.requestedBy.name??u(`common.user`)}):u(`editor.compiling`):Ui===`failed`?Ii&&Li?u(`editor.compileFailedRetained`,{time:te(Li,y.resolvedLanguage)}):u(`editor.compileFailedNoPdf`):Ui===`cancelled`?u(`compileControls.cancelled`):``,Na=cg(on,re,on===`disconnected`&&(L||c.hasWritableDraft)),Pa=Na===`editor.savedAt`&&ae?u(`editor.savedAt`,{time:te(ae,y.resolvedLanguage,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}):u(Na);return(0,X.jsxs)(`div`,{className:`workspace`,"data-texlite-tooltips":Ot.showTooltips?`on`:`off`,children:[(0,X.jsx)(sg,{agentTerminal:ca&&f.visible&&h.permission!==`read`?{open:p,activeCount:f.activeCount,toggle:()=>m(e=>!e)}:void 0,site:e,project:h,activeFile:E,saveStateLabel:Pa,editorPreferences:Ot,activeSessions:cn,collaborationStatus:on,reconnectCollaboration:yn,protocolUpgradeRequired:bn,showEditor:ca,filesCollapsed:he?!ge:Ke,toggleFilesPanel:aa,workspaceLayout:pe,changeWorkspaceLayout:da,onBack:s,onShare:()=>Ye(!0),showCitationLibrary:ca&&/\.bib$/i.test(E),citationLibraryOpen:nt,onCitationLibrary:()=>rt(!0),onHistory:()=>$e(!0),onGit:()=>Ze(!0),canManageGit:h.ownerId===t.id,formatting:St,readOnly:ma,collaborationSynced:sn,onToggleComments:()=>{let e=je!==`comments`||!!Ie;Le(null),e&&ci(`project`),Me(e?`comments`:null)},commentsOpen:je===`comments`,unresolvedCommentCount:Zr?.unresolvedCount??h.unresolvedCommentCount??0,onToggleSettings:()=>Me(je===`settings`?null:`settings`),settingsOpen:je===`settings`,compileBusy:ya,sharedCompiling:va,localCompiling:Ji,cancelling:Yi,onCompile:Zi,onCancelCompile:()=>void Qi()}),bn&&(0,X.jsxs)(`div`,{className:`workspace-update-banner`,role:`alert`,children:[(0,X.jsx)(oe,{size:15}),(0,X.jsx)(`span`,{children:u(`workspaceUpdates.protocolUpgrade`)}),(0,X.jsx)(`button`,{type:`button`,onClick:()=>window.location.reload(),children:u(`common.reload`)})]}),Ma&&(0,X.jsxs)(`div`,{className:`compile-status-strip${Ui===`failed`?` failed`:``}`,role:`status`,"aria-live":`polite`,children:[(0,X.jsx)(Fe,{className:ya?`spin`:``,size:14}),(0,X.jsx)(`span`,{children:Ma})]}),(Bn.error||zn.error||wt||ga)&&(0,X.jsxs)(`div`,{className:`client-tool-recoveries`,children:[Bn.error&&(0,X.jsxs)(`div`,{className:`client-tool-recovery`,role:`alert`,title:Bn.error,children:[(0,X.jsx)(oe,{size:15}),(0,X.jsxs)(`span`,{children:[(0,X.jsx)(`strong`,{children:u(`editor.harperRecoveryTitle`)}),u(`editor.harperFallbackHint`)]}),(0,X.jsx)(`div`,{className:`client-tool-recovery-actions`,children:(0,X.jsx)(`button`,{type:`button`,onClick:Bn.retry,children:u(`common.retry`)})}),(0,X.jsx)(`button`,{type:`button`,className:`formatter-diagnostics-dismiss`,title:u(`common.close`),"aria-label":u(`common.close`),onClick:Bn.dismissError,children:(0,X.jsx)(V,{size:13})})]}),zn.error&&(0,X.jsxs)(`div`,{className:`client-tool-recovery`,role:`alert`,title:zn.error,children:[(0,X.jsx)(oe,{size:15}),(0,X.jsxs)(`span`,{children:[(0,X.jsx)(`strong`,{children:u(`chktex.recoveryTitle`)}),u(`chktex.recoveryHint`)]}),(0,X.jsx)(`div`,{className:`client-tool-recovery-actions`,children:(0,X.jsx)(`button`,{type:`button`,onClick:zn.retry,children:u(`common.retry`)})}),(0,X.jsx)(`button`,{type:`button`,className:`formatter-diagnostics-dismiss`,title:u(`common.close`),"aria-label":u(`common.close`),onClick:zn.dismissError,children:(0,X.jsx)(V,{size:13})})]}),wt&&(0,X.jsxs)(`div`,{className:`client-tool-recovery`,role:`alert`,title:wt.detail,children:[(0,X.jsx)(oe,{size:15}),(0,X.jsxs)(`span`,{children:[(0,X.jsx)(`strong`,{children:u(wt.kind===`format`?`editor.texFmtOptionsRecoveryTitle`:wt.kind===`load`?`editor.texFmtRecoveryTitle`:`editor.texFmtRuntimeRecoveryTitle`)}),u(`editor.clientToolRecoveryHint`)]}),(0,X.jsxs)(`div`,{className:`client-tool-recovery-actions`,children:[(0,X.jsx)(`button`,{type:`button`,disabled:St||ma,onClick:()=>ra(),children:u(`common.retry`)}),wt.kind===`format`&&Ot.texFmtConfig.trim()&&(0,X.jsx)(`button`,{type:`button`,disabled:St||ma,onClick:()=>ra(!0),children:u(`editor.resetFormatterOptions`)}),(0,X.jsx)(`button`,{type:`button`,onClick:()=>window.location.reload(),children:u(`common.reload`)})]}),(0,X.jsx)(`button`,{type:`button`,className:`formatter-diagnostics-dismiss`,title:u(`common.close`),"aria-label":u(`common.close`),onClick:()=>Tt(null),children:(0,X.jsx)(V,{size:13})})]}),ga&&(0,X.jsxs)(`div`,{className:`client-tool-recovery format-lease-status`,role:`status`,children:[(0,X.jsx)(Fe,{className:`spin`,size:15}),(0,X.jsx)(`span`,{children:u(`editor.formattingBy`,{name:ga.holderName})})]})]}),mn&&(0,X.jsxs)(`div`,{className:`client-tool-recovery`,role:`status`,children:[(0,X.jsx)(oe,{size:15}),(0,X.jsx)(`span`,{children:u(`history.saveWarning`)})]}),ve&&(0,X.jsx)(`div`,{className:`toast`,onClick:()=>G(``),children:ve}),ye&&(0,X.jsx)(`div`,{className:`toast success`,onClick:()=>be(``),children:ye}),(0,X.jsxs)(Se,{orientation:`horizontal`,className:`work-grid`,...ua,children:[ca&&(0,X.jsx)(Ee,{phoneDrawer:he?{open:ge,onClose:()=>_e(!1)}:void 0,project:h,filesPanel:Pt,visibleEntries:Rr,deletedPath:fn?.kind===`delete`?fn.path:null,activeFile:E,activeMainFile:O,selectedFile:yr,selectedFolder:_r,expandedFolders:xr,fileDragActive:Ar,uploadingFiles:Pr,uploadFeedback:Fr,readOnly:ma,formatting:St,canFormat:Pd(E),activeFormatLease:!!ha,collaborationSynced:sn,editorFontSize:Ot.fontSize,outline:oa,sourceCursorStore:U,wordCountBusy:gt,hasSelection:!!xe.selectedText.trim()&&/\.(?:tex|sty|cls)$/i.test(E),hasFormatSelection:!!xe.selectedText.trim(),uploadInput:Nt,setSelectedFolder:vr,setExpandedFolders:Sr,setMoveEntry:wr,setMoveName:Er,setMoveDestination:Or,setDeleteEntry:Q,setFileDialogError:gr,setNewFolderName:mr,setNewFolderOpen:fr,setNewFilePath:or,setNewFileOpen:ir,setQuickOpen:st,onProjectSearch:()=>lt(!0),setFileDragActive:jr,dismissUploadFeedback:Ir,setFilesCollapsed:qe,onError:G,uploadFiles:Vr,upload:Hr,openFile:e=>{Ur(e),he&&_e(!1)},movePathToFolder:Gr,onFormatFile:()=>void Xn(),onFormatSelection:()=>void $n(),jumpToSource:(...e)=>{Pn(...e),he&&_e(!1)},syncSourceToPdf:Fn,onWordCount:e=>void qn(e)}),ca&&!he&&(0,X.jsx)(Te,{className:`resize-handle`,children:(0,X.jsx)(fe,{size:12})}),ca&&(0,X.jsx)(fg,{mobileSync:he&&je!==`comments`?{disabled:!Ii||!Ea,onClick:Oa}:void 0,terminal:p?({maximized:e,toggleMaximized:t})=>(0,X.jsx)(Y.Suspense,{fallback:(0,X.jsx)(`div`,{className:`agent-task-empty`,children:(0,X.jsx)(Fe,{className:`spin`,size:18})}),children:(0,X.jsx)(__,{projectId:n,readOnly:ma,onHide:()=>m(!1),maximized:e,onToggleMaximized:t})}):null,project:h,activeFile:E,openTabs:At,content:A,loadedFile:F,readOnly:ma,comments:Xr,focusComment:li,editorPreferences:Ot,completionIndex:S,nativeSpellCheck:Bn.nativeFallback,spellCheckIssues:Bn.issues,spellCheckJump:Bn.jump,sourceJump:An,collaborativeText:ba,collaborationAwareness:c.awareness,undoManager:E?c.getUndoManager(E):void 0,editorNotice:qi,activateTab:ka,closeTab:an,handleTabKeyDown:ja,updateEditorContent:Vn,setSelection:(e,t,n)=>De({selectedText:e,startOffset:t,endOffset:n}),onAddComment:(e,t,n,r)=>fi({selectedText:e,startOffset:t,endOffset:n},r),onSelectionHistory:(e,t,n,r)=>{tt({filePath:E,selection:{selectedText:e,startOffset:t,endOffset:n},source:r})},onCommentClick:Fi,onSpellCheckReplace:_a,onReferenceNavigate:fa,onCursor:nn}),la&&(0,X.jsx)(Dg,{mobileSync:he,commentsOpen:je===`comments`,onCommentsHost:Pe,projectId:n,activeMainFile:O,previewTab:W,diagnosticTab:le,pdfUrl:Ii,pdfLoadingMode:zi,pdfLoading:Bi,pdfCompiledAt:Li,pdfSizeBytes:Ri,pdfCompiledLabel:xa,pdfTargetLabel:Sa,pdfDownloadUrl:wa,pdfTarget:On,pdfViewport:kn,activeFile:E,compileBusy:ya,compileLog:Vi,compileDiagnostics:Hi,compileMessages:sa,artifacts:Wi,artifactPreview:Gi,artifactLoading:Ki,cleaning:Xi,readOnly:ma,collaborationSynced:sn,workspaceLayout:pe,showSyncResize:ca&&la,diagnosticCount:Ca,selectPreviewTab:de,changeWorkspaceLayout:da,onSetPdfViewport:jn,onResetPdfViewport:Mn,onPdfDisplayed:ta,syncVisiblePdfToSource:Ln,syncCurrentSourceToPdf:Oa,syncPdfToSource:In,canSyncWithPdf:Ea,canSyncPdfToSource:Da,files:er,jumpToSource:Pn,onSetCleanMode:at,viewArtifact:ea}),(0,X.jsx)(p_,{phone:he,commentsHost:la?Ne:void 0,sidePanel:je,onClose:()=>Me(null),project:h,projectId:n,site:e,files:er,currentUserId:t.id,comments:Ie?Xr:ri,commentDraftStore:Oi,commentsLoading:Ie?ei:ii,commentsError:(Ie?ti:ai)||Tn,onRetryComments:Ie?ni:oi,activeFile:E,singleCommentId:Ie,onShowAllComments:()=>{Le(null),ci(`project`)},hasProjectCommentsScope:Ni,commentScope:si,onCommentScopeChange:ci,focusedCommentId:Ue?.filePath===E?Ue.id:li?.id,commentFocusNonce:Ue?.nonce,onClearFocusComment:()=>{Ge(null),ui(null),ze(null)},unreadMentions:wn,onMarkMentionRead:En,onMarkAllMentionsRead:Dn,targetCommentId:Re?.commentId,targetReplyId:Re?.replyId,onFocusComment:Pi,onToggleComment:Si,onReplyComment:Ci,onEditComment:wi,onDeleteComment:Ti,onEditCommentReply:Ei,onDeleteCommentReply:Di,dictionaryWords:b,onDictionaryChange:x,editorPreferences:Ot,onEditorPreferences:na,spellCheckCount:Bn.summary?.total??null,spellCheckUniqueCount:Bn.summary?.unique??null,spellCheckIndex:Bn.summary?Bn.index:-1,onSpellCheckNavigate:Bn.jumpToIssue,onProject:qr},n)]}),ut&&(0,X.jsx)(Ve,{title:u(`editor.wordCountTitle`),onClose:()=>dt(!1),children:(0,X.jsx)(v_,{open:!0,mode:ft,path:mt,busy:gt,error:vt,result:bt,onOpenChange:dt})}),(0,X.jsx)(s_,{projectSearchOpen:ct,setProjectSearchOpen:lt,onSearchNavigate:(e,t,n)=>{pe===`pdf-only`&&da(he?`editor-only`:`editor-pdf`),he&&_e(!1),Pn(e,t,n)},user:t,project:h,projectId:n,activeFile:E,content:A,maxCitationBibtexBytes:e.maxCitationBibtexBytes,files:er,directoryEntries:Lr,readOnly:ma,resourcePreview:sr,resourcePreviewLoading:lr,setResourcePreview:cr,setResourcePreviewLoading:ur,uploadConflict:Mr,setUploadConflict:Nr,dismissUploadFeedback:Ir,uploadFiles:Vr,cleanMode:it,setCleanMode:at,cleanCompile:$i,newFileOpen:rr,setNewFileOpen:ir,newFilePath:ar,setNewFilePath:or,newFolderOpen:dr,setNewFolderOpen:fr,newFolderName:pr,setNewFolderName:mr,selectedFolder:_r,fileDialogError:hr,setFileDialogError:gr,createFile:zr,createFolder:Br,moveEntry:Cr,setMoveEntry:wr,moveName:Tr,setMoveName:Er,moveDestination:Dr,setMoveDestination:Or,movePath:Wr,deleteEntry:kr,setDeleteEntry:Q,deleteActiveSessions:pa,removePath:Kr,commentOpen:di,closeComment:pi,commentSelection:gi,commentSuggestion:_i,setCommentSuggestion:vi,commentText:mi,setCommentText:hi,commentSubmitting:yi,cancelComment:ki,commentDraftRestored:Ai,commentDraftCanRetarget:ji,useCurrentCommentSelection:Mi,commentError:bi,addComment:xi,shareOpen:Je,setShareOpen:Ye,onSharedMemberCountChange:_,citationLibraryOpen:nt,setCitationLibraryOpen:rt,insertCitationAtCursor:Z,quickOpen:ot,setQuickOpen:st,openFile:Ur,selectionHistoryTarget:et,closeSelectionHistory:()=>tt(null),historyOpen:Qe,setHistoryOpen:$e,gitOpen:Xe,setGitOpen:Ze,save:Kn,permissionDowngrade:xn,permissionDowngradeBusy:Et,dismissPermissionDowngrade:Sn,discardPermissionDraft:ia})]})}export{io as A,sc as C,Ms as D,Os as E,en as F,Gt as I,xt as L,kn as M,On as N,Ds as O,un as P,C_ as ProjectWorkspace,Fu as S,Ps as T,Du as _,fd as a,Ou as b,sd as c,Ru as d,Hu as f,Vu as g,Bu as h,md as i,Ii as j,ro as k,qu as l,Wu as m,Md as n,dd as o,Uu as p,Nd as r,ud as s,g_ as t,zu as u,Cu as v,Fs as w,Pu as x,Mu as y};
|