@bryanhu/codexly 0.37.0 → 0.37.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -1
- package/README.md +2 -2
- package/README.zh-CN.md +2 -2
- package/dist/{chunk-JHBSDMIM.js → chunk-5AELLXXE.js} +1 -1
- package/dist/{chunk-43QCECCY.js → chunk-5ULADQG3.js} +16 -16
- package/dist/{chunk-YAHXVRU3.js → chunk-63NQMTXZ.js} +1 -1
- package/dist/{chunk-ZK5H37U3.js → chunk-PFNMH4LN.js} +3 -3
- package/dist/cli.js +3 -3
- package/dist/client/index.js +2 -2
- package/dist/{command-RGXPFWPR.js → command-R5BTONU5.js} +1 -1
- package/dist/protocol/index.js +1 -1
- package/dist/providers/codex/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/web/.vite/manifest.json +114 -114
- package/dist/web/.vite/manifest.json.br +0 -0
- package/dist/web/.vite/manifest.json.gz +0 -0
- package/dist/web/assets/{agent-settings-panel-K1YqqkJL.js → agent-settings-panel-CRNaBDDS.js} +1 -1
- package/dist/web/assets/agent-settings-panel-CRNaBDDS.js.br +0 -0
- package/dist/web/assets/agent-settings-panel-CRNaBDDS.js.gz +0 -0
- package/dist/web/assets/{background-image-picker-BHqZ3SX1.js → background-image-picker-glORbeMR.js} +1 -1
- package/dist/web/assets/background-image-picker-glORbeMR.js.br +0 -0
- package/dist/web/assets/background-image-picker-glORbeMR.js.gz +0 -0
- package/dist/web/assets/{code-highlighter-DIfBIRTg.js → code-highlighter-Cg1b4nzi.js} +1 -1
- package/dist/web/assets/code-highlighter-Cg1b4nzi.js.br +5 -0
- package/dist/web/assets/code-highlighter-Cg1b4nzi.js.gz +0 -0
- package/dist/web/assets/{commit-settings-panel-B0i2Bqmu.js → commit-settings-panel-C-ALJcjd.js} +1 -1
- package/dist/web/assets/commit-settings-panel-C-ALJcjd.js.br +0 -0
- package/dist/web/assets/commit-settings-panel-C-ALJcjd.js.gz +0 -0
- package/dist/web/assets/{file-review-dialog-B3jUcADI.js → file-review-dialog-DNWufkfZ.js} +2 -2
- package/dist/web/assets/file-review-dialog-DNWufkfZ.js.br +0 -0
- package/dist/web/assets/file-review-dialog-DNWufkfZ.js.gz +0 -0
- package/dist/web/assets/{git-commit-review-Bz_j3wJo.js → git-commit-review-B3GGQldl.js} +2 -2
- package/dist/web/assets/git-commit-review-B3GGQldl.js.br +0 -0
- package/dist/web/assets/git-commit-review-B3GGQldl.js.gz +0 -0
- package/dist/web/assets/{git-history-panel-Bk5XtV-h.js → git-history-panel-BvNkd60B.js} +1 -1
- package/dist/web/assets/git-history-panel-BvNkd60B.js.br +0 -0
- package/dist/web/assets/git-history-panel-BvNkd60B.js.gz +0 -0
- package/dist/web/assets/{global-search-dialog-nP5Zoo16.js → global-search-dialog-CZnsxRQ7.js} +1 -1
- package/dist/web/assets/global-search-dialog-CZnsxRQ7.js.br +0 -0
- package/dist/web/assets/global-search-dialog-CZnsxRQ7.js.gz +0 -0
- package/dist/web/assets/{global-settings-about-Bdzkr5Fi.js → global-settings-about-CnBVv1BA.js} +1 -1
- package/dist/web/assets/global-settings-about-CnBVv1BA.js.br +0 -0
- package/dist/web/assets/global-settings-about-CnBVv1BA.js.gz +0 -0
- package/dist/web/assets/{global-settings-page-Bm6WTYej.js → global-settings-page-VbyWoa5s.js} +2 -2
- package/dist/web/assets/global-settings-page-VbyWoa5s.js.br +0 -0
- package/dist/web/assets/global-settings-page-VbyWoa5s.js.gz +0 -0
- package/dist/web/assets/{global-settings-pets-ChV29f_6.js → global-settings-pets-CAXRRfK_.js} +1 -1
- package/dist/web/assets/global-settings-pets-CAXRRfK_.js.br +0 -0
- package/dist/web/assets/global-settings-pets-CAXRRfK_.js.gz +0 -0
- package/dist/web/assets/{highlighted-body-OFNGDK62-D1VJUKau.js → highlighted-body-OFNGDK62-ClNmIb2W.js} +1 -1
- package/dist/web/assets/highlighted-body-OFNGDK62-ClNmIb2W.js.br +0 -0
- package/dist/web/assets/highlighted-body-OFNGDK62-ClNmIb2W.js.gz +0 -0
- package/dist/web/assets/{history-task-timeline-CphChwX0.js → history-task-timeline-bx1YeO4E.js} +1 -1
- package/dist/web/assets/history-task-timeline-bx1YeO4E.js.br +0 -0
- package/dist/web/assets/history-task-timeline-bx1YeO4E.js.gz +0 -0
- package/dist/web/assets/{image-preview-CZiY9KQs.js → image-preview-Cufuk95q.js} +2 -2
- package/dist/web/assets/image-preview-Cufuk95q.js.br +0 -0
- package/dist/web/assets/image-preview-Cufuk95q.js.gz +0 -0
- package/dist/web/assets/{image-preview-content-D54Quns6.js → image-preview-content-C9_jCSeW.js} +1 -1
- package/dist/web/assets/image-preview-content-C9_jCSeW.js.br +0 -0
- package/dist/web/assets/image-preview-content-C9_jCSeW.js.gz +0 -0
- package/dist/web/assets/index-DudvUciK.js +4 -0
- package/dist/web/assets/index-DudvUciK.js.br +0 -0
- package/dist/web/assets/index-DudvUciK.js.gz +0 -0
- package/dist/web/assets/initial-deps-B7SS8XxM.js +2 -0
- package/dist/web/assets/initial-deps-B7SS8XxM.js.br +0 -0
- package/dist/web/assets/initial-deps-B7SS8XxM.js.gz +0 -0
- package/dist/web/assets/{installed-skills-pane-DnKCXx4r.js → installed-skills-pane-B0a8IOZ0.js} +1 -1
- package/dist/web/assets/installed-skills-pane-B0a8IOZ0.js.br +0 -0
- package/dist/web/assets/installed-skills-pane-B0a8IOZ0.js.gz +0 -0
- package/dist/web/assets/{lazy-message-response-S2-ZO_oT.js → lazy-message-response-Q7-W7qvB.js} +2 -2
- package/dist/web/assets/lazy-message-response-Q7-W7qvB.js.br +0 -0
- package/dist/web/assets/lazy-message-response-Q7-W7qvB.js.gz +0 -0
- package/dist/web/assets/{mcp-management-pane-CAcqH6Ft.js → mcp-management-pane-BaRHPwX2.js} +1 -1
- package/dist/web/assets/mcp-management-pane-BaRHPwX2.js.br +0 -0
- package/dist/web/assets/mcp-management-pane-BaRHPwX2.js.gz +0 -0
- package/dist/web/assets/mermaid-GHXKKRXX-DywTXJ81.js +1 -0
- package/dist/web/assets/mermaid-GHXKKRXX-DywTXJ81.js.br +0 -0
- package/dist/web/assets/mermaid-GHXKKRXX-DywTXJ81.js.gz +0 -0
- package/dist/web/assets/message-assistant-directive-CaNrh5lx.js +3 -0
- package/dist/web/assets/message-assistant-directive-CaNrh5lx.js.br +0 -0
- package/dist/web/assets/message-assistant-directive-CaNrh5lx.js.gz +0 -0
- package/dist/web/assets/{message-response-D6AZoXZR.js → message-response-WYZfuphQ.js} +25 -25
- package/dist/web/assets/message-response-WYZfuphQ.js.br +0 -0
- package/dist/web/assets/message-response-WYZfuphQ.js.gz +0 -0
- package/dist/web/assets/{official-plugins-pane-CBk4rbLt.js → official-plugins-pane-KGXjJvv3.js} +1 -1
- package/dist/web/assets/official-plugins-pane-KGXjJvv3.js.br +0 -0
- package/dist/web/assets/official-plugins-pane-KGXjJvv3.js.gz +0 -0
- package/dist/web/assets/{patch-diff-viewer-nIzfWkKE.js → patch-diff-viewer-D_Ts5rez.js} +2 -2
- package/dist/web/assets/patch-diff-viewer-D_Ts5rez.js.br +0 -0
- package/dist/web/assets/patch-diff-viewer-D_Ts5rez.js.gz +0 -0
- package/dist/web/assets/{pdf-preview-Zrj4u-KR.js → pdf-preview-D46KssiK.js} +3 -3
- package/dist/web/assets/pdf-preview-D46KssiK.js.br +0 -0
- package/dist/web/assets/pdf-preview-D46KssiK.js.gz +0 -0
- package/dist/web/assets/{personalization-settings-panel-D3OqsNUV.js → personalization-settings-panel-CllzRqsG.js} +1 -1
- package/dist/web/assets/personalization-settings-panel-CllzRqsG.js.br +0 -0
- package/dist/web/assets/personalization-settings-panel-CllzRqsG.js.gz +0 -0
- package/dist/web/assets/{project-file-popup-page-7yzFqPZq.js → project-file-popup-page-CVnfABUU.js} +1 -1
- package/dist/web/assets/project-file-popup-page-CVnfABUU.js.br +0 -0
- package/dist/web/assets/project-file-popup-page-CVnfABUU.js.gz +0 -0
- package/dist/web/assets/{project-source-panel-C1tTwC1j.js → project-source-panel-Dl6nuWfg.js} +1 -1
- package/dist/web/assets/project-source-panel-Dl6nuWfg.js.br +0 -0
- package/dist/web/assets/project-source-panel-Dl6nuWfg.js.gz +0 -0
- package/dist/web/assets/{prompt-input--2KQl6SR.js → prompt-input-Ceptl3B-.js} +1 -1
- package/dist/web/assets/prompt-input-Ceptl3B-.js.br +0 -0
- package/dist/web/assets/prompt-input-Ceptl3B-.js.gz +0 -0
- package/dist/web/assets/resources-en-CzuCDOU2.js +1 -0
- package/dist/web/assets/resources-en-CzuCDOU2.js.br +0 -0
- package/dist/web/assets/resources-en-CzuCDOU2.js.gz +0 -0
- package/dist/web/assets/{scheduled-task-date-time-picker-BVYVGT78.js → scheduled-task-date-time-picker-CpT4cTpn.js} +1 -1
- package/dist/web/assets/scheduled-task-date-time-picker-CpT4cTpn.js.br +0 -0
- package/dist/web/assets/scheduled-task-date-time-picker-CpT4cTpn.js.gz +0 -0
- package/dist/web/assets/{scheduled-tasks-container-CQkfAgKW.js → scheduled-tasks-container-CRV2di5K.js} +2 -2
- package/dist/web/assets/scheduled-tasks-container-CRV2di5K.js.br +0 -0
- package/dist/web/assets/scheduled-tasks-container-CRV2di5K.js.gz +0 -0
- package/dist/web/assets/{shiki-bundle-COC_j-nR.js → shiki-bundle-C942xz2H.js} +1 -1
- package/dist/web/assets/shiki-bundle-C942xz2H.js.br +2 -0
- package/dist/web/assets/shiki-bundle-C942xz2H.js.gz +0 -0
- package/dist/web/assets/{skills-market-container-_ME3wZFP.js → skills-market-container--8qzUyrx.js} +2 -2
- package/dist/web/assets/skills-market-container--8qzUyrx.js.br +0 -0
- package/dist/web/assets/skills-market-container--8qzUyrx.js.gz +0 -0
- package/dist/web/assets/{split-workspace-menu-content-CkpZv1Nz.js → split-workspace-menu-content-CAL4JQt9.js} +1 -1
- package/dist/web/assets/split-workspace-menu-content-CAL4JQt9.js.br +5 -0
- package/dist/web/assets/split-workspace-menu-content-CAL4JQt9.js.gz +0 -0
- package/dist/web/assets/{third-party-marketplace-pane-D3AJNSoF.js → third-party-marketplace-pane-Can5ly44.js} +1 -1
- package/dist/web/assets/third-party-marketplace-pane-Can5ly44.js.br +0 -0
- package/dist/web/assets/third-party-marketplace-pane-Can5ly44.js.gz +0 -0
- package/dist/web/assets/{workbench-inspector-changes-DSbBqbXe.js → workbench-inspector-changes-D2ZiHtIT.js} +1 -1
- package/dist/web/assets/workbench-inspector-changes-D2ZiHtIT.js.br +0 -0
- package/dist/web/assets/workbench-inspector-changes-D2ZiHtIT.js.gz +0 -0
- package/dist/web/assets/{workbench-pet-canvas-Ct1J6Adp.js → workbench-pet-canvas-DuBL3mip.js} +1 -1
- package/dist/web/assets/workbench-pet-canvas-DuBL3mip.js.br +0 -0
- package/dist/web/assets/workbench-pet-canvas-DuBL3mip.js.gz +0 -0
- package/dist/web/assets/workbench-shell-CfN-sr8U.js +16 -0
- package/dist/web/assets/workbench-shell-CfN-sr8U.js.br +0 -0
- package/dist/web/assets/workbench-shell-CfN-sr8U.js.gz +0 -0
- package/dist/web/index.html +2 -2
- package/dist/web/index.html.br +0 -0
- package/dist/web/index.html.gz +0 -0
- package/package.json +1 -1
- package/dist/web/assets/agent-settings-panel-K1YqqkJL.js.br +0 -0
- package/dist/web/assets/agent-settings-panel-K1YqqkJL.js.gz +0 -0
- package/dist/web/assets/background-image-picker-BHqZ3SX1.js.br +0 -0
- package/dist/web/assets/background-image-picker-BHqZ3SX1.js.gz +0 -0
- package/dist/web/assets/code-highlighter-DIfBIRTg.js.br +0 -0
- package/dist/web/assets/code-highlighter-DIfBIRTg.js.gz +0 -0
- package/dist/web/assets/commit-settings-panel-B0i2Bqmu.js.br +0 -0
- package/dist/web/assets/commit-settings-panel-B0i2Bqmu.js.gz +0 -0
- package/dist/web/assets/file-review-dialog-B3jUcADI.js.br +0 -0
- package/dist/web/assets/file-review-dialog-B3jUcADI.js.gz +0 -0
- package/dist/web/assets/git-commit-review-Bz_j3wJo.js.br +0 -0
- package/dist/web/assets/git-commit-review-Bz_j3wJo.js.gz +0 -0
- package/dist/web/assets/git-history-panel-Bk5XtV-h.js.br +0 -0
- package/dist/web/assets/git-history-panel-Bk5XtV-h.js.gz +0 -0
- package/dist/web/assets/global-search-dialog-nP5Zoo16.js.br +0 -0
- package/dist/web/assets/global-search-dialog-nP5Zoo16.js.gz +0 -0
- package/dist/web/assets/global-settings-about-Bdzkr5Fi.js.br +0 -0
- package/dist/web/assets/global-settings-about-Bdzkr5Fi.js.gz +0 -0
- package/dist/web/assets/global-settings-page-Bm6WTYej.js.br +0 -0
- package/dist/web/assets/global-settings-page-Bm6WTYej.js.gz +0 -0
- package/dist/web/assets/global-settings-pets-ChV29f_6.js.br +0 -0
- package/dist/web/assets/global-settings-pets-ChV29f_6.js.gz +0 -0
- package/dist/web/assets/highlighted-body-OFNGDK62-D1VJUKau.js.br +0 -0
- package/dist/web/assets/highlighted-body-OFNGDK62-D1VJUKau.js.gz +0 -0
- package/dist/web/assets/history-task-timeline-CphChwX0.js.br +0 -0
- package/dist/web/assets/history-task-timeline-CphChwX0.js.gz +0 -0
- package/dist/web/assets/image-preview-CZiY9KQs.js.br +0 -4
- package/dist/web/assets/image-preview-CZiY9KQs.js.gz +0 -0
- package/dist/web/assets/image-preview-content-D54Quns6.js.br +0 -0
- package/dist/web/assets/image-preview-content-D54Quns6.js.gz +0 -0
- package/dist/web/assets/index-CV7PO8FJ.js +0 -4
- package/dist/web/assets/index-CV7PO8FJ.js.br +0 -0
- package/dist/web/assets/index-CV7PO8FJ.js.gz +0 -0
- package/dist/web/assets/initial-deps-DElr8S4a.js +0 -2
- package/dist/web/assets/initial-deps-DElr8S4a.js.br +0 -0
- package/dist/web/assets/initial-deps-DElr8S4a.js.gz +0 -0
- package/dist/web/assets/installed-skills-pane-DnKCXx4r.js.br +0 -0
- package/dist/web/assets/installed-skills-pane-DnKCXx4r.js.gz +0 -0
- package/dist/web/assets/lazy-message-response-S2-ZO_oT.js.br +0 -0
- package/dist/web/assets/lazy-message-response-S2-ZO_oT.js.gz +0 -0
- package/dist/web/assets/mcp-management-pane-CAcqH6Ft.js.br +0 -0
- package/dist/web/assets/mcp-management-pane-CAcqH6Ft.js.gz +0 -0
- package/dist/web/assets/mermaid-GHXKKRXX-CRcc_eOq.js +0 -1
- package/dist/web/assets/mermaid-GHXKKRXX-CRcc_eOq.js.br +0 -1
- package/dist/web/assets/mermaid-GHXKKRXX-CRcc_eOq.js.gz +0 -0
- package/dist/web/assets/message-assistant-directive-7AH4Pn2V.js +0 -3
- package/dist/web/assets/message-assistant-directive-7AH4Pn2V.js.br +0 -0
- package/dist/web/assets/message-assistant-directive-7AH4Pn2V.js.gz +0 -0
- package/dist/web/assets/message-response-D6AZoXZR.js.br +0 -0
- package/dist/web/assets/message-response-D6AZoXZR.js.gz +0 -0
- package/dist/web/assets/official-plugins-pane-CBk4rbLt.js.br +0 -0
- package/dist/web/assets/official-plugins-pane-CBk4rbLt.js.gz +0 -0
- package/dist/web/assets/patch-diff-viewer-nIzfWkKE.js.br +0 -0
- package/dist/web/assets/patch-diff-viewer-nIzfWkKE.js.gz +0 -0
- package/dist/web/assets/pdf-preview-Zrj4u-KR.js.br +0 -0
- package/dist/web/assets/pdf-preview-Zrj4u-KR.js.gz +0 -0
- package/dist/web/assets/personalization-settings-panel-D3OqsNUV.js.br +0 -0
- package/dist/web/assets/personalization-settings-panel-D3OqsNUV.js.gz +0 -0
- package/dist/web/assets/project-file-popup-page-7yzFqPZq.js.br +0 -0
- package/dist/web/assets/project-file-popup-page-7yzFqPZq.js.gz +0 -0
- package/dist/web/assets/project-source-panel-C1tTwC1j.js.br +0 -0
- package/dist/web/assets/project-source-panel-C1tTwC1j.js.gz +0 -0
- package/dist/web/assets/prompt-input--2KQl6SR.js.br +0 -0
- package/dist/web/assets/prompt-input--2KQl6SR.js.gz +0 -0
- package/dist/web/assets/resources-en-CNO1wrxl.js +0 -1
- package/dist/web/assets/resources-en-CNO1wrxl.js.br +0 -0
- package/dist/web/assets/resources-en-CNO1wrxl.js.gz +0 -0
- package/dist/web/assets/scheduled-task-date-time-picker-BVYVGT78.js.br +0 -0
- package/dist/web/assets/scheduled-task-date-time-picker-BVYVGT78.js.gz +0 -0
- package/dist/web/assets/scheduled-tasks-container-CQkfAgKW.js.br +0 -0
- package/dist/web/assets/scheduled-tasks-container-CQkfAgKW.js.gz +0 -0
- package/dist/web/assets/shiki-bundle-COC_j-nR.js.br +0 -3
- package/dist/web/assets/shiki-bundle-COC_j-nR.js.gz +0 -0
- package/dist/web/assets/skills-market-container-_ME3wZFP.js.br +0 -0
- package/dist/web/assets/skills-market-container-_ME3wZFP.js.gz +0 -0
- package/dist/web/assets/split-workspace-menu-content-CkpZv1Nz.js.br +0 -0
- package/dist/web/assets/split-workspace-menu-content-CkpZv1Nz.js.gz +0 -0
- package/dist/web/assets/third-party-marketplace-pane-D3AJNSoF.js.br +0 -0
- package/dist/web/assets/third-party-marketplace-pane-D3AJNSoF.js.gz +0 -0
- package/dist/web/assets/workbench-inspector-changes-DSbBqbXe.js.br +0 -0
- package/dist/web/assets/workbench-inspector-changes-DSbBqbXe.js.gz +0 -0
- package/dist/web/assets/workbench-pet-canvas-Ct1J6Adp.js.br +0 -0
- package/dist/web/assets/workbench-pet-canvas-Ct1J6Adp.js.gz +0 -0
- package/dist/web/assets/workbench-shell-CP0njkD8.js +0 -16
- package/dist/web/assets/workbench-shell-CP0njkD8.js.br +0 -0
- package/dist/web/assets/workbench-shell-CP0njkD8.js.gz +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {createRequire}from'node:module';import {a as a$2}from'./chunk-
|
|
1
|
+
import {createRequire}from'node:module';import {a as a$2}from'./chunk-5AELLXXE.js';import {l,k,a as a$3,m,b as b$1,c as c$1,d,e as e$1}from'./chunk-5ULADQG3.js';import {o,a as a$1,k as k$1,b,i,j,m as m$1,l as l$1,d as d$1,c as c$2,g,h,e as e$2,f}from'./chunk-3WW7LK46.js';import {R,Bc as Bc$1,Td,Ig,Ab,Sg as Sg$1,Vg,bd as bd$1,og as og$1,xe,we,Db,Zd as Zd$1,_d as _d$1,Gg,He,pc,oc,Xf,rc,qc,xg as xg$1,Ie,Fe as Fe$1,Cd,Bd,Fb,Ib,yg as yg$1,Ag as Ag$1,Cg as Cg$1,zg,Bg,Dg,Eg as Eg$1,Ne,Pe,Oe,Te,Se as Se$1,Re,Qe as Qe$1,fa,ha,ga,Ce,Aa,ya as ya$1,wa,ta,Ia,Ka,Y,Ja as Ja$1,De,La,Ge as Ge$1,Ed,Dd as Dd$1,Da,Ca,Na,Ma,Pa,Oa,sc,uc as uc$1,Lc as Lc$1,Oc as Oc$1,Qc as Qc$1,Sc,yc,Ac as Ac$1,wc,Ic as Ic$1,Fc,Hc as Hc$1,Dc as Dc$1,Pd as Pd$1,Od,Ud,Vd as Vd$1,Sd as Sd$1,Wd as Wd$1,Xd as Xd$1,Ee,wf,ug as ug$1,kd,ac,bc as bc$1,nf,mf,pf,of,rf,qf,tf as tf$1,sf,vf,uf,ic,dc as dc$1,hc,gc,lf,kf,If,Hf,Kf,Jf,Vf,Uf,qe as qe$1,pe,Hg as Hg$1,Tg as Tg$1,Wg,Ug,Xg,Mg,Ng as Ng$1,Kg,Og,Qg,Pg as Pg$1,qd as qd$1,Mf,Lf,Of,Nf,Pf,Rf,Qf,Tf,Sf,md as md$1,Ue as Ue$1,Gb,Hb,Eb as Eb$1,rd,ia,$,_,Z,Ra,Sa,Va,Ua,Ya,Wa,_a,Za,$a,ab,jb,ib,ob,kb,xb,rb as rb$1,qb as qb$1,oa,ma,qa,pa,yb,dd as dd$1,xa,Ba as Ba$1,Qb as Qb$1,Fd,zd,Ef,Df,yf,xf as xf$1,Af,zf,Cf,Bf,Gf as Gf$1,Ff,kc as kc$1,jc as jc$1,jf,if as _if,Zg as Zg$1,Yg,Hd,Gd,vg as vg$1,Vb,Ub,ue,te,ve,Lg,Tb,cb,hb,db as db$1,gb,fb,eb,nb as nb$1,lb,ub,tb,wb,vb,$g as $g$1,ah,ch,bh,_g as _g$1,pg as pg$1,ng}from'./chunk-63NQMTXZ.js';import {c,a,e}from'./chunk-YXJGRSCL.js';import {Buffer as Buffer$1}from'buffer';import {randomBytes,createHash,timingSafeEqual,randomUUID}from'crypto';import {createReadStream,createWriteStream,constants}from'fs';import {mkdtemp,rm as rm$1,realpath,lstat,stat,readFile,open,readdir,mkdir,access,writeFile,rename,unlink,link,rmdir,readlink}from'fs/promises';import {tmpdir,homedir}from'os';import {normalize,join,isAbsolute,resolve,basename,relative,sep,dirname,extname,win32,posix}from'path';import {Transform,Readable}from'stream';import {pipeline}from'stream/promises';import {TextDecoder as TextDecoder$1,isDeepStrictEqual}from'util';import {spawn}from'child_process';import {EventEmitter}from'events';import {createRequire as createRequire$1}from'module';import {Worker}from'worker_threads';import {isIP}from'net';import {domainToASCII}from'url';import {setTimeout as setTimeout$1}from'timers/promises';createRequire(import.meta.url);
|
|
2
2
|
var M1=c((Nqe,D1)=>{function PX(e){var t=new e,r=t;function n(){var s=t;return s.next?t=s.next:(t=new e,r=t),s.next=null,s}function i(s){r.next=s,r=s;}return {get:n,release:i}}D1.exports=PX;});var jw=c((jqe,Nw)=>{var kX=M1();function F1(e,t,r){if(typeof e=="function"&&(r=t,t=e,e=null),!(r>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");var n=kX(xX),i=null,s=null,o=0,a=null,c={push:f,drain:kr,saturated:kr,pause:u,paused:false,get concurrency(){return r},set concurrency(R){if(!(R>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(r=R,!c.paused)for(;i&&o<r;)o++,y();},running:l,resume:p,idle:h,length:d,getQueue:m,unshift:g,empty:kr,kill:_,killAndDrain:v,error:E,abort:w};return c;function l(){return o}function u(){c.paused=true;}function d(){for(var R=i,P=0;R;)R=R.next,P++;return P}function m(){for(var R=i,P=[];R;)P.push(R.value),R=R.next;return P}function p(){if(c.paused){if(c.paused=false,i===null){o++,y();return}for(;i&&o<r;)o++,y();}}function h(){return o===0&&c.length()===0}function f(R,P){var b=n.get();b.context=e,b.release=y,b.value=R,b.callback=P||kr,b.errorHandler=a,o>=r||c.paused?s?(s.next=b,s=b):(i=b,s=b,c.saturated()):(o++,t.call(e,b.value,b.worked));}function g(R,P){var b=n.get();b.context=e,b.release=y,b.value=R,b.callback=P||kr,b.errorHandler=a,o>=r||c.paused?i?(b.next=i,i=b):(i=b,s=b,c.saturated()):(o++,t.call(e,b.value,b.worked));}function y(R){R&&n.release(R);var P=i;P&&o<=r?c.paused?o--:(s===i&&(s=null),i=P.next,P.next=null,t.call(e,P.value,P.worked),s===null&&c.empty()):--o===0&&c.drain();}function _(){i=null,s=null,c.drain=kr;}function v(){i=null,s=null,c.drain(),c.drain=kr;}function w(){var R=i;for(i=null,s=null;R;){var P=R.next,b=R.callback,O=R.errorHandler,F=R.value,j=R.context;R.value=null,R.callback=kr,R.errorHandler=null,O&&O(new Error("abort"),F),b.call(j,new Error("abort")),R.release(R),R=P;}c.drain=kr;}function E(R){a=R;}}function kr(){}function xX(){this.value=null,this.callback=kr,this.next=null,this.release=kr,this.context=null,this.errorHandler=null;var e=this;this.worked=function(r,n){var i=e.callback,s=e.errorHandler,o=e.value;e.value=null,e.callback=kr,e.errorHandler&&s(r,o),i.call(e.context,r,n),e.release(e);};}function AX(e,t,r){typeof e=="function"&&(r=t,t=e,e=null);function n(u,d){t.call(this,u).then(function(m){d(null,m);},d);}var i=F1(e,n,r),s=i.push,o=i.unshift;return i.push=a,i.unshift=c,i.drained=l,i;function a(u){var d=new Promise(function(m,p){s(u,function(h,f){if(h){p(h);return}m(f);});});return d.catch(kr),d}function c(u){var d=new Promise(function(m,p){o(u,function(h,f){if(h){p(h);return}m(f);});});return d.catch(kr),d}function l(){var u=new Promise(function(d){process.nextTick(function(){if(i.idle())d();else {var m=i.drain;i.drain=function(){typeof m=="function"&&m(),d(),i.drain=m;};}});});return u}}Nw.exports=F1;Nw.exports.promise=AX;});var Pl=c((Lqe,Rl)=>{var{format:IX}=a("util");function OX(){return `${this.name} [${this.code}]: ${this.message}`}var nh=Symbol.for("fastify-error-generic");function ga(e,t,r=500,n=Error,i=ga.captureStackTrace){let s=e===nh;if(s&&(e="FST_ERR"),!e)throw new Error("Fastify error code must not be empty");if(!t)throw new Error("Fastify error message must not be empty");e=e.toUpperCase(),!r&&(r=void 0);let o=Symbol.for(`fastify-error ${e}`);function a(...c){if(!new.target)return new a(...c);this.code=e,this.name="FastifyError",this.statusCode=r;let l=c.length-1;l!==-1&&c[l]&&typeof c[l]=="object"&&"cause"in c[l]&&(this.cause=c.pop().cause),this.message=IX(t,...c),Error.stackTraceLimit&&i&&Error.captureStackTrace(this,a);}return a.prototype=Object.create(n.prototype,{constructor:{value:a,enumerable:false,writable:true,configurable:true},[nh]:{value:true,enumerable:false,writable:false,configurable:false},[o]:{value:true,enumerable:false,writable:false,configurable:false}}),s?Object.defineProperty(a,Symbol.hasInstance,{value(c){return c&&c[nh]},configurable:false,writable:false,enumerable:false}):Object.defineProperty(a,Symbol.hasInstance,{value(c){return c&&c[o]},configurable:false,writable:false,enumerable:false}),a.prototype[Symbol.toStringTag]="Error",a.prototype.toString=OX,a}ga.captureStackTrace=true;var CX=ga(nh,"Fastify Error",500,Error);Rl.exports=ga;Rl.exports.FastifyError=CX;Rl.exports.default=ga;Rl.exports.createError=ga;});var ih=c((Dqe,$1)=>{var{createError:ns}=Pl();$1.exports={AVV_ERR_EXPOSE_ALREADY_DEFINED:ns("AVV_ERR_EXPOSE_ALREADY_DEFINED","'%s' is already defined, specify an expose option for '%s'"),AVV_ERR_ATTRIBUTE_ALREADY_DEFINED:ns("AVV_ERR_ATTRIBUTE_ALREADY_DEFINED","'%s' is already defined"),AVV_ERR_CALLBACK_NOT_FN:ns("AVV_ERR_CALLBACK_NOT_FN","Callback for '%s' hook is not a function. Received: '%s'"),AVV_ERR_PLUGIN_NOT_VALID:ns("AVV_ERR_PLUGIN_NOT_VALID","Plugin must be a function or a promise. Received: '%s'"),AVV_ERR_ROOT_PLG_BOOTED:ns("AVV_ERR_ROOT_PLG_BOOTED","Root plugin has already booted"),AVV_ERR_PARENT_PLG_LOADED:ns("AVV_ERR_PARENT_PLG_LOADED","Impossible to load '%s' plugin because the parent '%s' was already loaded"),AVV_ERR_READY_TIMEOUT:ns("AVV_ERR_READY_TIMEOUT","Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise"),AVV_ERR_PLUGIN_EXEC_TIMEOUT:ns("AVV_ERR_PLUGIN_EXEC_TIMEOUT","Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise")};});var ya=c((Mqe,q1)=>{var NX=Symbol("avvio.Boot"),jX=Symbol("isOnCloseHandler"),LX=Symbol("avvio.ThenifyDoNotWrap"),DX=Symbol("avvio.TimeTree.untrackNode"),MX=Symbol("avvio.TimeTree.trackNode"),FX=Symbol("avvio.TimeTree.getParent"),$X=Symbol("avvio.TimeTree.getNode"),qX=Symbol("avvio.TimeTree.addNode"),UX=Symbol.for("plugin-meta");q1.exports={kAvvio:NX,kIsOnCloseHandler:jX,kThenifyDoNotWrap:LX,kUntrackNode:DX,kTrackNode:MX,kGetParent:FX,kGetNode:$X,kAddNode:qX,kPluginMeta:UX};});var W1=c((Fqe,V1)=>{var{kUntrackNode:U1,kTrackNode:Lw,kGetParent:B1,kGetNode:H1,kAddNode:G1}=ya(),Dw=class{constructor(){this.root=null,this.tableId=new Map,this.tableLabel=new Map;}[Lw](t){this.tableId.set(t.id,t),this.tableLabel.has(t.label)?this.tableLabel.get(t.label).push(t):this.tableLabel.set(t.label,[t]);}[U1](t){this.tableId.delete(t.id);let r=this.tableLabel.get(t.label);r.pop(),r.length===0&&this.tableLabel.delete(t.label);}[B1](t){if(t===null)return null;if(this.tableLabel.has(t)){let r=this.tableLabel.get(t);return r[r.length-1]}else return null}[H1](t){return this.tableId.get(t)}[G1](t,r,n){let i=this[B1](t);if(i===null)return this.root={parent:null,id:"root",label:r,nodes:[],start:n,stop:null,diff:-1},this[Lw](this.root),this.root.id;let o=`${r}-${Math.random()}`,a={parent:t,id:o,label:r,nodes:[],start:n,stop:null,diff:-1};return i.nodes.push(a),this[Lw](a),o}start(t,r,n=Date.now()){return this[G1](t,r,n)}stop(t,r=Date.now()){let n=this[H1](t);n&&(n.stop=r,n.diff=n.stop-n.start||0,this[U1](n));}toJSON(){return Object.assign({},this.root)}prettyPrint(){return z1(this.toJSON())}};function z1(e,t=""){let r=t,n=e.nodes.length,i=n-1;r+=`${e.label} ${e.diff} ms
|
|
3
3
|
`;for(let s=0;s<n;++s){let o=e.nodes[s],a=t+(s===i?" ":"\u2502 ");r+=t,r+=s===i?"\u2514\u2500":"\u251C\u2500",r+=o.nodes.length===0?"\u2500 ":"\u252C ",r+=z1(o,a).slice(t.length+2);}return r}V1.exports={TimeTree:Dw};});var sh=c(($qe,K1)=>{var{debuglog:BX}=a("util"),HX=BX("avvio");K1.exports={debug:HX};});var Q1=c((qqe,Y1)=>{function GX(){let e={resolve:null,reject:null,promise:null};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r;}),e}Y1.exports={createPromise:GX};});var Z1=c((Uqe,X1)=>{var{kPluginMeta:J1}=ya();function zX(e,t){return e[J1]?.name?e[J1].name:t?.name?t.name:e.name?e.name:e.toString().split(`
|
|
4
4
|
`).slice(0,2).map(r=>r.trim()).join(" -- ")}X1.exports={getPluginName:zX};});var oh=c((Bqe,eN)=>{function VX(e){return e!==null&&typeof e=="object"&&typeof e.then=="function"}eN.exports={isPromiseLike:VX};});var rN=c((Hqe,tN)=>{var{EventEmitter:WX}=a("events"),{inherits:KX}=a("util"),{debug:Wt}=sh(),{createPromise:YX}=Q1(),{AVV_ERR_PLUGIN_EXEC_TIMEOUT:QX}=ih(),{getPluginName:JX}=Z1(),{isPromiseLike:XX}=oh();function wa(e,t,r,n,i){this.queue=e,this.func=t,this.options=r,this.isAfter=n,this.timeout=i,this.started=false,this.name=JX(t,r),this.queue.pause(),this._error=null,this.loaded=false,this._promise=null,this.startTime=null;}KX(wa,WX);wa.prototype.exec=function(e,t){Wt("exec",this.name),this.server=e;let r=this.func,n=this.name,i=false;this.options=typeof this.options=="function"?this.options(this.server):this.options;let s=null,o=c=>{if(i){Wt("loading complete",n);return}this._error=c,Wt(c?"exec errored":"exec completed",n),i=true,s&&clearTimeout(s),t(c);};this.timeout>0&&(Wt("setting up timeout",n,this.timeout),s=setTimeout(function(){Wt("timed out",n),s=null;let c=new QX(n);c.fn=r,o(c);},this.timeout)),this.started=true,this.startTime=Date.now(),this.emit("start",this.server?this.server.name:null,this.name,Date.now());let a=r(this.server,this.options,o);XX(a)?(Wt("exec: resolving promise",n),a.then(()=>process.nextTick(o),c=>process.nextTick(o,c))):r.length<3&&o();};wa.prototype.loadedSoFar=function(){if(Wt("loadedSoFar",this.name),this.loaded)return Promise.resolve();let e=()=>{this.server.after((r,n)=>{this._error=r,this.queue.pause(),this._promise&&(r?(Wt("rejecting promise",this.name,r),this._promise.reject(r)):(Wt("resolving promise",this.name),this._promise.resolve()),this._promise=null),process.nextTick(n,r);}),this.queue.resume();},t;return this._promise?t=Promise.resolve():(this._promise=YX(),t=this._promise.promise,this.server?e():this.on("start",e)),t};wa.prototype.enqueue=function(e,t){Wt("enqueue",this.name,e.name),this.emit("enqueue",this.server?this.server.name:null,this.name,Date.now()),this.queue.push(e,t);};wa.prototype.finish=function(e,t){Wt("finish",this.name,e);let r=()=>{this.loaded||(Wt("loaded",this.name),this.emit("loaded",this.server?this.server.name:null,this.name,Date.now()),this.loaded=true,t(e));};if(e){this._promise&&(this._promise.reject(e),this._promise=null),r();return}let n=()=>{if(Wt("check",this.name,this.queue.length(),this.queue.running(),this._promise),this.queue.length()===0&&this.queue.running()===0)if(this._promise){let i=()=>{Wt("wrap"),queueMicrotask(n);};this._promise.resolve(),this._promise.promise.then(i,i),this._promise=null;}else r();else Wt("delayed",this.name),this.queue.drain=()=>{Wt("drain",this.name),this.queue.drain=ZX,queueMicrotask(n);};};queueMicrotask(n),this.queue.resume();};function ZX(){}tN.exports={Plugin:wa};});var iN=c((Gqe,nN)=>{var{AVV_ERR_PLUGIN_NOT_VALID:Mw}=ih();function eZ(e){if(!(e&&(typeof e=="function"||typeof e.then=="function")))throw Array.isArray(e)?new Mw("array"):e===null?new Mw("null"):new Mw(typeof e)}nN.exports={validatePlugin:eZ};});var oN=c((zqe,sN)=>{function tZ(e){return e!==null&&typeof e=="object"&&typeof e.default=="function"}sN.exports={isBundledOrTypescriptPlugin:tZ};});var lN=c((Vqe,cN)=>{var{debug:aN}=sh(),{kThenifyDoNotWrap:Fw}=ya();function rZ(){if(this.booted){aN("thenify returning undefined because we are already booted");return}if(this[Fw]){this[Fw]=false;return}return aN("thenify"),(e,t)=>this._loadRegistered().then(()=>(this[Fw]=true,e(this._server)),t)}cN.exports={thenify:rZ};});var dN=c((Wqe,uN)=>{var{isPromiseLike:nZ}=oh(),{kAvvio:iZ}=ya();function sZ(e,t,r){let n;try{n=e.apply(e,t);}catch(i){r&&process.nextTick(r,i);return}nZ(n)&&!n[iZ]?n.then(()=>process.nextTick(r),i=>process.nextTick(r,i)):r&&process.nextTick(r);}uN.exports={executeWithThenable:sZ};});var _N=c((Kqe,vN)=>{var ah=jw(),oZ=a("events").EventEmitter,aZ=a("util").inherits,{AVV_ERR_EXPOSE_ALREADY_DEFINED:kl,AVV_ERR_CALLBACK_NOT_FN:va,AVV_ERR_ROOT_PLG_BOOTED:cZ,AVV_ERR_READY_TIMEOUT:lZ,AVV_ERR_ATTRIBUTE_ALREADY_DEFINED:uZ}=ih(),{kAvvio:pN,kIsOnCloseHandler:mN}=ya(),{TimeTree:dZ}=W1(),{Plugin:gN}=rN(),{debug:_a}=sh(),{validatePlugin:fZ}=iN(),{isBundledOrTypescriptPlugin:hZ}=oN(),{isPromiseLike:pZ}=oh(),{thenify:yN}=lN(),{executeWithThenable:fN}=dN();function kt(e,t,r){if(typeof e=="function"&&arguments.length===1&&(r=e,t={},e=null),typeof t=="function"&&(r=t,t={}),t=t||{},t.autostart=t.autostart!==false,t.timeout=Number(t.timeout)||0,t.expose=t.expose||{},!new.target)return new kt(e,t,r);this._server=e||this,this._opts=t,e&&this._expose(),this._current=[],this._error=null,this._lastUsed=null,this.setMaxListeners(0),r&&this.once("start",r),this.started=false,this.booted=false,this.pluginTree=new dZ,this._readyQ=ah(this,wN,1),this._readyQ.pause(),this._readyQ.drain=()=>{this.emit("start"),this._readyQ.drain=hN;},this._closeQ=ah(this,gZ,1),this._closeQ.pause(),this._closeQ.drain=()=>{this.emit("close"),this._closeQ.drain=hN;},this._doStart=null;let n=this;this._root=new gN(ah(this,this._loadPluginNextTick,1),function(s,o,a){n._doStart=a,o.autostart&&n.start();},t,false,0),this._trackPluginLoading(this._root),this._loadPlugin(this._root,i=>{_a("root plugin ready");try{this.emit("preReady"),this._root=null;}catch(s){i=i||this._error||s;}if(i){if(this._error=i,this._readyQ.length()===0)throw i}else this.booted=true;this._readyQ.resume();});}aZ(kt,oZ);"asyncDispose"in Symbol&&(kt.prototype[Symbol.asyncDispose]=function(){return new Promise((e,t)=>{this.close(r=>{if(r)return t(r);e();});})});kt.prototype.start=function(){return this.started=true,process.nextTick(this._doStart),this};kt.prototype.override=function(e,t,r){return e};kt.prototype[pN]=true;kt.prototype.use=function(e,t){return this._lastUsed=this._addPlugin(e,t,false),this};kt.prototype._loadRegistered=function(){let e=this._current[0];return !this.started&&!this.booted&&process.nextTick(()=>this._root.queue.resume()),e?e.loadedSoFar():Promise.resolve()};Object.defineProperty(kt.prototype,"then",{get:yN});kt.prototype._addPlugin=function(e,t,r){if(hZ(e)&&(e=e.default),fZ(e),t=t||{},this.booted)throw new cZ;let n=this._current[0],i=this._opts.timeout;if(!n.loaded&&n.timeout>0){let o=Date.now()-n.startTime;i=n.timeout-(o+3);}let s=new gN(ah(this,this._loadPluginNextTick,1),e,t,r,i);if(this._trackPluginLoading(s),n.loaded)throw new Error(s.name,n.name);return n.enqueue(s,o=>{o&&(this._error=o);}),s};kt.prototype._expose=function(){let t=this,r=t._server,{use:n="use",after:i="after",ready:s="ready",onClose:o="onClose",close:a="close"}=this._opts.expose;if(r[n])throw new kl(n,"use");if(r[n]=function(c,l){return t.use(c,l),this},r[i])throw new kl(i,"after");if(r[i]=function(c){return typeof c!="function"?t._loadRegistered():(t.after($w(c,this)),this)},r[s])throw new kl(s,"ready");if(r[s]=function(c){if(c&&typeof c!="function")throw new va(s,typeof c);return t.ready(c?$w(c,this):void 0)},r[o])throw new kl(o,"onClose");if(r[o]=function(c){if(typeof c!="function")throw new va(o,typeof c);return t.onClose(yZ(c,this)),this},r[a])throw new kl(a,"close");if(r[a]=function(c){if(c&&typeof c!="function")throw new va(a,typeof c);return c?(t.close($w(c,this)),this):t.close()},r.then)throw new uZ("then");Object.defineProperty(r,"then",{get:yN.bind(t)}),r[pN]=true;};kt.prototype.after=function(e){if(!e)return this._loadRegistered();this._addPlugin(t.bind(this),{},true);function t(r,n,i){wN.call(this,e,i);}return this};kt.prototype.onClose=function(e){if(typeof e!="function")throw new va("onClose",typeof e);return e[mN]=true,this._closeQ.unshift(e,t=>{t&&(this._error=t);}),this};kt.prototype.close=function(e){let t;if(e){if(typeof e!="function")throw new va("close",typeof e)}else t=new Promise(function(r,n){e=function(i){if(i)return n(i);r();};});return this.ready(()=>{this._error=null,this._closeQ.push(e),process.nextTick(this._closeQ.resume.bind(this._closeQ));}),t};kt.prototype.ready=function(e){if(e){if(typeof e!="function")throw new va("ready",typeof e);this._readyQ.push(e),queueMicrotask(this.start.bind(this));return}return new Promise((t,r)=>{this._readyQ.push(i),this.start();let n=this._current[0].server;function i(s,o,a){s?r(s):t(n),process.nextTick(a);}})};kt.prototype._trackPluginLoading=function(e){let t=this._current[0]?.name||null;e.once("start",(r,n,i)=>{let s=this.pluginTree.start(t||null,n,i);e.once("loaded",(o,a,c)=>{this.pluginTree.stop(s,c);});});};kt.prototype.prettyPrint=function(){return this.pluginTree.prettyPrint()};kt.prototype.toJSON=function(){return this.pluginTree.toJSON()};kt.prototype._loadPlugin=function(e,t){let r=this;if(pZ(e.func)){e.func.then(o=>{typeof o.default=="function"&&(o=o.default),e.func=o,this._loadPlugin(e,t);},t);return}let n=r._current[0];if(r._current.unshift(e),r._error&&!e.isAfter){_a("skipping loading of plugin as instance errored and it is not an after",e.name),process.nextTick(s);return}let i=n?.server||r._server;if(!e.isAfter)try{i=r.override(i,e.func,e.options);}catch(o){return _a("override errored",e.name),s(o)}e.exec(i,s);function s(o){e.finish(o,a=>{r._current.shift(),t(a);});}};kt.prototype._loadPluginNextTick=function(e,t){process.nextTick(this._loadPlugin.bind(this),e,t);};function hN(){}function wN(e,t){let r=this._server,n=this._error;if(this._error=null,e.length===0)this._error=n,fN(e,[],t);else if(e.length===1)fN(e,[n],t);else if(this._opts.timeout===0){let i=false,s=o=>{i||(i=true,this._error=o,process.nextTick(t,this._error));};e.length===2?e(n,s):e(n,r,s);}else mZ.call(this,e,n,r,t);}function mZ(e,t,r,n){let i=e.unwrappedName??e.name;_a("setting up ready timeout",i,this._opts.timeout);let s=setTimeout(()=>{_a("timed out",i),s=null;let a=new lZ(i);a.fn=e,this._error=a,n(a);},this._opts.timeout);e.length===2?e(t,o.bind(this)):e(t,r,o.bind(this));function o(a){s&&(clearTimeout(s),s=null,this._error=a,process.nextTick(n,this._error));}}function gZ(e,t){let r=this._server,n=e[mN];if(e.length===0||e.length===1){let i;n?i=e(r):i=e(this._error),i&&typeof i.then=="function"?(_a("resolving close/onClose promise"),i.then(()=>process.nextTick(t),s=>process.nextTick(t,s))):process.nextTick(t);}else e.length===2?e(n?r:this._error,t):n?e(r,t):e(this._error,r,t);}function yZ(e,t){return r.bind(t);function r(n,i){let s;e.length===0?(s=e(),s?.then?s.then(function(){process.nextTick(i);},i):process.nextTick(i)):e.length===1?(s=e(this),s?.then?s.then(function(){process.nextTick(i);},i):process.nextTick(i)):e(this,i);}}function $w(e,t){let r=n.bind(t);return r.unwrappedName=e.name,r;function n(i,s){let o;e?e.length===0?(o=e(),o?.then?o.then(function(){process.nextTick(s,i);},s):process.nextTick(s,i)):e.length===1?(o=e(i),o?.then?o.then(function(){process.nextTick(s);},s):process.nextTick(s)):e.length===2?e(i,s):e(i,this,s):process.nextTick(s);}}vN.exports=kt;});var St=c((Yqe,SN)=>{var wZ={kAvvioBoot:Symbol("fastify.avvioBoot"),kChildren:Symbol("fastify.children"),kServerBindings:Symbol("fastify.serverBindings"),kBodyLimit:Symbol("fastify.bodyLimit"),kSupportedHTTPMethods:Symbol("fastify.acceptedHTTPMethods"),kRoutePrefix:Symbol("fastify.routePrefix"),kLogLevel:Symbol("fastify.logLevel"),kLogSerializers:Symbol("fastify.logSerializers"),kHooks:Symbol("fastify.hooks"),kContentTypeParser:Symbol("fastify.contentTypeParser"),kState:Symbol("fastify.state"),kOptions:Symbol("fastify.options"),kPluginNameChain:Symbol("fastify.pluginNameChain"),kRouteContext:Symbol("fastify.context"),kGenReqId:Symbol("fastify.genReqId"),kHttp2ServerSessions:Symbol("fastify.http2ServerSessions"),kSchemaController:Symbol("fastify.schemaController"),kSchemaHeaders:Symbol("headers-schema"),kSchemaParams:Symbol("params-schema"),kSchemaQuerystring:Symbol("querystring-schema"),kSchemaBody:Symbol("body-schema"),kSchemaResponse:Symbol("response-schema"),kSchemaErrorFormatter:Symbol("fastify.schemaErrorFormatter"),kSchemaVisited:Symbol("fastify.schemas.visited"),kRequest:Symbol("fastify.Request"),kRequestPayloadStream:Symbol("fastify.RequestPayloadStream"),kRequestAcceptVersion:Symbol("fastify.RequestAcceptVersion"),kRequestCacheValidateFns:Symbol("fastify.request.cache.validateFns"),kRequestContentType:Symbol("fastify.request.contentType"),kRequestOriginalUrl:Symbol("fastify.request.originalUrl"),kRequestSignal:Symbol("fastify.request.signal"),kHandlerTimeout:Symbol("fastify.handlerTimeout"),kTimeoutTimer:Symbol("fastify.request.timeoutTimer"),kOnAbort:Symbol("fastify.request.onAbort"),kFourOhFour:Symbol("fastify.404"),kCanSetNotFoundHandler:Symbol("fastify.canSetNotFoundHandler"),kFourOhFourLevelInstance:Symbol("fastify.404LogLevelInstance"),kFourOhFourContext:Symbol("fastify.404ContextKey"),kDefaultJsonParse:Symbol("fastify.defaultJSONParse"),kReply:Symbol("fastify.Reply"),kReplySerializer:Symbol("fastify.reply.serializer"),kReplyIsError:Symbol("fastify.reply.isError"),kReplyHeaders:Symbol("fastify.reply.headers"),kReplyTrailers:Symbol("fastify.reply.trailers"),kReplyHasStatusCode:Symbol("fastify.reply.hasStatusCode"),kReplyHijacked:Symbol("fastify.reply.hijacked"),kReplyStartTime:Symbol("fastify.reply.startTime"),kReplyNextErrorHandler:Symbol("fastify.reply.nextErrorHandler"),kReplyEndTime:Symbol("fastify.reply.endTime"),kReplyErrorHandlerCalled:Symbol("fastify.reply.errorHandlerCalled"),kReplyIsRunningOnErrorHook:Symbol("fastify.reply.isRunningOnErrorHook"),kReplySerializerDefault:Symbol("fastify.replySerializerDefault"),kReplyCacheSerializeFns:Symbol("fastify.reply.cache.serializeFns"),kTestInternals:Symbol("fastify.testInternals"),kErrorHandler:Symbol("fastify.errorHandler"),kErrorHandlerAlreadySet:Symbol("fastify.errorHandlerAlreadySet"),kChildLoggerFactory:Symbol("fastify.childLoggerFactory"),kHasBeenDecorated:Symbol("fastify.hasBeenDecorated"),kKeepAliveConnections:Symbol("fastify.keepAliveConnections"),kRouteByFastify:Symbol("fastify.routeByFastify"),kLogController:Symbol("fastify.logController"),kDiagnosticsStore:Symbol("fastify.diagnosticsStore")};SN.exports=wZ;});var EN=c((Qqe,ch)=>{var{format:qw}=a("util"),xl=Symbol("process-warning.fn"),Sa=Symbol("process-warning.spyData");function vZ(e){if(e[Sa]===null){let t=e[xl];e[xl]=function(n,i,s){let o=[];s?o.push(n,i,s):i?o.push(n,i):n&&o.push(n),e[Sa].calls.push({arguments:o,result:t(n,i,s)});};let r={calls:[],callCount(){return r.calls.length},reset(){e.emitted=false,r.calls.length=0;},restore(){r.reset(),e[xl]=t,e[Sa]=null;}};e[Sa]=r;}return e[Sa]}function _Z(e){return bN({...e,name:"DeprecationWarning"})}function bN({name:e,code:t,message:r,unlimited:n=false}={}){if(!e)throw new Error("Warning name must not be empty");if(!t)throw new Error("Warning code must not be empty");if(!r)throw new Error("Warning message must not be empty");if(typeof n!="boolean")throw new Error("Warning opts.unlimited must be a boolean");t=t.toUpperCase();let i=n===true?function(a,c,l){return o.emitted=true,process.emitWarning(o.format(a,c,l),o.name,o.code),true}:function(a,c,l){return o.emitted===true&&o.unlimited!==true?false:(o.emitted=true,process.emitWarning(o.format(a,c,l),o.name,o.code),true)},o={[e]:function(a,c,l){return o[xl](a,c,l)}}[e];return o.emitted=false,o.message=r,o.unlimited=n,o.code=t,o[xl]=i,o[Sa]=null,o.format=function(a,c,l){let u;return a&&c&&l?u=qw(r,a,c,l):a&&c?u=qw(r,a,c):a?u=qw(r,a):u=r,u},o}var Uw={createWarning:bN,createDeprecation:_Z,spyWarning:vZ};ch.exports=Uw;ch.exports.default=Uw;ch.exports.processWarning=Uw;});var ba=c((Jqe,TN)=>{var{createWarning:vi}=EN(),SZ=vi({name:"FastifyWarning",code:"FSTWRN001",message:"The %s schema for %s: %s is missing. This may indicate the schema is not well specified.",unlimited:true}),bZ=vi({name:"FastifyWarning",code:"FSTWRN003",message:"The %s mixes async and callback styles that may lead to unhandled rejections. Please use only one of them.",unlimited:true}),EZ=vi({name:"FastifyWarning",code:"FSTWRN004",message:"It seems that you are overriding an errorHandler in the same scope, which can lead to subtle bugs. To disable this behavior, set 'allowErrorHandlerOverride' to false. For more information, visit: https://fastify.dev/docs/latest/Reference/Server/#allowerrorhandleroverride",unlimited:true}),TZ=vi({name:"FastifySecurity",code:"FSTSEC001",message:'You are using /%s/ Content-Type which may be vulnerable to CORS attack. Please make sure your RegExp start with "^" or include ";?" to proper detection of the essence MIME type.',unlimited:true}),RZ=vi({name:"FastifySecurity",code:"FSTSEC002",message:"The headers schema for %s: %s references an external $ref (%s) that is not case-normalized. Header names in the referenced schema keep their original case and will not match the lowercased request headers, so case-insensitive assertions such as required and dependencies may not apply. Inline the header schema instead of referencing it with an external $ref.",unlimited:true}),PZ=vi({name:"FastifyWarning",code:"FSTDEP022",message:'The router options for %s property access is deprecated. Please use "options.routerOptions" instead for accessing router options. The router options will be removed in `fastify@6`.',unlimited:true}),kZ=vi({name:"FastifyDeprecation",code:"FSTDEP023",message:"disableRequestLogging option is deprecated. Use the logController option with disableRequestLogging or isLogDisabled override instead. The disableRequestLogging top-level option will be removed in `fastify@6`.",unlimited:true}),xZ=vi({name:"FastifyDeprecation",code:"FSTDEP024",message:"requestIdLogLabel option is deprecated. Use the logController option with requestIdLogLabel instead. The requestIdLogLabel top-level option will be removed in `fastify@6`.",unlimited:true}),AZ=vi({name:"FastifyDeprecation",code:"FSTDEP025",message:'Calling addHttpMethod for existing method "%s" without { overrideExisting: true } is deprecated. In Fastify v6, this will throw an error.',unlimited:true});TN.exports={FSTWRN001:SZ,FSTWRN003:bZ,FSTWRN004:EZ,FSTSEC001:TZ,FSTSEC002:RZ,FSTDEP022:PZ,FSTDEP023:kZ,FSTDEP024:xZ,FSTDEP025:AZ};});var Ut=c((Xqe,lh)=>{var Z=Pl(),ro={FST_ERR_NOT_FOUND:Z("FST_ERR_NOT_FOUND","Not Found",404),FST_ERR_OPTIONS_NOT_OBJ:Z("FST_ERR_OPTIONS_NOT_OBJ","Options must be an object",500,TypeError),FST_ERR_QSP_NOT_FN:Z("FST_ERR_QSP_NOT_FN","querystringParser option should be a function, instead got '%s'",500,TypeError),FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN:Z("FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN","schemaController.bucket option should be a function, instead got '%s'",500,TypeError),FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN:Z("FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN","schemaErrorFormatter option should be a non async function. Instead got '%s'.",500,TypeError),FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ:Z("FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ","ajv.customOptions option should be an object, instead got '%s'",500,TypeError),FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR:Z("FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR","ajv.plugins option should be an array, instead got '%s'",500,TypeError),FST_ERR_VALIDATION:Z("FST_ERR_VALIDATION","%s",400),FST_ERR_LISTEN_OPTIONS_INVALID:Z("FST_ERR_LISTEN_OPTIONS_INVALID","Invalid listen options: '%s'",500,TypeError),FST_ERR_ERROR_HANDLER_NOT_FN:Z("FST_ERR_ERROR_HANDLER_NOT_FN","Error Handler must be a function",500,TypeError),FST_ERR_ERROR_HANDLER_ALREADY_SET:Z("FST_ERR_ERROR_HANDLER_ALREADY_SET","Error Handler already set in this scope. Set 'allowErrorHandlerOverride: true' to allow overriding.",500,TypeError),FST_ERR_CTP_ALREADY_PRESENT:Z("FST_ERR_CTP_ALREADY_PRESENT","Content type parser '%s' already present."),FST_ERR_CTP_INVALID_TYPE:Z("FST_ERR_CTP_INVALID_TYPE","The content type should be a string or a RegExp",500,TypeError),FST_ERR_CTP_EMPTY_TYPE:Z("FST_ERR_CTP_EMPTY_TYPE","The content type cannot be an empty string",500,TypeError),FST_ERR_CTP_INVALID_HANDLER:Z("FST_ERR_CTP_INVALID_HANDLER","The content type handler should be a function",500,TypeError),FST_ERR_CTP_INVALID_PARSE_TYPE:Z("FST_ERR_CTP_INVALID_PARSE_TYPE","The body parser can only parse your data as 'string' or 'buffer', you asked '%s' which is not supported.",500,TypeError),FST_ERR_CTP_BODY_TOO_LARGE:Z("FST_ERR_CTP_BODY_TOO_LARGE","Request body is too large",413,RangeError),FST_ERR_CTP_INVALID_MEDIA_TYPE:Z("FST_ERR_CTP_INVALID_MEDIA_TYPE","Unsupported Media Type",415),FST_ERR_CTP_INVALID_CONTENT_LENGTH:Z("FST_ERR_CTP_INVALID_CONTENT_LENGTH","Request body size did not match Content-Length",400,RangeError),FST_ERR_CTP_EMPTY_JSON_BODY:Z("FST_ERR_CTP_EMPTY_JSON_BODY","Body cannot be empty when content-type is set to 'application/json'",400),FST_ERR_CTP_INVALID_JSON_BODY:Z("FST_ERR_CTP_INVALID_JSON_BODY","Body is not valid JSON but content-type is set to 'application/json'",400),FST_ERR_CTP_INSTANCE_ALREADY_STARTED:Z("FST_ERR_CTP_INSTANCE_ALREADY_STARTED",'Cannot call "%s" when fastify instance is already started!',400),FST_ERR_DEC_ALREADY_PRESENT:Z("FST_ERR_DEC_ALREADY_PRESENT","The decorator '%s' has already been added!"),FST_ERR_DEC_DEPENDENCY_INVALID_TYPE:Z("FST_ERR_DEC_DEPENDENCY_INVALID_TYPE","The dependencies of decorator '%s' must be of type Array.",500,TypeError),FST_ERR_DEC_MISSING_DEPENDENCY:Z("FST_ERR_DEC_MISSING_DEPENDENCY","The decorator is missing dependency '%s'."),FST_ERR_DEC_AFTER_START:Z("FST_ERR_DEC_AFTER_START","The decorator '%s' has been added after start!"),FST_ERR_DEC_REFERENCE_TYPE:Z("FST_ERR_DEC_REFERENCE_TYPE","The decorator '%s' of type '%s' is a reference type. Use the { getter, setter } interface instead."),FST_ERR_DEC_UNDECLARED:Z("FST_ERR_DEC_UNDECLARED","No decorator '%s' has been declared on %s."),FST_ERR_HOOK_INVALID_TYPE:Z("FST_ERR_HOOK_INVALID_TYPE","The hook name must be a string",500,TypeError),FST_ERR_HOOK_INVALID_HANDLER:Z("FST_ERR_HOOK_INVALID_HANDLER","%s hook should be a function, instead got %s",500,TypeError),FST_ERR_HOOK_INVALID_ASYNC_HANDLER:Z("FST_ERR_HOOK_INVALID_ASYNC_HANDLER","Async function has too many arguments. Async hooks should not use the 'done' argument.",500,TypeError),FST_ERR_HOOK_NOT_SUPPORTED:Z("FST_ERR_HOOK_NOT_SUPPORTED","%s hook not supported!",500,TypeError),FST_ERR_MISSING_MIDDLEWARE:Z("FST_ERR_MISSING_MIDDLEWARE","You must register a plugin for handling middlewares, visit fastify.dev/docs/latest/Reference/Middleware/ for more info.",500),FST_ERR_HOOK_TIMEOUT:Z("FST_ERR_HOOK_TIMEOUT","A callback for '%s' hook%s timed out. You may have forgotten to call 'done' function or to resolve a Promise"),FST_ERR_LOG_INVALID_DESTINATION:Z("FST_ERR_LOG_INVALID_DESTINATION","Cannot specify both logger.stream and logger.file options"),FST_ERR_LOG_INVALID_LOGGER:Z("FST_ERR_LOG_INVALID_LOGGER","Invalid logger object provided. The logger instance should have these functions(s): '%s'.",500,TypeError),FST_ERR_LOG_INVALID_LOGGER_INSTANCE:Z("FST_ERR_LOG_INVALID_LOGGER_INSTANCE","loggerInstance only accepts a logger instance.",500,TypeError),FST_ERR_LOG_INVALID_LOGGER_CONFIG:Z("FST_ERR_LOG_INVALID_LOGGER_CONFIG","logger options only accepts a configuration object.",500,TypeError),FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED:Z("FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED","You cannot provide both logger and loggerInstance. Please provide only one.",500,TypeError),FST_ERR_LOG_INVALID_LOG_CONTROLLER:Z("FST_ERR_LOG_INVALID_LOG_CONTROLLER","logController option must be an instance of LogController, got '%s'.",500,TypeError),FST_ERR_REP_INVALID_PAYLOAD_TYPE:Z("FST_ERR_REP_INVALID_PAYLOAD_TYPE","Attempted to send payload of invalid type '%s'. Expected a string or Buffer.",500,TypeError),FST_ERR_REP_RESPONSE_BODY_CONSUMED:Z("FST_ERR_REP_RESPONSE_BODY_CONSUMED","Response.body is already consumed."),FST_ERR_REP_READABLE_STREAM_LOCKED:Z("FST_ERR_REP_READABLE_STREAM_LOCKED","ReadableStream was locked. You should call releaseLock() method on reader before sending."),FST_ERR_REP_ALREADY_SENT:Z("FST_ERR_REP_ALREADY_SENT",'Reply was already sent, did you forget to "return reply" in "%s" (%s)?'),FST_ERR_REP_SENT_VALUE:Z("FST_ERR_REP_SENT_VALUE","The only possible value for reply.sent is true.",500,TypeError),FST_ERR_SEND_INSIDE_ONERR:Z("FST_ERR_SEND_INSIDE_ONERR","You cannot use `send` inside the `onError` hook"),FST_ERR_SEND_UNDEFINED_ERR:Z("FST_ERR_SEND_UNDEFINED_ERR","Undefined error has occurred"),FST_ERR_BAD_STATUS_CODE:Z("FST_ERR_BAD_STATUS_CODE","Called reply with an invalid status code: %s"),FST_ERR_BAD_TRAILER_NAME:Z("FST_ERR_BAD_TRAILER_NAME","Called reply.trailer with an invalid header name: %s"),FST_ERR_BAD_TRAILER_VALUE:Z("FST_ERR_BAD_TRAILER_VALUE","Called reply.trailer('%s', fn) with an invalid type: %s. Expected a function."),FST_ERR_FAILED_ERROR_SERIALIZATION:Z("FST_ERR_FAILED_ERROR_SERIALIZATION","Failed to serialize an error. Error: %s. Original error: %s"),FST_ERR_MISSING_SERIALIZATION_FN:Z("FST_ERR_MISSING_SERIALIZATION_FN",'Missing serialization function. Key "%s"'),FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN:Z("FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN",'Missing serialization function. Key "%s:%s"'),FST_ERR_REQ_INVALID_VALIDATION_INVOCATION:Z("FST_ERR_REQ_INVALID_VALIDATION_INVOCATION",'Invalid validation invocation. Missing validation function for HTTP part "%s" nor schema provided.'),FST_ERR_SCH_MISSING_ID:Z("FST_ERR_SCH_MISSING_ID","Missing schema $id property"),FST_ERR_SCH_ALREADY_PRESENT:Z("FST_ERR_SCH_ALREADY_PRESENT","Schema with id '%s' already declared!"),FST_ERR_SCH_CONTENT_MISSING_SCHEMA:Z("FST_ERR_SCH_CONTENT_MISSING_SCHEMA","Schema is missing for the content type '%s'"),FST_ERR_SCH_DUPLICATE:Z("FST_ERR_SCH_DUPLICATE","Schema with '%s' already present!"),FST_ERR_SCH_VALIDATION_BUILD:Z("FST_ERR_SCH_VALIDATION_BUILD","Failed building the validation schema for %s: %s, due to error %s"),FST_ERR_SCH_SERIALIZATION_BUILD:Z("FST_ERR_SCH_SERIALIZATION_BUILD","Failed building the serialization schema for %s: %s, due to error %s"),FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX:Z("FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX",'response schemas should be nested under a valid status code, e.g { 2xx: { type: "object" } }'),FST_ERR_INIT_OPTS_INVALID:Z("FST_ERR_INIT_OPTS_INVALID","Invalid initialization options: '%s'"),FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE:Z("FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE","Cannot set forceCloseConnections to 'idle' as your HTTP server does not support closeIdleConnections method"),FST_ERR_DUPLICATED_ROUTE:Z("FST_ERR_DUPLICATED_ROUTE","Method '%s' already declared for route '%s'"),FST_ERR_BAD_URL:Z("FST_ERR_BAD_URL","'%s' is not a valid url component",400,URIError),FST_ERR_MAX_PARAM_LENGTH:Z("FST_ERR_MAX_PARAM_LENGTH","'%s' is exceeding the max param length",414,URIError),FST_ERR_ASYNC_CONSTRAINT:Z("FST_ERR_ASYNC_CONSTRAINT","Unexpected error from async constraint",500),FST_ERR_INVALID_URL:Z("FST_ERR_INVALID_URL","URL must be a string. Received '%s'",400,TypeError),FST_ERR_ROUTE_OPTIONS_NOT_OBJ:Z("FST_ERR_ROUTE_OPTIONS_NOT_OBJ",'Options for "%s:%s" route must be an object',500,TypeError),FST_ERR_ROUTE_DUPLICATED_HANDLER:Z("FST_ERR_ROUTE_DUPLICATED_HANDLER",'Duplicate handler for "%s:%s" route is not allowed!',500),FST_ERR_ROUTE_HANDLER_NOT_FN:Z("FST_ERR_ROUTE_HANDLER_NOT_FN","Error Handler for %s:%s route, if defined, must be a function",500,TypeError),FST_ERR_ROUTE_MISSING_HANDLER:Z("FST_ERR_ROUTE_MISSING_HANDLER",'Missing handler function for "%s:%s" route.',500),FST_ERR_ROUTE_METHOD_INVALID:Z("FST_ERR_ROUTE_METHOD_INVALID","Provided method is invalid!",500,TypeError),FST_ERR_ROUTE_METHOD_NOT_SUPPORTED:Z("FST_ERR_ROUTE_METHOD_NOT_SUPPORTED","%s method is not supported.",500),FST_ERR_ROUTE_LOG_LEVEL_INVALID:Z("FST_ERR_ROUTE_LOG_LEVEL_INVALID","Log level for '%s:%s' route must be a valid logger level. Received: '%s'",500,TypeError),FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED:Z("FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED","Body validation schema for %s:%s route is not supported!",500),FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT:Z("FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT","'bodyLimit' option must be an integer > 0. Got '%s'",500,TypeError),FST_ERR_HANDLER_TIMEOUT:Z("FST_ERR_HANDLER_TIMEOUT","Request timed out after %s ms on route '%s'",503),FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT:Z("FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT","'handlerTimeout' option must be an integer > 0. Got '%s'",500,TypeError),FST_ERR_ROUTE_REWRITE_NOT_STR:Z("FST_ERR_ROUTE_REWRITE_NOT_STR",'Rewrite url for "%s" needs to be of type "string" but received "%s"',500,TypeError),FST_ERR_ROUTE_MISSING_CONTENT_TYPE:Z("FST_ERR_ROUTE_MISSING_CONTENT_TYPE","Method '%s' must provide a 'Content-Type' header.",400),FST_ERR_ROUTE_MISSING_CONTENT:Z("FST_ERR_ROUTE_MISSING_CONTENT","Method '%s' must provide a request body.",400),FST_ERR_REOPENED_CLOSE_SERVER:Z("FST_ERR_REOPENED_CLOSE_SERVER","Fastify has already been closed and cannot be reopened"),FST_ERR_REOPENED_SERVER:Z("FST_ERR_REOPENED_SERVER","Fastify is already listening"),FST_ERR_INSTANCE_ALREADY_LISTENING:Z("FST_ERR_INSTANCE_ALREADY_LISTENING","Fastify instance is already listening. %s"),FST_ERR_PLUGIN_VERSION_MISMATCH:Z("FST_ERR_PLUGIN_VERSION_MISMATCH","fastify-plugin: %s - expected '%s' fastify version, '%s' is installed"),FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE:Z("FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE","The decorator '%s'%s is not present in %s"),FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER:Z("FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER","The %s plugin being registered mixes async and callback styles. Async plugin should not mix async and callback style.",500,TypeError),FST_ERR_PLUGIN_DEPENDENCY_NOT_REGISTERED:Z("FST_ERR_PLUGIN_DEPENDENCY_NOT_REGISTERED","The dependency '%s' of plugin '%s' is not registered"),FST_ERR_PLUGIN_CALLBACK_NOT_FN:Z("FST_ERR_PLUGIN_CALLBACK_NOT_FN","fastify-plugin: %s",500,TypeError),FST_ERR_PLUGIN_NOT_VALID:Z("FST_ERR_PLUGIN_NOT_VALID","fastify-plugin: %s"),FST_ERR_ROOT_PLG_BOOTED:Z("FST_ERR_ROOT_PLG_BOOTED","fastify-plugin: %s"),FST_ERR_PARENT_PLUGIN_BOOTED:Z("FST_ERR_PARENT_PLUGIN_BOOTED","fastify-plugin: %s"),FST_ERR_PLUGIN_TIMEOUT:Z("FST_ERR_PLUGIN_TIMEOUT","fastify-plugin: %s")};function IZ(e,t){return t.cause=e,t}lh.exports=ro;lh.exports.appendStackTrace=IZ;lh.exports.AVVIO_ERRORS_MAP={AVV_ERR_CALLBACK_NOT_FN:ro.FST_ERR_PLUGIN_CALLBACK_NOT_FN,AVV_ERR_PLUGIN_NOT_VALID:ro.FST_ERR_PLUGIN_NOT_VALID,AVV_ERR_ROOT_PLG_BOOTED:ro.FST_ERR_ROOT_PLG_BOOTED,AVV_ERR_PARENT_PLG_LOADED:ro.FST_ERR_PARENT_PLUGIN_BOOTED,AVV_ERR_READY_TIMEOUT:ro.FST_ERR_PLUGIN_TIMEOUT,AVV_ERR_PLUGIN_EXEC_TIMEOUT:ro.FST_ERR_PLUGIN_TIMEOUT};});var is=c((Zqe,NN)=>{var OZ=["onRoute","onRegister","onReady","onListen","preClose","onClose"],xN=["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError","onRequestAbort"],CZ=xN.concat(OZ),{FST_ERR_HOOK_INVALID_TYPE:NZ,FST_ERR_HOOK_INVALID_HANDLER:jZ,FST_ERR_SEND_UNDEFINED_ERR:uh,FST_ERR_HOOK_TIMEOUT:LZ,FST_ERR_HOOK_NOT_SUPPORTED:DZ,AVVIO_ERRORS_MAP:RN,appendStackTrace:PN}=Ut(),{kChildren:Al,kHooks:AN,kRequestPayloadStream:kN}=St();function Il(){this.onRequest=[],this.preParsing=[],this.preValidation=[],this.preSerialization=[],this.preHandler=[],this.onResponse=[],this.onSend=[],this.onError=[],this.onRoute=[],this.onRegister=[],this.onReady=[],this.onListen=[],this.onTimeout=[],this.onRequestAbort=[],this.preClose=[];}Il.prototype=Object.create(null);Il.prototype.validate=function(e,t){if(typeof e!="string")throw new NZ;if(Array.isArray(this[e])===false)throw new DZ(e);if(typeof t!="function")throw new jZ(e,Object.prototype.toString.call(t))};Il.prototype.add=function(e,t){this.validate(e,t),this[e].push(t);};function MZ(e){let t=new Il;return t.onRequest=e.onRequest.slice(),t.preParsing=e.preParsing.slice(),t.preValidation=e.preValidation.slice(),t.preSerialization=e.preSerialization.slice(),t.preHandler=e.preHandler.slice(),t.onSend=e.onSend.slice(),t.onResponse=e.onResponse.slice(),t.onError=e.onError.slice(),t.onRoute=e.onRoute.slice(),t.onRegister=e.onRegister.slice(),t.onTimeout=e.onTimeout.slice(),t.onRequestAbort=e.onRequestAbort.slice(),t.onReady=[],t.onListen=[],t.preClose=[],t}function IN(e,t,r,n){let i=r[AN][e],s=0,o=0;c();function a(u){let d=i[s-1]?.name,m=d?` "${d}"`:"";if(u){u.code==="AVV_ERR_READY_TIMEOUT"?u=PN(u,new LZ(e,m)):u=RN[u.code]!=null?PN(u,new RN[u.code](u.message)):u,n(u);return}n();}function c(u){if(u){a(u);return}if(s===i.length&&o===r[Al].length){s===0&&o===0?a():t(function(m,p){a(m),p(m);});return}if(s===i.length&&o<r[Al].length){let d=r[Al][o++];IN(e,t,d,c);return}t(l(i[s++],r)),c();}function l(u,d){return function(m,p){if(m){p(m);return}if(u.length===1){try{u.call(d,p);}catch(h){p(h);}return}try{let h=u.call(d);if(h&&typeof h.then=="function"){h.then(p,p);return}}catch(h){m=h;}p(m);}}}function ON(e){let t=e[AN].onListen,r=t.length,n=0,i=0;s();function s(a){if(a&&e.log.error(a),n===r){for(;i<e[Al].length;){let c=e[Al][i++];ON(c);}return}o(t[n++],e,s);}async function o(a,c,l){if(a.length===1){try{a.call(c,l);}catch(u){l(u);}return}try{let u=a.call(c);if(u&&typeof u.then=="function"){u.then(l,l);return}l();}catch(u){l(u);}}}function Ea(e){return function(r,n,i,s){let o=0;function a(u){if(u||o===r.length){s(u,n,i);return}let d;try{d=e(r[o++],n,i,a);}catch(m){s(m,n,i);return}d&&typeof d.then=="function"&&d.then(c,l);}function c(){a();}function l(u){u||(u=new uh),s(u,n,i);}a();}}function FZ(e,t,r,n){return e(t,r,n)}var $Z=Ea(FZ),qZ=Ea(Ol),UZ=Ea(Ol),BZ=Ea(Ol),HZ=Ea(Ol);function CN(e,t,r,n,i){let s=0;function o(l,u){if(l){i(l,t,r,n);return}if(u!==void 0&&(n=u),s===e.length){i(null,t,r,n);return}let d;try{d=e[s++](t,r,n,o);}catch(m){i(m,t,r);return}d&&typeof d.then=="function"&&d.then(a,c);}function a(l){try{o(null,l);}catch(u){i(u,t,r,n);}}function c(l){l||(l=new uh),i(l,t,r,n);}o();}var GZ=CN;function zZ(e,t,r,n){let i=0;function s(c,l){if(r.sent)return;if(l!==void 0&&(t[kN]=l),c||i===e.length){n(c,t,r);return}let u;try{u=e[i++](t,r,t[kN],s);}catch(d){n(d,t,r);return}u&&typeof u.then=="function"&&u.then(o,a);}function o(c){s(null,c);}function a(c){c||(c=new uh),n(c,t,r);}s();}function VZ(e,t,r){let n=0;function i(a){if(a||n===e.length){r(a,t);return}let c;try{c=e[n++](t,i);}catch(l){r(l,t);return}c&&typeof c.then=="function"&&c.then(s,o);}function s(){i();}function o(a){a||(a=new uh),r(a,t);}i();}function Ol(e,t,r,n){if(r.sent!==true)return e(t,r,n)}NN.exports={Hooks:Il,buildHooks:MZ,hookRunnerGenerator:Ea,preParsingHookRunner:zZ,onResponseHookRunner:$Z,onSendHookRunner:CN,preSerializationHookRunner:GZ,onRequestAbortHookRunner:VZ,hookIterator:Ol,hookRunnerApplication:IN,onListenHookRunner:ON,preHandlerHookRunner:UZ,preValidationHookRunner:qZ,onRequestHookRunner:HZ,onTimeoutHookRunner:BZ,lifecycleHooks:xN,supportedHooks:CZ};});var LN=c((eUe,jN)=>{jN.exports=function(){return {[Symbol.iterator]:function*(){},add(){},delete(){},has(){return true}}};});var Bw=c((tUe,MN)=>{var{kTestInternals:WZ}=St();function DN(){let e,t;return {promise:new Promise((n,i)=>{e=n,t=i;}),resolve:e,reject:t}}MN.exports={withResolvers:typeof Promise.withResolvers=="function"?Promise.withResolvers.bind(Promise):DN,[WZ]:{withResolvers:DN}};});var KN=c((rUe,WN)=>{var KZ=a("http"),YZ=a("https"),FN=a("http2"),QZ=a("dns"),JZ=a("os"),{kState:xt,kOptions:XZ,kServerBindings:ZZ,kHttp2ServerSessions:no}=St(),{FSTWRN003:eee}=ba(),{onListenHookRunner:dh}=is(),{FST_ERR_REOPENED_CLOSE_SERVER:qN,FST_ERR_REOPENED_SERVER:UN,FST_ERR_LISTEN_OPTIONS_INVALID:tee,FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE:ree}=Ut(),nee=LN(),BN=Bw();WN.exports.createServer=iee;function HN(e){return `Server listening at ${e}`}function iee(e,t){let r=zN(e,t);function n(l={port:0,host:"localhost"},u=void 0){if(typeof u=="function"&&(u.constructor.name==="AsyncFunction"&&eee("listen method"),l.cb=u),l.signal){if(typeof l.signal.on!="function"&&typeof l.signal.addEventListener!="function")throw new tee("Invalid options.signal");if(this[xt].aborted=l.signal.aborted,this[xt].aborted)return this.close();{let m=()=>{this[xt].aborted=true,this.close();};l.signal.addEventListener("abort",m,{once:true});}}let d;if(l.path==null?d=l.host??"localhost":d=l.host,(!Object.hasOwn(l,"host")||l.host==null)&&(l.host=d),d==="localhost"?l.cb=(m,p)=>{if(m){u(m,p);return}$N.call(this,r,t,e,l,()=>{this[xt].listening=true,u(null,p),dh(this);});}:l.cb=(m,p)=>{if(m){u(m,p);return}this[xt].listening=true,u(null,p),dh(this);},u===void 0)return see.call(this,r,l).then(p=>{let{promise:h,resolve:f}=BN.withResolvers();return d==="localhost"?$N.call(this,r,t,e,l,()=>{this[xt].listening=true,f(p),dh(this);}):(f(p),dh(this)),h});this.ready(GN.call(this,r,l));}let i=typeof r.closeAllConnections=="function",s=typeof r.closeIdleConnections=="function",o=typeof r.closeHttp2Sessions=="function",a=e.forceCloseConnections;if(a==="idle"&&!s)throw new ree;typeof a!="boolean"&&(a=s?"idle":false);let c=!i&&a===true?new Set:nee();return {server:r,listen:n,forceCloseConnections:a,serverHasCloseAllConnections:i,serverHasCloseHttp2Sessions:o,keepAliveConnections:c}}function $N(e,t,r,n,i){this[xt].listening=false,QZ.lookup(n.host,{all:true},(s,o)=>{if(s||this[xt].aborted){i();return}let a=e.listening&&r.serverFactory,c=0,l=0;if(!a){let d=e.address();for(let m of o)if(m.address!==d.address){c++;let p=Object.assign({},n,{host:m.address,port:d.port,cb:g=>{l++,g||this[ZZ].push(h),l===c&&i();}}),h=zN(r,t),f=()=>{h.close(()=>{}),typeof h.closeAllConnections=="function"&&r.forceCloseConnections===true&&h.closeAllConnections(),typeof h.closeHttp2Sessions=="function"&&h.closeHttp2Sessions();};h.on("upgrade",e.emit.bind(e,"upgrade")),e.on("unref",f),e.on("close",f),e.on("error",f),this[xt].listening=false,GN.call(this,h,p)();}}if(c===0){i();return}let u=e.unref;e.unref=function(){u.call(e),e.emit("unref");};});}function GN(e,t){let r=n=>{if(e.removeListener("error",r),e.removeListener("listening",r),n)this[xt].listening=false,t.cb(n,null);else {let i=VN.call(this,e,t.listenTextResolver||HN);t.cb(null,i);}};return n=>{if(n!=null)return t.cb(n);if(this[xt].listening&&this[xt].closing)return t.cb(new qN,null);if(this[xt].listening)return t.cb(new UN,null);e.once("error",r),this[xt].closing||(e.once("listening",r),e.listen(t),this[xt].listening=true);}}function see(e,t){return this[xt].listening&&this[xt].closing?Promise.reject(new qN):this[xt].listening?Promise.reject(new UN):this.ready().then(()=>{if(this[xt].aborted)return;let{promise:r,resolve:n,reject:i}=BN.withResolvers(),s=c=>{a(),this[xt].listening=false,i(c);},o=()=>{a(),this[xt].listening=true,n(VN.call(this,e,t.listenTextResolver||HN));};function a(){e.removeListener("error",s),e.removeListener("listening",o);}return e.once("error",s),e.once("listening",o),e.listen(t),r})}function zN(e,t){if(e.serverFactory)return e.serverFactory(t,e);let r=e.https===true?{}:e.https;if(e.http2){let i=typeof r=="object"?FN.createSecureServer(r,t):FN.createServer(e.http,t);return i.on("session",s=>s.setTimeout(e.http2SessionTimeout,()=>{s.close();})),e.forceCloseConnections===true&&(i.closeHttp2Sessions=aee(i)),i.setTimeout(e.connectionTimeout),i}let n=r?YZ.createServer(r,t):KZ.createServer(e.http,t);return n.keepAliveTimeout=e.keepAliveTimeout,n.requestTimeout=e.requestTimeout,n.setTimeout(e.connectionTimeout),e.maxRequestsPerSocket>0&&(n.maxRequestsPerSocket=e.maxRequestsPerSocket),n}function oee(e){return e.address==="0.0.0.0"?Object.values(JZ.networkInterfaces()).flatMap(t=>t.filter(r=>r.family==="IPv4")).sort(t=>t.internal?-1:1).map(t=>t.address):[e.address]}function VN(e,t){let r;typeof e.address()=="string"?r=[e.address()]:(e.address().address.indexOf(":")===-1?r=oee(e.address()).map(i=>i+":"+e.address().port):r=["["+e.address().address+"]:"+e.address().port],r=r.map(i=>"http"+(this[XZ].https?"s":"")+"://"+i));for(let i of r)this.log.info(t(i));return r[0]}function aee(e){return e[no]=new Set,e.on("session",function(t){t.once("connect",function(){e[no].add(t);}),t.once("close",function(){e[no].delete(t);}),t.once("frameError",function(r,n,i){i===0&&e[no].delete(t);}),t.once("goaway",function(){e[no].delete(t);});}),function(){if(e[no].size!==0)for(let r of e[no])r.close();}}});var fh=c((nUe,YN)=>{var{kReplyHasStatusCode:cee}=St();function lee(e,t){if(!e[cee]||e.statusCode===200){let r=t&&(t.statusCode||t.status);e.code(r>=400?r:500);}}YN.exports={setErrorStatusCode:lee};});var Hw=c((iUe,JN)=>{var{kReplyIsError:QN,kReplyHijacked:uee}=St(),{setErrorStatusCode:dee}=fh(),fee=a("diagnostics_channel"),Cl=fee.tracingChannel("fastify.request.handler");function hee(e,t,r){r&&(r.async=true),e.then(function(n){if(t[uee]!==true){r&&Cl.asyncStart.publish(r);try{if(n!==void 0||t.sent===!1&&t.raw.headersSent===!1&&t.request.raw.aborted===!1&&t.request.socket&&!t.request.socket.destroyed)try{t.send(n);}catch(i){t[QN]=!0,t.send(i);}}finally{r&&Cl.asyncEnd.publish(r);}}},function(n){r&&(r.error=n,dee(t,n),Cl.error.publish(r),Cl.asyncStart.publish(r));try{if(t.sent===!0){t.log.error({err:n},"Promise errored, but reply.sent = true was set");return}t[QN]=!0,t.send(n);}catch(i){t.send(i);}finally{r&&Cl.asyncEnd.publish(r);}});}JN.exports=hee;});var zw=c((sUe,ZN)=>{var{kSchemaHeaders:Nl,kSchemaParams:mh,kSchemaQuerystring:gh,kSchemaBody:ss,kSchemaResponse:XN}=St(),pee=/^[1-5](?:\d{2}|xx)$|^default$/,{FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX:mee}=Ut(),{FSTWRN001:hh,FSTSEC002:gee}=ba();function yee(e,t){if(!e.schema||!e.schema.response)return;let{method:r,url:n}=e.config||{};e[XN]=Object.keys(e.schema.response).reduce(function(i,s){let o=e.schema.response[s];if(s=s.toLowerCase(),!pee.test(s))throw new mee;if(o.content){let a={};for(let c of Object.keys(o.content)){let l=o.content[c].schema;a[c]=t({schema:l,url:n,method:r,httpStatus:s,contentType:c});}i[s]=a;}else i[s]=t({schema:o,url:n,method:r,httpStatus:s});return i},{});}function io(e){if(Array.isArray(e))return e.map(io);if(e===null||typeof e!="object")return e;let t={};for(let r of Object.keys(e)){let n=e[r];switch(r){case "properties":{if(n===null||typeof n!="object"){t.properties=n;break}let i={};for(let s of Object.keys(n))i[s.toLowerCase()]=io(n[s]);t.properties=i;break}case "required":t.required=Array.isArray(n)?n.map(i=>i.toLowerCase()):n;break;case "dependencies":{if(n===null||typeof n!="object"){t.dependencies=n;break}let i={};for(let s of Object.keys(n)){let o=n[s];Array.isArray(o)?i[s.toLowerCase()]=o.map(a=>a.toLowerCase()):i[s.toLowerCase()]=io(o);}t.dependencies=i;break}case "dependentSchemas":{if(n===null||typeof n!="object"){t.dependentSchemas=n;break}let i={};for(let s of Object.keys(n))i[s.toLowerCase()]=io(n[s]);t.dependentSchemas=i;break}case "dependentRequired":{if(n===null||typeof n!="object"){t.dependentRequired=n;break}let i={};for(let s of Object.keys(n))i[s.toLowerCase()]=n[s].map(o=>o.toLowerCase());t.dependentRequired=i;break}case "allOf":case "anyOf":case "oneOf":case "not":case "if":case "then":case "else":case "items":case "additionalItems":case "additionalProperties":case "unevaluatedItems":case "unevaluatedProperties":case "contains":case "propertyNames":case "contentSchema":t[r]=io(n);break;case "definitions":case "$defs":case "patternProperties":{if(n===null||typeof n!="object"){t[r]=n;break}let i={};for(let s of Object.keys(n))i[s]=io(n[s]);t[r]=i;break}default:t[r]=n;}}return t}function Gw(e){if(Array.isArray(e)){for(let t of e){let r=Gw(t);if(r!==void 0)return r}return}if(!(e===null||typeof e!="object")){if(typeof e.$ref=="string"&&e.$ref[0]!=="#")return e.$ref;for(let t of Object.keys(e)){let r=Gw(e[t]);if(r!==void 0)return r}}}function wee(e,t,r){let{schema:n}=e;if(!n)return;let{method:i,url:s}=e.config||{},o=n.headers;if(o!==void 0)if(r||typeof o!="object"||o===null||Object.getPrototypeOf(o)!==Object.prototype)e[Nl]=t({schema:o,method:i,url:s,httpPart:"headers"});else {let a=io(o),c=Gw(o);c!==void 0&&gee(i,s,c),e[Nl]=t({schema:a,method:i,url:s,httpPart:"headers"});}else Object.hasOwn(n,"headers")&&hh("headers",i,s);if(n.body!==void 0){let a=n.body!==null&&typeof n.body=="object"?n.body.content:void 0;if(a){let c={};for(let l of Object.keys(a)){let u=a[l].schema;c[l]=t({schema:u,method:i,url:s,httpPart:"body",contentType:l});}e[ss]=c;}else e[ss]=t({schema:n.body,method:i,url:s,httpPart:"body"});}else Object.hasOwn(n,"body")&&hh("body",i,s);n.querystring!==void 0?e[gh]=t({schema:n.querystring,method:i,url:s,httpPart:"querystring"}):Object.hasOwn(n,"querystring")&&hh("querystring",i,s),n.params!==void 0?e[mh]=t({schema:n.params,method:i,url:s,httpPart:"params"}):Object.hasOwn(n,"params")&&hh("params",i,s);}function ph(e,t,r){if(e==null)return false;let n=t[r],i;try{let o=n===void 0?null:n;e.schemaEnv?i=e(o,{parentData:t,parentDataProperty:r}):i=e(o);}catch(o){return o.statusCode=500,o}if(i&&typeof i.then=="function")return i.then(o=>o===false?e.errors:false).catch(o=>o);return s(i);function s(o){return o===false?e.errors:o&&o.error?o.error:(o&&typeof o=="object"&&"value"in o&&(t[r]=o.value),false)}}function yh(e,t,r){let n=r===void 0;if(n&&e[mh]===void 0&&e[ss]===void 0&&e[gh]===void 0&&e[Nl]===void 0)return false;if(n||!r.skipParams){let s=ph(e[mh],t,"params");if(s)return typeof s.then!="function"?os(s,"params",e.schemaErrorFormatter):vee(s,e,t)}if(n||!r.skipBody){let s=null;if(typeof e[ss]=="function")s=e[ss];else if(e[ss]){let a=e[ss][t.mediaType];a&&(s=a);}let o=ph(s,t,"body");if(o)return typeof o.then!="function"?os(o,"body",e.schemaErrorFormatter):_ee(o,e,t)}if(n||!r.skipQuery){let s=ph(e[gh],t,"query");if(s)return typeof s.then!="function"?os(s,"querystring",e.schemaErrorFormatter):See(s,e,t)}let i=ph(e[Nl],t,"headers");return i?typeof i.then!="function"?os(i,"headers",e.schemaErrorFormatter):bee(i,e):false}function vee(e,t,r){return e.then(n=>n?os(n,"params",t.schemaErrorFormatter):yh(t,r,{skipParams:true}))}function _ee(e,t,r){return e.then(n=>n?os(n,"body",t.schemaErrorFormatter):yh(t,r,{skipParams:true,skipBody:true}))}function See(e,t,r){return e.then(n=>n?os(n,"querystring",t.schemaErrorFormatter):yh(t,r,{skipParams:true,skipBody:true,skipQuery:true}))}function bee(e,t,r){return e.then(n=>n?os(n,"headers",t.schemaErrorFormatter):false)}function os(e,t,r){if(e instanceof Error)return e.statusCode=e.statusCode||400,e.code=e.code||"FST_ERR_VALIDATION",e.validationContext=e.validationContext||t,e;let n=r(e,t);return n.statusCode=n.statusCode||400,n.code=n.code||"FST_ERR_VALIDATION",n.validation=e,n.validationContext=t,n}ZN.exports={symbols:{bodySchema:ss,querystringSchema:gh,responseSchema:XN,paramsSchema:mh,headersSchema:Nl},compileSchemasForValidation:wee,compileSchemasForSerialization:yee,validate:yh};});var Qw=c(Hn=>{function Sh(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new Error("Invalid max value");if(typeof t!="number"||!Number.isInteger(t)||t<0)throw new Error("Invalid ttl value")}var Vw=class{constructor(t=1e3,r=0){Sh(t,r),this.first=null,this.items=new Map,this.last=null,this.max=t,this.ttl=r;}get size(){return this.items.size}clear(){this.items.clear(),this.first=null,this.last=null;}delete(t){let r=this.items.get(t);r!==void 0&&(this.items.delete(t),r.prev!==null&&(r.prev.next=r.next),r.next!==null&&(r.next.prev=r.prev),this.first===r&&(this.first=r.next),this.last===r&&(this.last=r.prev));}deleteMany(t){for(var r=0;r<t.length;r++)this.delete(t[r]);}evict(){if(this.size>0){let t=this.first;this.items.delete(t.key),this.size===0?(this.first=null,this.last=null):(this.first=t.next,this.first.prev=null);}}expiresAt(t){let r=this.items.get(t);if(r!==void 0)return r.expiry}get(t){let r=this.items.get(t);if(r!==void 0){if(this.ttl>0&&r.expiry<=Date.now()){this.delete(t);return}return r.value}}getMany(t){let r=new Array(t.length);for(var n=0;n<t.length;n++)r[n]=this.get(t[n]);return r}keys(){return this.items.keys()}set(t,r){let n=this.items.get(t);if(n!==void 0){n.value=r,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size>=this.max&&this.evict();let i={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:t,prev:this.last,next:null,value:r};this.items.set(t,i),this.size===1?this.first=i:this.last.next=i,this.last=i;}},wh=class{constructor(t=1e3,r=0){Sh(t,r),this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=t,this.ttl=r;}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0;}delete(t){let r=this.items[t];r!==void 0&&(delete this.items[t],this.size--,r.prev!==null&&(r.prev.next=r.next),r.next!==null&&(r.next.prev=r.prev),this.first===r&&(this.first=r.next),this.last===r&&(this.last=r.prev));}deleteMany(t){for(var r=0;r<t.length;r++)this.delete(t[r]);}evict(){if(this.size>0){let t=this.first;delete this.items[t.key],--this.size===0?(this.first=null,this.last=null):(this.first=t.next,this.first.prev=null);}}expiresAt(t){let r=this.items[t];if(r!==void 0)return r.expiry}get(t){let r=this.items[t];if(r!==void 0){if(this.ttl>0&&r.expiry<=Date.now()){this.delete(t);return}return r.value}}getMany(t){let r=new Array(t.length);for(var n=0;n<t.length;n++)r[n]=this.get(t[n]);return r}keys(){return Object.keys(this.items)}set(t,r){let n=this.items[t];if(n!==void 0){n.value=r,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size>=this.max&&this.evict();let i={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:t,prev:this.last,next:null,value:r};this.items[t]=i,++this.size===1?this.first=i:this.last.next=i,this.last=i;}};function Ww(){return {cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,invalidateOne:0,invalidateAll:0,sets:0}}var vh=class{constructor(){this.records={};}initForCache(t,r){this.records[t]={[r]:Ww()};}resetForCache(t){if(this.records[t])for(let r of Object.keys(this.records[t]))this.records[t][r]=Ww();}getStatistics(){return this.records}},Kw=class{constructor(t=1e3,r=0){Sh(t,r),this.first=null,this.items=new Map,this.last=null,this.max=t,this.ttl=r;}get size(){return this.items.size}bumpLru(t){if(this.last===t)return;let r=this.last,n=t.next,i=t.prev;this.first===t&&(this.first=n),t.next=null,t.prev=r,r.next=t,i!==null&&(i.next=n),n!==null&&(n.prev=i),this.last=t;}clear(){this.items.clear(),this.first=null,this.last=null;}delete(t){let r=this.items.get(t);r!==void 0&&(this.items.delete(t),r.prev!==null&&(r.prev.next=r.next),r.next!==null&&(r.next.prev=r.prev),this.first===r&&(this.first=r.next),this.last===r&&(this.last=r.prev));}deleteMany(t){for(var r=0;r<t.length;r++)this.delete(t[r]);}evict(){if(this.size>0){let t=this.first;this.items.delete(t.key),this.size===0?(this.first=null,this.last=null):(this.first=t.next,this.first.prev=null);}}expiresAt(t){let r=this.items.get(t);if(r!==void 0)return r.expiry}get(t){let r=this.items.get(t);if(r!==void 0){if(this.ttl>0&&r.expiry<=Date.now()){this.delete(t);return}return this.bumpLru(r),r.value}}getMany(t){let r=new Array(t.length);for(var n=0;n<t.length;n++)r[n]=this.get(t[n]);return r}keys(){return this.items.keys()}set(t,r){let n=this.items.get(t);if(n!==void 0){n.value=r,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.bumpLru(n);return}this.max>0&&this.size>=this.max&&this.evict();let i={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:t,prev:this.last,next:null,value:r};this.items.set(t,i),this.size===1?this.first=i:this.last.next=i,this.last=i;}},jl=class{constructor(t=1e3,r=0){Sh(t,r),this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=t,this.ttl=r;}bumpLru(t){if(this.last===t)return;let r=this.last,n=t.next,i=t.prev;this.first===t&&(this.first=n),t.next=null,t.prev=r,r.next=t,i!==null&&(i.next=n),n!==null&&(n.prev=i),this.last=t;}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0;}delete(t){let r=this.items[t];r!==void 0&&(delete this.items[t],this.size--,r.prev!==null&&(r.prev.next=r.next),r.next!==null&&(r.next.prev=r.prev),this.first===r&&(this.first=r.next),this.last===r&&(this.last=r.prev));}deleteMany(t){for(var r=0;r<t.length;r++)this.delete(t[r]);}evict(){if(this.size>0){let t=this.first;delete this.items[t.key],--this.size===0?(this.first=null,this.last=null):(this.first=t.next,this.first.prev=null);}}expiresAt(t){let r=this.items[t];if(r!==void 0)return r.expiry}get(t){let r=this.items[t];if(r!==void 0){if(this.ttl>0&&r.expiry<=Date.now()){this.delete(t);return}return this.bumpLru(r),r.value}}getMany(t){let r=new Array(t.length);for(var n=0;n<t.length;n++)r[n]=this.get(t[n]);return r}keys(){return Object.keys(this.items)}set(t,r){let n=this.items[t];if(n!==void 0){n.value=r,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.bumpLru(n);return}this.max>0&&this.size>=this.max&&this.evict();let i={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:t,prev:this.last,next:null,value:r};this.items[t]=i,++this.size===1?this.first=i:this.last.next=i,this.last=i;}};function ej(e){return `${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,"0")}-${e.getDate().toString().padStart(2,"0")}`}var Yw=class{constructor(t,r,n){this.cacheId=t,this.statisticTtlInHours=r,this.collectionStart=new Date,this.currentTimeStamp=ej(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records=n||new vh,this.records.initForCache(this.cacheId,this.currentTimeStamp);}get currentRecord(){let t=this.records.records[this.cacheId];return t[this.currentTimeStamp]||(t[this.currentTimeStamp]=Ww()),t[this.currentTimeStamp]}hoursPassed(){return (Date.now()-this.collectionStart)/1e3/60/60}addHit(){this.archiveIfNeeded(),this.currentRecord.hits++;}addFalsyHit(){this.archiveIfNeeded(),this.currentRecord.falsyHits++;}addEmptyHit(){this.archiveIfNeeded(),this.currentRecord.emptyHits++;}addMiss(){this.archiveIfNeeded(),this.currentRecord.misses++;}addEviction(){this.archiveIfNeeded(),this.currentRecord.evictions++;}setCacheSize(t){this.archiveIfNeeded(),this.currentRecord.cacheSize=t;}addExpiration(){this.archiveIfNeeded(),this.currentRecord.expirations++;}addSet(){this.archiveIfNeeded(),this.currentRecord.sets++;}addInvalidateOne(){this.archiveIfNeeded(),this.currentRecord.invalidateOne++;}addInvalidateAll(){this.archiveIfNeeded(),this.currentRecord.invalidateAll++;}getStatistics(){return this.records.getStatistics()}archiveIfNeeded(){Date.now()>=this.archiveAfter&&(this.collectionStart=new Date,this.currentTimeStamp=ej(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records.initForCache(this.cacheId,this.currentTimeStamp));}},_h=class extends jl{constructor(t,r,n,i,s){if(super(t,r),!n)throw new Error("Cache id is mandatory");this.hitStatistics=new Yw(n,s!==void 0?s:24,i);}getStatistics(){return this.hitStatistics.getStatistics()}set(t,r){super.set(t,r),this.hitStatistics.addSet(),this.hitStatistics.setCacheSize(this.size);}evict(){let t=this.size>0;super.evict(),t&&this.hitStatistics.addEviction(),this.hitStatistics.setCacheSize(this.size);}delete(t,r=false){let n=this.items[t]!==void 0;super.delete(t),n&&!r&&this.hitStatistics.addInvalidateOne(),this.hitStatistics.setCacheSize(this.size);}clear(){super.clear(),this.hitStatistics.addInvalidateAll(),this.hitStatistics.setCacheSize(this.size);}get(t){let r=this.items[t];if(r!==void 0){if(this.ttl>0&&r.expiry<=Date.now()){this.delete(t,true),this.hitStatistics.addExpiration();return}return this.bumpLru(r),r.value||(this.hitStatistics.addFalsyHit(),(r.value===void 0||r.value===null||r.value==="")&&this.hitStatistics.addEmptyHit()),this.hitStatistics.addHit(),r.value}this.hitStatistics.addMiss();}};Hn.Fifo=wh;Hn.FifoMap=Vw;Hn.FifoObject=wh;Hn.HitStatisticsRecord=vh;Hn.Lru=jl;Hn.LruHitStatistics=_h;Hn.LruMap=Kw;Hn.LruObject=jl;Hn.LruObjectHitStatistics=_h;});var Ta=c((aUe,ij)=>{var{LruMap:Eee}=Qw(),tj=/(?:^|;)\s*([\w!#$%&'*+.^`|~-]+)=("(?:[\t\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\t\u0020-\u00ff])*"|[\w!#$%&'*+.^`|~-]+)/gu,Tee=/\\([\t\u0020-\u00ff])/gu,rj=/^[\w!#$%&'*+.^`|~-]+$/,nj=/^[\w!#$%&'*+.^`|~-]+\s*$/,Jw=new Eee(100),Xw=class e{#e=false;#t=true;#n="";#r="";#i=new Map;#o;static get cache(){return Jw}static from(t){let r=Jw.get(t);return r!==void 0||(r=new e(t),Jw.set(t,r)),r}constructor(t){if(t==null||t===""||t==="undefined")return;let r=t.indexOf(";");if(r===-1){if(r=t.indexOf("/"),r===-1)return;let c=t.slice(0,r).trimStart().toLowerCase(),l=t.slice(r+1).trimEnd().toLowerCase();rj.test(c)===true&&nj.test(l)===true&&(this.#e=true,this.#t=false,this.#n=c,this.#r=l);return}let n=t.slice(0,r).toLowerCase(),i=t.slice(r+1).trim();if(r=n.indexOf("/"),r===-1)return;let s=n.slice(0,r).trimStart(),o=n.slice(r+1).trimEnd();if(rj.test(s)===false||nj.test(o)===false)return;this.#n=s,this.#r=o,this.#e=true,this.#t=false;let a=tj.exec(i);for(;a;){let c=a[1].toLowerCase(),l=a[2];l.charCodeAt(0)===34&&(l=l.slice(1,-1),l.indexOf("\\")!==-1&&(l=l.replace(Tee,"$1"))),this.#i.set(c,l),a=tj.exec(i);}}get[Symbol.toStringTag](){return "ContentType"}get isEmpty(){return this.#t}get isValid(){return this.#e}get mediaType(){if(this.#e!==false)return `${this.#n}/${this.#r}`}get type(){return this.#n}get subtype(){return this.#r}get parameters(){return this.#i}toString(){if(this.#o)return this.#o;let t=[];for(let[n,i]of this.#i.entries())t.push(`${n}="${i}"`);let r=[this.#n,"/",this.#r];return t.length>0&&(r.push("; "),r.push(t.join("; "))),this.#o=r.join(""),this.#o}};ij.exports=Xw;});var rv=c((cUe,tv)=>{var Ree=a("diagnostics_channel"),Pee=Hw(),{validate:kee}=zw(),{preValidationHookRunner:xee,preHandlerHookRunner:Aee}=is(),{FST_ERR_CTP_INVALID_MEDIA_TYPE:Iee,FST_ERR_ROUTE_MISSING_CONTENT_TYPE:Oee,FST_ERR_ROUTE_MISSING_CONTENT:Cee}=Ut(),{setErrorStatusCode:sj}=fh(),{kReplyIsError:so,kRouteContext:Gn,kFourOhFourContext:Nee,kSupportedHTTPMethods:oj,kRequestContentType:bh,kDiagnosticsStore:jee}=St(),Lee=Ta(),Ll=Ree.tracingChannel("fastify.request.handler");function Dee(e,t,r){if(r.sent===true)return;if(e!=null){r[so]=true,r.send(e);return}let n=t.method;if(this[oj].bodyless.has(n)){Ra(t,r);return}if(this[oj].bodywith.has(n)){let i=t.headers,s=i["content-type"];if(n==="QUERY"){if(s===void 0){r[so]=true,r.status(400).send(new Oee(n));return}if(aj(i)){r[so]=true,r.status(400).send(new Cee(n));return}}if(s===void 0){if(aj(i)){Ra(t,r);return}t[Gn].contentTypeParser.run("",Ra,t,r);return}if(t[bh]||(t[bh]=Lee.from(s)),t[bh].isValid===false){r[so]=true,r.status(415).send(new Iee);return}t[Gn].contentTypeParser.run(t[bh].toString(),Ra,t,r);return}Ra(t,r);}function Ra(e,t){try{e[Gn].preValidation!==null?xee(e[Gn].preValidation,e,t,Zw):Zw(null,e,t);}catch(r){Zw(r,e,t);}}function aj(e){let t=e["content-length"];return e["transfer-encoding"]===void 0&&(t===void 0||t==="0")}function Zw(e,t,r){if(r.sent===true)return;if(e!=null){r[so]=true,r.send(e);return}let n=kee(r[Gn],t);if(n&&typeof n.then=="function"||false){let s=cj.bind(null,t,r);n.then(s,s);}else cj(t,r,n);}function cj(e,t,r){if(r){if(t[Gn].attachValidation===false){t.send(r);return}t.request.validationError=r;}e[Gn].preHandler!==null?Aee(e[Gn].preHandler,e,t,ev):ev(null,e,t);}function ev(e,t,r){if(r.sent)return;let n=t[Gn];if(!Ll.hasSubscribers||n[Nee]===null)lj(e,t,r);else {let i={request:t,reply:r,async:false,route:{url:n.config.url,method:n.config.method}};r[jee]=i,Ll.start.runStores(i,lj,void 0,e,t,r,i);}}function lj(e,t,r,n){let i=t[Gn];try{if(e!=null){r[so]=!0,n&&(n.error=e,sj(r,e),Ll.error.publish(n)),r.send(e);return}let s;try{s=i.handler(t,r);}catch(o){n&&(n.error=o,sj(r,o),Ll.error.publish(n)),r[so]=!0,r.send(o);return}s!==void 0&&(s!==null&&typeof s.then=="function"?Pee(s,r,n):r.send(s));}finally{n&&Ll.end.publish(n);}}tv.exports=Dee;tv.exports[Symbol.for("internals")]={handler:Ra,preHandlerCallback:ev};});var uj=c((lUe,Eh)=>{Eh.exports=$e;Eh.exports.default=$e;var Mee={properties:{connectionTimeout:{type:"integer",default:0},keepAliveTimeout:{type:"integer",default:72e3},forceCloseConnections:{oneOf:[{type:"string",pattern:"idle"},{type:"boolean"}]},maxRequestsPerSocket:{type:"integer",default:0,nullable:true},requestTimeout:{type:"integer",default:0},handlerTimeout:{type:"integer",default:0},bodyLimit:{type:"integer",default:1048576},caseSensitive:{type:"boolean",default:true},allowUnsafeRegex:{type:"boolean",default:false},http2:{type:"boolean"},https:{if:{not:{oneOf:[{type:"boolean"},{type:"null"},{type:"object",additionalProperties:false,required:["allowHTTP1"],properties:{allowHTTP1:{type:"boolean"}}}]}},then:{setDefaultValue:true}},ignoreTrailingSlash:{type:"boolean",default:false},ignoreDuplicateSlashes:{type:"boolean",default:false},disableRequestLogging:{default:false},maxParamLength:{type:"integer",default:100},onProtoPoisoning:{type:"string",default:"error"},onConstructorPoisoning:{type:"string",default:"error"},pluginTimeout:{type:"integer",default:1e4},requestIdHeader:{anyOf:[{type:"boolean"},{type:"string"}],default:false},requestIdLogLabel:{type:"string",default:"reqId"},http2SessionTimeout:{type:"integer",default:72e3},exposeHeadRoutes:{type:"boolean",default:true},useSemicolonDelimiter:{type:"boolean",default:false},routerOptions:{type:"object",additionalProperties:true,properties:{ignoreTrailingSlash:{type:"boolean",default:false},ignoreDuplicateSlashes:{type:"boolean",default:false},maxParamLength:{type:"integer",default:100},allowUnsafeRegex:{type:"boolean",default:false},useSemicolonDelimiter:{type:"boolean",default:false}}},constraints:{type:"object",additionalProperties:{type:"object",required:["name","storage","validate","deriveConstraint"],additionalProperties:true,properties:{name:{type:"string"},storage:{},validate:{},deriveConstraint:{}}}}}},Fee=Object.prototype.hasOwnProperty,$ee=new RegExp("idle","u");function $e(e,{instancePath:t="",parentData:r,parentDataProperty:n,rootData:i=e}={}){let s=null,o=0;if(o===0)if(e&&typeof e=="object"&&!Array.isArray(e)){e.connectionTimeout===void 0&&(e.connectionTimeout=0),e.keepAliveTimeout===void 0&&(e.keepAliveTimeout=72e3),e.maxRequestsPerSocket===void 0&&(e.maxRequestsPerSocket=0),e.requestTimeout===void 0&&(e.requestTimeout=0),e.handlerTimeout===void 0&&(e.handlerTimeout=0),e.bodyLimit===void 0&&(e.bodyLimit=1048576),e.caseSensitive===void 0&&(e.caseSensitive=true),e.allowUnsafeRegex===void 0&&(e.allowUnsafeRegex=false),e.ignoreTrailingSlash===void 0&&(e.ignoreTrailingSlash=false),e.ignoreDuplicateSlashes===void 0&&(e.ignoreDuplicateSlashes=false),e.disableRequestLogging===void 0&&(e.disableRequestLogging=false),e.maxParamLength===void 0&&(e.maxParamLength=100),e.onProtoPoisoning===void 0&&(e.onProtoPoisoning="error"),e.onConstructorPoisoning===void 0&&(e.onConstructorPoisoning="error"),e.pluginTimeout===void 0&&(e.pluginTimeout=1e4),e.requestIdHeader===void 0&&(e.requestIdHeader=false),e.requestIdLogLabel===void 0&&(e.requestIdLogLabel="reqId"),e.http2SessionTimeout===void 0&&(e.http2SessionTimeout=72e3),e.exposeHeadRoutes===void 0&&(e.exposeHeadRoutes=true),e.useSemicolonDelimiter===void 0&&(e.useSemicolonDelimiter=false);let f=o;for(let g in e)Fee.call(Mee.properties,g)||delete e[g];if(f===o){let g=e.connectionTimeout,y=o;if(!(typeof g=="number"&&!(g%1)&&!isNaN(g)&&isFinite(g))){let _=typeof g,v;if(v===void 0)if(_==="boolean"||g===null||_==="string"&&g&&g==+g&&!(g%1))v=+g;else return $e.errors=[{instancePath:t+"/connectionTimeout",schemaPath:"#/properties/connectionTimeout/type",keyword:"type",params:{type:"integer"},message:"must be integer"}],false;v!==void 0&&(g=v,e!==void 0&&(e.connectionTimeout=v));}var a=y===o;if(a){let _=e.keepAliveTimeout,v=o;if(!(typeof _=="number"&&!(_%1)&&!isNaN(_)&&isFinite(_))){let E=typeof _,R;if(R===void 0)if(E==="boolean"||_===null||E==="string"&&_&&_==+_&&!(_%1))R=+_;else return $e.errors=[{instancePath:t+"/keepAliveTimeout",schemaPath:"#/properties/keepAliveTimeout/type",keyword:"type",params:{type:"integer"},message:"must be integer"}],false;R!==void 0&&(_=R,e!==void 0&&(e.keepAliveTimeout=R));}var a=v===o;if(a){if(e.forceCloseConnections!==void 0){let E=e.forceCloseConnections,R=o,P=o,b=false,O=null,F=o;if(typeof E!="string"){let M=typeof E,q;if(q===void 0)if(M=="number"||M=="boolean")q=""+E;else if(E===null)q="";else {let z={instancePath:t+"/forceCloseConnections",schemaPath:"#/properties/forceCloseConnections/oneOf/0/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[z]:s.push(z),o++;}q!==void 0&&(E=q,e!==void 0&&(e.forceCloseConnections=q));}if(o===F&&typeof E=="string"&&!$ee.test(E)){let M={instancePath:t+"/forceCloseConnections",schemaPath:"#/properties/forceCloseConnections/oneOf/0/pattern",keyword:"pattern",params:{pattern:"idle"},message:'must match pattern "idle"'};s===null?s=[M]:s.push(M),o++;}var c=F===o;c&&(b=true,O=0);let j=o;if(typeof E!="boolean"){let M;if(M===void 0)if(E==="false"||E===0||E===null)M=false;else if(E==="true"||E===1)M=true;else {let q={instancePath:t+"/forceCloseConnections",schemaPath:"#/properties/forceCloseConnections/oneOf/1/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};s===null?s=[q]:s.push(q),o++;}M!==void 0&&(E=M,e!==void 0&&(e.forceCloseConnections=M));}var c=j===o;if(c&&b?(b=false,O=[O,1]):c&&(b=true,O=1),b)o=P,s!==null&&(P?s.length=P:s=null);else {let M={instancePath:t+"/forceCloseConnections",schemaPath:"#/properties/forceCloseConnections/oneOf",keyword:"oneOf",params:{passingSchemas:O},message:"must match exactly one schema in oneOf"};return s===null?s=[M]:s.push(M),o++,$e.errors=s,false}var a=R===o;}else var a=true;if(a){let E=e.maxRequestsPerSocket,R=o;if(!(typeof E=="number"&&!(E%1)&&!isNaN(E)&&isFinite(E))&&E!==null){let b=typeof E,O;if(O===void 0)if(b==="boolean"||E===null||b==="string"&&E&&E==+E&&!(E%1))O=+E;else if(E===""||E===0||E===false)O=null;else return $e.errors=[{instancePath:t+"/maxRequestsPerSocket",schemaPath:"#/properties/maxRequestsPerSocket/type",keyword:"type",params:{type:"integer"},message:"must be integer"}],false;O!==void 0&&(E=O,e!==void 0&&(e.maxRequestsPerSocket=O));}var a=R===o;if(a){let b=e.requestTimeout,O=o;if(!(typeof b=="number"&&!(b%1)&&!isNaN(b)&&isFinite(b))){let j=typeof b,N;if(N===void 0)if(j==="boolean"||b===null||j==="string"&&b&&b==+b&&!(b%1))N=+b;else return $e.errors=[{instancePath:t+"/requestTimeout",schemaPath:"#/properties/requestTimeout/type",keyword:"type",params:{type:"integer"},message:"must be integer"}],false;N!==void 0&&(b=N,e!==void 0&&(e.requestTimeout=N));}var a=O===o;if(a){let j=e.handlerTimeout,N=o;if(!(typeof j=="number"&&!(j%1)&&!isNaN(j)&&isFinite(j))){let q=typeof j,z;if(z===void 0)if(q==="boolean"||j===null||q==="string"&&j&&j==+j&&!(j%1))z=+j;else return $e.errors=[{instancePath:t+"/handlerTimeout",schemaPath:"#/properties/handlerTimeout/type",keyword:"type",params:{type:"integer"},message:"must be integer"}],false;z!==void 0&&(j=z,e!==void 0&&(e.handlerTimeout=z));}var a=N===o;if(a){let q=e.bodyLimit,z=o;if(!(typeof q=="number"&&!(q%1)&&!isNaN(q)&&isFinite(q))){let H=typeof q,J;if(J===void 0)if(H==="boolean"||q===null||H==="string"&&q&&q==+q&&!(q%1))J=+q;else return $e.errors=[{instancePath:t+"/bodyLimit",schemaPath:"#/properties/bodyLimit/type",keyword:"type",params:{type:"integer"},message:"must be integer"}],false;J!==void 0&&(q=J,e!==void 0&&(e.bodyLimit=J));}var a=z===o;if(a){let H=e.caseSensitive,J=o;if(typeof H!="boolean"){let he;if(he===void 0)if(H==="false"||H===0||H===null)he=false;else if(H==="true"||H===1)he=true;else return $e.errors=[{instancePath:t+"/caseSensitive",schemaPath:"#/properties/caseSensitive/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],false;he!==void 0&&(H=he,e!==void 0&&(e.caseSensitive=he));}var a=J===o;if(a){let he=e.allowUnsafeRegex,Te=o;if(typeof he!="boolean"){let B;if(B===void 0)if(he==="false"||he===0||he===null)B=false;else if(he==="true"||he===1)B=true;else return $e.errors=[{instancePath:t+"/allowUnsafeRegex",schemaPath:"#/properties/allowUnsafeRegex/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],false;B!==void 0&&(he=B,e!==void 0&&(e.allowUnsafeRegex=B));}var a=Te===o;if(a){if(e.http2!==void 0){let B=e.http2,de=o;if(typeof B!="boolean"){let ie;if(ie===void 0)if(B==="false"||B===0||B===null)ie=false;else if(B==="true"||B===1)ie=true;else return $e.errors=[{instancePath:t+"/http2",schemaPath:"#/properties/http2/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],false;ie!==void 0&&(B=ie,e!==void 0&&(e.http2=ie));}var a=de===o;}else var a=true;if(a){if(e.https!==void 0){let B=e.https,de=o,we=o,ie=true,U=o,Q=o,x=o,A=o,D=false,$=null,V=o;if(typeof B!="boolean"){let C;if(C===void 0)if(B==="false"||B===0||B===null)C=false;else if(B==="true"||B===1)C=true;else {let G={};s===null?s=[G]:s.push(G),o++;}C!==void 0&&(B=C,e!==void 0&&(e.https=C));}var l=V===o;l&&(D=true,$=0);let S=o;if(B!==null){let C;if(C===void 0)if(B===""||B===0||B===false)C=null;else {let G={};s===null?s=[G]:s.push(G),o++;}C!==void 0&&(B=C,e!==void 0&&(e.https=C));}var l=S===o;if(l&&D)D=false,$=[$,1];else {l&&(D=true,$=1);let C=o;if(o===C)if(B&&typeof B=="object"&&!Array.isArray(B)){if(B.allowHTTP1===void 0&&("allowHTTP1")){let ne={};s===null?s=[ne]:s.push(ne),o++;}else {let ne=o;for(let te in B)te!=="allowHTTP1"&&delete B[te];if(ne===o&&B.allowHTTP1!==void 0){let te=B.allowHTTP1;if(typeof te!="boolean"){let se;if(se===void 0)if(te==="false"||te===0||te===null)se=false;else if(te==="true"||te===1)se=true;else {let ve={};s===null?s=[ve]:s.push(ve),o++;}se!==void 0&&(te=se,B!==void 0&&(B.allowHTTP1=se));}}}}else {let Y={};s===null?s=[Y]:s.push(Y),o++;}var l=C===o;l&&D?(D=false,$=[$,2]):l&&(D=true,$=2);}if(D)o=A,s!==null&&(A?s.length=A:s=null);else {let C={};s===null?s=[C]:s.push(C),o++;}var u=x===o;if(u){let C={};s===null?s=[C]:s.push(C),o++;}else o=Q,s!==null&&(Q?s.length=Q:s=null);var d=U===o;if(o=we,s!==null&&(we?s.length=we:s=null),d){let C=o;e.https=true;var d=C===o;ie=d;}if(!ie){let C={instancePath:t+"/https",schemaPath:"#/properties/https/if",keyword:"if",params:{failingKeyword:"then"},message:'must match "then" schema'};return s===null?s=[C]:s.push(C),o++,$e.errors=s,false}var a=de===o;}else var a=true;if(a){let B=e.ignoreTrailingSlash,de=o;if(typeof B!="boolean"){let ie;if(ie===void 0)if(B==="false"||B===0||B===null)ie=false;else if(B==="true"||B===1)ie=true;else return $e.errors=[{instancePath:t+"/ignoreTrailingSlash",schemaPath:"#/properties/ignoreTrailingSlash/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],false;ie!==void 0&&(B=ie,e!==void 0&&(e.ignoreTrailingSlash=ie));}var a=de===o;if(a){let ie=e.ignoreDuplicateSlashes,U=o;if(typeof ie!="boolean"){let x;if(x===void 0)if(ie==="false"||ie===0||ie===null)x=false;else if(ie==="true"||ie===1)x=true;else return $e.errors=[{instancePath:t+"/ignoreDuplicateSlashes",schemaPath:"#/properties/ignoreDuplicateSlashes/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],false;x!==void 0&&(ie=x,e!==void 0&&(e.ignoreDuplicateSlashes=x));}var a=U===o;if(a){let x=e.maxParamLength,A=o;if(!(typeof x=="number"&&!(x%1)&&!isNaN(x)&&isFinite(x))){let $=typeof x,V;if(V===void 0)if($==="boolean"||x===null||$==="string"&&x&&x==+x&&!(x%1))V=+x;else return $e.errors=[{instancePath:t+"/maxParamLength",schemaPath:"#/properties/maxParamLength/type",keyword:"type",params:{type:"integer"},message:"must be integer"}],false;V!==void 0&&(x=V,e!==void 0&&(e.maxParamLength=V));}var a=A===o;if(a){let $=e.onProtoPoisoning,V=o;if(typeof $!="string"){let k=typeof $,C;if(C===void 0)if(k=="number"||k=="boolean")C=""+$;else if($===null)C="";else return $e.errors=[{instancePath:t+"/onProtoPoisoning",schemaPath:"#/properties/onProtoPoisoning/type",keyword:"type",params:{type:"string"},message:"must be string"}],false;C!==void 0&&($=C,e!==void 0&&(e.onProtoPoisoning=C));}var a=V===o;if(a){let k=e.onConstructorPoisoning,C=o;if(typeof k!="string"){let Y=typeof k,ne;if(ne===void 0)if(Y=="number"||Y=="boolean")ne=""+k;else if(k===null)ne="";else return $e.errors=[{instancePath:t+"/onConstructorPoisoning",schemaPath:"#/properties/onConstructorPoisoning/type",keyword:"type",params:{type:"string"},message:"must be string"}],false;ne!==void 0&&(k=ne,e!==void 0&&(e.onConstructorPoisoning=ne));}var a=C===o;if(a){let Y=e.pluginTimeout,ne=o;if(!(typeof Y=="number"&&!(Y%1)&&!isNaN(Y)&&isFinite(Y))){let se=typeof Y,ve;if(ve===void 0)if(se==="boolean"||Y===null||se==="string"&&Y&&Y==+Y&&!(Y%1))ve=+Y;else return $e.errors=[{instancePath:t+"/pluginTimeout",schemaPath:"#/properties/pluginTimeout/type",keyword:"type",params:{type:"integer"},message:"must be integer"}],false;ve!==void 0&&(Y=ve,e!==void 0&&(e.pluginTimeout=ve));}var a=ne===o;if(a){let se=e.requestIdHeader,ve=o,Re=o,Ae=false,tt=o;if(typeof se!="boolean"){let Le;if(Le===void 0)if(se==="false"||se===0||se===null)Le=false;else if(se==="true"||se===1)Le=true;else {let Je={instancePath:t+"/requestIdHeader",schemaPath:"#/properties/requestIdHeader/anyOf/0/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};s===null?s=[Je]:s.push(Je),o++;}Le!==void 0&&(se=Le,e!==void 0&&(e.requestIdHeader=Le));}var m=tt===o;if(Ae=Ae||m,!Ae){let Le=o;if(typeof se!="string"){let Tt=typeof se,Ie;if(Ie===void 0)if(Tt=="number"||Tt=="boolean")Ie=""+se;else if(se===null)Ie="";else {let vt={instancePath:t+"/requestIdHeader",schemaPath:"#/properties/requestIdHeader/anyOf/1/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[vt]:s.push(vt),o++;}Ie!==void 0&&(se=Ie,e!==void 0&&(e.requestIdHeader=Ie));}var m=Le===o;Ae=Ae||m;}if(Ae)o=Re,s!==null&&(Re?s.length=Re:s=null);else {let Le={instancePath:t+"/requestIdHeader",schemaPath:"#/properties/requestIdHeader/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};return s===null?s=[Le]:s.push(Le),o++,$e.errors=s,false}var a=ve===o;if(a){let Le=e.requestIdLogLabel,Je=o;if(typeof Le!="string"){let Ie=typeof Le,vt;if(vt===void 0)if(Ie=="number"||Ie=="boolean")vt=""+Le;else if(Le===null)vt="";else return $e.errors=[{instancePath:t+"/requestIdLogLabel",schemaPath:"#/properties/requestIdLogLabel/type",keyword:"type",params:{type:"string"},message:"must be string"}],false;vt!==void 0&&(Le=vt,e!==void 0&&(e.requestIdLogLabel=vt));}var a=Je===o;if(a){let Ie=e.http2SessionTimeout,vt=o;if(!(typeof Ie=="number"&&!(Ie%1)&&!isNaN(Ie)&&isFinite(Ie))){let Rt=typeof Ie,Sn;if(Sn===void 0)if(Rt==="boolean"||Ie===null||Rt==="string"&&Ie&&Ie==+Ie&&!(Ie%1))Sn=+Ie;else return $e.errors=[{instancePath:t+"/http2SessionTimeout",schemaPath:"#/properties/http2SessionTimeout/type",keyword:"type",params:{type:"integer"},message:"must be integer"}],false;Sn!==void 0&&(Ie=Sn,e!==void 0&&(e.http2SessionTimeout=Sn));}var a=vt===o;if(a){let Rt=e.exposeHeadRoutes,Sn=o;if(typeof Rt!="boolean"){let Rr;if(Rr===void 0)if(Rt==="false"||Rt===0||Rt===null)Rr=false;else if(Rt==="true"||Rt===1)Rr=true;else return $e.errors=[{instancePath:t+"/exposeHeadRoutes",schemaPath:"#/properties/exposeHeadRoutes/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],false;Rr!==void 0&&(Rt=Rr,e!==void 0&&(e.exposeHeadRoutes=Rr));}var a=Sn===o;if(a){let Rr=e.useSemicolonDelimiter,uX=o;if(typeof Rr!="boolean"){let Pe;if(Pe===void 0)if(Rr==="false"||Rr===0||Rr===null)Pe=false;else if(Rr==="true"||Rr===1)Pe=true;else return $e.errors=[{instancePath:t+"/useSemicolonDelimiter",schemaPath:"#/properties/useSemicolonDelimiter/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],false;Pe!==void 0&&(Rr=Pe,e!==void 0&&(e.useSemicolonDelimiter=Pe));}var a=uX===o;if(a){if(e.routerOptions!==void 0){let Pe=e.routerOptions,yl=o;if(o===yl)if(Pe&&typeof Pe=="object"&&!Array.isArray(Pe)){Pe.ignoreTrailingSlash===void 0&&(Pe.ignoreTrailingSlash=false),Pe.ignoreDuplicateSlashes===void 0&&(Pe.ignoreDuplicateSlashes=false),Pe.maxParamLength===void 0&&(Pe.maxParamLength=100),Pe.allowUnsafeRegex===void 0&&(Pe.allowUnsafeRegex=false),Pe.useSemicolonDelimiter===void 0&&(Pe.useSemicolonDelimiter=false);let Yr=Pe.ignoreTrailingSlash,qr=o;if(typeof Yr!="boolean"){let Vt;if(Vt===void 0)if(Yr==="false"||Yr===0||Yr===null)Vt=false;else if(Yr==="true"||Yr===1)Vt=true;else return $e.errors=[{instancePath:t+"/routerOptions/ignoreTrailingSlash",schemaPath:"#/properties/routerOptions/properties/ignoreTrailingSlash/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],false;Vt!==void 0&&(Yr=Vt,Pe!==void 0&&(Pe.ignoreTrailingSlash=Vt));}var p=qr===o;if(p){let Vt=Pe.ignoreDuplicateSlashes,es=o;if(typeof Vt!="boolean"){let _t;if(_t===void 0)if(Vt==="false"||Vt===0||Vt===null)_t=false;else if(Vt==="true"||Vt===1)_t=true;else return $e.errors=[{instancePath:t+"/routerOptions/ignoreDuplicateSlashes",schemaPath:"#/properties/routerOptions/properties/ignoreDuplicateSlashes/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],false;_t!==void 0&&(Vt=_t,Pe!==void 0&&(Pe.ignoreDuplicateSlashes=_t));}var p=es===o;if(p){let _t=Pe.maxParamLength,ts=o;if(!(typeof _t=="number"&&!(_t%1)&&!isNaN(_t)&&isFinite(_t))){let Bn=typeof _t,to;if(to===void 0)if(Bn==="boolean"||_t===null||Bn==="string"&&_t&&_t==+_t&&!(_t%1))to=+_t;else return $e.errors=[{instancePath:t+"/routerOptions/maxParamLength",schemaPath:"#/properties/routerOptions/properties/maxParamLength/type",keyword:"type",params:{type:"integer"},message:"must be integer"}],false;to!==void 0&&(_t=to,Pe!==void 0&&(Pe.maxParamLength=to));}var p=ts===o;if(p){let Bn=Pe.allowUnsafeRegex,to=o;if(typeof Bn!="boolean"){let Pr;if(Pr===void 0)if(Bn==="false"||Bn===0||Bn===null)Pr=false;else if(Bn==="true"||Bn===1)Pr=true;else return $e.errors=[{instancePath:t+"/routerOptions/allowUnsafeRegex",schemaPath:"#/properties/routerOptions/properties/allowUnsafeRegex/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],false;Pr!==void 0&&(Bn=Pr,Pe!==void 0&&(Pe.allowUnsafeRegex=Pr));}var p=to===o;if(p){let Pr=Pe.useSemicolonDelimiter,dX=o;if(typeof Pr!="boolean"){let ha;if(ha===void 0)if(Pr==="false"||Pr===0||Pr===null)ha=false;else if(Pr==="true"||Pr===1)ha=true;else return $e.errors=[{instancePath:t+"/routerOptions/useSemicolonDelimiter",schemaPath:"#/properties/routerOptions/properties/useSemicolonDelimiter/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],false;ha!==void 0&&(Pr=ha,Pe!==void 0&&(Pe.useSemicolonDelimiter=ha));}var p=dX===o;}}}}}else return $e.errors=[{instancePath:t+"/routerOptions",schemaPath:"#/properties/routerOptions/type",keyword:"type",params:{type:"object"},message:"must be object"}],false;var a=yl===o;}else var a=true;if(a)if(e.constraints!==void 0){let Pe=e.constraints,yl=o;if(o===yl)if(Pe&&typeof Pe=="object"&&!Array.isArray(Pe))for(let Yr in Pe){let qr=Pe[Yr],Vt=o;if(o===Vt)if(qr&&typeof qr=="object"&&!Array.isArray(qr)){let es;if(qr.name===void 0&&(es="name")||qr.storage===void 0&&(es="storage")||qr.validate===void 0&&(es="validate")||qr.deriveConstraint===void 0&&(es="deriveConstraint"))return $e.errors=[{instancePath:t+"/constraints/"+Yr.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/properties/constraints/additionalProperties/required",keyword:"required",params:{missingProperty:es},message:"must have required property '"+es+"'"}],false;if(qr.name!==void 0){let wl=qr.name;if(typeof wl!="string"){let _t=typeof wl,ts;if(ts===void 0)if(_t=="number"||_t=="boolean")ts=""+wl;else if(wl===null)ts="";else return $e.errors=[{instancePath:t+"/constraints/"+Yr.replace(/~/g,"~0").replace(/\//g,"~1")+"/name",schemaPath:"#/properties/constraints/additionalProperties/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"}],false;ts!==void 0&&(wl=ts,qr!==void 0&&(qr.name=ts));}}}else return $e.errors=[{instancePath:t+"/constraints/"+Yr.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/properties/constraints/additionalProperties/type",keyword:"type",params:{type:"object"},message:"must be object"}],false;var h=Vt===o;if(!h)break}else return $e.errors=[{instancePath:t+"/constraints",schemaPath:"#/properties/constraints/type",keyword:"type",params:{type:"object"},message:"must be object"}],false;var a=yl===o;}else var a=true;}}}}}}}}}}}}}}}}}}}}}}}}else return $e.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"}],false;return $e.errors=s,o===0}Eh.exports.defaultInitOptions={connectionTimeout:0,keepAliveTimeout:72e3,maxRequestsPerSocket:0,requestTimeout:0,handlerTimeout:0,bodyLimit:1048576,caseSensitive:true,allowUnsafeRegex:false,disableRequestLogging:false,ignoreTrailingSlash:false,ignoreDuplicateSlashes:false,maxParamLength:100,onProtoPoisoning:"error",onConstructorPoisoning:"error",pluginTimeout:1e4,requestIdHeader:false,requestIdLogLabel:"reqId",http2SessionTimeout:72e3,exposeHeadRoutes:true,useSemicolonDelimiter:false,allowErrorHandlerOverride:true,routerOptions:{ignoreTrailingSlash:false,ignoreDuplicateSlashes:false,maxParamLength:100,allowUnsafeRegex:false,useSemicolonDelimiter:false}};});var Th=c((uUe,dj)=>{dj.exports=qee;function Pa(e){return e instanceof Buffer?Buffer.from(e):new e.constructor(e.buffer.slice(),e.byteOffset,e.length)}function qee(e){if(e=e||{},e.circles)return Uee(e);let t=new Map;if(t.set(Date,o=>new Date(o)),t.set(Map,(o,a)=>new Map(n(Array.from(o),a))),t.set(Set,(o,a)=>new Set(n(Array.from(o),a))),e.constructorHandlers)for(let o of e.constructorHandlers)t.set(o[0],o[1]);let r=null;return e.proto?s:i;function n(o,a){let c=Object.keys(o),l=new Array(c.length);for(let u=0;u<c.length;u++){let d=c[u],m=o[d];typeof m!="object"||m===null?l[d]=m:m.constructor!==Object&&(r=t.get(m.constructor))?l[d]=r(m,a):ArrayBuffer.isView(m)?l[d]=Pa(m):l[d]=a(m);}return l}function i(o){if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return n(o,i);if(o.constructor!==Object&&(r=t.get(o.constructor)))return r(o,i);let a={};for(let c in o){if(Object.hasOwnProperty.call(o,c)===false)continue;let l=o[c];typeof l!="object"||l===null?a[c]=l:l.constructor!==Object&&(r=t.get(l.constructor))?a[c]=r(l,i):ArrayBuffer.isView(l)?a[c]=Pa(l):a[c]=i(l);}return a}function s(o){if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return n(o,s);if(o.constructor!==Object&&(r=t.get(o.constructor)))return r(o,s);let a={};for(let c in o){let l=o[c];typeof l!="object"||l===null?a[c]=l:l.constructor!==Object&&(r=t.get(l.constructor))?a[c]=r(l,s):ArrayBuffer.isView(l)?a[c]=Pa(l):a[c]=s(l);}return a}}function Uee(e){let t=[],r=[],n=new Map;if(n.set(Date,c=>new Date(c)),n.set(Map,(c,l)=>new Map(s(Array.from(c),l))),n.set(Set,(c,l)=>new Set(s(Array.from(c),l))),e.constructorHandlers)for(let c of e.constructorHandlers)n.set(c[0],c[1]);let i=null;return e.proto?a:o;function s(c,l){let u=Object.keys(c),d=new Array(u.length);for(let m=0;m<u.length;m++){let p=u[m],h=c[p];if(typeof h!="object"||h===null)d[p]=h;else if(h.constructor!==Object&&(i=n.get(h.constructor)))d[p]=i(h,l);else if(ArrayBuffer.isView(h))d[p]=Pa(h);else {let f=t.indexOf(h);f!==-1?d[p]=r[f]:d[p]=l(h);}}return d}function o(c){if(typeof c!="object"||c===null)return c;if(Array.isArray(c))return s(c,o);if(c.constructor!==Object&&(i=n.get(c.constructor)))return i(c,o);let l={};t.push(c),r.push(l);for(let u in c){if(Object.hasOwnProperty.call(c,u)===false)continue;let d=c[u];if(typeof d!="object"||d===null)l[u]=d;else if(d.constructor!==Object&&(i=n.get(d.constructor)))l[u]=i(d,o);else if(ArrayBuffer.isView(d))l[u]=Pa(d);else {let m=t.indexOf(d);m!==-1?l[u]=r[m]:l[u]=o(d);}}return t.pop(),r.pop(),l}function a(c){if(typeof c!="object"||c===null)return c;if(Array.isArray(c))return s(c,a);if(c.constructor!==Object&&(i=n.get(c.constructor)))return i(c,a);let l={};t.push(c),r.push(l);for(let u in c){let d=c[u];if(typeof d!="object"||d===null)l[u]=d;else if(d.constructor!==Object&&(i=n.get(d.constructor)))l[u]=i(d,a);else if(ArrayBuffer.isView(d))l[u]=Pa(d);else {let m=t.indexOf(d);m!==-1?l[u]=r[m]:l[u]=a(d);}}return t.pop(),r.pop(),l}}});var iv=c((dUe,Ph)=>{var Rh=uj(),Bee=Th()({circles:true,proto:false}),{FST_ERR_INIT_OPTS_INVALID:Hee}=Ut();function Gee(e){let t=Bee(e);if(!Rh(t)){let r=new Hee(JSON.stringify(Rh.errors.map(n=>n.message)));throw r.errors=Rh.errors,r}return nv(t)}function nv(e){let t=Object.getOwnPropertyNames(e);for(let r of t){let n=e[r];ArrayBuffer.isView(n)&&!(n instanceof DataView)||(e[r]=n&&typeof n=="object"?nv(n):n);}return Object.freeze(e)}Ph.exports=Gee;Ph.exports.defaultInitOptions=Rh.defaultInitOptions;Ph.exports.utils={deepFreezeObject:nv};});var pj=c((fUe,hj)=>{var{defaultInitOptions:fj}=iv(),sv=class{constructor(t){let r=t||{};this.disableRequestLogging=r.disableRequestLogging||fj.disableRequestLogging,this.isDisableRequestLoggingFunction=typeof this.disableRequestLogging=="function",this.requestIdLogLabel=r.requestIdLogLabel||fj.requestIdLogLabel;}isLogDisabled(t){return this.isDisableRequestLoggingFunction?this.disableRequestLogging(t):this.disableRequestLogging}incomingRequest(t,r,n){this.isLogDisabled(t)||t.log.info({req:t},"incoming request");}requestCompleted(t,r,n,i){this.isLogDisabled(r)||(t?n.log.error({res:n,err:t,responseTime:n.elapsedTime},"request errored"):n.log.info({res:n,responseTime:n.elapsedTime},"request completed"));}defaultErrorLog(t,r,n,i){this.isLogDisabled(r)||(n.statusCode>=500?n.log.error({req:r,res:n,err:t},t?.message):n.log.info({res:n,err:t},t?.message));}streamError(t,r,n,i){this.isLogDisabled(r)||(t.code==="ERR_STREAM_PREMATURE_CLOSE"?n.log.info({res:n},"stream closed prematurely"):n.log.warn({err:t},"response terminated with an error with headers already sent"));}routeNotFound(t,r,n){if(this.isLogDisabled(t))return;let{url:i,method:s}=t.raw;t.log.info(`Route ${s}:${i} not found`);}writeHeadError(t,r,n,i){this.isLogDisabled(r)||n.log.warn({req:r,res:n,err:t},t?.message);}serializerError(t,r,n,i){this.isLogDisabled(r)||n.log.error({err:t,statusCode:i.statusCode},"The serializer for the given status code failed");}serviceUnavailable(t,r){t.info({res:{statusCode:503}},"request aborted - refusing to accept new requests as server is closing");}};hj.exports={LogController:sv};});var gj=c((hUe,mj)=>{function ka(){}var zee={fatal:ka,error:ka,warn:ka,info:ka,debug:ka,trace:ka};Object.defineProperty(mj,"exports",{get(){return Object.create(zee)}});});var vj=c((pUe,wj)=>{var kh=l(),{serializersSym:yj}=kh.symbols,{FST_ERR_LOG_INVALID_DESTINATION:Vee}=Ut();function Wee(e){if(e.stream&&e.file)throw new Vee;e.file&&(e.stream=kh.destination(e.file),delete e.file);let t=e.logger,r=e.genReqId,n=null;return t?(e.logger=void 0,e.genReqId=void 0,t[yj]&&(e.serializers=Object.assign({},e.serializers,t[yj])),n=t.child({},e),e.logger=t,e.genReqId=r):n=kh(e,e.stream),n}var Kee={req:function(t){return {method:t.method,url:t.url,version:t.headers&&t.headers["accept-version"],host:t.host,remoteAddress:t.ip,remotePort:t.socket?t.socket.remotePort:void 0}},err:kh.stdSerializers.err,res:function(t){return {statusCode:t.statusCode}}};wj.exports={serializers:Kee,createPinoLogger:Wee};});var Dl=c((mUe,Sj)=>{var{performance:Yee}=a("perf_hooks"),{FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED:Qee,FST_ERR_LOG_INVALID_LOGGER_CONFIG:Jee,FST_ERR_LOG_INVALID_LOGGER_INSTANCE:Xee,FST_ERR_LOG_INVALID_LOGGER:Zee,FST_ERR_LOG_INVALID_LOG_CONTROLLER:ete}=Ut(),{kLogController:tte}=St(),{LogController:ov}=pj();function rte(e,t,r,n,i){let s={[e.server[tte].requestIdLogLabel]:n},o=e.childLoggerFactory.call(e.server,t,s,i||{},r);return e.childLoggerFactory!==_j&&xh(o,true),o}function _j(e,t,r){return e.child(t,r)}function xh(e,t){let r=["info","error","debug","fatal","warn","trace","child"],n=e?r.filter(i=>!e[i]||typeof e[i]!="function"):r;if(n.length){if(n.length===r.length&&!t)return false;throw Zee(n.join(","))}else return true}function nte(e){if(e.logger&&e.loggerInstance)throw new Qee;if(!e.loggerInstance&&!e.logger){let o=gj();return o.child=()=>o,{logger:o,hasLogger:false}}let{createPinoLogger:t,serializers:r}=vj();if(xh(e.loggerInstance))return {logger:t({logger:e.loggerInstance,serializers:Object.assign({},r,e.loggerInstance.serializers)}),hasLogger:true};if(xh(e.logger))throw Jee();if(e.loggerInstance)throw Xee();let n={};return Object.prototype.toString.call(e.logger)==="[object Object]"&&Reflect.ownKeys(e.logger).forEach(s=>{Object.defineProperty(n,s,{value:e.logger[s],writable:true,enumerable:true,configurable:true});}),n.level=n.level||"info",n.serializers=Object.assign({},r,n.serializers),e.logger=n,{logger:t(e.logger),hasLogger:true}}function ite(e){let t=e.logController;if(!t)return new ov(e);if(t instanceof ov)return t;throw new ete(typeof t)}function ste(){return Yee.now()}Sj.exports={createChildLogger:rte,defaultChildLoggerFactory:_j,createLogController:ite,createLogger:nte,LogController:ov,validateLogger:xh,now:ste};});var Ml=c((gUe,Pj)=>{var ote=Th()({circles:false,proto:true}),{kSchemaVisited:bj,kSchemaResponse:ate}=St(),cv=Symbol.for("fluent-schema-object"),{FST_ERR_SCH_MISSING_ID:cte,FST_ERR_SCH_ALREADY_PRESENT:lte,FST_ERR_SCH_DUPLICATE:ute,FST_ERR_SCH_CONTENT_MISSING_SCHEMA:Ej}=Ut(),av=Ta(),Rj=["params","body","querystring","query","headers"];function Ah(e){this.store=e||{};}Ah.prototype.add=function(e){let t=ote(e.isFluentSchema||e.isFluentJSONSchema||e[cv]?e.valueOf():e),r=t.$id;if(!r)throw new cte;if(this.store[r])throw new lte(r);this.store[r]=t;};Ah.prototype.getSchemas=function(){return Object.assign({},this.store)};Ah.prototype.getSchema=function(e){return this.store[e]};function Tj(e){return typeof e=="object"&&Object.getPrototypeOf(e)!==Object.prototype}function dte(e,t){if(e[bj])return e;if(e.query!==void 0){if(e.querystring!==void 0)throw new ute("querystring");e.querystring=e.query;}fte(e);for(let r of Rj){let n=e[r];if(n&&!Tj(n)&&r==="body"&&n.content){let i=n.content,s=Object.keys(i);for(let o=0;o<s.length;o++){let a=s[o];if(!i[a].schema)throw new Ej(a)}continue}}if(e.response){let r=Object.keys(e.response);for(let n of r){if(Tj(e.response[n]))continue;let i=e.response[n].content;if(i){let s=Object.keys(i);for(let o=0;o<s.length;o++){let a=s[o];if(!i[a].schema)throw new Ej(a)}}}}return e[bj]=true,e}function fte(e){for(let t of Rj)e[t]&&(e[t].isFluentSchema||e[t][cv])&&(e[t]=e[t].valueOf());if(e.response){let t=Object.keys(e.response);for(let r of t)(e.response[r].isFluentSchema||e.response[r][cv])&&(e.response[r]=e.response[r].valueOf());}}function hte(e,t,r){let n=e[ate];if(!n)return false;if(n[t]){if(n[t].constructor===Object){let s=av.from(r);if(s.isValid)return n[t][s.mediaType]?n[t][s.mediaType]:n[t]["*/*"]?n[t]["*/*"]:false}return n[t]}let i=(t+"")[0]+"xx";if(n[i]){if(n[i].constructor===Object){let s=av.from(r);if(s.isValid)return n[i][s.mediaType]?n[i][s.mediaType]:n[i]["*/*"]?n[i]["*/*"]:false}return n[i]}if(n.default){if(n.default.constructor===Object){let s=av.from(r);if(s.isValid)return n.default[s.mediaType]?n.default[s.mediaType]:n.default["*/*"]?n.default["*/*"]:false}return n.default}return false}Pj.exports={buildSchemas(e){return new Ah(e)},getSchemaSerializer:hte,normalizeSchema:dte};});var Ih=c((yUe,xj)=>{var pte=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;xj.exports=class kj{constructor(t){switch(t&&t.rounding){case "floor":this.parseInteger=Math.floor;break;case "ceil":this.parseInteger=Math.ceil;break;case "round":this.parseInteger=Math.round;break;default:this.parseInteger=Math.trunc;break}this._options=t;}asInteger(t){if(Number.isInteger(t))return ""+t;if(typeof t=="bigint")return t.toString();let r=this.parseInteger(t);if(r===1/0||r===-1/0||r!==r)throw new Error(`The value "${t}" cannot be converted to an integer.`);return ""+r}asNumber(t){let r=Number(t);if(r!==r)throw new Error(`The value "${t}" cannot be converted to a number.`);return r===1/0||r===-1/0?"null":""+r}asBoolean(t){return t&&"true"||"false"}asDateTime(t){if(t===null)return '""';if(t instanceof Date)return '"'+t.toISOString()+'"';if(typeof t=="string")return '"'+t+'"';throw new Error(`The value "${t}" cannot be converted to a date-time.`)}asDate(t){if(t===null)return '""';if(t instanceof Date)return '"'+new Date(t.getTime()-t.getTimezoneOffset()*6e4).toISOString().slice(0,10)+'"';if(typeof t=="string")return '"'+t+'"';throw new Error(`The value "${t}" cannot be converted to a date.`)}asTime(t){if(t===null)return '""';if(t instanceof Date)return '"'+new Date(t.getTime()-t.getTimezoneOffset()*6e4).toISOString().slice(11,19)+'"';if(typeof t=="string")return '"'+t+'"';throw new Error(`The value "${t}" cannot be converted to a time.`)}asString(t){let r=t.length;if(r===0)return '""';if(r<42){let n="",i=-1,s=255;for(let o=0;o<r;o++)if(s=t.charCodeAt(o),s===34||s===92)i===-1&&(i=0),n+=t.slice(i,o)+"\\",i=o;else if(s<32||s>=55296&&s<=57343)return JSON.stringify(t);return i===-1&&'"'+t+'"'||'"'+n+t.slice(i)+'"'}else return r<5e3&&pte.test(t)===false?'"'+t+'"':JSON.stringify(t)}asUnsafeString(t){return '"'+t+'"'}getState(){return this._options}static restoreFromState(t){return new kj(t)}};});var Ij=c((wUe,Aj)=>{var mte=Ih(),gte={mode:"standalone"},yte=mte.restoreFromState(gte),wte=null;Aj.exports=(function(t,r){let {asString:n,asNumber:i,asBoolean:s,asDateTime:o,asDate:a,asTime:c,asUnsafeString:l}=r;r.asInteger.bind(r);let d="{",m="}",f=",",y='"',_=d+m,w=y+y;function R(b){let O=b&&typeof b.toJSON=="function"?b.toJSON():b;if(O===null)return _;let F="";F+=d;let j=false,N=O.statusCode;N!==void 0&&(!j&&(j=true)||(F+=f),F+='"statusCode":',F+=i(N));let M=O.code;M!==void 0&&(!j&&(j=true)||(F+=f),F+='"code":',typeof M!="string"?M===null?F+=w:M instanceof Date?F+=y+M.toISOString()+y:M instanceof RegExp?F+=n(M.source):F+=n(M.toString()):F+=n(M));let q=O.error;q!==void 0&&(!j&&(j=true)||(F+=f),F+='"error":',typeof q!="string"?q===null?F+=w:q instanceof Date?F+=y+q.toISOString()+y:q instanceof RegExp?F+=n(q.source):F+=n(q.toString()):F+=n(q));let z=O.message;return z!==void 0&&(!j&&(j=true)||(F+=f),F+='"message":',typeof z!="string"?z===null?F+=w:z instanceof Date?F+=y+z.toISOString()+y:z instanceof RegExp?F+=n(z.source):F+=n(z.toString()):F+=n(z)),F+=m,F}return R})(wte,yte);});var Fl=c((vUe,jj)=>{var Oj=a("http").STATUS_CODES,vte=Hw(),{setErrorStatusCode:_te}=fh(),{kReplyHeaders:oo,kReplyNextErrorHandler:Oh,kReplyIsRunningOnErrorHook:Ste,kRouteContext:Nj,kLogController:uv,kDiagnosticsStore:bte}=St(),{FST_ERR_REP_INVALID_PAYLOAD_TYPE:Ete,FST_ERR_FAILED_ERROR_SERIALIZATION:Tte}=Ut(),{getSchemaSerializer:Rte}=Ml(),lv=Ij(),Pte={func:xte,toJSON(){return this.func.name.toString()+"()"}};function kte(e,t,r){e[Ste]=false;let n=e[Nj];if(e[Oh]===false){Cj(t,e,function(o,a){try{o.raw.writeHead(o.raw.statusCode,o[oo]);}catch(c){o.server[uv].writeHeadError(c,o.request,o),o.raw.writeHead(o.raw.statusCode);}o.raw.end(a);});return}let i=e[Oh]||n.errorHandler;e[Oh]=Object.getPrototypeOf(i),delete e[oo]["content-type"],delete e[oo]["content-length"];let s=i.func;if(!s){e[Oh]=false,Cj(t,e,r);return}try{let o=s(t,e.request,e);if(o!==void 0)if(o!==null&&typeof o.then=="function"){let a=e[bte]||null;vte(o,e,a);}else e.send(o);}catch(o){e.send(o);}}function xte(e,t,r){Ite(e,r),_te(r,e),t.server[uv].defaultErrorLog(e,t,r),r.send(e);}function Cj(e,t,r){let n=t.raw,i=t.statusCode;t[oo]["content-type"]=t[oo]["content-type"]??"application/json; charset=utf-8";let s;try{let o=Rte(t[Nj],i,t[oo]["content-type"]);o===!1?s=lv({error:Oj[i+""],code:e.code,message:e.message,statusCode:i}):s=o(Object.create(e,{error:{value:Oj[i+""]},message:{value:e.message},statusCode:{value:i}}));}catch(o){t.server[uv].serializerError(o,t.request,t,{statusCode:n.statusCode}),t.code(500),s=lv(new Tte(o.message,e.message));}typeof s!="string"&&!Buffer.isBuffer(s)&&(s=lv(new Ete(typeof s))),t[oo]["content-length"]=""+Buffer.byteLength(s),r(t,s);}function Ate(e=Pte,t){if(!t)return e;let r=Object.create(e);return r.func=t,r}function Ite(e,t){let r=t.raw,n=r.statusCode;n=n>=400?n:500,e!=null&&(e.headers!==void 0&&t.headers(e.headers),e.status>=400?n=e.status:e.statusCode>=400&&(n=e.statusCode)),r.statusCode=n;}jj.exports={buildErrorHandler:Ate,handleError:kte};});var Ul=c((_Ue,Fj)=>{var{kReply:Ch,kRequest:Nh,kState:Ote,kHasBeenDecorated:Cte}=St(),{FST_ERR_DEC_ALREADY_PRESENT:Lj,FST_ERR_DEC_MISSING_DEPENDENCY:Nte,FST_ERR_DEC_AFTER_START:jte,FST_ERR_DEC_REFERENCE_TYPE:Lte,FST_ERR_DEC_DEPENDENCY_INVALID_TYPE:Dte,FST_ERR_DEC_UNDECLARED:Mte}=Ut();function Fte(e,t,r,n){if(Object.hasOwn(e,t))throw new Lj(t);dv(e,t,n),r&&(typeof r.getter=="function"||typeof r.setter=="function")?Object.defineProperty(e,t,{get:r.getter,set:r.setter}):e[t]=r;}function $te(e){if(!$l(this,e))throw new Mte(e,"instance");return typeof this[e]=="function"?this[e].bind(this):this[e]}function Dj(e,t,r,n){let i=e.prototype;if(Object.hasOwn(i,t)||ql(e,t)||jh(e,t))throw new Lj(t);e[Cte]=true,dv(e,t,n),r&&(typeof r.getter=="function"||typeof r.setter=="function")?Object.defineProperty(i,t,{get:r.getter,set:r.setter}):typeof r=="function"?i[t]=r:e.props.push({key:t,value:r});}function Mj(e,t){if(typeof t=="object"&&t&&!(typeof t.getter=="function"||typeof t.setter=="function"))throw new Lte(e,typeof t)}function qte(e,t,r){return fv(this,e),Fte(this,e,t,r),this}function $l(e,t){return t?t in e||e.prototype&&t in e.prototype||ql(e,t):e in this}function ql(e,t){return e.props?e.props.some(r=>r.key===t):false}function jh(e,t){let r=e;for(;r;){if(r.instanceProperties&&r.instanceProperties.has(t))return true;r=r.parent;}return false}function Ute(e){return e&&ql(this[Nh],e)||e&&jh(this[Nh],e)?true:$l(this[Nh].prototype,e)}function Bte(e){return e&&ql(this[Ch],e)||e&&jh(this[Ch],e)?true:$l(this[Ch].prototype,e)}function dv(e,t,r){if(r!=null){if(!Array.isArray(r))throw new Dte(t);for(let n=0;n!==r.length;++n)if(!$l(e,r[n])&&!jh(e,r[n]))throw new Nte(r[n])}}function Hte(e,t,r){return fv(this,e),Mj(e,t),Dj(this[Ch],e,t,r),this}function Gte(e,t,r){return fv(this,e),Mj(e,t),Dj(this[Nh],e,t,r),this}function fv(e,t){if(e[Ote].started)throw new jte(t)}Fj.exports={add:qte,exist:$l,existRequest:Ute,existReply:Bte,dependencies:dv,decorateReply:Hte,decorateRequest:Gte,getInstanceDecorator:$te,hasKey:ql};});var Hh=c((SUe,Bh)=>{var Lh=a("stream").finished,{kFourOhFourContext:$j,kReplyErrorHandlerCalled:Vj,kReplyHijacked:yv,kReplyStartTime:Bl,kReplyEndTime:wv,kReplySerializer:_i,kReplySerializerDefault:Dh,kReplyIsError:Mh,kReplyHeaders:rt,kReplyTrailers:jt,kReplyHasStatusCode:vv,kReplyIsRunningOnErrorHook:_v,kReplyNextErrorHandler:zte,kSchemaResponse:Fh,kReplyCacheSerializeFns:as,kSchemaController:hv,kOptions:Vte,kRouteContext:De,kTimeoutTimer:$h,kOnAbort:xa,kRequestSignal:Wj,kLogController:Kj}=St(),{onSendHookRunner:Yj,onResponseHookRunner:Wte,preHandlerHookRunner:Kte,preSerializationHookRunner:Yte}=is(),qj=rv()[Symbol.for("internals")],Qte=Dl(),gv=Qte.now,{handleError:Uj}=Fl(),{getSchemaSerializer:Jte}=Ml(),pv={JSON:"application/json; charset=utf-8",PLAIN:"text/plain; charset=utf-8",OCTET:"application/octet-stream"},{FST_ERR_REP_INVALID_PAYLOAD_TYPE:Xte,FST_ERR_REP_RESPONSE_BODY_CONSUMED:Zte,FST_ERR_REP_READABLE_STREAM_LOCKED:ere,FST_ERR_REP_ALREADY_SENT:tre,FST_ERR_SEND_INSIDE_ONERR:rre,FST_ERR_BAD_STATUS_CODE:nre,FST_ERR_BAD_TRAILER_NAME:ire,FST_ERR_BAD_TRAILER_VALUE:sre,FST_ERR_MISSING_SERIALIZATION_FN:ore,FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN:are,FST_ERR_DEC_UNDECLARED:cre}=Ut(),Bj=Ul(),Qj=Ta(),Jj=Object.prototype.toString,Xj=64*1024;function Ze(e,t,r){this.raw=e,this[_i]=null,this[Vj]=false,this[Mh]=false,this[_v]=false,this.request=t,this[rt]={},this[jt]=null,this[vv]=false,this[Bl]=void 0,this.log=r;}Ze.props=[];Ze.instanceProperties=new Set(["raw","request","log"]);Object.defineProperties(Ze.prototype,{[De]:{get(){return this.request[De]}},elapsedTime:{get(){return this[Bl]===void 0?0:(this[wv]||gv())-this[Bl]}},mediaType:{get(){let e=this[rt]["content-type"];return Qj.from(e).mediaType}},server:{get(){return this.request[De].server}},sent:{enumerable:true,get(){return (this[yv]||this.raw.writableEnded)===true}},statusCode:{get(){return this.raw.statusCode},set(e){this.code(e);}},routeOptions:{get(){return this.request.routeOptions}}});Ze.prototype.writeEarlyHints=function(e,t){return this.raw.writeEarlyHints(e,t),this};Ze.prototype.hijack=function(){this[yv]=true,this.request[Wj]&&(clearTimeout(this.request[$h]),this.request[$h]=null,this.request[xa]&&(this.request.raw.removeListener("close",this.request[xa]),this.request[xa]=null));let e=this.request.raw.socket;return e?._meta?.request===this.request&&(e.removeListener("timeout",e._meta.onTimeout),e._meta=null),this};Ze.prototype.send=function(e){if(this[_v])throw new rre;if(this.sent===true)return this.log.warn({err:new tre(this.request.url,this.request.method)}),this;if(this[Mh]||e instanceof Error)return this[Mh]=false,Ia(this,e,ao),this;if(e===void 0)return ao(this,e),this;let t=Qj.from(this.getHeader("content-type")),r=t.isEmpty===false;if(e!==null){if(typeof e.pipe=="function"||typeof e.getReader=="function"||typeof e=="object"&&Jj.call(e)==="[object Response]")return ao(this,e),this;if(e.buffer instanceof ArrayBuffer){r||(this[rt]["content-type"]=pv.OCTET);let n=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength);return ao(this,n),this}if(!r&&typeof e=="string")return this[rt]["content-type"]=pv.PLAIN,ao(this,e),this}if(this[_i]!==null){if(typeof e!="string")return Hj(this,e),this;e=this[_i](e);}else if(!r||t.mediaType.indexOf("json")!==-1){if(!r)this[rt]["content-type"]=pv.JSON;else if(t.parameters.has("charset")===false){let n=t.toString();this[rt]["content-type"]=`${n}; charset=utf-8`;}if(typeof e!="string")return Hj(this,e),this}return ao(this,e),this};Ze.prototype.getHeader=function(e){e=e.toLowerCase();let t=this[rt][e];return t!==void 0?t:this.raw.getHeader(e)};Ze.prototype.getHeaders=function(){return {...this.raw.getHeaders(),...this[rt]}};Ze.prototype.hasHeader=function(e){return e=e.toLowerCase(),this[rt][e]!==void 0||this.raw.hasHeader(e)};Ze.prototype.removeHeader=function(e){return e=e.toLowerCase(),delete this[rt][e],this.raw.headersSent||this.raw.removeHeader(e),this};Ze.prototype.header=function(e,t=""){return e=e.toLowerCase(),this[rt][e]&&e==="set-cookie"?(typeof this[rt][e]=="string"&&(this[rt][e]=[this[rt][e]]),Array.isArray(t)?Array.prototype.push.apply(this[rt][e],t):this[rt][e].push(t)):this[rt][e]=t,this};Ze.prototype.headers=function(e){let t=Object.keys(e);for(let r=0;r!==t.length;++r){let n=t[r];this.header(n,e[n]);}return this};var lre=new Set(["transfer-encoding","content-length","host","cache-control","max-forwards","te","authorization","set-cookie","content-encoding","content-type","content-range","trailer"]);Ze.prototype.trailer=function(e,t){if(e=e.toLowerCase(),lre.has(e))throw new ire(e);if(typeof t!="function")throw new sre(e,typeof t);return this[jt]===null&&(this[jt]={}),this[jt][e]=t,this};Ze.prototype.hasTrailer=function(e){return this[jt]?.[e.toLowerCase()]!==void 0};Ze.prototype.removeTrailer=function(e){return this[jt]===null?this:(this[jt][e.toLowerCase()]=void 0,this)};Ze.prototype.code=function(e){let t=+e;if(!(t>=100&&t<=599))throw new nre(e||String(e));return this.raw.statusCode=t,this[vv]=true,this};Ze.prototype.status=Ze.prototype.code;Ze.prototype.getSerializationFunction=function(e,t){let r;return typeof e=="string"||typeof e=="number"?typeof t=="string"?r=this[De][Fh]?.[e]?.[t]:r=this[De][Fh]?.[e]:typeof e=="object"&&(r=this[De][as]?.get(e)),r};Ze.prototype.compileSerializationSchema=function(e,t=null,r=null){let{request:n}=this,{method:i,url:s}=n;if(this[De][as]?.has(e))return this[De][as].get(e);let a=(this[De].serializerCompiler||this.server[hv].serializerCompiler||this.server[hv].setupSerializer(this.server[Vte])||this.server[hv].serializerCompiler)({schema:e,method:i,url:s,httpStatus:t,contentType:r});return this[De][as]==null&&(this[De][as]=new WeakMap),this[De][as].set(e,a),a};Ze.prototype.serializeInput=function(e,t,r,n){let i=r,s;if(r=typeof t=="string"||typeof t=="number"?t:r,n=r&&i!==r?i:n,r!=null){if(n!=null?s=this[De][Fh]?.[r]?.[n]:s=this[De][Fh]?.[r],s==null)throw n?new are(r,n):new ore(r)}else this[De][as]?.has(t)?s=this[De][as].get(t):s=this.compileSerializationSchema(t,r,n);return s(e)};Ze.prototype.serialize=function(e){return this[_i]!==null?this[_i](e):this[De]&&this[De][Dh]?this[De][Dh](e,this.raw.statusCode):tL(this[De],e,this.raw.statusCode)};Ze.prototype.serializer=function(e){return this[_i]=e,this};Ze.prototype.type=function(e){return this[rt]["content-type"]=e,this};Ze.prototype.redirect=function(e,t){return t||(t=this[vv]?this.raw.statusCode:302),this.header("location",e).code(t).send()};Ze.prototype.callNotFound=function(){return vre(this),this};Ze.prototype.then=function(e,t){if(this.sent){e();return}Lh(this.raw,r=>{r&&r.code!=="ERR_STREAM_PREMATURE_CLOSE"?t?t(r):this.log&&this.log.warn("unhandled rejection on reply.then"):e();});};Ze.prototype.getDecorator=function(e){if(!Bj.hasKey(this,e)&&!Bj.exist(this,e))throw new cre(e,"reply");let t=this[e];return typeof t=="function"?t.bind(this):t};function Hj(e,t){e[De].preSerialization!==null?Yte(e[De].preSerialization,e.request,e,t,Gj):Gj(null,void 0,e,t);}function Gj(e,t,r,n){if(e!=null){Ia(r,e);return}try{r[_i]!==null?n=r[_i](n):r[De]&&r[De][Dh]?n=r[De][Dh](n,r.raw.statusCode):n=tL(r[De],n,r.raw.statusCode,r[rt]["content-type"]);}catch(i){ure(i,r),Ia(r,i);return}ao(r,n);}function ure(e,t){e.serialization=t[De].config;}function ao(e,t){e[De].onSend!==null?Yj(e[De].onSend,e.request,e,t,dre):Zj(e,t);}function dre(e,t,r,n){e!=null?Ia(r,e):Zj(r,n);}function mv(e,t){let r=e.raw;try{r.writeHead(t,e[rt]);}catch(n){throw n.code==="ERR_HTTP_HEADERS_SENT"&&e.log.warn(`Reply was already sent, did you forget to "return reply" in the "${e.request.raw.url}" (${e.request.raw.method}) route?`),n}}function Zj(e,t){let r=e.raw,n=e.request;if(e[jt]!==null){let s=Object.keys(e[jt]),o="";for(let a of s)typeof e[jt][a]=="function"&&(o+=" ",o+=a);o!==""?(eL(e)||e.header("Transfer-Encoding","chunked"),e.header("Trailer",o.trim())):e[jt]=null;}if(t!=null&&typeof t=="object"&&Jj.call(t)==="[object Response]"){if(typeof t.status=="number"&&e.code(t.status),typeof t.headers=="object"&&typeof t.headers.forEach=="function")for(let[s,o]of t.headers)e.header(s,o);if(t.body!==null&&t.bodyUsed)throw new Zte;t=t.body;}let i=r.statusCode;if(t==null){i>=200&&i!==204&&i!==304&&n.method!=="HEAD"&&e[jt]===null&&(e[rt]["content-length"]="0"),mv(e,i),Aa(t,r,e);return}if(i>=100&&i<200||i===204){e.removeHeader("content-type"),e.removeHeader("content-length"),mv(e,i),Aa(void 0,r,e),typeof t.resume=="function"&&(t.on("error",Uh),t.resume());return}if(typeof t.pipe=="function"){mre(t,r,e);return}if(typeof t.getReader=="function"){pre(t,r,e);return}if(typeof t!="string"&&!Buffer.isBuffer(t))throw new Xte(typeof t);if(e[jt]===null){let s=e[rt]["content-length"];(!s||n.raw.method!=="HEAD"&&Number(s)!==Buffer.byteLength(t))&&(e[rt]["content-length"]=""+Buffer.byteLength(t));}mv(e,i),fre(t,r,e);}function eL(e){return e.request.raw?.httpVersionMajor===2}function fre(e,t,r){if(!eL(r)||Buffer.byteLength(e)<=Xj){if(r[jt]===null){t.end(e,null,null);return}t.write(e),Aa(e,t,r);return}hre(e,t,()=>{Aa(e,t,r);});}function hre(e,t,r){let n=Buffer.isBuffer(e)?e:Buffer.from(e),i=0;function s(){for(;i<n.length;){if(t.destroyed||t.writableEnded)return;let o=Math.min(i+Xj,n.length),a=t.write(n.subarray(i,o));if(i=o,a===false){t.once("drain",s);return}}r();}s();}function qh(e,t,r){t.server[Kj].streamError(e,t.request,t);}function pre(e,t,r){if(e.locked)throw new ere;let n=true,i=false,s=false,o=e.getReader();if(Lh(t,function(u){n&&(u!=null&&t.headersSent&&!i&&(i=true,qh(u,r)),o.cancel().catch(Uh));}),t.headersSent)r.log.warn("response will send, but you shouldn't use res.writeHead in stream mode");else for(let u in r[rt])t.setHeader(u,r[rt][u]);function a(u){if(u.done){n=false,Aa(null,t,r);return}if(t.destroyed){n=false,o.cancel().catch(Uh);return}if(t.write(u.value)===false){s=true,t.once("drain",c);return}o.read().then(a,l);}function c(){!s||!n||t.destroyed||(s=false,o.read().then(a,l));}function l(u){n=false,t.headersSent||r.request.raw.aborted===true?(i||(i=true,qh(u,r)),t.destroy()):Ia(r,u);}o.read().then(a,l);}function mre(e,t,r){let n=true,i=false;if(gre(e,t,r),Lh(e,{readable:true,writable:false},function(s){n=false,s!=null&&(t.headersSent||r.request.raw.aborted===true?(i||(i=true,qh(s,r)),t.destroy()):Ia(r,s));}),Lh(t,function(s){n&&(s!=null&&t.headersSent&&!i&&(i=true,qh(s,r)),typeof e.destroy=="function"?e.destroy():typeof e.close=="function"?e.close(Uh):typeof e.abort=="function"?e.abort():r.log.warn("stream payload does not end properly"));}),t.headersSent)r.log.warn("response will send, but you shouldn't use res.writeHead in stream mode");else for(let s in r[rt])t.setHeader(s,r[rt][s]);e.pipe(t);}function Aa(e,t,r){if(r[jt]===null){t.end(null,null,null);return}let n=Object.keys(r[jt]),i={},s=0,o=true,a=false;function c(){s===0&&!a&&(a=true,t.addTrailers(i),t.end(null,null,null));}for(let l of n){let d=function(p,h){u||(u=true,s++,p?r.log.debug(p):i[l]=h,process.nextTick(c));};if(typeof r[jt][l]!="function")continue;o=false,s--;let u=false,m=r[jt][l](r,e,d);typeof m=="object"&&typeof m.then=="function"&&m.then(p=>d(null,p),d);}o&&t.end(null,null,null);}function gre(e,t,r){r[jt]!==null&&e.on("end",()=>Aa(null,t,r));}function Ia(e,t,r){e[De].onError!==null&&!e[zte]?(e[_v]=true,Yj(e[De].onError,e.request,e,t,()=>Uj(e,t,r))):Uj(e,t,r);}function yre(e){e[Bl]=gv();let t=r=>{e[wv]=gv(),e.raw.removeListener("finish",t),e.raw.removeListener("error",t);let n=e[De];e.request[Wj]&&(clearTimeout(e.request[$h]),e.request[$h]=null,e.request[xa]&&(e.request.raw.removeListener("close",e.request[xa]),e.request[xa]=null));let i=e.request.raw.socket;i&&i._meta&&i._meta.request===e.request&&(i.removeListener("timeout",i._meta.onTimeout),i._meta=null),n&&n.onResponse!==null?Wte(n.onResponse,e.request,e,zj):zj(r,e.request,e);};e.raw.on("finish",t),e.raw.on("error",t);}function zj(e,t,r){r.server[Kj].requestCompleted(e,t,r);}function wre(e){let t=e.props.slice();function r(n,i,s){this.raw=n,this[Mh]=false,this[Vj]=false,this[yv]=false,this[_i]=null,this.request=i,this[rt]={},this[jt]=null,this[Bl]=void 0,this[wv]=void 0,this.log=s;let o;for(let a=0;a<t.length;a++)o=t[a],this[o.key]=o.value;}return Object.setPrototypeOf(r.prototype,e.prototype),Object.setPrototypeOf(r,e),r.parent=e,r.props=t,r}function vre(e){if(e[De][$j]===null){e.log.warn("Trying to send a NotFound error inside a 404 handler. Sending basic 404 response."),e.code(404).send("404 Not Found");return}e.request[De]=e[De][$j],e[De].preHandler!==null?Kte(e[De].preHandler,e.request,e,qj.preHandlerCallback):qj.preHandlerCallback(null,e.request,e);}function tL(e,t,r,n){let i=Jte(e,r,n);return i?i(t):JSON.stringify(t)}function Uh(){}Bh.exports=Ze;Bh.exports.buildReply=wre;Bh.exports.setupResponseListeners=yre;});var rL=c((bUe,Gh)=>{function Sv(e){if(!e)throw new TypeError("argument req is required");let t=e.headers["x-forwarded-for"],r=e.socket.remoteAddress;if(!t||typeof t!="string")return [r];if(t.indexOf(",")===-1){let n=t.trim();return n.length?[r,n]:[r]}else return _re(t,r)}function _re(e,t){let r=[t],n=e.length,i=n,s,o;for(o=n-1;o>=0;--o)s=e[o],s===" "?i===n&&(i=n=o):s===","?(i!==n&&r.push(e.slice(i,n)),i=n=o):i=o;return i!==n&&r.push(e.substring(i,n)),r}Gh.exports=Sv;Gh.exports.default=Sv;Gh.exports.forwarded=Sv;});var iL=c((nL,zh)=>{(function(e){let t="(0?\\d+|0x[a-f0-9]+)",r={fourOctet:new RegExp(`^${t}\\.${t}\\.${t}\\.${t}$`,"i"),threeOctet:new RegExp(`^${t}\\.${t}\\.${t}$`,"i"),twoOctet:new RegExp(`^${t}\\.${t}$`,"i"),longValue:new RegExp(`^${t}$`,"i")},n=new RegExp("^0[0-7]+$","i"),i=new RegExp("^0x[a-f0-9]+$","i"),s="%[0-9a-z]{1,}",o="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(s,"i"),native:new RegExp(`^(::)?(${o})?([0-9a-f]+)?(::)?(${s})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${t}\\.${t}\\.${t}\\.${t}(${s})?)$`,"i"),transitional:new RegExp(`^((?:${o})|(?:::)(?:${o})?)${t}\\.${t}\\.${t}\\.${t}(${s})?$`,"i")};function c(p,h){if(p.indexOf("::")!==p.lastIndexOf("::"))return null;let f=0,g=-1,y=(p.match(a.zoneIndex)||[])[0],_,v;for(y&&(y=y.substring(1),p=p.replace(/%.+$/,""));(g=p.indexOf(":",g+1))>=0;)f++;if(p.substr(0,2)==="::"&&f--,p.substr(-2,2)==="::"&&f--,f>h)return null;for(v=h-f,_=":";v--;)_+="0:";return p=p.replace("::",_),p[0]===":"&&(p=p.slice(1)),p[p.length-1]===":"&&(p=p.slice(0,-1)),h=(function(){let w=p.split(":"),E=[];for(let R=0;R<w.length;R++)E.push(parseInt(w[R],16));return E})(),{parts:h,zoneId:y}}function l(p,h,f,g){if(p.length!==h.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let y=0,_;for(;g>0;){if(_=f-g,_<0&&(_=0),p[y]>>_!==h[y]>>_)return false;g-=f,y+=1;}return true}function u(p){if(i.test(p))return parseInt(p,16);if(p[0]==="0"&&!isNaN(parseInt(p[1],10))){if(n.test(p))return parseInt(p,8);throw new Error(`ipaddr: cannot parse ${p} as octal`)}return parseInt(p,10)}function d(p,h){for(;p.length<h;)p=`0${p}`;return p}let m={};m.IPv4=(function(){function p(h){if(h.length!==4)throw new Error("ipaddr: ipv4 octet count should be 4");let f,g;for(f=0;f<h.length;f++)if(g=h[f],!(0<=g&&g<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=h;}return p.prototype.SpecialRanges={unspecified:[[new p([0,0,0,0]),8]],broadcast:[[new p([255,255,255,255]),32]],multicast:[[new p([224,0,0,0]),4]],linkLocal:[[new p([169,254,0,0]),16]],loopback:[[new p([127,0,0,0]),8]],carrierGradeNat:[[new p([100,64,0,0]),10]],private:[[new p([10,0,0,0]),8],[new p([172,16,0,0]),12],[new p([192,168,0,0]),16]],reserved:[[new p([192,0,0,0]),24],[new p([192,0,2,0]),24],[new p([192,88,99,0]),24],[new p([198,18,0,0]),15],[new p([198,51,100,0]),24],[new p([203,0,113,0]),24],[new p([240,0,0,0]),4]],as112:[[new p([192,175,48,0]),24],[new p([192,31,196,0]),24]],amt:[[new p([192,52,193,0]),24]]},p.prototype.kind=function(){return "ipv4"},p.prototype.match=function(h,f){let g;if(f===void 0&&(g=h,h=g[0],f=g[1]),h.kind()!=="ipv4")throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return l(this.octets,h.octets,8,f)},p.prototype.prefixLengthFromSubnetMask=function(){let h=0,f=false,g={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},y,_,v;for(y=3;y>=0;y-=1)if(_=this.octets[y],_ in g){if(v=g[_],f&&v!==0)return null;v!==8&&(f=true),h+=v;}else return null;return 32-h},p.prototype.range=function(){return m.subnetMatch(this,this.SpecialRanges)},p.prototype.toByteArray=function(){return this.octets.slice(0)},p.prototype.toIPv4MappedAddress=function(){return m.IPv6.parse(`::ffff:${this.toString()}`)},p.prototype.toNormalizedString=function(){return this.toString()},p.prototype.toString=function(){return this.octets.join(".")},p})(),m.IPv4.broadcastAddressFromCIDR=function(p){try{let h=this.parseCIDR(p),f=h[0].toByteArray(),g=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),y=[],_=0;for(;_<4;)y.push(parseInt(f[_],10)|parseInt(g[_],10)^255),_++;return new this(y)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},m.IPv4.isIPv4=function(p){return this.parser(p)!==null},m.IPv4.isValid=function(p){try{return new this(this.parser(p)),!0}catch{return false}},m.IPv4.isValidCIDR=function(p){try{return this.parseCIDR(p),!0}catch{return false}},m.IPv4.isValidFourPartDecimal=function(p){return !!(m.IPv4.isValid(p)&&p.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},m.IPv4.isValidCIDRFourPartDecimal=function(p){let h=p.match(/^(.+)\/(\d+)$/);return !m.IPv4.isValidCIDR(p)||!h?false:m.IPv4.isValidFourPartDecimal(h[1])},m.IPv4.networkAddressFromCIDR=function(p){let h,f,g,y,_;try{for(h=this.parseCIDR(p),g=h[0].toByteArray(),_=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),y=[],f=0;f<4;)y.push(parseInt(g[f],10)&parseInt(_[f],10)),f++;return new this(y)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},m.IPv4.parse=function(p){let h=this.parser(p);if(h===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(h)},m.IPv4.parseCIDR=function(p){let h;if(h=p.match(/^(.+)\/(\d+)$/)){let f=parseInt(h[2]);if(f>=0&&f<=32){let g=[this.parse(h[1]),f];return Object.defineProperty(g,"toString",{value:function(){return this.join("/")}}),g}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},m.IPv4.parser=function(p){let h,f,g;if(h=p.match(r.fourOctet))return (function(){let y=h.slice(1,6),_=[];for(let v=0;v<y.length;v++)f=y[v],_.push(u(f));return _})();if(h=p.match(r.longValue)){if(g=u(h[1]),g>4294967295||g<0)throw new Error("ipaddr: address outside defined range");return (function(){let y=[],_;for(_=0;_<=24;_+=8)y.push(g>>_&255);return y})().reverse()}else return (h=p.match(r.twoOctet))?(function(){let y=h.slice(1,4),_=[];if(g=u(y[1]),g>16777215||g<0)throw new Error("ipaddr: address outside defined range");return _.push(u(y[0])),_.push(g>>16&255),_.push(g>>8&255),_.push(g&255),_})():(h=p.match(r.threeOctet))?(function(){let y=h.slice(1,5),_=[];if(g=u(y[2]),g>65535||g<0)throw new Error("ipaddr: address outside defined range");return _.push(u(y[0])),_.push(u(y[1])),_.push(g>>8&255),_.push(g&255),_})():null},m.IPv4.subnetMaskFromPrefixLength=function(p){if(p=parseInt(p),p<0||p>32)throw new Error("ipaddr: invalid IPv4 prefix length");let h=[0,0,0,0],f=0,g=Math.floor(p/8);for(;f<g;)h[f]=255,f++;return g<4&&(h[g]=Math.pow(2,p%8)-1<<8-p%8),new this(h)},m.IPv6=(function(){function p(h,f){let g,y;if(h.length===16)for(this.parts=[],g=0;g<=14;g+=2)this.parts.push(h[g]<<8|h[g+1]);else if(h.length===8)this.parts=h;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(g=0;g<this.parts.length;g++)if(y=this.parts[g],!(0<=y&&y<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");f&&(this.zoneId=f);}return p.prototype.SpecialRanges={unspecified:[new p([0,0,0,0,0,0,0,0]),128],linkLocal:[new p([65152,0,0,0,0,0,0,0]),10],multicast:[new p([65280,0,0,0,0,0,0,0]),8],loopback:[new p([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new p([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new p([0,0,0,0,0,65535,0,0]),96],deprecatedSiteLocal:[new p([65216,0,0,0,0,0,0,0]),10],discard:[new p([256,0,0,0,0,0,0,0]),64],rfc6145:[new p([0,0,0,0,65535,0,0,0]),96],rfc6052:[[new p([100,65435,0,0,0,0,0,0]),96],[new p([100,65435,1,0,0,0,0,0]),48]],"6to4":[new p([8194,0,0,0,0,0,0,0]),16],teredo:[new p([8193,0,0,0,0,0,0,0]),32],benchmarking:[new p([8193,2,0,0,0,0,0,0]),48],amt:[new p([8193,3,0,0,0,0,0,0]),32],as112v6:[[new p([8193,4,274,0,0,0,0,0]),48],[new p([9760,79,32768,0,0,0,0,0]),48]],deprecatedOrchid:[new p([8193,16,0,0,0,0,0,0]),28],orchid2:[new p([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new p([8193,48,0,0,0,0,0,0]),28],segmentRouting:[new p([24320,0,0,0,0,0,0,0]),16],reserved:[[new p([8193,0,0,0,0,0,0,0]),23],[new p([8193,3512,0,0,0,0,0,0]),32],[new p([16383,0,0,0,0,0,0,0]),20]]},p.prototype.isIPv4MappedAddress=function(){return this.range()==="ipv4Mapped"},p.prototype.kind=function(){return "ipv6"},p.prototype.match=function(h,f){let g;if(f===void 0&&(g=h,h=g[0],f=g[1]),h.kind()!=="ipv6")throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return l(this.parts,h.parts,16,f)},p.prototype.prefixLengthFromSubnetMask=function(){let h=0,f=false,g={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},y,_;for(let v=7;v>=0;v-=1)if(y=this.parts[v],y in g){if(_=g[y],f&&_!==0)return null;_!==16&&(f=true),h+=_;}else return null;return 128-h},p.prototype.range=function(){return m.subnetMatch(this,this.SpecialRanges)},p.prototype.toByteArray=function(){let h,f=[],g=this.parts;for(let y=0;y<g.length;y++)h=g[y],f.push(h>>8),f.push(h&255);return f},p.prototype.toFixedLengthString=function(){let h=(function(){let g=[];for(let y=0;y<this.parts.length;y++)g.push(d(this.parts[y].toString(16),4));return g}).call(this).join(":"),f="";return this.zoneId&&(f=`%${this.zoneId}`),h+f},p.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");let h=this.parts.slice(-2),f=h[0],g=h[1];return new m.IPv4([f>>8,f&255,g>>8,g&255])},p.prototype.toNormalizedString=function(){let h=(function(){let g=[];for(let y=0;y<this.parts.length;y++)g.push(this.parts[y].toString(16));return g}).call(this).join(":"),f="";return this.zoneId&&(f=`%${this.zoneId}`),h+f},p.prototype.toRFC5952String=function(){let h=/((^|:)(0(:|$)){2,})/g,f=this.toNormalizedString(),g=0,y=-1,_;for(;_=h.exec(f);)_[0].length>y&&(g=_.index,y=_[0].length);return y<0?f:`${f.substring(0,g)}::${f.substring(g+y)}`},p.prototype.toString=function(){return this.toRFC5952String()},p})(),m.IPv6.broadcastAddressFromCIDR=function(p){try{let h=this.parseCIDR(p),f=h[0].toByteArray(),g=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),y=[],_=0;for(;_<16;)y.push(parseInt(f[_],10)|parseInt(g[_],10)^255),_++;return new this(y)}catch(h){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${h})`)}},m.IPv6.isIPv6=function(p){return this.parser(p)!==null},m.IPv6.isValid=function(p){if(typeof p=="string"&&p.indexOf(":")===-1)return false;try{let h=this.parser(p);return new this(h.parts,h.zoneId),!0}catch{return false}},m.IPv6.isValidCIDR=function(p){if(typeof p=="string"&&p.indexOf(":")===-1)return false;try{return this.parseCIDR(p),!0}catch{return false}},m.IPv6.networkAddressFromCIDR=function(p){let h,f,g,y,_;try{for(h=this.parseCIDR(p),g=h[0].toByteArray(),_=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),y=[],f=0;f<16;)y.push(parseInt(g[f],10)&parseInt(_[f],10)),f++;return new this(y)}catch(v){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${v})`)}},m.IPv6.parse=function(p){let h=this.parser(p);if(h.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(h.parts,h.zoneId)},m.IPv6.parseCIDR=function(p){let h,f,g;if((f=p.match(/^(.+)\/(\d+)$/))&&(h=parseInt(f[2]),h>=0&&h<=128))return g=[this.parse(f[1]),h],Object.defineProperty(g,"toString",{value:function(){return this.join("/")}}),g;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},m.IPv6.parser=function(p){let h,f,g,y,_,v;if(g=p.match(a.deprecatedTransitional))return this.parser(`::ffff:${g[1]}`);if(a.native.test(p))return c(p,8);if((g=p.match(a.transitional))&&(v=g[6]||"",h=g[1],g[1].endsWith("::")||(h=h.slice(0,-1)),h=c(h+v,6),h.parts)){for(_=[parseInt(g[2]),parseInt(g[3]),parseInt(g[4]),parseInt(g[5])],f=0;f<_.length;f++)if(y=_[f],!(0<=y&&y<=255))return null;return h.parts.push(_[0]<<8|_[1]),h.parts.push(_[2]<<8|_[3]),{parts:h.parts,zoneId:h.zoneId}}return null},m.IPv6.subnetMaskFromPrefixLength=function(p){if(p=parseInt(p),p<0||p>128)throw new Error("ipaddr: invalid IPv6 prefix length");let h=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],f=0,g=Math.floor(p/8);for(;f<g;)h[f]=255,f++;return g<16&&(h[g]=Math.pow(2,p%8)-1<<8-p%8),new this(h)},m.fromByteArray=function(p){let h=p.length;if(h===4)return new m.IPv4(p);if(h===16)return new m.IPv6(p);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},m.isValid=function(p){return m.IPv6.isValid(p)||m.IPv4.isValid(p)},m.isValidCIDR=function(p){return m.IPv6.isValidCIDR(p)||m.IPv4.isValidCIDR(p)},m.parse=function(p){if(m.IPv6.isValid(p))return m.IPv6.parse(p);if(m.IPv4.isValid(p))return m.IPv4.parse(p);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},m.parseCIDR=function(p){try{return m.IPv6.parseCIDR(p)}catch{try{return m.IPv4.parseCIDR(p)}catch{throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},m.process=function(p){let h=this.parse(p);return h.kind()==="ipv6"&&h.isIPv4MappedAddress()?h.toIPv4Address():h},m.subnetMatch=function(p,h,f){let g,y,_,v;f==null&&(f="unicast");for(y in h)if(Object.prototype.hasOwnProperty.call(h,y)){for(_=h[y],_[0]&&!(_[0]instanceof Array)&&(_=[_]),g=0;g<_.length;g++)if(v=_[g],p.kind()===v[0].kind()&&p.match.apply(p,v))return y}return f},typeof zh<"u"&&zh.exports?zh.exports=m:e.ipaddr=m;})(nL);});var lL=c((EUe,Oa)=>{Oa.exports=bv;Oa.exports.default=bv;Oa.exports.proxyaddr=bv;Oa.exports.all=aL;Oa.exports.compile=cL;var Sre=rL(),oL=iL(),bre=/^\d+$/u,Vh=oL.isValid,Wh=oL.parse,sL={linklocal:["169.254.0.0/16","fe80::/10"],loopback:["127.0.0.1/8","::1/128"],uniquelocal:["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","fc00::/7"]};function aL(e,t){let r=Sre(e);if(!t)return r;typeof t!="function"&&(t=cL(t));for(let n=0;n<r.length-1;n++)t(r[n],n)||(r.length=n+1);return r}function cL(e){if(!e)throw new TypeError("argument is required");let t;if(typeof e=="string")t=[e];else if(Array.isArray(e))t=e.slice();else throw new TypeError("unsupported trust argument");for(let r=0;r<t.length;r++)e=t[r],Object.hasOwn(sL,e)&&(e=sL[e],t.splice.apply(t,[r,1].concat(e)),r+=e.length-1);return Tre(Ere(t))}function Ere(e){let t=new Array(e.length);for(let r=0;r<e.length;r++)t[r]=Rre(e[r]);return t}function Tre(e){let t=e.length;return t===0?kre:t===1?Are(e[0]):xre(e)}function Rre(e){let t=e.lastIndexOf("/"),r=t!==-1?e.substring(0,t):e;if(!Vh(r))throw new TypeError("invalid IP address: "+r);let n=Wh(r);t===-1&&n.kind()==="ipv6"&&n.isIPv4MappedAddress()&&(n=n.toIPv4Address());let i=n.kind()==="ipv6"?128:32,s=t!==-1?e.substring(t+1,e.length):null;if(s===null?s=i:bre.test(s)?s=parseInt(s,10):n.kind()==="ipv4"&&Vh(s)?s=Pre(s):s=null,s<=0||s>i)throw new TypeError("invalid range on address: "+e);return [n,s]}function Pre(e){let t=Wh(e);return t.kind()==="ipv4"?t.prefixLengthFromSubnetMask():null}function bv(e,t){if(!e)throw new TypeError("req argument is required");if(!t)throw new TypeError("trust argument is required");let r=aL(e,t);return r[r.length-1]}function kre(){return false}function xre(e){return function(r){if(!Vh(r))return false;let n=Wh(r),i,s=n.kind();for(let o=0;o<e.length;o++){let a=e[o],c=a[0],l=c.kind(),u=a[1],d=n;if(s!==l){let m=l==="ipv4";if(m&&!n.isIPv4MappedAddress())continue;i||(i=m?n.toIPv4Address():n.toIPv4MappedAddress()),d=i;}if(d.match(c,u))return true}return false}}function Are(e){let t=e[0],r=t.kind(),n=r==="ipv4",i=e[1];return function(o){if(!Vh(o))return false;let a=Wh(o);if(a.kind()!==r){if(n&&!a.isIPv4MappedAddress())return false;a=n?a.toIPv4Address():a.toIPv4MappedAddress();}return a.match(t,i)}}});var Qh=c((TUe,Pv)=>{var Kh=lL(),{kHasBeenDecorated:Ire,kSchemaBody:Ore,kSchemaHeaders:Cre,kSchemaParams:Nre,kSchemaQuerystring:uL,kSchemaController:Ev,kOptions:jre,kRequestCacheValidateFns:cs,kRequestContentType:Tv,kRouteContext:sr,kRequestOriginalUrl:Rv,kRequestSignal:dL,kOnAbort:Lre}=St(),{FST_ERR_REQ_INVALID_VALIDATION_INVOCATION:Dre,FST_ERR_DEC_UNDECLARED:Mre}=Ut(),fL=Ul(),Fre=Ta(),hL={body:Ore,headers:Cre,params:Nre,querystring:uL,query:uL};function Yh(e,t,r,n,i,s){this.id=e,this[sr]=s,this.params=t,this.raw=r,this.query=n,this.log=i,this.body=void 0;}Yh.props=[];Yh.instanceProperties=new Set(["id","params","raw","query","log","body"]);function $re(e){if(typeof e=="function")return e;if(e===true)return function(){return true};if(typeof e=="number")return function(){return false};if(typeof e=="string"){let t=e.split(",").map(r=>r.trim());return Kh.compile(t)}return Kh.compile(e)}function qre(e,t){return t?Ure(e,t):gL(e)}function gL(e){let t=e.props.slice();function r(n,i,s,o,a,c){this.id=n,this[sr]=c,this.params=i,this.raw=s,this.query=o,this.log=a,this.body=void 0;let l;for(let u=0;u<t.length;u++)l=t[u],this[l.key]=l.value;}return Object.setPrototypeOf(r.prototype,e.prototype),Object.setPrototypeOf(r,e),r.props=t,r.parent=e,r}function pL(e){let t=e.lastIndexOf(",");return t===-1?e.trim():e.slice(t+1).trim()}function Ure(e,t){let r=gL(e),n=$re(t);return r[Ire]=true,Object.defineProperties(r.prototype,{ip:{get(){let i=Kh.all(this.raw,n);return i[i.length-1]}},ips:{get(){return Kh.all(this.raw,n)}},host:{get(){let i=this.raw.socket;return this.headers["x-forwarded-host"]&&i!=null&&n(i.remoteAddress,0)?pL(this.headers["x-forwarded-host"]):this.headers.host??this.headers[":authority"]??""}},protocol:{get(){let i=this.raw.socket;if(this.headers["x-forwarded-proto"]&&i!=null&&n(i.remoteAddress,0))return pL(this.headers["x-forwarded-proto"]);if(this.socket)return this.socket.encrypted?"https":"http"}}}),r}function mL(e,t){if(!fL.hasKey(e,t)&&!fL.exist(e,t))throw new Mre(t,"request")}Object.defineProperties(Yh.prototype,{server:{get(){return this[sr].server}},url:{get(){return this.raw.url}},originalUrl:{get(){return this[Rv]||(this[Rv]=this.raw.originalUrl||this.raw.url),this[Rv]}},method:{get(){return this.raw.method}},routeOptions:{get(){let e=this[sr],t=e._parserOptions.limit,r=e.server.initialConfig.bodyLimit,n=e.server.hasConstraintStrategy("version")?this.raw.headers["accept-version"]:void 0;return {method:e.config?.method,url:e.config?.url,bodyLimit:t||r,handlerTimeout:e.handlerTimeout,attachValidation:e.attachValidation,logLevel:e.logLevel,exposeHeadRoute:e.exposeHeadRoute,prefixTrailingSlash:e.prefixTrailingSlash,handler:e.handler,config:e.config,schema:e.schema,version:n}}},is404:{get(){return this[sr].config?.url===void 0}},socket:{get(){return this.raw.socket}},signal:{get(){let e=this[dL];if(e)return e.signal;e=new AbortController,this[dL]=e;let t=()=>{e.signal.aborted||e.abort();};return this.raw.on("close",t),this[Lre]=t,e.signal}},ip:{get(){if(this.socket)return this.socket.remoteAddress}},host:{get(){return this.raw.headers.host??this.raw.headers[":authority"]??""}},hostname:{get(){return this.host[0]==="["?this.host.slice(0,this.host.indexOf("]")+1):this.host.split(":",1)[0]}},port:{get(){let t=/(?<port>:\d+)$/.exec(this.host);return t===null||t[1]===void 0?null:parseInt(t.groups.port.slice(1),10)}},protocol:{get(){if(this.socket)return this.socket.encrypted?"https":"http"}},headers:{get(){return this.additionalHeaders?Object.assign({},this.raw.headers,this.additionalHeaders):this.raw.headers},set(e){this.additionalHeaders=e;}},mediaType:{get(){return !this[Tv]&&this.headers["content-type"]!==void 0&&(this[Tv]=Fre.from(this.headers["content-type"])),this[Tv]?.mediaType}},getValidationFunction:{value:function(e){if(typeof e=="string"){let t=hL[e];return this[sr][t]}else if(typeof e=="object")return this[sr][cs]?.get(e)}},compileValidationSchema:{value:function(e,t=null){let{method:r,url:n}=this;if(this[sr][cs]?.has(e))return this[sr][cs].get(e);let s=(this[sr].validatorCompiler||this.server[Ev].validatorCompiler||this.server[Ev].setupValidator(this.server[jre])||this.server[Ev].validatorCompiler)({schema:e,method:r,url:n,httpPart:t});return this[sr][cs]==null&&(this[sr][cs]=new WeakMap),this[sr][cs].set(e,s),s}},validateInput:{value:function(e,t,r){r=typeof t=="string"?t:r;let n=r!=null&&typeof r=="string"&&hL[r],i;if(n&&(i=this[sr][n]),i==null&&(t==null||typeof t!="object"||Array.isArray(t)))throw new Dre(r);return i==null&&(this[sr][cs]?.has(t)?i=this[sr][cs].get(t):i=this.compileValidationSchema(t,r)),i(e)}},getDecorator:{value:function(e){mL(this,e);let t=this[e];return typeof t=="function"?t.bind(this):t}},setDecorator:{value:function(e,t){mL(this,e),this[e]=t;}}});Pv.exports=Yh;Pv.exports.buildRequest=qre;});var Jh=c((RUe,yL)=>{var{kFourOhFourContext:Bre,kReplySerializerDefault:Hre,kSchemaErrorFormatter:Gre,kErrorHandler:zre,kChildLoggerFactory:Vre,kReply:Wre,kRequest:Kre,kBodyLimit:Yre,kLogLevel:Qre,kContentTypeParser:Jre,kRouteByFastify:Xre,kRequestCacheValidateFns:Zre,kReplyCacheSerializeFns:ene,kHandlerTimeout:tne}=St();function rne({schema:e,handler:t,config:r,childLoggerFactory:n,errorHandler:i,bodyLimit:s,logLevel:o,logSerializers:a,attachValidation:c,validatorCompiler:l,serializerCompiler:u,replySerializer:d,schemaErrorFormatter:m,exposeHeadRoute:p,prefixTrailingSlash:h,server:f,isFastify:g,handlerTimeout:y}){this.schema=e,this.handler=t,this.Reply=f[Wre],this.Request=f[Kre],this.contentTypeParser=f[Jre],this.onRequest=null,this.onSend=null,this.onError=null,this.onTimeout=null,this.preHandler=null,this.onResponse=null,this.preSerialization=null,this.onRequestAbort=null,this.config=r,this.errorHandler=i||f[zre],this.childLoggerFactory=n||f[Vre],this._middie=null,this._parserOptions={limit:s||f[Yre]},this.exposeHeadRoute=p,this.prefixTrailingSlash=h,this.logLevel=o||f[Qre],this.logSerializers=a,this[Bre]=null,this.attachValidation=c,this[Hre]=d,this.schemaErrorFormatter=m||f[Gre]||nne,this[Xre]=g,this[Zre]=null,this[ene]=null,this.validatorCompiler=l||null,this.serializerCompiler=u||null,this.handlerTimeout=y||f[tne]||0,this.server=f;}function nne(e,t){let r="";for(let i=0;i!==e.length;++i){let s=e[i];r+=t+(s.instancePath||"")+" "+s.message+", ";}return new Error(r.slice(0,-2))}yL.exports=rne;});var xv=c((PUe,Ca)=>{var ine=typeof Buffer<"u",wL=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,vL=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function _L(e,t,r){r==null&&t!==null&&typeof t=="object"&&(r=t,t=void 0),ine&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let n=JSON.parse(e,t);if(n===null||typeof n!="object")return n;let i=r&&r.protoAction||"error",s=r&&r.constructorAction||"error";if(i==="ignore"&&s==="ignore")return n;if(i!=="ignore"&&s!=="ignore"){if(wL.test(e)===false&&vL.test(e)===false)return n}else if(i!=="ignore"&&s==="ignore"){if(wL.test(e)===false)return n}else if(vL.test(e)===false)return n;return SL(n,{protoAction:i,constructorAction:s,safe:r&&r.safe})}function SL(e,{protoAction:t="error",constructorAction:r="error",safe:n}={}){let i=[e];for(;i.length;){let s=i;i=[];for(let o of s){if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(o,"__proto__")){if(n===true)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete o.__proto__;}if(r!=="ignore"&&Object.prototype.hasOwnProperty.call(o,"constructor")&&o.constructor!==null&&typeof o.constructor=="object"&&Object.prototype.hasOwnProperty.call(o.constructor,"prototype")){if(n===true)return null;if(r==="error")throw new SyntaxError("Object contains forbidden prototype property");delete o.constructor;}for(let a in o){let c=o[a];c&&typeof c=="object"&&i.push(c);}}}return e}function kv(e,t,r){let{stackTraceLimit:n}=Error;Error.stackTraceLimit=0;try{return _L(e,t,r)}finally{Error.stackTraceLimit=n;}}function sne(e,t){let{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return _L(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=r;}}Ca.exports=kv;Ca.exports.default=kv;Ca.exports.parse=kv;Ca.exports.safeParse=sne;Ca.exports.scan=SL;});var Nv=c((kUe,zl)=>{var{AsyncResource:one}=a("async_hooks"),{FifoMap:TL}=Qw(),{parse:ane}=xv(),Gl=Ta(),{kDefaultJsonParse:Hl,kContentTypeParser:Na,kBodyLimit:cne,kRequestPayloadStream:RL,kState:Iv,kTestInternals:lne,kReplyIsError:bL,kRouteContext:une}=St(),{FST_ERR_CTP_INVALID_TYPE:Xh,FST_ERR_CTP_EMPTY_TYPE:dne,FST_ERR_CTP_ALREADY_PRESENT:fne,FST_ERR_CTP_INVALID_HANDLER:hne,FST_ERR_CTP_INVALID_PARSE_TYPE:pne,FST_ERR_CTP_BODY_TOO_LARGE:EL,FST_ERR_CTP_INVALID_MEDIA_TYPE:mne,FST_ERR_CTP_INVALID_CONTENT_LENGTH:gne,FST_ERR_CTP_EMPTY_JSON_BODY:yne,FST_ERR_CTP_INSTANCE_ALREADY_STARTED:Ov,FST_ERR_CTP_INVALID_JSON_BODY:wne}=Ut(),{FSTSEC001:vne}=ba();function Si(e,t,r){this[Hl]=kL(t,r),this.customParsers=new Map,this.customParsers.set("application/json",new Av(true,false,e,this[Hl])),this.customParsers.set("text/plain",new Av(true,false,e,Cv)),this.parserList=["application/json","text/plain"],this.parserRegExpList=[],this.cache=new TL(100);}Si.prototype.add=function(e,t,r){let n=typeof e=="string";if(n){if(e=e.trim().toLowerCase(),e.length===0)throw new dne}else if(!(e instanceof RegExp))throw new Xh;if(typeof r!="function")throw new hne;if(this.existingParser(e))throw new fne(e);if(t.parseAs!==void 0&&t.parseAs!=="string"&&t.parseAs!=="buffer")throw new pne(t.parseAs);let i=new Av(t.parseAs==="string",t.parseAs==="buffer",t.bodyLimit,r);if(e==="*")this.customParsers.set("",i);else if(n){let s=new Gl(e);if(s.isValid===false)throw new Xh;let o=s.toString();this.parserList.unshift(o),this.customParsers.set(o,i);}else Rne(e),this.parserRegExpList.unshift(e),this.customParsers.set(e.toString(),i);};Si.prototype.hasParser=function(e){if(typeof e=="string")e=new Gl(e).toString();else {if(!(e instanceof RegExp))throw new Xh;e=e.toString();}return this.customParsers.has(e)};Si.prototype.existingParser=function(e){if(typeof e=="string"){let t=new Gl(e).toString();if(e==="application/json"&&this.customParsers.has(e))return this.customParsers.get(t).fn!==this[Hl];if(e==="text/plain"&&this.customParsers.has(e))return this.customParsers.get(t).fn!==Cv}return this.hasParser(e)};Si.prototype.getParser=function(e){if(typeof e=="string"){let n=this.cache.get(e);if(n!==void 0)return n;e=new Gl(e);}let t=e.toString(),r=this.cache.get(t);if(r!==void 0)return r;if(r=this.customParsers.get(t),r!==void 0)return this.cache.set(t,r),r;if(r=this.customParsers.get(e.mediaType),r!==void 0)return this.cache.set(t,r),r;for(let n=0;n!==this.parserRegExpList.length;++n){let i=this.parserRegExpList[n];if(i.lastIndex=0,i.test(t))return r=this.customParsers.get(i.toString()),this.cache.set(t,r),r}return this.customParsers.get("")};Si.prototype.removeAll=function(){this.customParsers=new Map,this.parserRegExpList=[],this.parserList=[],this.cache=new TL(100);};Si.prototype.remove=function(e){let t;if(typeof e=="string")e=new Gl(e).toString(),t=this.parserList;else {if(!(e instanceof RegExp))throw new Xh;e=e.toString(),t=this.parserRegExpList;}let r=this.customParsers.delete(e),n=t.findIndex(i=>i.toString()===e);return n>-1&&t.splice(n,1),r||n>-1};Si.prototype.run=function(e,t,r,n){let i=this.getParser(e);if(i===void 0){if(r.is404===true){t(r,n);return}n[bL]=true,n.send(new mne);return}let s=new one("content-type-parser:run",r);function o(l,u){s.runInAsyncScope(c,void 0,l,u);}if(i.asString===true||i.asBuffer===true){PL(r,n,n[une]._parserOptions,i,o);return}let a=i.fn(r,r[RL],o);a&&typeof a.then=="function"&&a.then(l=>{o(null,l);},o);function c(l,u){if(s.emitDestroy(),l!=null){n.header("connection","close"),n[bL]=true,n.send(l);return}r.body=u,t(r,n);}};function PL(e,t,r,n,i){let s=n.asString===true,o=r.limit===null?n.bodyLimit:r.limit,a=Number(e.headers["content-length"]);if(a>o){i(new EL,void 0);return}let c=0,l=s?"":[],u=e[RL]||e.raw;s&&u.setEncoding("utf8"),u.on("data",d),u.on("end",m),u.on("error",m),u.resume();function d(p){c+=s?Buffer.byteLength(p):p.length;let{receivedEncodedLength:h=0}=u;if(c>o||h>o){u.removeListener("data",d),u.removeListener("end",m),u.removeListener("error",m),i(new EL,void 0);return}s?l+=p:l.push(p);}function m(p){if(u.removeListener("data",d),u.removeListener("end",m),u.removeListener("error",m),p!=null){typeof p.statusCode=="number"&&p.statusCode>=400||(p.statusCode=400),i(p,void 0);return}if(!Number.isNaN(a)&&(u.receivedEncodedLength||c)!==a){i(new gne,void 0);return}s||(l=Buffer.concat(l));let h=n.fn(e,l,i);h&&typeof h.then=="function"&&h.then(f=>{i(null,f);},i);}}function kL(e,t){let r={protoAction:e,constructorAction:t};return n;function n(i,s,o){if(s.length===0){o(new yne,void 0);return}try{o(null,ane(s,r));}catch{o(new wne,void 0);}}}function Cv(e,t,r){r(null,t);}function Av(e,t,r,n){this.asString=e,this.asBuffer=t,this.bodyLimit=r,this.fn=n;}function _ne(e){let t=new Si;return t[Hl]=e[Hl],t.customParsers=new Map(e.customParsers.entries()),t.parserList=e.parserList.slice(),t.parserRegExpList=e.parserRegExpList.slice(),t}function Sne(e,t,r){if(this[Iv].started)throw new Ov("addContentTypeParser");return typeof t=="function"&&(r=t,t={}),t||(t={}),t.bodyLimit||(t.bodyLimit=this[cne]),Array.isArray(e)?e.forEach(n=>this[Na].add(n,t,r)):this[Na].add(e,t,r),this}function bne(e){return this[Na].hasParser(e)}function Ene(e){if(this[Iv].started)throw new Ov("removeContentTypeParser");if(Array.isArray(e))for(let t of e)this[Na].remove(t);else this[Na].remove(e);}function Tne(){if(this[Iv].started)throw new Ov("removeAllContentTypeParsers");this[Na].removeAll();}function Rne(e){e.source[0]!=="^"&&e.source.includes(";?")===false&&vne(e.source);}zl.exports=Si;zl.exports.helpers={buildContentTypeParser:_ne,addContentTypeParser:Sne,hasContentTypeParser:bne,removeContentTypeParser:Ene,removeAllContentTypeParsers:Tne};zl.exports.defaultParsers={getDefaultJsonParser:kL,defaultTextParser:Cv};zl.exports[lne]={rawBody:PL};});var ja=c(We=>{Object.defineProperty(We,"__esModule",{value:true});We.regexpCode=We.getEsmExportName=We.getProperty=We.safeStringify=We.stringify=We.strConcat=We.addCodeArg=We.str=We._=We.nil=We._Code=We.Name=We.IDENTIFIER=We._CodeOrName=void 0;var Vl=class{};We._CodeOrName=Vl;We.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var co=class extends Vl{constructor(t){if(super(),!We.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t;}toString(){return this.str}emptyStr(){return false}get names(){return {[this.str]:1}}};We.Name=co;var Jr=class extends Vl{constructor(t){super(),this._items=typeof t=="string"?[t]:t;}toString(){return this.str}emptyStr(){if(this._items.length>1)return false;let t=this._items[0];return t===""||t==='""'}get str(){var t;return (t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return (t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof co&&(r[n.str]=(r[n.str]||0)+1),r),{})}};We._Code=Jr;We.nil=new Jr("");function xL(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Lv(r,t[n]),r.push(e[++n]);return new Jr(r)}We._=xL;var jv=new Jr("+");function AL(e,...t){let r=[Wl(e[0])],n=0;for(;n<t.length;)r.push(jv),Lv(r,t[n]),r.push(jv,Wl(e[++n]));return Pne(r),new Jr(r)}We.str=AL;function Lv(e,t){t instanceof Jr?e.push(...t._items):t instanceof co?e.push(t):e.push(Ane(t));}We.addCodeArg=Lv;function Pne(e){let t=1;for(;t<e.length-1;){if(e[t]===jv){let r=kne(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+";}t++;}}function kne(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof co||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof co))return `"${e}${t.slice(1)}`}function xne(e,t){return t.emptyStr()?e:e.emptyStr()?t:AL`${e}${t}`}We.strConcat=xne;function Ane(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Wl(Array.isArray(e)?e.join(","):e)}function Ine(e){return new Jr(Wl(e))}We.stringify=Ine;function Wl(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}We.safeStringify=Wl;function One(e){return typeof e=="string"&&We.IDENTIFIER.test(e)?new Jr(`.${e}`):xL`[${e}]`}We.getProperty=One;function Cne(e){if(typeof e=="string"&&We.IDENTIFIER.test(e))return new Jr(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}We.getEsmExportName=Cne;function Nne(e){return new Jr(e.toString())}We.regexpCode=Nne;});var rp=c(Ar=>{Object.defineProperty(Ar,"__esModule",{value:true});Ar.ValueScope=Ar.ValueScopeName=Ar.Scope=Ar.varKinds=Ar.UsedValueState=void 0;var xr=ja(),Dv=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value;}},Zh;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed";})(Zh||(Ar.UsedValueState=Zh={}));Ar.varKinds={const:new xr.Name("const"),let:new xr.Name("let"),var:new xr.Name("var")};var ep=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r;}toName(t){return t instanceof xr.Name?t:this.name(t)}name(t){return new xr.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return `${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Ar.Scope=ep;var tp=class extends xr.Name{constructor(t,r){super(r),this.prefix=t;}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0, xr._)`.${new xr.Name(r)}[${n}]`;}};Ar.ValueScopeName=tp;var jne=(0, xr._)`\n`,Mv=class extends ep{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?jne:xr.nil};}get(){return this._scope}name(t){return new tp(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(t),{prefix:s}=i,o=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let u=a.get(o);if(u)return u}else a=this._values[s]=new Map;a.set(o,i);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=r.ref,i.setValue(r,{property:s,itemIndex:l}),i}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return (0, xr._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(t,r,n={},i){let s=xr.nil;for(let o in t){let a=t[o];if(!a)continue;let c=n[o]=n[o]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Zh.Started);let u=r(l);if(u){let d=this.opts.es5?Ar.varKinds.var:Ar.varKinds.const;s=(0, xr._)`${s}${d} ${l} = ${u};${this.opts._n}`;}else if(u=i?.(l))s=(0, xr._)`${s}${u}${this.opts._n}`;else throw new Dv(l);c.set(l,Zh.Completed);});}return s}};Ar.ValueScope=Mv;});var ye=c(Oe=>{Object.defineProperty(Oe,"__esModule",{value:true});Oe.or=Oe.and=Oe.not=Oe.CodeGen=Oe.operators=Oe.varKinds=Oe.ValueScopeName=Oe.ValueScope=Oe.Scope=Oe.Name=Oe.regexpCode=Oe.stringify=Oe.getProperty=Oe.nil=Oe.strConcat=Oe.str=Oe._=void 0;var He=ja(),En=rp(),ls=ja();Object.defineProperty(Oe,"_",{enumerable:true,get:function(){return ls._}});Object.defineProperty(Oe,"str",{enumerable:true,get:function(){return ls.str}});Object.defineProperty(Oe,"strConcat",{enumerable:true,get:function(){return ls.strConcat}});Object.defineProperty(Oe,"nil",{enumerable:true,get:function(){return ls.nil}});Object.defineProperty(Oe,"getProperty",{enumerable:true,get:function(){return ls.getProperty}});Object.defineProperty(Oe,"stringify",{enumerable:true,get:function(){return ls.stringify}});Object.defineProperty(Oe,"regexpCode",{enumerable:true,get:function(){return ls.regexpCode}});Object.defineProperty(Oe,"Name",{enumerable:true,get:function(){return ls.Name}});var op=rp();Object.defineProperty(Oe,"Scope",{enumerable:true,get:function(){return op.Scope}});Object.defineProperty(Oe,"ValueScope",{enumerable:true,get:function(){return op.ValueScope}});Object.defineProperty(Oe,"ValueScopeName",{enumerable:true,get:function(){return op.ValueScopeName}});Object.defineProperty(Oe,"varKinds",{enumerable:true,get:function(){return op.varKinds}});Oe.operators={GT:new He._Code(">"),GTE:new He._Code(">="),LT:new He._Code("<"),LTE:new He._Code("<="),EQ:new He._Code("==="),NEQ:new He._Code("!=="),NOT:new He._Code("!"),OR:new He._Code("||"),AND:new He._Code("&&"),ADD:new He._Code("+")};var bi=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},Fv=class extends bi{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n;}render({es5:t,_n:r}){let n=t?En.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return `${n} ${this.name}${i};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Da(this.rhs,t,r)),this}get names(){return this.rhs instanceof He._CodeOrName?this.rhs.names:{}}},np=class extends bi{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n;}render({_n:t}){return `${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof He.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Da(this.rhs,t,r),this}get names(){let t=this.lhs instanceof He.Name?{}:{...this.lhs.names};return sp(t,this.rhs)}},$v=class extends np{constructor(t,r,n,i){super(t,n,i),this.op=r;}render({_n:t}){return `${this.lhs} ${this.op}= ${this.rhs};`+t}},qv=class extends bi{constructor(t){super(),this.label=t,this.names={};}render({_n:t}){return `${this.label}:`+t}},Uv=class extends bi{constructor(t){super(),this.label=t,this.names={};}render({_n:t}){return `break${this.label?` ${this.label}`:""};`+t}},Bv=class extends bi{constructor(t){super(),this.error=t;}render({_n:t}){return `throw ${this.error};`+t}get names(){return this.error.names}},Hv=class extends bi{constructor(t){super(),this.code=t;}render({_n:t}){return `${this.code};`+t}optimizeNodes(){return `${this.code}`?this:void 0}optimizeNames(t,r){return this.code=Da(this.code,t,r),this}get names(){return this.code instanceof He._CodeOrName?this.code.names:{}}},Kl=class extends bi{constructor(t=[]){super(),this.nodes=t;}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1);}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,i=n.length;for(;i--;){let s=n[i];s.optimizeNames(t,r)||(Lne(t,s.names),n.splice(i,1));}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>fo(t,r.names),{})}},Ei=class extends Kl{render(t){return "{"+t._n+super.render(t)+"}"+t._n}},Gv=class extends Kl{},La=class extends Ei{};La.kind="else";var lo=class e extends Ei{constructor(t,r){super(r),this.condition=t;}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===true)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new La(n):n;}if(r)return t===false?r instanceof e?r:r.nodes:this.nodes.length?this:new e(IL(t),r instanceof e?[r]:r.nodes);if(!(t===false||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=Da(this.condition,t,r),this}get names(){let t=super.names;return sp(t,this.condition),this.else&&fo(t,this.else.names),t}};lo.kind="if";var uo=class extends Ei{};uo.kind="for";var zv=class extends uo{constructor(t){super(),this.iteration=t;}render(t){return `for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=Da(this.iteration,t,r),this}get names(){return fo(super.names,this.iteration.names)}},Vv=class extends uo{constructor(t,r,n,i){super(),this.varKind=t,this.name=r,this.from=n,this.to=i;}render(t){let r=t.es5?En.varKinds.var:this.varKind,{name:n,from:i,to:s}=this;return `for(${r} ${n}=${i}; ${n}<${s}; ${n}++)`+super.render(t)}get names(){let t=sp(super.names,this.from);return sp(t,this.to)}},ip=class extends uo{constructor(t,r,n,i){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=i;}render(t){return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=Da(this.iterable,t,r),this}get names(){return fo(super.names,this.iterable.names)}},Yl=class extends Ei{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n;}render(t){return `${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};Yl.kind="func";var Ql=class extends Kl{render(t){return "return "+super.render(t)}};Ql.kind="return";var Wv=class extends Ei{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,i;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(i=this.finally)===null||i===void 0||i.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&fo(t,this.catch.names),this.finally&&fo(t,this.finally.names),t}},Jl=class extends Ei{constructor(t){super(),this.error=t;}render(t){return `catch(${this.error})`+super.render(t)}};Jl.kind="catch";var Xl=class extends Ei{render(t){return "finally"+super.render(t)}};Xl.kind="finally";var Kv=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
@@ -526,7 +526,7 @@ return fn.apply(this, arguments)
|
|
|
526
526
|
`+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
|
|
527
527
|
`)+`\r
|
|
528
528
|
\r
|
|
529
|
-
`+r);}function oa(e,t,r,n,i,s){if(e.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,oa),e.emit("wsClientError",o,r,t);}else jf(r,n,i,s);}});var u7=c((b7e,l7)=>{var xFe=ZQ(),AFe=M0(),IFe=al(),OFe=iA(),CFe=aA(),NFe=hA(),Un=U0(),c7=a7();Un.createWebSocketStream=xFe;Un.extension=AFe;Un.PerMessageDeflate=IFe;Un.Receiver=OFe;Un.Sender=CFe;Un.Server=c7;Un.subprotocol=NFe;Un.WebSocket=Un;Un.WebSocketServer=c7;l7.exports=Un;});var mA=c((E7e,d7)=>{d7.exports=a("stream");});var y7=c((T7e,g7)=>{function f7(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n);}return r}function h7(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?f7(Object(r),true).forEach(function(n){jFe(e,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):f7(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n));});}return e}function jFe(e,t,r){return t=m7(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:true,configurable:true,writable:true}):e[t]=r,e}function LFe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function p7(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||false,n.configurable=true,"value"in n&&(n.writable=true),Object.defineProperty(e,m7(n.key),n);}}function DFe(e,t,r){return t&&p7(e.prototype,t),Object.defineProperty(e,"prototype",{writable:false}),e}function m7(e){var t=MFe(e,"string");return typeof t=="symbol"?t:String(t)}function MFe(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (String)(e)}var FFe=a("buffer"),H0=FFe.Buffer,$Fe=a("util"),gA=$Fe.inspect,qFe=gA&&gA.custom||"inspect";function UFe(e,t,r){H0.prototype.copy.call(e,t,r);}g7.exports=(function(){function e(){LFe(this,e),this.head=null,this.tail=null,this.length=0;}return DFe(e,[{key:"push",value:function(r){var n={data:r,next:null};this.length>0?this.tail.next=n:this.head=n,this.tail=n,++this.length;}},{key:"unshift",value:function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length;}},{key:"shift",value:function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0;}},{key:"join",value:function(r){if(this.length===0)return "";for(var n=this.head,i=""+n.data;n=n.next;)i+=r+n.data;return i}},{key:"concat",value:function(r){if(this.length===0)return H0.alloc(0);for(var n=H0.allocUnsafe(r>>>0),i=this.head,s=0;i;)UFe(i.data,n,s),s+=i.data.length,i=i.next;return n}},{key:"consume",value:function(r,n){var i;return r<this.head.data.length?(i=this.head.data.slice(0,r),this.head.data=this.head.data.slice(r)):r===this.head.data.length?i=this.shift():i=n?this._getString(r):this._getBuffer(r),i}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(r){var n=this.head,i=1,s=n.data;for(r-=s.length;n=n.next;){var o=n.data,a=r>o.length?o.length:r;if(a===o.length?s+=o:s+=o.slice(0,r),r-=a,r===0){a===o.length?(++i,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=o.slice(a));break}++i;}return this.length-=i,s}},{key:"_getBuffer",value:function(r){var n=H0.allocUnsafe(r),i=this.head,s=1;for(i.data.copy(n),r-=i.data.length;i=i.next;){var o=i.data,a=r>o.length?o.length:r;if(o.copy(n,n.length-r,0,a),r-=a,r===0){a===o.length?(++s,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=o.slice(a));break}++s;}return this.length-=s,n}},{key:qFe,value:function(r,n){return gA(this,h7(h7({},n),{},{depth:0,customInspect:false}))}}]),e})();});var wA=c((R7e,v7)=>{function BFe(e,t){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=true,process.nextTick(yA,this,e)):process.nextTick(yA,this,e)),this):(this._readableState&&(this._readableState.destroyed=true),this._writableState&&(this._writableState.destroyed=true),this._destroy(e||null,function(s){!t&&s?r._writableState?r._writableState.errorEmitted?process.nextTick(G0,r):(r._writableState.errorEmitted=true,process.nextTick(w7,r,s)):process.nextTick(w7,r,s):t?(process.nextTick(G0,r),t(s)):process.nextTick(G0,r);}),this)}function w7(e,t){yA(e,t),G0(e);}function G0(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close");}function HFe(){this._readableState&&(this._readableState.destroyed=false,this._readableState.reading=false,this._readableState.ended=false,this._readableState.endEmitted=false),this._writableState&&(this._writableState.destroyed=false,this._writableState.ended=false,this._writableState.ending=false,this._writableState.finalCalled=false,this._writableState.prefinished=false,this._writableState.finished=false,this._writableState.errorEmitted=false);}function yA(e,t){e.emit("error",t);}function GFe(e,t){var r=e._readableState,n=e._writableState;r&&r.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t);}v7.exports={destroy:BFe,undestroy:HFe,errorOrDestroy:GFe};});var Qs=c((P7e,b7)=>{var S7={};function vn(e,t,r){r||(r=Error);function n(s,o,a){return typeof t=="string"?t:t(s,o,a)}class i extends r{constructor(o,a,c){super(n(o,a,c));}}i.prototype.name=r.name,i.prototype.code=e,S7[e]=i;}function _7(e,t){if(Array.isArray(e)){let r=e.length;return e=e.map(n=>String(n)),r>2?`one of ${t} ${e.slice(0,r-1).join(", ")}, or `+e[r-1]:r===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}else return `of ${t} ${String(e)}`}function zFe(e,t,r){return e.substr(0,t.length)===t}function VFe(e,t,r){return (r===void 0||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}function WFe(e,t,r){return typeof r!="number"&&(r=0),r+t.length>e.length?false:e.indexOf(t,r)!==-1}vn("ERR_INVALID_OPT_VALUE",function(e,t){return 'The value "'+t+'" is invalid for option "'+e+'"'},TypeError);vn("ERR_INVALID_ARG_TYPE",function(e,t,r){let n;typeof t=="string"&&zFe(t,"not ")?(n="must not be",t=t.replace(/^not /,"")):n="must be";let i;if(VFe(e," argument"))i=`The ${e} ${n} ${_7(t,"type")}`;else {let s=WFe(e,".")?"property":"argument";i=`The "${e}" ${s} ${n} ${_7(t,"type")}`;}return i+=`. Received type ${typeof r}`,i},TypeError);vn("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");vn("ERR_METHOD_NOT_IMPLEMENTED",function(e){return "The "+e+" method is not implemented"});vn("ERR_STREAM_PREMATURE_CLOSE","Premature close");vn("ERR_STREAM_DESTROYED",function(e){return "Cannot call "+e+" after a stream was destroyed"});vn("ERR_MULTIPLE_CALLBACK","Callback called multiple times");vn("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");vn("ERR_STREAM_WRITE_AFTER_END","write after end");vn("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);vn("ERR_UNKNOWN_ENCODING",function(e){return "Unknown encoding: "+e},TypeError);vn("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");b7.exports.codes=S7;});var vA=c((k7e,E7)=>{var KFe=Qs().codes.ERR_INVALID_OPT_VALUE;function YFe(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}function QFe(e,t,r,n){var i=YFe(t,n,r);if(i!=null){if(!(isFinite(i)&&Math.floor(i)===i)||i<0){var s=n?r:"highWaterMark";throw new KFe(s,i)}return Math.floor(i)}return e.objectMode?16:16*1024}E7.exports={getHighWaterMark:QFe};});var R7=c((x7e,T7)=>{T7.exports=a("util").deprecate;});var bA=c((A7e,O7)=>{O7.exports=Et;function k7(e){var t=this;this.next=null,this.entry=null,this.finish=function(){E$e(t,e);};}var hl;Et.WritableState=Df;var JFe={deprecate:R7()},x7=mA(),V0=a("buffer").Buffer,XFe=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function ZFe(e){return V0.from(e)}function e$e(e){return V0.isBuffer(e)||e instanceof XFe}var SA=wA(),t$e=vA(),r$e=t$e.getHighWaterMark,Js=Qs().codes,n$e=Js.ERR_INVALID_ARG_TYPE,i$e=Js.ERR_METHOD_NOT_IMPLEMENTED,s$e=Js.ERR_MULTIPLE_CALLBACK,o$e=Js.ERR_STREAM_CANNOT_PIPE,a$e=Js.ERR_STREAM_DESTROYED,c$e=Js.ERR_STREAM_NULL_VALUES,l$e=Js.ERR_STREAM_WRITE_AFTER_END,u$e=Js.ERR_UNKNOWN_ENCODING,pl=SA.errorOrDestroy;Ws()(Et,x7);function d$e(){}function Df(e,t,r){hl=hl||aa(),e=e||{},typeof r!="boolean"&&(r=t instanceof hl),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=r$e(this,e,"writableHighWaterMark",r),this.finalCalled=false,this.needDrain=false,this.ending=false,this.ended=false,this.finished=false,this.destroyed=false;var n=e.decodeStrings===false;this.decodeStrings=!n,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=false,this.corked=0,this.sync=true,this.bufferProcessing=false,this.onwrite=function(i){w$e(t,i);},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=false,this.errorEmitted=false,this.emitClose=e.emitClose!==false,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new k7(this);}Df.prototype.getBuffer=function(){for(var t=this.bufferedRequest,r=[];t;)r.push(t),t=t.next;return r};(function(){try{Object.defineProperty(Df.prototype,"buffer",{get:JFe.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")});}catch{}})();var z0;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(z0=Function.prototype[Symbol.hasInstance],Object.defineProperty(Et,Symbol.hasInstance,{value:function(t){return z0.call(this,t)?true:this!==Et?false:t&&t._writableState instanceof Df}})):z0=function(t){return t instanceof this};function Et(e){hl=hl||aa();var t=this instanceof hl;if(!t&&!z0.call(Et,this))return new Et(e);this._writableState=new Df(e,this,t),this.writable=true,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),x7.call(this);}Et.prototype.pipe=function(){pl(this,new o$e);};function f$e(e,t){var r=new l$e;pl(e,r),process.nextTick(t,r);}function h$e(e,t,r,n){var i;return r===null?i=new c$e:typeof r!="string"&&!t.objectMode&&(i=new n$e("chunk",["string","Buffer"],r)),i?(pl(e,i),process.nextTick(n,i),false):true}Et.prototype.write=function(e,t,r){var n=this._writableState,i=false,s=!n.objectMode&&e$e(e);return s&&!V0.isBuffer(e)&&(e=ZFe(e)),typeof t=="function"&&(r=t,t=null),s?t="buffer":t||(t=n.defaultEncoding),typeof r!="function"&&(r=d$e),n.ending?f$e(this,r):(s||h$e(this,n,e,r))&&(n.pendingcb++,i=m$e(this,n,s,e,t,r)),i};Et.prototype.cork=function(){this._writableState.corked++;};Et.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&A7(this,e));};Et.prototype.setDefaultEncoding=function(t){if(typeof t=="string"&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new u$e(t);return this._writableState.defaultEncoding=t,this};Object.defineProperty(Et.prototype,"writableBuffer",{enumerable:false,get:function(){return this._writableState&&this._writableState.getBuffer()}});function p$e(e,t,r){return !e.objectMode&&e.decodeStrings!==false&&typeof t=="string"&&(t=V0.from(t,r)),t}Object.defineProperty(Et.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function m$e(e,t,r,n,i,s){if(!r){var o=p$e(t,n,i);n!==o&&(r=true,i="buffer",n=o);}var a=t.objectMode?1:n.length;t.length+=a;var c=t.length<t.highWaterMark;if(c||(t.needDrain=true),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:i,isBuf:r,callback:s,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1;}else _A(e,t,false,a,n,i,s);return c}function _A(e,t,r,n,i,s,o){t.writelen=n,t.writecb=o,t.writing=true,t.sync=true,t.destroyed?t.onwrite(new a$e("write")):r?e._writev(i,t.onwrite):e._write(i,s,t.onwrite),t.sync=false;}function g$e(e,t,r,n,i){--t.pendingcb,r?(process.nextTick(i,n),process.nextTick(Lf,e,t),e._writableState.errorEmitted=true,pl(e,n)):(i(n),e._writableState.errorEmitted=true,pl(e,n),Lf(e,t));}function y$e(e){e.writing=false,e.writecb=null,e.length-=e.writelen,e.writelen=0;}function w$e(e,t){var r=e._writableState,n=r.sync,i=r.writecb;if(typeof i!="function")throw new s$e;if(y$e(r),t)g$e(e,r,n,t,i);else {var s=I7(r)||e.destroyed;!s&&!r.corked&&!r.bufferProcessing&&r.bufferedRequest&&A7(e,r),n?process.nextTick(P7,e,r,s,i):P7(e,r,s,i);}}function P7(e,t,r,n){r||v$e(e,t),t.pendingcb--,n(),Lf(e,t);}function v$e(e,t){t.length===0&&t.needDrain&&(t.needDrain=false,e.emit("drain"));}function A7(e,t){t.bufferProcessing=true;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,i=new Array(n),s=t.corkedRequestsFree;s.entry=r;for(var o=0,a=true;r;)i[o]=r,r.isBuf||(a=false),r=r.next,o+=1;i.allBuffers=a,_A(e,t,true,t.length,i,"",s.finish),t.pendingcb++,t.lastBufferedRequest=null,s.next?(t.corkedRequestsFree=s.next,s.next=null):t.corkedRequestsFree=new k7(t),t.bufferedRequestCount=0;}else {for(;r;){var c=r.chunk,l=r.encoding,u=r.callback,d=t.objectMode?1:c.length;if(_A(e,t,false,d,c,l,u),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null);}t.bufferedRequest=r,t.bufferProcessing=false;}Et.prototype._write=function(e,t,r){r(new i$e("_write()"));};Et.prototype._writev=null;Et.prototype.end=function(e,t,r){var n=this._writableState;return typeof e=="function"?(r=e,e=null,t=null):typeof t=="function"&&(r=t,t=null),e!=null&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||b$e(this,n,r),this};Object.defineProperty(Et.prototype,"writableLength",{enumerable:false,get:function(){return this._writableState.length}});function I7(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function _$e(e,t){e._final(function(r){t.pendingcb--,r&&pl(e,r),t.prefinished=true,e.emit("prefinish"),Lf(e,t);});}function S$e(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final=="function"&&!t.destroyed?(t.pendingcb++,t.finalCalled=true,process.nextTick(_$e,e,t)):(t.prefinished=true,e.emit("prefinish")));}function Lf(e,t){var r=I7(t);if(r&&(S$e(e,t),t.pendingcb===0&&(t.finished=true,e.emit("finish"),t.autoDestroy))){var n=e._readableState;(!n||n.autoDestroy&&n.endEmitted)&&e.destroy();}return r}function b$e(e,t,r){t.ending=true,Lf(e,t),r&&(t.finished?process.nextTick(r):e.once("finish",r)),t.ended=true,e.writable=false;}function E$e(e,t,r){var n=e.entry;for(e.entry=null;n;){var i=n.callback;t.pendingcb--,i(r),n=n.next;}t.corkedRequestsFree.next=e;}Object.defineProperty(Et.prototype,"destroyed",{enumerable:false,get:function(){return this._writableState===void 0?false:this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t);}});Et.prototype.destroy=SA.destroy;Et.prototype._undestroy=SA.undestroy;Et.prototype._destroy=function(e,t){t(e);};});var aa=c((I7e,N7)=>{var T$e=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};N7.exports=gi;var C7=RA(),TA=bA();Ws()(gi,C7);for(EA=T$e(TA.prototype),W0=0;W0<EA.length;W0++)K0=EA[W0],gi.prototype[K0]||(gi.prototype[K0]=TA.prototype[K0]);var EA,K0,W0;function gi(e){if(!(this instanceof gi))return new gi(e);C7.call(this,e),TA.call(this,e),this.allowHalfOpen=true,e&&(e.readable===false&&(this.readable=false),e.writable===false&&(this.writable=false),e.allowHalfOpen===false&&(this.allowHalfOpen=false,this.once("end",R$e)));}Object.defineProperty(gi.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});Object.defineProperty(gi.prototype,"writableBuffer",{enumerable:false,get:function(){return this._writableState&&this._writableState.getBuffer()}});Object.defineProperty(gi.prototype,"writableLength",{enumerable:false,get:function(){return this._writableState.length}});function R$e(){this._writableState.ended||process.nextTick(P$e,this);}function P$e(e){e.end();}Object.defineProperty(gi.prototype,"destroyed",{enumerable:false,get:function(){return this._readableState===void 0||this._writableState===void 0?false:this._readableState.destroyed&&this._writableState.destroyed},set:function(t){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=t,this._writableState.destroyed=t);}});});var D7=c((PA,L7)=>{var Y0=a("buffer"),yi=Y0.Buffer;function j7(e,t){for(var r in e)t[r]=e[r];}yi.from&&yi.alloc&&yi.allocUnsafe&&yi.allocUnsafeSlow?L7.exports=Y0:(j7(Y0,PA),PA.Buffer=ca);function ca(e,t,r){return yi(e,t,r)}ca.prototype=Object.create(yi.prototype);j7(yi,ca);ca.from=function(e,t,r){if(typeof e=="number")throw new TypeError("Argument must not be a number");return yi(e,t,r)};ca.alloc=function(e,t,r){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=yi(e);return t!==void 0?typeof r=="string"?n.fill(t,r):n.fill(t):n.fill(0),n};ca.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return yi(e)};ca.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return Y0.SlowBuffer(e)};});var AA=c(F7=>{var xA=D7().Buffer,M7=xA.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case "hex":case "utf8":case "utf-8":case "ascii":case "binary":case "base64":case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":case "raw":return true;default:return false}};function k$e(e){if(!e)return "utf8";for(var t;;)switch(e){case "utf8":case "utf-8":return "utf8";case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return "utf16le";case "latin1":case "binary":return "latin1";case "base64":case "ascii":case "hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=true;}}function x$e(e){var t=k$e(e);if(typeof t!="string"&&(xA.isEncoding===M7||!M7(e)))throw new Error("Unknown encoding: "+e);return t||e}F7.StringDecoder=Mf;function Mf(e){this.encoding=x$e(e);var t;switch(this.encoding){case "utf16le":this.text=j$e,this.end=L$e,t=4;break;case "utf8":this.fillLast=O$e,t=4;break;case "base64":this.text=D$e,this.end=M$e,t=3;break;default:this.write=F$e,this.end=$$e;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=xA.allocUnsafe(t);}Mf.prototype.write=function(e){if(e.length===0)return "";var t,r;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return "";r=this.lastNeed,this.lastNeed=0;}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""};Mf.prototype.end=N$e;Mf.prototype.text=C$e;Mf.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length;};function kA(e){return e<=127?0:e>>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}function A$e(e,t,r){var n=t.length-1;if(n<r)return 0;var i=kA(t[n]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--n<r||i===-2?0:(i=kA(t[n]),i>=0?(i>0&&(e.lastNeed=i-2),i):--n<r||i===-2?0:(i=kA(t[n]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function I$e(e,t,r){if((t[0]&192)!==128)return e.lastNeed=0,"\uFFFD";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"\uFFFD";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"\uFFFD"}}function O$e(e){var t=this.lastTotal-this.lastNeed,r=I$e(this,e);if(r!==void 0)return r;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length;}function C$e(e,t){var r=A$e(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}function N$e(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"\uFFFD":t}function j$e(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function L$e(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function D$e(e,t){var r=(e.length-t)%3;return r===0?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function M$e(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function F$e(e){return e.toString(this.encoding)}function $$e(e){return e&&e.length?this.write(e):""}});var Q0=c((C7e,U7)=>{var $7=Qs().codes.ERR_STREAM_PREMATURE_CLOSE;function q$e(e){var t=false;return function(){if(!t){t=true;for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];e.apply(this,n);}}}function U$e(){}function B$e(e){return e.setHeader&&typeof e.abort=="function"}function q7(e,t,r){if(typeof t=="function")return q7(e,null,t);t||(t={}),r=q$e(r||U$e);var n=t.readable||t.readable!==false&&e.readable,i=t.writable||t.writable!==false&&e.writable,s=function(){e.writable||a();},o=e._writableState&&e._writableState.finished,a=function(){i=false,o=true,n||r.call(e);},c=e._readableState&&e._readableState.endEmitted,l=function(){n=false,c=true,i||r.call(e);},u=function(h){r.call(e,h);},d=function(){var h;if(n&&!c)return (!e._readableState||!e._readableState.ended)&&(h=new $7),r.call(e,h);if(i&&!o)return (!e._writableState||!e._writableState.ended)&&(h=new $7),r.call(e,h)},m=function(){e.req.on("finish",a);};return B$e(e)?(e.on("complete",a),e.on("abort",d),e.req?m():e.on("request",m)):i&&!e._writableState&&(e.on("end",s),e.on("close",s)),e.on("end",l),e.on("finish",a),t.error!==false&&e.on("error",u),e.on("close",d),function(){e.removeListener("complete",a),e.removeListener("abort",d),e.removeListener("request",m),e.req&&e.req.removeListener("finish",a),e.removeListener("end",s),e.removeListener("close",s),e.removeListener("finish",a),e.removeListener("end",l),e.removeListener("error",u),e.removeListener("close",d);}}U7.exports=q7;});var H7=c((N7e,B7)=>{var J0;function Xs(e,t,r){return t=H$e(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:true,configurable:true,writable:true}):e[t]=r,e}function H$e(e){var t=G$e(e,"string");return typeof t=="symbol"?t:String(t)}function G$e(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (t==="string"?String:Number)(e)}var z$e=Q0(),Zs=Symbol("lastResolve"),la=Symbol("lastReject"),Ff=Symbol("error"),X0=Symbol("ended"),ua=Symbol("lastPromise"),IA=Symbol("handlePromise"),da=Symbol("stream");function eo(e,t){return {value:e,done:t}}function V$e(e){var t=e[Zs];if(t!==null){var r=e[da].read();r!==null&&(e[ua]=null,e[Zs]=null,e[la]=null,t(eo(r,false)));}}function W$e(e){process.nextTick(V$e,e);}function K$e(e,t){return function(r,n){e.then(function(){if(t[X0]){r(eo(void 0,true));return}t[IA](r,n);},n);}}var Y$e=Object.getPrototypeOf(function(){}),Q$e=Object.setPrototypeOf((J0={get stream(){return this[da]},next:function(){var t=this,r=this[Ff];if(r!==null)return Promise.reject(r);if(this[X0])return Promise.resolve(eo(void 0,true));if(this[da].destroyed)return new Promise(function(o,a){process.nextTick(function(){t[Ff]?a(t[Ff]):o(eo(void 0,true));});});var n=this[ua],i;if(n)i=new Promise(K$e(n,this));else {var s=this[da].read();if(s!==null)return Promise.resolve(eo(s,false));i=new Promise(this[IA]);}return this[ua]=i,i}},Xs(J0,Symbol.asyncIterator,function(){return this}),Xs(J0,"return",function(){var t=this;return new Promise(function(r,n){t[da].destroy(null,function(i){if(i){n(i);return}r(eo(void 0,true));});})}),J0),Y$e),J$e=function(t){var r,n=Object.create(Q$e,(r={},Xs(r,da,{value:t,writable:true}),Xs(r,Zs,{value:null,writable:true}),Xs(r,la,{value:null,writable:true}),Xs(r,Ff,{value:null,writable:true}),Xs(r,X0,{value:t._readableState.endEmitted,writable:true}),Xs(r,IA,{value:function(s,o){var a=n[da].read();a?(n[ua]=null,n[Zs]=null,n[la]=null,s(eo(a,false))):(n[Zs]=s,n[la]=o);},writable:true}),r));return n[ua]=null,z$e(t,function(i){if(i&&i.code!=="ERR_STREAM_PREMATURE_CLOSE"){var s=n[la];s!==null&&(n[ua]=null,n[Zs]=null,n[la]=null,s(i)),n[Ff]=i;return}var o=n[Zs];o!==null&&(n[ua]=null,n[Zs]=null,n[la]=null,o(eo(void 0,true))),n[X0]=true;}),t.on("readable",W$e.bind(null,n)),n};B7.exports=J$e;});var W7=c((j7e,V7)=>{function G7(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value;}catch(l){r(l);return}a.done?t(c):Promise.resolve(c).then(n,i);}function X$e(e){return function(){var t=this,r=arguments;return new Promise(function(n,i){var s=e.apply(t,r);function o(c){G7(s,n,i,o,a,"next",c);}function a(c){G7(s,n,i,o,a,"throw",c);}o(void 0);})}}function z7(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n);}return r}function Z$e(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?z7(Object(r),true).forEach(function(n){e2e(e,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):z7(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n));});}return e}function e2e(e,t,r){return t=t2e(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:true,configurable:true,writable:true}):e[t]=r,e}function t2e(e){var t=r2e(e,"string");return typeof t=="symbol"?t:String(t)}function r2e(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (t==="string"?String:Number)(e)}var n2e=Qs().codes.ERR_INVALID_ARG_TYPE;function i2e(e,t,r){var n;if(t&&typeof t.next=="function")n=t;else if(t&&t[Symbol.asyncIterator])n=t[Symbol.asyncIterator]();else if(t&&t[Symbol.iterator])n=t[Symbol.iterator]();else throw new n2e("iterable",["Iterable"],t);var i=new e(Z$e({objectMode:true},r)),s=false;i._read=function(){s||(s=true,o());};function o(){return a.apply(this,arguments)}function a(){return a=X$e(function*(){try{var c=yield n.next(),l=c.value,u=c.done;u?i.push(null):i.push(yield l)?o():s=!1;}catch(d){i.destroy(d);}}),a.apply(this,arguments)}return i}V7.exports=i2e;});var RA=c((D7e,nJ)=>{nJ.exports=Ke;var ml;Ke.ReadableState=J7;a("events").EventEmitter;var Q7=function(t,r){return t.listeners(r).length},qf=mA(),Z0=a("buffer").Buffer,s2e=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function o2e(e){return Z0.from(e)}function a2e(e){return Z0.isBuffer(e)||e instanceof s2e}var OA=a("util"),je;OA&&OA.debuglog?je=OA.debuglog("stream"):je=function(){};var c2e=y7(),FA=wA(),l2e=vA(),u2e=l2e.getHighWaterMark,ew=Qs().codes,d2e=ew.ERR_INVALID_ARG_TYPE,f2e=ew.ERR_STREAM_PUSH_AFTER_EOF,h2e=ew.ERR_METHOD_NOT_IMPLEMENTED,p2e=ew.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,gl,CA,NA;Ws()(Ke,qf);var $f=FA.errorOrDestroy,jA=["error","close","destroy","pause","resume"];function m2e(e,t,r){if(typeof e.prependListener=="function")return e.prependListener(t,r);!e._events||!e._events[t]?e.on(t,r):Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]];}function J7(e,t,r){ml=ml||aa(),e=e||{},typeof r!="boolean"&&(r=t instanceof ml),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=u2e(this,e,"readableHighWaterMark",r),this.buffer=new c2e,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=false,this.endEmitted=false,this.reading=false,this.sync=true,this.needReadable=false,this.emittedReadable=false,this.readableListening=false,this.resumeScheduled=false,this.paused=true,this.emitClose=e.emitClose!==false,this.autoDestroy=!!e.autoDestroy,this.destroyed=false,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=false,this.decoder=null,this.encoding=null,e.encoding&&(gl||(gl=AA().StringDecoder),this.decoder=new gl(e.encoding),this.encoding=e.encoding);}function Ke(e){if(ml=ml||aa(),!(this instanceof Ke))return new Ke(e);var t=this instanceof ml;this._readableState=new J7(e,this,t),this.readable=true,e&&(typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)),qf.call(this);}Object.defineProperty(Ke.prototype,"destroyed",{enumerable:false,get:function(){return this._readableState===void 0?false:this._readableState.destroyed},set:function(t){this._readableState&&(this._readableState.destroyed=t);}});Ke.prototype.destroy=FA.destroy;Ke.prototype._undestroy=FA.undestroy;Ke.prototype._destroy=function(e,t){t(e);};Ke.prototype.push=function(e,t){var r=this._readableState,n;return r.objectMode?n=true:typeof e=="string"&&(t=t||r.defaultEncoding,t!==r.encoding&&(e=Z0.from(e,t),t=""),n=true),X7(this,e,t,false,n)};Ke.prototype.unshift=function(e){return X7(this,e,null,true,false)};function X7(e,t,r,n,i){je("readableAddChunk",t);var s=e._readableState;if(t===null)s.reading=false,w2e(e,s);else {var o;if(i||(o=g2e(s,t)),o)$f(e,o);else if(s.objectMode||t&&t.length>0)if(typeof t!="string"&&!s.objectMode&&Object.getPrototypeOf(t)!==Z0.prototype&&(t=o2e(t)),n)s.endEmitted?$f(e,new p2e):LA(e,s,t,true);else if(s.ended)$f(e,new f2e);else {if(s.destroyed)return false;s.reading=false,s.decoder&&!r?(t=s.decoder.write(t),s.objectMode||t.length!==0?LA(e,s,t,false):MA(e,s)):LA(e,s,t,false);}else n||(s.reading=false,MA(e,s));}return !s.ended&&(s.length<s.highWaterMark||s.length===0)}function LA(e,t,r,n){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&tw(e)),MA(e,t);}function g2e(e,t){var r;return !a2e(t)&&typeof t!="string"&&t!==void 0&&!e.objectMode&&(r=new d2e("chunk",["string","Buffer","Uint8Array"],t)),r}Ke.prototype.isPaused=function(){return this._readableState.flowing===false};Ke.prototype.setEncoding=function(e){gl||(gl=AA().StringDecoder);var t=new gl(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,n="";r!==null;)n+=t.write(r.data),r=r.next;return this._readableState.buffer.clear(),n!==""&&this._readableState.buffer.push(n),this._readableState.length=n.length,this};var K7=1073741824;function y2e(e){return e>=K7?e=K7:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function Y7(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=y2e(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=true,0))}Ke.prototype.read=function(e){je("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(e!==0&&(t.emittedReadable=false),e===0&&t.needReadable&&((t.highWaterMark!==0?t.length>=t.highWaterMark:t.length>0)||t.ended))return je("read: emitReadable",t.length,t.ended),t.length===0&&t.ended?DA(this):tw(this),null;if(e=Y7(e,t),e===0&&t.ended)return t.length===0&&DA(this),null;var n=t.needReadable;je("need readable",n),(t.length===0||t.length-e<t.highWaterMark)&&(n=true,je("length less than watermark",n)),t.ended||t.reading?(n=false,je("reading or ended",n)):n&&(je("do read"),t.reading=true,t.sync=true,t.length===0&&(t.needReadable=true),this._read(t.highWaterMark),t.sync=false,t.reading||(e=Y7(r,t)));var i;return e>0?i=tJ(e,t):i=null,i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=true),r!==e&&t.ended&&DA(this)),i!==null&&this.emit("data",i),i};function w2e(e,t){if(je("onEofChunk"),!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length);}t.ended=true,t.sync?tw(e):(t.needReadable=false,t.emittedReadable||(t.emittedReadable=true,Z7(e)));}}function tw(e){var t=e._readableState;je("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=false,t.emittedReadable||(je("emitReadable",t.flowing),t.emittedReadable=true,process.nextTick(Z7,e));}function Z7(e){var t=e._readableState;je("emitReadable_",t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit("readable"),t.emittedReadable=false),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,$A(e);}function MA(e,t){t.readingMore||(t.readingMore=true,process.nextTick(v2e,e,t));}function v2e(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var r=t.length;if(je("maybeReadMore read 0"),e.read(0),r===t.length)break}t.readingMore=false;}Ke.prototype._read=function(e){$f(this,new h2e("_read()"));};Ke.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e);break}n.pipesCount+=1,je("pipe count=%d opts=%j",n.pipesCount,t);var i=(!t||t.end!==false)&&e!==process.stdout&&e!==process.stderr,s=i?a:f;n.endEmitted?process.nextTick(s):r.once("end",s),e.on("unpipe",o);function o(g,y){je("onunpipe"),g===r&&y&&y.hasUnpiped===false&&(y.hasUnpiped=true,u());}function a(){je("onend"),e.end();}var c=_2e(r);e.on("drain",c);var l=false;function u(){je("cleanup"),e.removeListener("close",p),e.removeListener("finish",h),e.removeListener("drain",c),e.removeListener("error",m),e.removeListener("unpipe",o),r.removeListener("end",a),r.removeListener("end",f),r.removeListener("data",d),l=true,n.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c();}r.on("data",d);function d(g){je("ondata");var y=e.write(g);je("dest.write",y),y===false&&((n.pipesCount===1&&n.pipes===e||n.pipesCount>1&&rJ(n.pipes,e)!==-1)&&!l&&(je("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause());}function m(g){je("onerror",g),f(),e.removeListener("error",m),Q7(e,"error")===0&&$f(e,g);}m2e(e,"error",m);function p(){e.removeListener("finish",h),f();}e.once("close",p);function h(){je("onfinish"),e.removeListener("close",p),f();}e.once("finish",h);function f(){je("unpipe"),r.unpipe(e);}return e.emit("pipe",r),n.flowing||(je("pipe resume"),r.resume()),e};function _2e(e){return function(){var r=e._readableState;je("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,r.awaitDrain===0&&Q7(e,"data")&&(r.flowing=true,$A(e));}}Ke.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:false};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=false,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=false;for(var s=0;s<i;s++)n[s].emit("unpipe",this,{hasUnpiped:false});return this}var o=rJ(t.pipes,e);return o===-1?this:(t.pipes.splice(o,1),t.pipesCount-=1,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,r),this)};Ke.prototype.on=function(e,t){var r=qf.prototype.on.call(this,e,t),n=this._readableState;return e==="data"?(n.readableListening=this.listenerCount("readable")>0,n.flowing!==false&&this.resume()):e==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=true,n.flowing=false,n.emittedReadable=false,je("on readable",n.length,n.reading),n.length?tw(this):n.reading||process.nextTick(S2e,this)),r};Ke.prototype.addListener=Ke.prototype.on;Ke.prototype.removeListener=function(e,t){var r=qf.prototype.removeListener.call(this,e,t);return e==="readable"&&process.nextTick(eJ,this),r};Ke.prototype.removeAllListeners=function(e){var t=qf.prototype.removeAllListeners.apply(this,arguments);return (e==="readable"||e===void 0)&&process.nextTick(eJ,this),t};function eJ(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=true:e.listenerCount("data")>0&&e.resume();}function S2e(e){je("readable nexttick read 0"),e.read(0);}Ke.prototype.resume=function(){var e=this._readableState;return e.flowing||(je("resume"),e.flowing=!e.readableListening,b2e(this,e)),e.paused=false,this};function b2e(e,t){t.resumeScheduled||(t.resumeScheduled=true,process.nextTick(E2e,e,t));}function E2e(e,t){je("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=false,e.emit("resume"),$A(e),t.flowing&&!t.reading&&e.read(0);}Ke.prototype.pause=function(){return je("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==false&&(je("pause"),this._readableState.flowing=false,this.emit("pause")),this._readableState.paused=true,this};function $A(e){var t=e._readableState;for(je("flow",t.flowing);t.flowing&&e.read()!==null;);}Ke.prototype.wrap=function(e){var t=this,r=this._readableState,n=false;e.on("end",function(){if(je("wrapped end"),r.decoder&&!r.ended){var o=r.decoder.end();o&&o.length&&t.push(o);}t.push(null);}),e.on("data",function(o){if(je("wrapped data"),r.decoder&&(o=r.decoder.write(o)),!(r.objectMode&&o==null)&&!(!r.objectMode&&(!o||!o.length))){var a=t.push(o);a||(n=true,e.pause());}});for(var i in e)this[i]===void 0&&typeof e[i]=="function"&&(this[i]=(function(a){return function(){return e[a].apply(e,arguments)}})(i));for(var s=0;s<jA.length;s++)e.on(jA[s],this.emit.bind(this,jA[s]));return this._read=function(o){je("wrapped _read",o),n&&(n=false,e.resume());},this};typeof Symbol=="function"&&(Ke.prototype[Symbol.asyncIterator]=function(){return CA===void 0&&(CA=H7()),CA(this)});Object.defineProperty(Ke.prototype,"readableHighWaterMark",{enumerable:false,get:function(){return this._readableState.highWaterMark}});Object.defineProperty(Ke.prototype,"readableBuffer",{enumerable:false,get:function(){return this._readableState&&this._readableState.buffer}});Object.defineProperty(Ke.prototype,"readableFlowing",{enumerable:false,get:function(){return this._readableState.flowing},set:function(t){this._readableState&&(this._readableState.flowing=t);}});Ke._fromList=tJ;Object.defineProperty(Ke.prototype,"readableLength",{enumerable:false,get:function(){return this._readableState.length}});function tJ(e,t){if(t.length===0)return null;var r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(t.decoder?r=t.buffer.join(""):t.buffer.length===1?r=t.buffer.first():r=t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r}function DA(e){var t=e._readableState;je("endReadable",t.endEmitted),t.endEmitted||(t.ended=true,process.nextTick(T2e,t,e));}function T2e(e,t){if(je("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=true,t.readable=false,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy();}}typeof Symbol=="function"&&(Ke.from=function(e,t){return NA===void 0&&(NA=W7()),NA(Ke,e,t)});function rJ(e,t){for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return -1}});var qA=c((M7e,sJ)=>{sJ.exports=Zi;var rw=Qs().codes,R2e=rw.ERR_METHOD_NOT_IMPLEMENTED,P2e=rw.ERR_MULTIPLE_CALLBACK,k2e=rw.ERR_TRANSFORM_ALREADY_TRANSFORMING,x2e=rw.ERR_TRANSFORM_WITH_LENGTH_0,nw=aa();Ws()(Zi,nw);function A2e(e,t){var r=this._transformState;r.transforming=false;var n=r.writecb;if(n===null)return this.emit("error",new P2e);r.writechunk=null,r.writecb=null,t!=null&&this.push(t),n(e);var i=this._readableState;i.reading=false,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark);}function Zi(e){if(!(this instanceof Zi))return new Zi(e);nw.call(this,e),this._transformState={afterTransform:A2e.bind(this),needTransform:false,transforming:false,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=true,this._readableState.sync=false,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.on("prefinish",I2e);}function I2e(){var e=this;typeof this._flush=="function"&&!this._readableState.destroyed?this._flush(function(t,r){iJ(e,t,r);}):iJ(this,null,null);}Zi.prototype.push=function(e,t){return this._transformState.needTransform=false,nw.prototype.push.call(this,e,t)};Zi.prototype._transform=function(e,t,r){r(new R2e("_transform()"));};Zi.prototype._write=function(e,t,r){var n=this._transformState;if(n.writecb=r,n.writechunk=e,n.writeencoding=t,!n.transforming){var i=this._readableState;(n.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark);}};Zi.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=true,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=true;};Zi.prototype._destroy=function(e,t){nw.prototype._destroy.call(this,e,function(r){t(r);});};function iJ(e,t,r){if(t)return e.emit("error",t);if(r!=null&&e.push(r),e._writableState.length)throw new x2e;if(e._transformState.transforming)throw new k2e;return e.push(null)}});var cJ=c((F7e,aJ)=>{aJ.exports=Uf;var oJ=qA();Ws()(Uf,oJ);function Uf(e){if(!(this instanceof Uf))return new Uf(e);oJ.call(this,e);}Uf.prototype._transform=function(e,t,r){r(null,e);};});var hJ=c(($7e,fJ)=>{var UA;function O2e(e){var t=false;return function(){t||(t=true,e.apply(void 0,arguments));}}var dJ=Qs().codes,C2e=dJ.ERR_MISSING_ARGS,N2e=dJ.ERR_STREAM_DESTROYED;function lJ(e){if(e)throw e}function j2e(e){return e.setHeader&&typeof e.abort=="function"}function L2e(e,t,r,n){n=O2e(n);var i=false;e.on("close",function(){i=true;}),UA===void 0&&(UA=Q0()),UA(e,{readable:t,writable:r},function(o){if(o)return n(o);i=true,n();});var s=false;return function(o){if(!i&&!s){if(s=true,j2e(e))return e.abort();if(typeof e.destroy=="function")return e.destroy();n(o||new N2e("pipe"));}}}function uJ(e){e();}function D2e(e,t){return e.pipe(t)}function M2e(e){return !e.length||typeof e[e.length-1]!="function"?lJ:e.pop()}function F2e(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=M2e(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new C2e("streams");var i,s=t.map(function(o,a){var c=a<t.length-1,l=a>0;return L2e(o,c,l,function(u){i||(i=u),u&&s.forEach(uJ),!c&&(s.forEach(uJ),n(i));})});return t.reduce(D2e)}fJ.exports=F2e;});var pJ=c((_n,Hf)=>{var Bf=a("stream");process.env.READABLE_STREAM==="disable"&&Bf?(Hf.exports=Bf.Readable,Object.assign(Hf.exports,Bf),Hf.exports.Stream=Bf):(_n=Hf.exports=RA(),_n.Stream=Bf||_n,_n.Readable=_n,_n.Writable=bA(),_n.Duplex=aa(),_n.Transform=qA(),_n.PassThrough=cJ(),_n.finished=Q0(),_n.pipeline=hJ());});var yJ=c((q7e,gJ)=>{gJ.exports=mJ;function mJ(e,t){if(e&&t)return mJ(e)(t);if(typeof e!="function")throw new TypeError("need wrapper function");return Object.keys(e).forEach(function(n){r[n]=e[n];}),r;function r(){for(var n=new Array(arguments.length),i=0;i<n.length;i++)n[i]=arguments[i];var s=e.apply(this,n),o=n[n.length-1];return typeof s=="function"&&s!==o&&Object.keys(o).forEach(function(a){s[a]=o[a];}),s}}});var _J=c((U7e,BA)=>{var wJ=yJ();BA.exports=wJ(iw);BA.exports.strict=wJ(vJ);iw.proto=iw(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return iw(this)},configurable:true}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return vJ(this)},configurable:true});});function iw(e){var t=function(){return t.called?t.value:(t.called=true,t.value=e.apply(this,arguments))};return t.called=false,t}function vJ(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=true,t.value=e.apply(this,arguments)},r=e.name||"Function wrapped with `once`";return t.onceError=r+" shouldn't be called more than once",t.called=false,t}});var EJ=c((B7e,bJ)=>{var $2e=_J(),q2e=function(){},U2e=global.Bare?queueMicrotask:process.nextTick.bind(process),B2e=function(e){return e.setHeader&&typeof e.abort=="function"},H2e=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},SJ=function(e,t,r){if(typeof t=="function")return SJ(e,null,t);t||(t={}),r=$2e(r||q2e);var n=e._writableState,i=e._readableState,s=t.readable||t.readable!==false&&e.readable,o=t.writable||t.writable!==false&&e.writable,a=false,c=function(){e.writable||l();},l=function(){o=false,s||r.call(e);},u=function(){s=false,o||r.call(e);},d=function(g){r.call(e,g?new Error("exited with error code: "+g):null);},m=function(g){r.call(e,g);},p=function(){U2e(h);},h=function(){if(!a){if(s&&!(i&&i.ended&&!i.destroyed))return r.call(e,new Error("premature close"));if(o&&!(n&&n.ended&&!n.destroyed))return r.call(e,new Error("premature close"))}},f=function(){e.req.on("finish",l);};return B2e(e)?(e.on("complete",l),e.on("abort",p),e.req?f():e.on("request",f)):o&&!n&&(e.on("end",c),e.on("close",c)),H2e(e)&&e.on("exit",d),e.on("end",u),e.on("finish",l),t.error!==false&&e.on("error",m),e.on("close",p),function(){a=true,e.removeListener("complete",l),e.removeListener("abort",p),e.removeListener("request",f),e.req&&e.req.removeListener("finish",l),e.removeListener("end",c),e.removeListener("close",c),e.removeListener("finish",l),e.removeListener("exit",d),e.removeListener("end",u),e.removeListener("error",m),e.removeListener("close",p);}};bJ.exports=SJ;});var RJ=c((H7e,TJ)=>{TJ.exports=G2e;function G2e(e){var t=e._readableState;return t?t.objectMode||typeof e._duplexState=="number"?e.read():e.read(z2e(t)):null}function z2e(e){if(e.buffer.length){var t=e.bufferIndex||0;if(e.buffer.head)return e.buffer.head.data.length;if(e.buffer.length-t>0&&e.buffer[t])return e.buffer[t].length}return e.length}});var IJ=c((G7e,AJ)=>{var sw=pJ(),PJ=EJ(),V2e=Ws(),W2e=RJ(),kJ=Buffer.from&&Buffer.from!==Uint8Array.from?Buffer.from([0]):new Buffer([0]),HA=function(e,t){e._corked?e.once("uncork",t):t();},K2e=function(e,t){e._autoDestroy&&e.destroy(t);},xJ=function(e,t){return function(r){r?K2e(e,r.message==="premature close"?null:r):t&&!e._ended&&e.end();}},Y2e=function(e,t){if(!e||e._writableState&&e._writableState.finished)return t();if(e._writableState)return e.end(t);e.end(),t();},Q2e=function(){},J2e=function(e){return new sw.Readable({objectMode:true,highWaterMark:16}).wrap(e)},ir=function(e,t,r){if(!(this instanceof ir))return new ir(e,t,r);sw.Duplex.call(this,r),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!r||r.autoDestroy!==false,this._forwardDestroy=!r||r.destroy!==false,this._forwardEnd=!r||r.end!==false,this._corked=1,this._ondrain=null,this._drained=false,this._forwarding=false,this._unwrite=null,this._unread=null,this._ended=false,this.destroyed=false,e&&this.setWritable(e),t&&this.setReadable(t);};V2e(ir,sw.Duplex);ir.obj=function(e,t,r){return r||(r={}),r.objectMode=true,r.highWaterMark=16,new ir(e,t,r)};ir.prototype.cork=function(){++this._corked===1&&this.emit("cork");};ir.prototype.uncork=function(){this._corked&&--this._corked===0&&this.emit("uncork");};ir.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===false){this.end();return}var t=this,r=PJ(e,{writable:true,readable:false},xJ(this,this._forwardEnd)),n=function(){var s=t._ondrain;t._ondrain=null,s&&s();},i=function(){t._writable.removeListener("drain",n),r();};this._unwrite&&process.nextTick(n),this._writable=e,this._writable.on("drain",n),this._unwrite=i,this.uncork();};ir.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===false){this.push(null),this.resume();return}var t=this,r=PJ(e,{writable:false,readable:true},xJ(this)),n=function(){t._forward();},i=function(){t.push(null);},s=function(){t._readable2.removeListener("readable",n),t._readable2.removeListener("end",i),r();};this._drained=true,this._readable=e,this._readable2=e._readableState?e:J2e(e),this._readable2.on("readable",n),this._readable2.on("end",i),this._unread=s,this._forward();};ir.prototype._read=function(){this._drained=true,this._forward();};ir.prototype._forward=function(){if(!(this._forwarding||!this._readable2||!this._drained)){this._forwarding=true;for(var e;this._drained&&(e=W2e(this._readable2))!==null;)this.destroyed||(this._drained=this.push(e));this._forwarding=false;}};ir.prototype.destroy=function(e,t){if(t||(t=Q2e),this.destroyed)return t(null);this.destroyed=true;var r=this;process.nextTick(function(){r._destroy(e),t(null);});};ir.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit("error",e);}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close");};ir.prototype._write=function(e,t,r){if(!this.destroyed){if(this._corked)return HA(this,this._write.bind(this,e,t,r));if(e===kJ)return this._finish(r);if(!this._writable)return r();this._writable.write(e)===false?this._ondrain=r:this.destroyed||r();}};ir.prototype._finish=function(e){var t=this;this.emit("preend"),HA(this,function(){Y2e(t._forwardEnd&&t._writable,function(){t._writableState.prefinished===false&&(t._writableState.prefinished=true),t.emit("prefinish"),HA(t,e);});});};ir.prototype.end=function(e,t,r){return typeof e=="function"?this.end(null,null,e):typeof t=="function"?this.end(e,null,t):(this._ended=true,e&&this.write(e),!this._writableState.ending&&!this._writableState.destroyed&&this.write(kJ),sw.Writable.prototype.end.call(this,r))};AJ.exports=ir;});var jJ=c((z7e,aw)=>{var{ServerResponse:X2e}=a("http"),{PassThrough:OJ}=a("stream"),{randomBytes:Z2e}=a("crypto"),eqe=tf(),CJ=u7(),NJ=IJ(),fa=Symbol("ws-socket"),ow=Symbol("ws-head"),tqe=/HTTP\/1.1 (\d+)/u;function GA(e,t,r){e.decorateRequest("ws",null);let n=p;if(t.errorHandler){if(typeof t.errorHandler!="function")return r(new Error("invalid errorHandler function"));n=t.errorHandler;}let i=d;if(t?.preClose){if(typeof t.preClose!="function")return r(new Error("invalid preClose function"));i=t.preClose;}if(t.options?.noServer)return r(new Error("fastify-websocket doesn't support the ws noServer option. If you want to create a websocket server detatched from fastify, use the ws library directly."));let s=Object.assign({noServer:true},t.options);s.path&&e.log.warn("ws server path option shouldn't be provided, use a route instead");let o=s.server||e.server;delete s.server;let a=new CJ.Server(s);e.decorate("websocketServer",a);async function c(h="/",f={},g={}){let y=new OJ,_=new OJ,v=new NJ(y,_),w=new NJ(_,y),E=new CJ(null,void 0,{isServer:false}),R=Buffer.from([]),P,b,O=new Promise((N,M)=>{P=N,b=M;});typeof g.onInit=="function"&&g.onInit(E),E.on("open",()=>{typeof g.onOpen=="function"&&g.onOpen(E),w.removeListener("data",F),P(E);});let F=N=>{if(N.toString().includes("HTTP/1.1 101 Switching Protocols"))E._isServer=false,E.setSocket(w,R,{maxPayload:0});else {w.removeListener("data",F);let M=Number(tqe.exec(N.toString())[1]);b(new Error("Unexpected server response: "+M));}};w.on("data",F);let j={...f,method:"GET",headers:{...f.headers,connection:"upgrade",upgrade:"websocket","sec-websocket-version":13,"sec-websocket-key":Z2e(16).toString("base64")},httpVersion:"1.1",url:h,[fa]:v,[ow]:R};return o.emit("upgrade",j,j[fa],j[ow]),O}e.decorate("injectWS",c);function l(h,f,g){h[fa]=f,h[ow]=g;let y=new X2e(h);try{y.assignSocket(f),e.routing(h,y);}catch(_){e.log.warn({err:_},"websocket upgrade failed");}}o.on("upgrade",l);let u=(h,f)=>{a.handleUpgrade(h,h[fa],h[ow],g=>{a.emit("connection",g,h),g.on("error",y=>{e.log.error(y);}),f(g);});};e.addHook("onRequest",(h,f,g)=>{h.raw[fa]?h.ws=true:h.ws=false,g();}),e.addHook("onResponse",(h,f,g)=>{h.ws&&h.raw[fa].destroy(),g();}),e.addHook("onRoute",h=>{let f=false,g=h.wsHandler,y=h.handler;if(h.websocket||h.wsHandler){if(h.method==="HEAD")return;if(h.method!=="GET")throw new Error("websocket handler can only be declared in GET method");if(f=true,h.websocket&&(h.schema||(h.schema={}),h.schema.hide=true,g=h.handler,y=function(_,v){v.code(404).send();}),typeof g!="function")throw new TypeError("invalid wsHandler function")}h.handler=function(_,v){if(_.raw[fa])v.hijack(),u(_.raw,w=>{let E;try{f?E=g.call(this,w,_):E=m.call(this,w,_);}catch(R){return n.call(this,R,w,_,v)}E&&typeof E.catch=="function"&&E.catch(R=>n.call(this,R,w,_,v));});else return y.call(this,_,v)};}),e.addHook("preClose",i);function d(h){let f=this.websocketServer;if(f.clients)for(let g of f.clients)g.close();e.server.removeListener("upgrade",l),f.close(h),h();}function m(h,f){this.log.info({path:f.url},"closed incoming websocket connection for path with no websocket handler"),h.close();}function p(h,f,g){g.log.error(h),f.terminate();}r();}aw.exports=eqe(GA,{fastify:"5.x",name:"@fastify/websocket"});aw.exports.default=GA;aw.exports.fastifyWebsocket=GA;});var mX=256*1024,k1=1024*1024,I1='{"events":[',O1='],"type":"events.batch","version":3}',gX=I1.length+O1.length,x1=new WeakMap,A1=new WeakMap;function Ow(e){let t=x1.get(e);if(t!==void 0)return t;let r=JSON.stringify(e),n={byteLength:Buffer$1.byteLength(r),data:r};return x1.set(e,n),n}function yX(e){return Ow(e)}function Cw(e){return Ow(e).byteLength}function wX(e,t,r,n){return e.length!==n-r?false:e.every((i,s)=>i===t[r+s])}function vX(e,t){let r=Math.min(t+ng,e.length),n=t,i=gX,s=[];for(;n<r;n+=1){let f=e[n];if(f===void 0)throw new RangeError("Event batch must contain defined events");let g=Ow(f);if(g.byteLength>og$1){if(n===t)return;break}let y=i+g.byteLength+(n===t?0:1);if(y>pg$1)break;i=y,s.push(g);}let o=e[t];if(o===void 0)throw new RangeError("Event batch must contain at least one event");let a=n-t,c=A1.get(o),l=c?.get(a);if(l!==void 0&&wX(l.events,e,t,n))return l;let u=e.slice(t,n),d=`${I1}${s.map(f=>f.data).join(",")}${O1}`,p={events:u,message:{byteLength:i,data:d}},h=c??new Map;return h.set(a,p),c===void 0&&A1.set(o,h),p}function C1(e,t,r,n){if(e.readyState!==1)return false;if(e.bufferedAmount>k1)return n(),e.close(1013,"Client is too slow; refresh the snapshot"),false;let i=t();if(i===void 0||i.byteLength>pg$1)return e.close(1009,"Event frame is too large; refresh the snapshot"),false;let s=e.bufferedAmount+i.byteLength;return s>k1?(n(),e.close(1013,"Client is too slow; refresh the snapshot"),false):(s>mX&&r(),e.send(i.data),true)}function N1(e,t,r,n){return C1(e,()=>{if(!(t.type==="events.batch"&&t.events.some(i=>Cw(i)>og$1)))return yX(t)},r,n)}function j1(e,t,r,n){for(let i=0;i<t.length;){let s=i;if(!C1(e,()=>{let o=vX(t,i);if(o!==void 0)return s+=o.events.length,o.message},r,n))return false;i=s;}return true}var _X=16,SX=og$1,bX=4*1048576,EX=32;function TX(e){return e.type==="command.output_delta"||e.type==="file_change.updated"||e.type==="message.delta"||e.type==="plan.delta"||e.type==="reasoning.delta"||e.type==="tool.progress"}function L1(e){let t=e.type==="reasoning.delta"?`${e.payload.field}:${String(e.payload.sectionIndex??-1)}`:"value";return JSON.stringify([e.taskId,e.turnId,e.itemId,e.type,t])}function RX(e,t){return e.type==="command.output_delta"&&t.type==="command.output_delta"||e.type==="message.delta"&&t.type==="message.delta"||e.type==="plan.delta"&&t.type==="plan.delta"||e.type==="reasoning.delta"&&t.type==="reasoning.delta"?{...e,payload:{...e.payload,delta:e.payload.delta+t.payload.delta}}:t}var Tl=class{#e;#t;#n;#r=new Set;#i;#o;#f;#l=[];#s;#p;#h;#d=0;#c=false;#a=0;#m=0;#y=0;#g;#k=0;#b=0;#T=0;#R=0;#v=0;#w=0;#E=false;constructor(t){let r=t.capacity??1e3;if(!Number.isInteger(r)||r<=0)throw new RangeError("Agent Event capacity must be a positive integer");let n=t.coalescingWindowMs??_X,i=t.maxEventBytes??SX,s=t.maxRetainedBytes??bX,o=t.pressureCoalescingWindowMs??EX;if(!Number.isFinite(n)||n<=0)throw new RangeError("Agent Event coalescing window must be a positive number");if(!Number.isFinite(o)||o<n)throw new RangeError("Agent Event pressure coalescing window must not be shorter than the normal window");if(!Number.isSafeInteger(i)||i<0)throw new RangeError("Agent Event maxEventBytes must be a non-negative safe integer");if(!Number.isSafeInteger(s)||s<0)throw new RangeError("Agent Event maxRetainedBytes must be a non-negative safe integer");this.#e=r,this.#t=n,this.#n=new Array(r),this.#i=i,this.#o=s,this.#f=t.now??(()=>new Date),this.#s=o,this.#p=t.provider,this.#h=t.sessionId;}get checkpoint(){return this.#_(),{sequence:this.#w,sessionId:this.#h}}get metrics(){return {backpressureSignals:this.#d,coalescedEvents:this.#a,pendingDeltas:this.#l.length,providerEventsReceived:this.#b,publishedEvents:this.#T,retainedEvents:this.#m,retentionEvictions:this.#v}}publish(t){if(this.#c)return;if(this.#b+=1,!TX(t)){this.#_(),this.#u(t);return}if(this.#g===void 0){this.#u(t),this.#O();return}let r=this.#l.length-1,n=this.#l[r];n===void 0||L1(n)!==L1(t)?this.#l.push(t):(this.#l[r]=RX(n,t),this.#a+=1);}noteBackpressure(){this.#c||(this.#d+=1,this.#E=true);}replayAfter(t){if(this.#_(),t>this.#w)return {latestSequence:this.#w,reason:"session_changed",type:"resync"};let r=this.#I();return t<this.#k?{latestSequence:this.#w,reason:"event_retention_exceeded",type:"resync"}:{events:r.filter(n=>n.sequence>t),type:"events"}}subscribe(t){return this.#c?()=>{}:(this.#r.add(t),()=>{this.#r.delete(t);})}close(){this.#c||(this.#_(),this.#c=true,this.#r.clear());}#_(){if(this.#g!==void 0&&(clearTimeout(this.#g),this.#g=void 0),this.#l.length===0)return;let t=this.#l.splice(0);for(let r of t)this.#u(r);}#u(t){this.#w+=1;let r={...t,provider:this.#p,sequence:this.#w,sessionId:this.#h,timestamp:this.#f().toISOString(),version:2};this.#P(r),this.#T+=1;for(let n of this.#r)n(r);}#P(t){let r=Cw(t);if(r>this.#i||r>this.#o){for(;this.#m>0;)this.#x();this.#k=t.sequence,this.#v+=1;return}for(this.#m===this.#e&&this.#x();this.#m>0&&this.#R+r>this.#o;)this.#x();let n=(this.#y+this.#m)%this.#e;this.#n[n]={event:t,retainedBytes:r},this.#m+=1,this.#R+=r;}#I(){let t=[];for(let r=0;r<this.#m;r+=1){let n=this.#n[(this.#y+r)%this.#e];n!==void 0&&t.push(n.event);}return t}#x(){let t=this.#n[this.#y];t!==void 0&&(this.#n[this.#y]=void 0,this.#y=(this.#y+1)%this.#e,this.#m-=1,this.#R-=t.retainedBytes,this.#k=t.event.sequence,this.#v+=1);}#O(){if(this.#g!==void 0)return;let t=this.#E?this.#s:this.#t;this.#E=false,this.#g=setTimeout(()=>{this.#g=void 0,this.#_();},t);}};var OH=e(gT(),1),yT=new WeakMap,E_e=3e3;function wT(e,t){yT.set(e,t);}var nd=class extends OH.LogController{incomingRequest(){}routeNotFound(){}requestCompleted(t,r,n){let i=r.routeOptions.url,s=yT.get(r)??(t?"REQUEST_FAILED":void 0);yT.delete(r);let o=r.params,a={durationMs:n.elapsedTime,...s===void 0?{}:{errorCode:s},method:r.method,requestId:r.id,route:i,statusCode:n.statusCode,...Object.fromEntries(["projectId","taskId","turnId"].filter(c=>typeof o?.[c]=="string").map(c=>[c,o?.[c]]))};t||n.statusCode>=500?r.log.error(a,"request completed"):i?.startsWith("/v1/")&&i!=="/v1/health"&&(n.statusCode>=400?r.log.warn(a,"request rejected"):n.elapsedTime>=E_e&&!r.ws?r.log.warn(a,"slow request completed"):["POST","PUT","PATCH","DELETE"].includes(r.method)&&r.log.info(a,"operation completed"));}};var vT=e(k(),1);vT.default.configure;var CH=vT.default;function qe(e,t){return e instanceof Error&&e.message.length>0?e.message:typeof e=="string"&&e.length>0?e:t}var L=class extends Error{constructor(r,n,i,s=false){super(n);this.code=r;this.statusCode=i;this.retryable=s;this.name="MutationHttpError";}code;statusCode;retryable};function Vm(e){let t=e instanceof Error&&e.message.trim().length>0?e.message:"MCP provider request failed";return new L("PROVIDER_ERROR",t,502,true)}var DH=64*1024;function MH(e){return e==="image"?Fb:e==="text"?Ib:Db}function jH(e){return [...e].sort((t,r)=>t.id.localeCompare(r.id,"en"))}function Mi(e,t,r="workspace-write"){let n=jH(e),i=n.find(a=>a.id===t?.model)??n.find(a=>a.isDefault)??n[0];if(i===void 0)throw new L("PROVIDER_ERROR","No Agent models are available",502,true);let s=jH(i.supportedReasoningEfforts),o=s.find(a=>a.id===t?.reasoningEffort)?.id??s.find(a=>a.id===i.defaultReasoningEffort)?.id??s[0]?.id;if(o===void 0)throw new L("PROVIDER_ERROR","The selected Agent model has no reasoning effort",502,true);return {model:i.id,reasoningEffort:o,sandboxMode:t?.sandboxMode??r}}function Km(e,t){let r=Mi(e,t);if(r.model!==t.model||r.reasoningEffort!==t.reasoningEffort)throw new L("INVALID_REQUEST","Model and reasoning effort combination is invalid",400)}function FH(e,t={}){return {id:e.id,pinned:e.pinned,projectId:e.projectId,...e.threadConfiguration===void 0?{}:{threadConfiguration:e.threadConfiguration},title:t.title??e.title,updatedAt:e.updatedAt,...e.workspacePath===void 0?{}:{workspacePath:e.workspacePath}}}function $H(e,t){return async()=>{let r=await e.readProviderConnection(),n,i;try{n=await e.listModels();}catch(o){i=o instanceof Error?o:new Error("Model catalog unavailable");}if(n===void 0||n.data.length===0){if(r.mode!=="custom")throw i??new L("PROVIDER_ERROR","No Agent models are available",502,true);let o$1=await t.readProviderConnection().catch(()=>{});if(o$1?.mode==="custom"&&r.customBaseUrl?.replace(/\/+$/u,"")===o$1.customBaseUrl?.replace(/\/+$/u,"")&&o$1.customModels!==null&&o$1.customModels.data.length>0)return o(o$1.customModels);throw i??new L("PROVIDER_ERROR","No Agent models are available",502,true)}let s=r.mode==="custom"?o(n):n;return await t.writeProviderConnection({customBaseUrl:r.customBaseUrl,customModels:r.mode==="custom"?{data:s.data.map(o=>({...o,supportedReasoningEfforts:[...o.supportedReasoningEfforts]})),nextCursor:s.nextCursor}:null,mode:r.mode,updatedAt:new Date().toISOString()}).catch(()=>{}),s}}var Wm=class{#e;#t;#n;#r;#i=0;#o;constructor(t,r){this.#e=t,this.#t=r.maxBytes,this.#n=r.ttlMs;}read(){let t=this.#r;if(t!==void 0&&t.expiresAt>Date.now())return Promise.resolve(t.page);if(this.#r=void 0,this.#o!==void 0)return this.#o;let r=this.#i,n=this.#e().then(i=>{let s=Buffer$1.byteLength(JSON.stringify(i),"utf8");return r===this.#i&&s<=this.#t&&(this.#r={expiresAt:Date.now()+this.#n,page:i}),i}).finally(()=>{this.#o===n&&(this.#o=void 0);});return this.#o=n,n}clear(){this.#i+=1,this.#r=void 0,this.#o=void 0;}replace(t){this.#i+=1,this.#o=void 0;let r=Buffer$1.byteLength(JSON.stringify(t),"utf8");this.#r=r<=this.#t?{expiresAt:Date.now()+this.#n,page:t}:void 0;}},qH=1e3,UH=600*1e3,BH=6e4,HH=1*1024*1024,GH=3e4,T_e=55e3,R_e={additionalProperties:false,properties:{message:{maxLength:1e4,minLength:1,type:"string"}},required:["message"],type:"object"};function _c(e){let t=CH(e);if(t===void 0)throw new TypeError("Payload must be JSON-serializable");return t}function zH(e){switch(e.code){case "not_found":return new L("PENDING_REQUEST_NOT_FOUND","Pending request not found",404);case "expired":return new L("PENDING_REQUEST_EXPIRED","Pending request expired",409);case "resolved":return new L("PENDING_REQUEST_ALREADY_RESOLVED","Pending request already resolved",409);case "mismatch":return new L("PENDING_REQUEST_MISMATCH","Pending request identity does not match",409)}}function VH(e,t){if(e.repositoryMode!=="root")throw new L("GIT_REPOSITORY_UNAVAILABLE","Git commits require the project root to be a repository",409);if(e.snapshot!==t.expectedSnapshot)throw new L("GIT_STATUS_CHANGED","Git changes changed before the request completed",409);let r=new Set([...e.staged,...e.unstaged].map(n=>n.path));if(t.paths.some(n=>!r.has(n)))throw new L("GIT_PATH_UNAVAILABLE","A selected file is no longer available",409)}function LH(e,t){if(e.status!=="completed")throw new L("COMMIT_MESSAGE_GENERATION_FAILED",e.error??"Commit message generation did not complete",502,true);let r=t;for(let n of [...e.items].reverse())if(n.type==="message"&&n.role==="assistant"){r=n.text;break}if(r===void 0)throw new L("COMMIT_MESSAGE_GENERATION_FAILED","Codex returned no commit message",502,true);try{let n=JSON.parse(r);if(typeof n!="object"||n===null||Object.keys(n).length!==1||!("message"in n)||typeof n.message!="string"||n.message.trim().length===0||n.message.length>1e4)throw new Error("Invalid structured output");return n.message.trim()}catch{throw new L("COMMIT_MESSAGE_GENERATION_FAILED","Codex returned an invalid commit message",502,true)}}async function WH(e,t,r){let n=await e.startTask({ephemeral:true}),i=new Map,s,o=false,a,c;try{let l=new Promise((m,p)=>{c=e.subscribeEvents(h=>{h.taskId===n.id&&(h.type==="item.completed"&&h.payload.item.type==="message"&&h.payload.item.role==="assistant"?i.set(h.turnId,h.payload.item.text):h.type==="turn.completed"?(o=!0,m(h.payload.turn)):h.type==="provider.error"&&!h.payload.willRetry&&p(new Error(h.payload.message)));},{includeEphemeral:!0}),a=setTimeout(()=>{p(new Error("Commit message generation timed out"));},T_e);}),u=await e.startTurn(n.id,{files:[],images:[],outputSchema:R_e,skills:[],text:t,textAttachments:[]},{...r,approvalPolicy:"never",approvalsReviewer:"user",sandboxMode:"read-only"});if(s=u.id,u.status!=="running")return o=!0,LH(u);let d=await l;return LH(d,i.get(d.id))}catch(l){throw l instanceof L?l:new L("COMMIT_MESSAGE_GENERATION_FAILED",qe(l,"Codex could not generate a commit message"),502,true)}finally{a!==void 0&&clearTimeout(a),c?.(),!o&&s!==void 0&&await e.interruptTurn(n.id,s).catch(()=>{}),await e.unsubscribeTask(n.id).catch(()=>{});}}function KH(e){let t=e.code==="GIT_COMMIT_FAILED"?502:409;return new L(e.code,e.message,t)}function YH(e,t,r){let n={...t,...r},i=Mi(e,n,n.sandboxMode??"workspace-write"),s=Mi(e,{model:t?.commitMessageModel??rd,sandboxMode:"read-only"},"read-only"),o=n.approvalPolicy??"on-request",a=n.approvalsReviewer??"user";return {approvalPolicy:o,approvalsReviewer:a,commitMessageModel:s.model,commitMessagePrompt:t?.commitMessagePrompt??"",modelContextWindow:r.modelContextWindow??null,defaultOpenAppId:t?.defaultOpenAppId??null,fastMode:r.fastMode??t?.fastMode??false,followUpBehavior:t?.followUpBehavior??"queue",pet:t?.pet??{enabled:false,selectedPetId:null},...i}}var ge={additionalProperties:false,properties:{projectId:{minLength:1,type:"string"}},required:["projectId"],type:"object"},QH={additionalProperties:false,properties:{kind:Qb$1,projectId:{minLength:1,type:"string"}},required:["kind","projectId"],type:"object"},JH={additionalProperties:false,properties:{kind:xa,projectId:{minLength:1,type:"string"}},required:["kind","projectId"],type:"object"},XH={additionalProperties:false,properties:{attachmentId:{minLength:1,type:"string"},projectId:{minLength:1,type:"string"}},required:["attachmentId","projectId"],type:"object"},Fe={additionalProperties:false,properties:{projectId:{minLength:1,type:"string"},taskId:{minLength:1,type:"string"}},required:["projectId","taskId"],type:"object"},_T={additionalProperties:false,properties:{projectId:{minLength:1,type:"string"},taskId:{minLength:1,type:"string"},turnId:{minLength:1,type:"string"}},required:["projectId","taskId","turnId"],type:"object"},ST={additionalProperties:false,properties:{projectId:{minLength:1,type:"string"},queuedSubmissionId:{minLength:1,type:"string"},taskId:{minLength:1,type:"string"}},required:["projectId","taskId","queuedSubmissionId"],type:"object"},ZH={additionalProperties:false,properties:{projectId:{minLength:1,type:"string"},taskId:{minLength:1,type:"string"},terminalId:{minLength:1,type:"string"}},required:["projectId","taskId","terminalId"],type:"object"},bT={additionalProperties:false,properties:{attachmentId:{minLength:1,type:"string"},projectId:{minLength:1,type:"string"},taskId:{minLength:1,type:"string"}},required:["attachmentId","projectId","taskId"],type:"object"},eG={additionalProperties:false,properties:{projectId:{minLength:1,type:"string"},requestId:{minLength:1,type:"string"},taskId:{minLength:1,type:"string"}},required:["projectId","taskId","requestId"],type:"object"},X={properties:{"idempotency-key":{minLength:1,type:"string"}},required:["idempotency-key"],type:"object"},tG={additionalProperties:false,properties:{archived:{const:true,type:"boolean"},completed:{const:true,type:"boolean"},cursor:{minLength:1,type:"string"},limit:{maximum:100,minimum:1,type:"integer"},pinned:{const:true,type:"boolean"},searchTerm:{maxLength:200,minLength:1,type:"string"}},type:"object"},rG={additionalProperties:false,properties:{cursor:{maxLength:8192,minLength:1,type:"string"}},type:"object"};var nG={additionalProperties:false,properties:{afterSequence:{minimum:0,type:"integer"}},required:["afterSequence"],type:"object"},le={additionalProperties:false,properties:{code:{minLength:1,type:"string"},message:{minLength:1,type:"string"}},required:["code","message"],type:"object"};var iG=(e,t,r)=>{e.post("/v1/history/compress",{schema:{body:{type:"object",additionalProperties:false},headers:X,response:{200:Eg$1,502:Xf,503:Xf}}},n=>t.runIdempotent(["compress-history"],n.headers["idempotency-key"],n.body,async()=>{let i=t.provider.historyStorage;if(i===void 0)throw new L("PROVIDER_ERROR","History compression is unavailable",503,true);try{return await i.compress()}catch(s){throw new L("PROVIDER_ERROR",s instanceof Error?s.message:"History compression request failed",502,true)}})),r();};var Ym=class{#e=new Set;subscribe(t){return this.#e.add(t),()=>{this.#e.delete(t);}}publish(t){for(let r of this.#e)r(t);}publishAgentEvent(t,r){(r.type==="turn.started"||r.type==="turn.completed"||r.type==="item.completed"&&r.payload.item.type==="message"&&(r.payload.item.questions?.length??0)>0)&&this.publish({type:"async-questions.changed",projectId:t,taskId:r.taskId});}};var cn="codexly_session";function Qm(e,t){return {authenticated:e,mode:t,version:1}}var sG=(e,t,r)=>{let{access:n,service:i}=t,s=n===void 0?"local":"lan";e.get("/v1/access",{schema:{response:{200:Zd$1}}},o=>Qm(s==="local"||i?.validate(o.cookies[cn])===true,s)),e.post("/v1/access/pair",{schema:{body:_d$1,response:{200:Zd$1}}},(o,a)=>{if(n===void 0||i===void 0)return Qm(true,"local");let c=i.pair(o.body.code,o.ip);return c.status!=="paired"?a.code(c.status==="rate_limited"?429:403).send({code:c.status==="rate_limited"?"PAIRING_RATE_LIMITED":"PAIRING_FAILED",message:"Pairing request failed",retryable:c.status==="rate_limited"}):(a.setCookie(cn,c.sessionId,{...c.expiresAt===null||n.sessionTtlMs===void 0?{}:{expires:new Date(c.expiresAt),maxAge:Math.ceil(n.sessionTtlMs/1e3)},httpOnly:true,path:"/",sameSite:"strict",secure:false}),Qm(true,"lan"))}),e.post("/v1/access/logout",{schema:{response:{200:Zd$1}}},(o,a)=>(i?.logout(o.cookies[cn]),a.clearCookie(cn,{path:"/",sameSite:"strict"}),Qm(s==="local",s))),r();};var P_e=2147483647;function ET(e,t){let r,n=()=>{let i=t-Date.now();if(i<=0){e.close(1008,"Access session expired");return}r=setTimeout(n,Math.min(i,P_e)),r.unref();};return n(),()=>{r!==void 0&&clearTimeout(r);}}var oG=(e,t,r)=>{let{accessService:n,getProjectContext:i,projectContexts:s}=t;e.get("/v1/projects/:projectId/events",{async preValidation(o,a){if(await i(o.params.projectId)===void 0)return await a.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"})},schema:{params:ge,querystring:nG},websocket:true},(o,a)=>{let c=n?.expiresAt(a.cookies[cn]);if(n!==void 0&&c===void 0){o.close(1008,"Access session expired");return}let l=s.get(a.params.projectId);if(l===void 0){o.close(1008,"Project not found");return}let u=l.eventStream;l.transportMetrics.activeClients+=1;let d=false,m=false,p=[],h=()=>{},f=()=>{},g=c==null?()=>{}:ET(o,c),y=()=>{d||(d=true,p.length=0,g(),f(),h(),l.transportMetrics.activeClients-=1);};if(o.once("close",y),o.once("error",y),f=n?.onInvalidated(a.cookies[cn],()=>{y(),o.close(1008,"Access session expired");})??(()=>{}),o.readyState!==o.OPEN)return;let _=j=>N1(o,j,()=>{u.noteBackpressure();},()=>{l.transportMetrics.slowClientDisconnects+=1;}),v=j=>j1(o,j,()=>{u.noteBackpressure();},()=>{l.transportMetrics.slowClientDisconnects+=1;}),w=()=>{if(m=false,d||p.length===0)return;let j=p.splice(0);v(j);},E=j=>{if(p.push(j),p.length>=ng){w();return}m||(m=true,queueMicrotask(()=>{m&&w();}));},R=u.replayAfter(a.query.afterSequence);if(R.type==="resync"){_({latestSequence:R.latestSequence,reason:R.reason,sessionId:u.checkpoint.sessionId,type:"resync.required",version:3})&&o.close(1e3,"Snapshot resync required");return}let P=u.checkpoint,b=[],O=true;h=u.subscribe(j=>{if(O){b.push(j);return}E(j);}),_({latestSequence:P.sequence,sessionId:P.sessionId,type:"connection.ready",version:3})&&v(R.events)&&(O=false,v(b));}),r();};function aG(e,t){TT(e,t,"/v1/workbench/events",{type:"workbench.ready"},r=>t.workbenchChanges.subscribe(r));}function TT(e,t,r,n,i){e.get(r,{websocket:true},(s,o)=>{let a=t.accessService?.expiresAt(o.cookies[cn]);if(t.accessService!==void 0&&a===void 0){s.close(1008,"Access session expired");return}let c=a==null?()=>{}:ET(s,a),l=new Set,u=false,d=y=>{if(!(u||s.readyState!==1)){if(s.bufferedAmount>65536){s.close(1013,"Slow client");return}s.send(y,_=>{_&&s.terminate();});}},m=i(y=>{if(u)return;let _=l.size>0;if(l.add(JSON.stringify(y)),l.size>256){s.close(1013,"Too many changes");return}_||queueMicrotask(()=>{for(let v of l)d(v);l.clear();});}),p=true;s.on("pong",()=>{p=true;});let h=setInterval(()=>{if(!p){s.terminate();return}p=false,s.ping();},3e4);h.unref();let f=()=>{},g=()=>{u||(u=true,m(),l.clear(),c(),f(),clearInterval(h));};s.once("close",g),s.once("error",g),f=t.accessService?.onInvalidated(o.cookies[cn],()=>{g(),s.close(1008,"Access session expired");})??(()=>{}),d(JSON.stringify(n));});}var KJ=e(gT(),1);function RT(e,t){return `${e}\0${t}`}var Jm=class{#e=new Map;retain(t,r,n){this.#e.set(RT(t,r),new Set(n));}take(t,r){let n=RT(t,r),i=[...this.#e.get(n)??[]];return this.#e.delete(n),i}replace(t,r,n){let i=RT(t,r),s=this.#e.get(i)??new Set,o=new Set(n);return this.#e.set(i,o),[...s].filter(a=>!o.has(a))}hasAttachment(t){return [...this.#e.values()].some(r=>r.has(t))}deleteAttachment(t){for(let[r,n]of this.#e)n.delete(t),n.size===0&&this.#e.delete(r);}clearProject(t){let r=`${t}\0`;for(let n of this.#e.keys())n.startsWith(r)&&this.#e.delete(n);}};var M_e=1800*1e3,F_e=1500,$_e=Hb+Eb$1,q_e=new Map([["image/gif",".gif"],["image/jpeg",".jpg"],["image/png",".png"],["image/webp",".webp"]]),er=class extends Error{constructor(){super("Attachment was not found or has expired"),this.name="AttachmentNotFoundError";}};function U_e(e){return e==="image"?Fb:e==="text"?Ib:Db}function B_e(e){if(e.name.length===0||e.name.length>255||e.mediaType.length>255)throw new TypeError("Attachment metadata is invalid");if(e.kind==="image"){let r=q_e.get(e.mediaType);if(r===void 0)throw new TypeError("Attachment image type is unsupported");return r}if(e.kind==="text"){if(e.mediaType!=="text/plain")throw new TypeError("Generated text attachment must use text/plain");return ".txt"}return extname(e.name).toLowerCase()}async function hG(e,t){let r=await open(e,"r");try{let n=Buffer$1.alloc(t),{bytesRead:i}=await r.read(n,0,t,0);return n.subarray(0,i)}finally{await r.close();}}async function H_e(e){let t=await open(e,"r"),r=13,n=0,i=async o=>{let a=Buffer$1.alloc(o),{bytesRead:c}=await t.read(a,0,o,r);if(c===o)return r+=o,a},s=async()=>{for(;;){let o=(await i(1))?.[0];if(o===void 0)return false;if(o===0)return true;if(await i(o)===void 0)return false}};try{let o=await hG(e,13),a=o[10];if(o.length<13||a===void 0)return !1;for((a&128)!==0&&(r+=3*2**((a&7)+1));;){let c=(await i(1))?.[0];if(c===void 0||c===59)return n>1;if(c===33){if(await i(1)===void 0||!await s())return !1;continue}if(c!==44)return !1;if(n+=1,n>1)return !0;let l=await i(9);if(l===void 0)return !1;let u=l[8]??0;if((u&128)!==0&&(r+=3*2**((u&7)+1)),await i(1)===void 0||!await s())return !1}}finally{await t.close();}}async function G_e(e,t){let r=await hG(e,12);if(!(t==="image/png"&&r.subarray(0,8).equals(Buffer$1.from("89504e470d0a1a0a","hex"))||t==="image/jpeg"&&r[0]===255&&r[1]===216&&r[2]===255||t==="image/webp"&&r.subarray(0,4).toString("ascii")==="RIFF"&&r.subarray(8,12).toString("ascii")==="WEBP"||t==="image/gif"&&/^GIF8[79]a$/u.test(r.subarray(0,6).toString("ascii")))||t==="image/gif"&&await H_e(e))throw new TypeError("Attachment image content is invalid or animated")}async function z_e(e){let t=new TextDecoder$1("utf-8",{fatal:true});for await(let r of createReadStream(e))t.decode(r,{stream:true});t.decode();}async function uG(e){try{await unlink(e);}catch(t){if(!(t instanceof Error&&"code"in t&&t.code==="ENOENT"))throw t}}var Xm=class{#e;#t;#n;#r=new Map;#i=new Jm;#o;#f;#l;#s;#p=0;#h=0;constructor(t={}){this.#e=t.attachmentDirectory??join(tmpdir(),`codexly-attachments-${randomUUID()}`),this.#t=t.clock??Date.now,this.#n=t.createId??randomUUID,this.#o=t.maxBytes,this.#f=t.maxEntries??F_e,this.#l=t.maxTotalBytes??$_e,this.#s=t.ttlMs??M_e;}async add(t,r){await this.#c();let n=B_e(r),i=this.#o??U_e(r.kind);if(this.#r.size+this.#p>=this.#f)throw new RangeError("Attachment store capacity exceeded");this.#p+=1;let s;try{let o=this.#n();s=join(this.#e,`${Buffer$1.from(o).toString("base64url")}${n}`);let a=createHash("sha256"),c=0,l=new Transform({transform(d,m,p){let h=Buffer$1.isBuffer(d)?d:Buffer$1.from(d);if(c+=h.byteLength,c>i){p(new RangeError("Attachment exceeds the maximum size"));return}a.update(h),p(null,h);}});if(await mkdir(this.#e,{recursive:!0}),await pipeline(r.content,l,createWriteStream(s,{flags:"wx"})),c===0)throw new RangeError("Attachment must not be empty");r.kind==="image"?await G_e(s,r.mediaType):r.kind==="text"&&await z_e(s);let u={id:o,kind:r.kind,mediaType:r.mediaType,name:r.name,size:c};if(this.#h+c>this.#l)throw new RangeError("Attachment store capacity exceeded");return this.#r.set(o,{attachment:u,expiresAt:this.#t()+this.#s,path:s,projectId:t}),this.#h+=c,{attachment:u,contentDigest:a.digest("hex")}}catch(o){throw s!==void 0&&await uG(s),o}finally{this.#p-=1;}}async resolve(t,r){await this.#c();let n=r.map(s=>{let o=this.#r.get(s);if(o?.projectId!==t||o.consumedTurnId!==void 0)throw new er;return o}),i=[];for(let s of n){let{attachment:o,path:a}=s;if(o.kind==="file")i.push({kind:"file",mediaType:o.mediaType,name:o.name,path:a,size:o.size});else if(o.kind==="image"){let c=o.mediaType;i.push({kind:"image",mediaType:c,path:a,size:o.size});}else {let c=await readFile(a);i.push({kind:"text",mediaType:"text/plain",name:o.name,size:o.size,text:new TextDecoder$1("utf-8",{fatal:true}).decode(c)});}}return i}async read(t,r){await this.#c();let n=this.#r.get(r);if(n?.projectId!==t||n.consumedTurnId!==void 0)throw new er;return {attachment:n.attachment,content:await readFile(n.path)}}async readSubmitted(t,r){await this.#c();let n=this.#r.get(r);if(n?.projectId!==t||n.consumedTurnId===void 0)throw new er;return {attachment:n.attachment,content:await readFile(n.path)}}async consume(t,r,n){for(let i of new Set(r)){let s=this.#r.get(i);s?.projectId===t&&(n!==void 0?(s.consumedTurnId=n,s.expiresAt=this.#t()+this.#s):await this.#d(i));}}async retainQueue(t,r,n,i=false){let s=[...new Set(r)];for(let a of s){let c=this.#r.get(a);if(c?.projectId!==t||c.consumedTurnId!==void 0)throw new er;c.expiresAt=this.#t()+this.#s;}if(!i){this.#i.retain(t,n,s);return}let o=this.#i.replace(t,n,s);await Promise.all(o.map(a=>this.#d(a)));}startQueue(t,r,n){for(let i of this.#i.take(t,r)){let s=this.#r.get(i);s?.projectId===t&&(s.consumedTurnId=n,s.expiresAt=this.#t()+this.#s);}return Promise.resolve()}async releaseQueue(t,r){let n=this.#i.take(t,r);await Promise.all(n.map(async i=>{let s=this.#r.get(i);s?.projectId===t&&s.consumedTurnId===void 0&&await this.#d(i);}));}async discard(t){await this.#d(t);}async releaseTurn(t,r){for(let[n,i]of this.#r)i.projectId===t&&i.consumedTurnId===r&&await this.#d(n);}async releaseProject(t){this.#i.clearProject(t);let r=[...this.#r].filter(([,n])=>n.projectId===t).map(([n])=>n);await Promise.all(r.map(n=>this.#d(n)));}async releaseProjectRuntime(t){let r=[...this.#r].filter(([n,i])=>i.projectId===t&&!this.#i.hasAttachment(n)).map(([n])=>n);await Promise.all(r.map(n=>this.#d(n)));}async clear(){await Promise.all([...this.#r.keys()].map(t=>this.#d(t)));}async dispose(){await this.clear(),await rm$1(this.#e,{force:true,recursive:true});}async#d(t){let r=this.#r.get(t);r!==void 0&&(this.#r.delete(t),this.#i.deleteAttachment(t),this.#h-=r.attachment.size,await uG(r.path));}async#c(){let t=this.#t();for(let[r,n]of this.#r)n.expiresAt<=t&&!this.#i.hasAttachment(r)&&await this.#d(r);}};var kT=new WeakMap;function id(...e){let t=new String(e);return kT.set(t,e),t}function ti(e){return e instanceof String&&kT.has(e)}function bc(e){return kT.get(e)??[]}var yg=e(PG(),1),wg=e(OT(),1),As=e(kG(),1);function*xG(e,t){let r=t==="global";for(let n of e)n.isGlobal===r&&(yield n);}var bSe=new Set(["--add","--edit","--remove-section","--rename-section","--replace-all","--unset","--unset-all","-e"]),ESe=new Set(["--get","--get-all","--get-color","--get-colorbool","--get-regexp","--get-urlmatch","--list","-l"]),TSe=new Set(["edit","remove-section","rename-section","set","unset"]),RSe=new Set(["get","get-color","get-colorbool","list"]);function PSe(e,t){for(let{name:n}of xG(e,"task")){if(bSe.has(n))return kc(true,t);if(ESe.has(n))return kc(false,t)}let r=t.at(0)?.toLowerCase();return r===void 0?null:TSe.has(r)?kc(true,t.slice(1)):RSe.has(r)?kc(false,t.slice(1)):t.length===1?kc(false,t):kc(true,t)}function kc(e=false,t=[]){let r=t.at(0)?.toLowerCase();return r===void 0?null:{isWrite:e,isRead:!e,key:r,value:t.at(1)}}function kSe(e,t){return t.isWrite&&t.value!==void 0?{key:t.key,value:t.value,scope:e}:{key:t.key,scope:e}}function xSe(e){let t=e?.indexOf("=")||-1;return !e||t<0?null:{key:e.slice(0,t).trim().toLowerCase(),value:e.slice(t+1)}}function ASe(e){for(let{name:t}of xG(e,"task"))switch(t){case "--global":return "global";case "--system":return "system";case "--worktree":return "worktree";case "--local":return "local";case "--file":case "-f":return "file"}return "local"}function ISe({name:e}){if(e==="-c"||e==="--config")return "inline";if(e==="--config-env")return "env"}function*OSe(e){for(let t of e){let r=ISe(t),n=r&&xSe(t.value);n&&(yield {...n,scope:r});}}function CSe(e,t,r){let n={read:[],write:[...OSe(t)]};return e==="config"&&NSe(n,ASe(t),PSe(t,r)),n}function NSe(e,t,r){if(r===null)return;let n=kSe(t,r);r.isWrite?e.write.push(n):e.read.push(n);}var AG={short:new Map([["c",true]])},jSe={short:new Map([["C",true],["P",false],["h",false],["p",false],["v",false],...AG.short.entries()]),long:new Set(["attr-source","config-env","exec-path","git-dir","list-cmds","namespace","super-prefix","work-tree"])},LSe={clone:{short:new Map([["b",true],["j",true],["l",false],["n",false],["o",true],["q",false],["s",false],["u",true]]),long:new Set(["branch","config","jobs","origin","upload-pack","u","template"])},commit:{short:new Map([["C",true],["F",true],["c",true],["m",true],["t",true]]),long:new Set(["file","message","reedit-message","reuse-message","template"])},config:{short:new Map([["e",false],["f",true],["l",false]]),long:new Set(["blob","comment","default","file","type","value"])},fetch:{short:new Map,long:new Set(["upload-pack"])},init:{short:new Map,long:new Set(["template"])},pull:{short:new Map,long:new Set(["upload-pack"])},push:{short:new Map,long:new Set(["exec","receive-pack"])},rebase:{short:new Map([["X",true],["f",false],["i",false],["k",false],["m",false],["n",false],["q",false],["r",false],["s",true],["v",false],["x",true]]),long:new Set(["exec","onto","strategy","strategy-option"])}},DSe={short:new Map,long:new Set};function MSe(e){let t=LSe[e??""]??DSe;return {short:new Map([...AG.short.entries(),...t.short.entries()]),long:t.long}}function IG(e,t=jSe){if(e.startsWith("--")){let r=e.indexOf("=");if(r>2)return [{name:e.slice(0,r),value:e.slice(r+1),needsNext:false}];let n=e.slice(2);return [{name:e,needsNext:t.long.has(n)}]}if(e.length===2){let r=e.charAt(1),n=t.short.get(r);return [{name:e,needsNext:n===true}]}return FSe(e,t.short)}function FSe(e,t){let r=e.slice(1).split(""),n=[];for(let i=0;i<r.length;i++){let s=r[i],o=t.get(s);if(o===void 0)return [{name:e,needsNext:false}];if(o){let a=r.slice(i+1).join("");if(a&&![...a].every(c=>t.has(c)))return n.push({name:`-${s}`,value:a,needsNext:false}),n}n.push({name:`-${s}`,needsNext:o});}return n}function $Se(e,t=[]){let r=0;for(;r<e.length;){let n=String(e[r]);if(!n.startsWith("-")||n.length<2)break;let i=IG(n),s=r+1;for(let o of i){let a={name:o.name,value:o.value,absorbedNext:false,isGlobal:true};o.needsNext&&a.value===void 0&&s<e.length&&(a.value=String(e[s]),a.absorbedNext=true,s++),t.push(a);}r=s;}return {flags:t,taskIndex:r}}function qSe(e,t,r=[]){let n=MSe(t),i=[],s=[],o=0;for(;o<e.length;){let a=e[o];if(ti(a)){s.push(...bc(a)),o++;continue}let c=String(a);if(c==="--"){for(let d=o+1;d<e.length;d++){let m=e[d];ti(m)?s.push(...bc(m)):s.push(String(m));}break}if(!c.startsWith("-")||c.length<2){i.push(c),o++;continue}let l=IG(c,n),u=o+1;for(let d of l){let m={name:d.name,value:d.value,absorbedNext:false,isGlobal:false};d.needsNext&&m.value===void 0&&u<e.length&&!ti(e[u])&&(m.value=String(e[u]),m.absorbedNext=true,u++),r.push(m);}o=u;}return {flags:r,positionals:i,pathspecs:s}}function*USe({write:e}){for(let t of e)for(let r of BSe){let n=r(t.key);n&&(yield n);}}function Lr(e,t,r=String(e)){let n=typeof e=="string"?new RegExp(`\\s*${e.toLowerCase()}`):e;return function(i){if(n.test(i))return {category:t,message:`Configuring ${r} is not permitted without enabling ${t}`}}}function Ct(e,t){let r=new RegExp(`\\s*${e.toLowerCase().replace(/\./g,"(..+)?.")}`);return Lr(r,t,e)}var BSe=[Lr("alias","allowUnsafeAlias"),Lr("core.askPass","allowUnsafeAskPass"),Lr("core.editor","allowUnsafeEditor"),Lr("core.fsmonitor","allowUnsafeFsMonitor"),Lr("core.gitProxy","allowUnsafeGitProxy"),Lr("core.hooksPath","allowUnsafeHooksPath"),Lr("core.pager","allowUnsafePager"),Lr("core.sshCommand","allowUnsafeSshCommand"),Ct("credential.helper","allowUnsafeCredentialHelper"),Ct("diff.command","allowUnsafeDiffExternal"),Lr("diff.external","allowUnsafeDiffExternal"),Ct("difftool.cmd","allowUnsafeDiffExternal"),Ct("diff.textconv","allowUnsafeDiffTextConv"),Ct("filter.clean","allowUnsafeFilter"),Ct("filter.process","allowUnsafeFilter"),Ct("filter.smudge","allowUnsafeFilter"),Ct("gpg.program","allowUnsafeGpgProgram"),Lr("include.path","allowUnsafeInclude"),Ct("includeIf","allowUnsafeInclude"),Lr("init.templateDir","allowUnsafeTemplateDir"),Ct("pager.","allowUnsafePager"),Ct("merge.driver","allowUnsafeMergeDriver"),Ct("mergetool.path","allowUnsafeMergeDriver"),Ct("mergetool.cmd","allowUnsafeMergeDriver"),Ct("protocol.allow","allowUnsafeProtocolOverride"),Ct("remote.receivepack","allowUnsafePack"),Ct("remote.uploadpack","allowUnsafePack"),Lr("uploadpack.packObjectsHook","allowUnsafePack"),Lr("sequence.editor","allowUnsafeEditor"),Ct("submodule.update","allowUnsafeSubmodule"),Ct("tar.command","allowUnsafeCommandBinaries"),Ct("trailer.cmd","allowUnsafeCommandBinaries"),Ct("trailer.command","allowUnsafeCommandBinaries"),Ct("url.insteadOf","allowUnsafeUrlRewrite")];function*HSe(e,t){for(let r of t)for(let n of GSe){let i=n(e,r);i&&(yield i);}}function ri(e,t,r,{name:n=String(t),globalOnly:i=false,withValue:s=false}={}){let o=typeof t=="string"?new RegExp(`\\s*${t.toLowerCase()}`):t,a=`Use of ${e?`${e} with option `:""}${n} is not permitted without enabling ${r}`;return function(c,l){if(!(e&&c!==e)&&!(i&&!l.isGlobal)&&!(s&&l.value===void 0)&&o.test(l.name))return {category:r,message:a}}}var sg={globalOnly:true,withValue:true},GSe=[ri(null,/--(upload|receive)-pack/,"allowUnsafePack",{name:"--upload-pack or --receive-pack"}),ri("clone",/^-\w*u/,"allowUnsafePack"),ri("clone","--u","allowUnsafePack"),ri("push",/^--exec$/,"allowUnsafePack",{name:"--exec"}),ri("rebase",/^(-x|--ex(ec?)?)$/,"allowUnsafeExec",{name:"-x or --exec"}),ri(null,"--template","allowUnsafeTemplateDir"),ri(null,"--exec-path","allowUnsafeExec",sg),ri(null,"--git-dir","allowUnsafeConfigPaths",sg),ri(null,"--work-tree","allowUnsafeConfigPaths",sg),ri(null,/^-C$/,"allowUnsafeConfigPaths",{...sg,name:"-C"})];function OG(e,t,r){return [...HSe(e,t),...USe(r)]}function zSe(...e){let{flags:t,taskIndex:r}=$Se(e),n=r<e.length?String(e[r]).toLowerCase():null,i=n!==null?e.slice(r+1):[],{positionals:s,pathspecs:o}=qSe(i,n,t),a=CSe(n,t,s);return {task:n,flags:t.map(WSe),paths:o,config:a,vulnerabilities:VSe(OG(n,t,a))}}function VSe(e){return Object.defineProperty(e,"vulnerabilities",{value:e})}function WSe({value:e,name:t}){return e!==void 0?{name:t,value:e}:{name:t}}var CG={editor:"allowUnsafeEditor",git_askpass:"allowUnsafeAskPass",git_config_global:"allowUnsafeConfigPaths",git_config_system:"allowUnsafeConfigPaths",git_config_count:"allowUnsafeConfigEnvCount",git_config_parameters:"allowUnsafeConfigEnvCount",git_config:"allowUnsafeConfigPaths",git_editor:"allowUnsafeEditor",git_exec_path:"allowUnsafeExec",git_external_diff:"allowUnsafeDiffExternal",git_pager:"allowUnsafePager",git_proxy_command:"allowUnsafeGitProxy",git_template_dir:"allowUnsafeTemplateDir",git_sequence_editor:"allowUnsafeEditor",git_ssh:"allowUnsafeSshCommand",git_ssh_command:"allowUnsafeSshCommand",pager:"allowUnsafePager",prefix:"allowUnsafeConfigPaths",ssh_askpass:"allowUnsafeAskPass",visual:"allowUnsafeEditor"};function*KSe(e){let t=parseInt(e.git_config_count??"0",10);for(let r=0;r<t;r++){let n=e[`git_config_key_${r}`],i=e[`git_config_value_${r}`];n!==void 0&&(yield {key:n.toLowerCase().trim(),value:i,scope:"env"});}}function*YSe(e){for(let t of Object.keys(e))if(og(t)){let r=CG[t];yield {category:r,message:`Use of "${t.toUpperCase()}" is not permitted without enabling ${r}`};}}function og(e){return Object.hasOwn(CG,e)}function QSe(e){let t={};for(let[r,n]of Object.entries(e)){let i=r.toLowerCase().trim();(og(i)||i.startsWith("git"))&&(t[i]=String(n));}return t}function JSe(e){let t=QSe(e),r={read:[],write:[...KSe(t)]},n=[...YSe(t),...OG(null,[],r)];return {config:r,vulnerabilities:n}}function NG(e,t){return [...zSe(...e).vulnerabilities,...JSe(t).vulnerabilities]}var In=class extends Error{constructor(t,r){super(r),this.task=t,Object.setPrototypeOf(this,new.target.prototype);}},FT=class extends In{constructor(t,r){super(void 0,r),this.config=t;}},Fi=class extends In{constructor(t,r,n){super(t,n),this.task=t,this.plugin=r,Object.setPrototypeOf(this,new.target.prototype);}},ad=class extends In{constructor(t,r){super(void 0,r||String(t)),this.git=t;}},$T=class extends In{constructor(t){super(void 0,t);}},lg="\0",vg=()=>{};function tbe(e){return typeof e!="function"?vg:e}function rbe(e){return typeof e=="function"&&e!==vg}function nbe(e,t){let r=e.indexOf(t);return r<=0?[e,""]:[e.substr(0,r),e.substr(r+1)]}function ibe(e,t=0){return JG(e)&&e.length>t?e[t]:void 0}function xc(e,t=0){if(JG(e)&&e.length>t)return e[e.length-1-t]}function JG(e){return e3(e)}function _g(e="",t=true,r=`
|
|
529
|
+
`+r);}function oa(e,t,r,n,i,s){if(e.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,oa),e.emit("wsClientError",o,r,t);}else jf(r,n,i,s);}});var u7=c((b7e,l7)=>{var xFe=ZQ(),AFe=M0(),IFe=al(),OFe=iA(),CFe=aA(),NFe=hA(),Un=U0(),c7=a7();Un.createWebSocketStream=xFe;Un.extension=AFe;Un.PerMessageDeflate=IFe;Un.Receiver=OFe;Un.Sender=CFe;Un.Server=c7;Un.subprotocol=NFe;Un.WebSocket=Un;Un.WebSocketServer=c7;l7.exports=Un;});var mA=c((E7e,d7)=>{d7.exports=a("stream");});var y7=c((T7e,g7)=>{function f7(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n);}return r}function h7(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?f7(Object(r),true).forEach(function(n){jFe(e,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):f7(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n));});}return e}function jFe(e,t,r){return t=m7(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:true,configurable:true,writable:true}):e[t]=r,e}function LFe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function p7(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||false,n.configurable=true,"value"in n&&(n.writable=true),Object.defineProperty(e,m7(n.key),n);}}function DFe(e,t,r){return t&&p7(e.prototype,t),Object.defineProperty(e,"prototype",{writable:false}),e}function m7(e){var t=MFe(e,"string");return typeof t=="symbol"?t:String(t)}function MFe(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (String)(e)}var FFe=a("buffer"),H0=FFe.Buffer,$Fe=a("util"),gA=$Fe.inspect,qFe=gA&&gA.custom||"inspect";function UFe(e,t,r){H0.prototype.copy.call(e,t,r);}g7.exports=(function(){function e(){LFe(this,e),this.head=null,this.tail=null,this.length=0;}return DFe(e,[{key:"push",value:function(r){var n={data:r,next:null};this.length>0?this.tail.next=n:this.head=n,this.tail=n,++this.length;}},{key:"unshift",value:function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length;}},{key:"shift",value:function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0;}},{key:"join",value:function(r){if(this.length===0)return "";for(var n=this.head,i=""+n.data;n=n.next;)i+=r+n.data;return i}},{key:"concat",value:function(r){if(this.length===0)return H0.alloc(0);for(var n=H0.allocUnsafe(r>>>0),i=this.head,s=0;i;)UFe(i.data,n,s),s+=i.data.length,i=i.next;return n}},{key:"consume",value:function(r,n){var i;return r<this.head.data.length?(i=this.head.data.slice(0,r),this.head.data=this.head.data.slice(r)):r===this.head.data.length?i=this.shift():i=n?this._getString(r):this._getBuffer(r),i}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(r){var n=this.head,i=1,s=n.data;for(r-=s.length;n=n.next;){var o=n.data,a=r>o.length?o.length:r;if(a===o.length?s+=o:s+=o.slice(0,r),r-=a,r===0){a===o.length?(++i,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=o.slice(a));break}++i;}return this.length-=i,s}},{key:"_getBuffer",value:function(r){var n=H0.allocUnsafe(r),i=this.head,s=1;for(i.data.copy(n),r-=i.data.length;i=i.next;){var o=i.data,a=r>o.length?o.length:r;if(o.copy(n,n.length-r,0,a),r-=a,r===0){a===o.length?(++s,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=o.slice(a));break}++s;}return this.length-=s,n}},{key:qFe,value:function(r,n){return gA(this,h7(h7({},n),{},{depth:0,customInspect:false}))}}]),e})();});var wA=c((R7e,v7)=>{function BFe(e,t){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=true,process.nextTick(yA,this,e)):process.nextTick(yA,this,e)),this):(this._readableState&&(this._readableState.destroyed=true),this._writableState&&(this._writableState.destroyed=true),this._destroy(e||null,function(s){!t&&s?r._writableState?r._writableState.errorEmitted?process.nextTick(G0,r):(r._writableState.errorEmitted=true,process.nextTick(w7,r,s)):process.nextTick(w7,r,s):t?(process.nextTick(G0,r),t(s)):process.nextTick(G0,r);}),this)}function w7(e,t){yA(e,t),G0(e);}function G0(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close");}function HFe(){this._readableState&&(this._readableState.destroyed=false,this._readableState.reading=false,this._readableState.ended=false,this._readableState.endEmitted=false),this._writableState&&(this._writableState.destroyed=false,this._writableState.ended=false,this._writableState.ending=false,this._writableState.finalCalled=false,this._writableState.prefinished=false,this._writableState.finished=false,this._writableState.errorEmitted=false);}function yA(e,t){e.emit("error",t);}function GFe(e,t){var r=e._readableState,n=e._writableState;r&&r.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t);}v7.exports={destroy:BFe,undestroy:HFe,errorOrDestroy:GFe};});var Qs=c((P7e,b7)=>{var S7={};function vn(e,t,r){r||(r=Error);function n(s,o,a){return typeof t=="string"?t:t(s,o,a)}class i extends r{constructor(o,a,c){super(n(o,a,c));}}i.prototype.name=r.name,i.prototype.code=e,S7[e]=i;}function _7(e,t){if(Array.isArray(e)){let r=e.length;return e=e.map(n=>String(n)),r>2?`one of ${t} ${e.slice(0,r-1).join(", ")}, or `+e[r-1]:r===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}else return `of ${t} ${String(e)}`}function zFe(e,t,r){return e.substr(0,t.length)===t}function VFe(e,t,r){return (r===void 0||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}function WFe(e,t,r){return typeof r!="number"&&(r=0),r+t.length>e.length?false:e.indexOf(t,r)!==-1}vn("ERR_INVALID_OPT_VALUE",function(e,t){return 'The value "'+t+'" is invalid for option "'+e+'"'},TypeError);vn("ERR_INVALID_ARG_TYPE",function(e,t,r){let n;typeof t=="string"&&zFe(t,"not ")?(n="must not be",t=t.replace(/^not /,"")):n="must be";let i;if(VFe(e," argument"))i=`The ${e} ${n} ${_7(t,"type")}`;else {let s=WFe(e,".")?"property":"argument";i=`The "${e}" ${s} ${n} ${_7(t,"type")}`;}return i+=`. Received type ${typeof r}`,i},TypeError);vn("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");vn("ERR_METHOD_NOT_IMPLEMENTED",function(e){return "The "+e+" method is not implemented"});vn("ERR_STREAM_PREMATURE_CLOSE","Premature close");vn("ERR_STREAM_DESTROYED",function(e){return "Cannot call "+e+" after a stream was destroyed"});vn("ERR_MULTIPLE_CALLBACK","Callback called multiple times");vn("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");vn("ERR_STREAM_WRITE_AFTER_END","write after end");vn("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);vn("ERR_UNKNOWN_ENCODING",function(e){return "Unknown encoding: "+e},TypeError);vn("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");b7.exports.codes=S7;});var vA=c((k7e,E7)=>{var KFe=Qs().codes.ERR_INVALID_OPT_VALUE;function YFe(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}function QFe(e,t,r,n){var i=YFe(t,n,r);if(i!=null){if(!(isFinite(i)&&Math.floor(i)===i)||i<0){var s=n?r:"highWaterMark";throw new KFe(s,i)}return Math.floor(i)}return e.objectMode?16:16*1024}E7.exports={getHighWaterMark:QFe};});var R7=c((x7e,T7)=>{T7.exports=a("util").deprecate;});var bA=c((A7e,O7)=>{O7.exports=Et;function k7(e){var t=this;this.next=null,this.entry=null,this.finish=function(){E$e(t,e);};}var hl;Et.WritableState=Df;var JFe={deprecate:R7()},x7=mA(),V0=a("buffer").Buffer,XFe=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function ZFe(e){return V0.from(e)}function e$e(e){return V0.isBuffer(e)||e instanceof XFe}var SA=wA(),t$e=vA(),r$e=t$e.getHighWaterMark,Js=Qs().codes,n$e=Js.ERR_INVALID_ARG_TYPE,i$e=Js.ERR_METHOD_NOT_IMPLEMENTED,s$e=Js.ERR_MULTIPLE_CALLBACK,o$e=Js.ERR_STREAM_CANNOT_PIPE,a$e=Js.ERR_STREAM_DESTROYED,c$e=Js.ERR_STREAM_NULL_VALUES,l$e=Js.ERR_STREAM_WRITE_AFTER_END,u$e=Js.ERR_UNKNOWN_ENCODING,pl=SA.errorOrDestroy;Ws()(Et,x7);function d$e(){}function Df(e,t,r){hl=hl||aa(),e=e||{},typeof r!="boolean"&&(r=t instanceof hl),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=r$e(this,e,"writableHighWaterMark",r),this.finalCalled=false,this.needDrain=false,this.ending=false,this.ended=false,this.finished=false,this.destroyed=false;var n=e.decodeStrings===false;this.decodeStrings=!n,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=false,this.corked=0,this.sync=true,this.bufferProcessing=false,this.onwrite=function(i){w$e(t,i);},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=false,this.errorEmitted=false,this.emitClose=e.emitClose!==false,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new k7(this);}Df.prototype.getBuffer=function(){for(var t=this.bufferedRequest,r=[];t;)r.push(t),t=t.next;return r};(function(){try{Object.defineProperty(Df.prototype,"buffer",{get:JFe.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")});}catch{}})();var z0;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(z0=Function.prototype[Symbol.hasInstance],Object.defineProperty(Et,Symbol.hasInstance,{value:function(t){return z0.call(this,t)?true:this!==Et?false:t&&t._writableState instanceof Df}})):z0=function(t){return t instanceof this};function Et(e){hl=hl||aa();var t=this instanceof hl;if(!t&&!z0.call(Et,this))return new Et(e);this._writableState=new Df(e,this,t),this.writable=true,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),x7.call(this);}Et.prototype.pipe=function(){pl(this,new o$e);};function f$e(e,t){var r=new l$e;pl(e,r),process.nextTick(t,r);}function h$e(e,t,r,n){var i;return r===null?i=new c$e:typeof r!="string"&&!t.objectMode&&(i=new n$e("chunk",["string","Buffer"],r)),i?(pl(e,i),process.nextTick(n,i),false):true}Et.prototype.write=function(e,t,r){var n=this._writableState,i=false,s=!n.objectMode&&e$e(e);return s&&!V0.isBuffer(e)&&(e=ZFe(e)),typeof t=="function"&&(r=t,t=null),s?t="buffer":t||(t=n.defaultEncoding),typeof r!="function"&&(r=d$e),n.ending?f$e(this,r):(s||h$e(this,n,e,r))&&(n.pendingcb++,i=m$e(this,n,s,e,t,r)),i};Et.prototype.cork=function(){this._writableState.corked++;};Et.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&A7(this,e));};Et.prototype.setDefaultEncoding=function(t){if(typeof t=="string"&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new u$e(t);return this._writableState.defaultEncoding=t,this};Object.defineProperty(Et.prototype,"writableBuffer",{enumerable:false,get:function(){return this._writableState&&this._writableState.getBuffer()}});function p$e(e,t,r){return !e.objectMode&&e.decodeStrings!==false&&typeof t=="string"&&(t=V0.from(t,r)),t}Object.defineProperty(Et.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function m$e(e,t,r,n,i,s){if(!r){var o=p$e(t,n,i);n!==o&&(r=true,i="buffer",n=o);}var a=t.objectMode?1:n.length;t.length+=a;var c=t.length<t.highWaterMark;if(c||(t.needDrain=true),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:i,isBuf:r,callback:s,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1;}else _A(e,t,false,a,n,i,s);return c}function _A(e,t,r,n,i,s,o){t.writelen=n,t.writecb=o,t.writing=true,t.sync=true,t.destroyed?t.onwrite(new a$e("write")):r?e._writev(i,t.onwrite):e._write(i,s,t.onwrite),t.sync=false;}function g$e(e,t,r,n,i){--t.pendingcb,r?(process.nextTick(i,n),process.nextTick(Lf,e,t),e._writableState.errorEmitted=true,pl(e,n)):(i(n),e._writableState.errorEmitted=true,pl(e,n),Lf(e,t));}function y$e(e){e.writing=false,e.writecb=null,e.length-=e.writelen,e.writelen=0;}function w$e(e,t){var r=e._writableState,n=r.sync,i=r.writecb;if(typeof i!="function")throw new s$e;if(y$e(r),t)g$e(e,r,n,t,i);else {var s=I7(r)||e.destroyed;!s&&!r.corked&&!r.bufferProcessing&&r.bufferedRequest&&A7(e,r),n?process.nextTick(P7,e,r,s,i):P7(e,r,s,i);}}function P7(e,t,r,n){r||v$e(e,t),t.pendingcb--,n(),Lf(e,t);}function v$e(e,t){t.length===0&&t.needDrain&&(t.needDrain=false,e.emit("drain"));}function A7(e,t){t.bufferProcessing=true;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,i=new Array(n),s=t.corkedRequestsFree;s.entry=r;for(var o=0,a=true;r;)i[o]=r,r.isBuf||(a=false),r=r.next,o+=1;i.allBuffers=a,_A(e,t,true,t.length,i,"",s.finish),t.pendingcb++,t.lastBufferedRequest=null,s.next?(t.corkedRequestsFree=s.next,s.next=null):t.corkedRequestsFree=new k7(t),t.bufferedRequestCount=0;}else {for(;r;){var c=r.chunk,l=r.encoding,u=r.callback,d=t.objectMode?1:c.length;if(_A(e,t,false,d,c,l,u),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null);}t.bufferedRequest=r,t.bufferProcessing=false;}Et.prototype._write=function(e,t,r){r(new i$e("_write()"));};Et.prototype._writev=null;Et.prototype.end=function(e,t,r){var n=this._writableState;return typeof e=="function"?(r=e,e=null,t=null):typeof t=="function"&&(r=t,t=null),e!=null&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||b$e(this,n,r),this};Object.defineProperty(Et.prototype,"writableLength",{enumerable:false,get:function(){return this._writableState.length}});function I7(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function _$e(e,t){e._final(function(r){t.pendingcb--,r&&pl(e,r),t.prefinished=true,e.emit("prefinish"),Lf(e,t);});}function S$e(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final=="function"&&!t.destroyed?(t.pendingcb++,t.finalCalled=true,process.nextTick(_$e,e,t)):(t.prefinished=true,e.emit("prefinish")));}function Lf(e,t){var r=I7(t);if(r&&(S$e(e,t),t.pendingcb===0&&(t.finished=true,e.emit("finish"),t.autoDestroy))){var n=e._readableState;(!n||n.autoDestroy&&n.endEmitted)&&e.destroy();}return r}function b$e(e,t,r){t.ending=true,Lf(e,t),r&&(t.finished?process.nextTick(r):e.once("finish",r)),t.ended=true,e.writable=false;}function E$e(e,t,r){var n=e.entry;for(e.entry=null;n;){var i=n.callback;t.pendingcb--,i(r),n=n.next;}t.corkedRequestsFree.next=e;}Object.defineProperty(Et.prototype,"destroyed",{enumerable:false,get:function(){return this._writableState===void 0?false:this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t);}});Et.prototype.destroy=SA.destroy;Et.prototype._undestroy=SA.undestroy;Et.prototype._destroy=function(e,t){t(e);};});var aa=c((I7e,N7)=>{var T$e=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};N7.exports=gi;var C7=RA(),TA=bA();Ws()(gi,C7);for(EA=T$e(TA.prototype),W0=0;W0<EA.length;W0++)K0=EA[W0],gi.prototype[K0]||(gi.prototype[K0]=TA.prototype[K0]);var EA,K0,W0;function gi(e){if(!(this instanceof gi))return new gi(e);C7.call(this,e),TA.call(this,e),this.allowHalfOpen=true,e&&(e.readable===false&&(this.readable=false),e.writable===false&&(this.writable=false),e.allowHalfOpen===false&&(this.allowHalfOpen=false,this.once("end",R$e)));}Object.defineProperty(gi.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});Object.defineProperty(gi.prototype,"writableBuffer",{enumerable:false,get:function(){return this._writableState&&this._writableState.getBuffer()}});Object.defineProperty(gi.prototype,"writableLength",{enumerable:false,get:function(){return this._writableState.length}});function R$e(){this._writableState.ended||process.nextTick(P$e,this);}function P$e(e){e.end();}Object.defineProperty(gi.prototype,"destroyed",{enumerable:false,get:function(){return this._readableState===void 0||this._writableState===void 0?false:this._readableState.destroyed&&this._writableState.destroyed},set:function(t){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=t,this._writableState.destroyed=t);}});});var D7=c((PA,L7)=>{var Y0=a("buffer"),yi=Y0.Buffer;function j7(e,t){for(var r in e)t[r]=e[r];}yi.from&&yi.alloc&&yi.allocUnsafe&&yi.allocUnsafeSlow?L7.exports=Y0:(j7(Y0,PA),PA.Buffer=ca);function ca(e,t,r){return yi(e,t,r)}ca.prototype=Object.create(yi.prototype);j7(yi,ca);ca.from=function(e,t,r){if(typeof e=="number")throw new TypeError("Argument must not be a number");return yi(e,t,r)};ca.alloc=function(e,t,r){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=yi(e);return t!==void 0?typeof r=="string"?n.fill(t,r):n.fill(t):n.fill(0),n};ca.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return yi(e)};ca.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return Y0.SlowBuffer(e)};});var AA=c(F7=>{var xA=D7().Buffer,M7=xA.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case "hex":case "utf8":case "utf-8":case "ascii":case "binary":case "base64":case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":case "raw":return true;default:return false}};function k$e(e){if(!e)return "utf8";for(var t;;)switch(e){case "utf8":case "utf-8":return "utf8";case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return "utf16le";case "latin1":case "binary":return "latin1";case "base64":case "ascii":case "hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=true;}}function x$e(e){var t=k$e(e);if(typeof t!="string"&&(xA.isEncoding===M7||!M7(e)))throw new Error("Unknown encoding: "+e);return t||e}F7.StringDecoder=Mf;function Mf(e){this.encoding=x$e(e);var t;switch(this.encoding){case "utf16le":this.text=j$e,this.end=L$e,t=4;break;case "utf8":this.fillLast=O$e,t=4;break;case "base64":this.text=D$e,this.end=M$e,t=3;break;default:this.write=F$e,this.end=$$e;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=xA.allocUnsafe(t);}Mf.prototype.write=function(e){if(e.length===0)return "";var t,r;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return "";r=this.lastNeed,this.lastNeed=0;}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""};Mf.prototype.end=N$e;Mf.prototype.text=C$e;Mf.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length;};function kA(e){return e<=127?0:e>>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}function A$e(e,t,r){var n=t.length-1;if(n<r)return 0;var i=kA(t[n]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--n<r||i===-2?0:(i=kA(t[n]),i>=0?(i>0&&(e.lastNeed=i-2),i):--n<r||i===-2?0:(i=kA(t[n]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function I$e(e,t,r){if((t[0]&192)!==128)return e.lastNeed=0,"\uFFFD";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"\uFFFD";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"\uFFFD"}}function O$e(e){var t=this.lastTotal-this.lastNeed,r=I$e(this,e);if(r!==void 0)return r;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length;}function C$e(e,t){var r=A$e(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}function N$e(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"\uFFFD":t}function j$e(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function L$e(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function D$e(e,t){var r=(e.length-t)%3;return r===0?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function M$e(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function F$e(e){return e.toString(this.encoding)}function $$e(e){return e&&e.length?this.write(e):""}});var Q0=c((C7e,U7)=>{var $7=Qs().codes.ERR_STREAM_PREMATURE_CLOSE;function q$e(e){var t=false;return function(){if(!t){t=true;for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];e.apply(this,n);}}}function U$e(){}function B$e(e){return e.setHeader&&typeof e.abort=="function"}function q7(e,t,r){if(typeof t=="function")return q7(e,null,t);t||(t={}),r=q$e(r||U$e);var n=t.readable||t.readable!==false&&e.readable,i=t.writable||t.writable!==false&&e.writable,s=function(){e.writable||a();},o=e._writableState&&e._writableState.finished,a=function(){i=false,o=true,n||r.call(e);},c=e._readableState&&e._readableState.endEmitted,l=function(){n=false,c=true,i||r.call(e);},u=function(h){r.call(e,h);},d=function(){var h;if(n&&!c)return (!e._readableState||!e._readableState.ended)&&(h=new $7),r.call(e,h);if(i&&!o)return (!e._writableState||!e._writableState.ended)&&(h=new $7),r.call(e,h)},m=function(){e.req.on("finish",a);};return B$e(e)?(e.on("complete",a),e.on("abort",d),e.req?m():e.on("request",m)):i&&!e._writableState&&(e.on("end",s),e.on("close",s)),e.on("end",l),e.on("finish",a),t.error!==false&&e.on("error",u),e.on("close",d),function(){e.removeListener("complete",a),e.removeListener("abort",d),e.removeListener("request",m),e.req&&e.req.removeListener("finish",a),e.removeListener("end",s),e.removeListener("close",s),e.removeListener("finish",a),e.removeListener("end",l),e.removeListener("error",u),e.removeListener("close",d);}}U7.exports=q7;});var H7=c((N7e,B7)=>{var J0;function Xs(e,t,r){return t=H$e(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:true,configurable:true,writable:true}):e[t]=r,e}function H$e(e){var t=G$e(e,"string");return typeof t=="symbol"?t:String(t)}function G$e(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (t==="string"?String:Number)(e)}var z$e=Q0(),Zs=Symbol("lastResolve"),la=Symbol("lastReject"),Ff=Symbol("error"),X0=Symbol("ended"),ua=Symbol("lastPromise"),IA=Symbol("handlePromise"),da=Symbol("stream");function eo(e,t){return {value:e,done:t}}function V$e(e){var t=e[Zs];if(t!==null){var r=e[da].read();r!==null&&(e[ua]=null,e[Zs]=null,e[la]=null,t(eo(r,false)));}}function W$e(e){process.nextTick(V$e,e);}function K$e(e,t){return function(r,n){e.then(function(){if(t[X0]){r(eo(void 0,true));return}t[IA](r,n);},n);}}var Y$e=Object.getPrototypeOf(function(){}),Q$e=Object.setPrototypeOf((J0={get stream(){return this[da]},next:function(){var t=this,r=this[Ff];if(r!==null)return Promise.reject(r);if(this[X0])return Promise.resolve(eo(void 0,true));if(this[da].destroyed)return new Promise(function(o,a){process.nextTick(function(){t[Ff]?a(t[Ff]):o(eo(void 0,true));});});var n=this[ua],i;if(n)i=new Promise(K$e(n,this));else {var s=this[da].read();if(s!==null)return Promise.resolve(eo(s,false));i=new Promise(this[IA]);}return this[ua]=i,i}},Xs(J0,Symbol.asyncIterator,function(){return this}),Xs(J0,"return",function(){var t=this;return new Promise(function(r,n){t[da].destroy(null,function(i){if(i){n(i);return}r(eo(void 0,true));});})}),J0),Y$e),J$e=function(t){var r,n=Object.create(Q$e,(r={},Xs(r,da,{value:t,writable:true}),Xs(r,Zs,{value:null,writable:true}),Xs(r,la,{value:null,writable:true}),Xs(r,Ff,{value:null,writable:true}),Xs(r,X0,{value:t._readableState.endEmitted,writable:true}),Xs(r,IA,{value:function(s,o){var a=n[da].read();a?(n[ua]=null,n[Zs]=null,n[la]=null,s(eo(a,false))):(n[Zs]=s,n[la]=o);},writable:true}),r));return n[ua]=null,z$e(t,function(i){if(i&&i.code!=="ERR_STREAM_PREMATURE_CLOSE"){var s=n[la];s!==null&&(n[ua]=null,n[Zs]=null,n[la]=null,s(i)),n[Ff]=i;return}var o=n[Zs];o!==null&&(n[ua]=null,n[Zs]=null,n[la]=null,o(eo(void 0,true))),n[X0]=true;}),t.on("readable",W$e.bind(null,n)),n};B7.exports=J$e;});var W7=c((j7e,V7)=>{function G7(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value;}catch(l){r(l);return}a.done?t(c):Promise.resolve(c).then(n,i);}function X$e(e){return function(){var t=this,r=arguments;return new Promise(function(n,i){var s=e.apply(t,r);function o(c){G7(s,n,i,o,a,"next",c);}function a(c){G7(s,n,i,o,a,"throw",c);}o(void 0);})}}function z7(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n);}return r}function Z$e(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?z7(Object(r),true).forEach(function(n){e2e(e,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):z7(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n));});}return e}function e2e(e,t,r){return t=t2e(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:true,configurable:true,writable:true}):e[t]=r,e}function t2e(e){var t=r2e(e,"string");return typeof t=="symbol"?t:String(t)}function r2e(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (t==="string"?String:Number)(e)}var n2e=Qs().codes.ERR_INVALID_ARG_TYPE;function i2e(e,t,r){var n;if(t&&typeof t.next=="function")n=t;else if(t&&t[Symbol.asyncIterator])n=t[Symbol.asyncIterator]();else if(t&&t[Symbol.iterator])n=t[Symbol.iterator]();else throw new n2e("iterable",["Iterable"],t);var i=new e(Z$e({objectMode:true},r)),s=false;i._read=function(){s||(s=true,o());};function o(){return a.apply(this,arguments)}function a(){return a=X$e(function*(){try{var c=yield n.next(),l=c.value,u=c.done;u?i.push(null):i.push(yield l)?o():s=!1;}catch(d){i.destroy(d);}}),a.apply(this,arguments)}return i}V7.exports=i2e;});var RA=c((D7e,nJ)=>{nJ.exports=Ke;var ml;Ke.ReadableState=J7;a("events").EventEmitter;var Q7=function(t,r){return t.listeners(r).length},qf=mA(),Z0=a("buffer").Buffer,s2e=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function o2e(e){return Z0.from(e)}function a2e(e){return Z0.isBuffer(e)||e instanceof s2e}var OA=a("util"),je;OA&&OA.debuglog?je=OA.debuglog("stream"):je=function(){};var c2e=y7(),FA=wA(),l2e=vA(),u2e=l2e.getHighWaterMark,ew=Qs().codes,d2e=ew.ERR_INVALID_ARG_TYPE,f2e=ew.ERR_STREAM_PUSH_AFTER_EOF,h2e=ew.ERR_METHOD_NOT_IMPLEMENTED,p2e=ew.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,gl,CA,NA;Ws()(Ke,qf);var $f=FA.errorOrDestroy,jA=["error","close","destroy","pause","resume"];function m2e(e,t,r){if(typeof e.prependListener=="function")return e.prependListener(t,r);!e._events||!e._events[t]?e.on(t,r):Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]];}function J7(e,t,r){ml=ml||aa(),e=e||{},typeof r!="boolean"&&(r=t instanceof ml),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=u2e(this,e,"readableHighWaterMark",r),this.buffer=new c2e,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=false,this.endEmitted=false,this.reading=false,this.sync=true,this.needReadable=false,this.emittedReadable=false,this.readableListening=false,this.resumeScheduled=false,this.paused=true,this.emitClose=e.emitClose!==false,this.autoDestroy=!!e.autoDestroy,this.destroyed=false,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=false,this.decoder=null,this.encoding=null,e.encoding&&(gl||(gl=AA().StringDecoder),this.decoder=new gl(e.encoding),this.encoding=e.encoding);}function Ke(e){if(ml=ml||aa(),!(this instanceof Ke))return new Ke(e);var t=this instanceof ml;this._readableState=new J7(e,this,t),this.readable=true,e&&(typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)),qf.call(this);}Object.defineProperty(Ke.prototype,"destroyed",{enumerable:false,get:function(){return this._readableState===void 0?false:this._readableState.destroyed},set:function(t){this._readableState&&(this._readableState.destroyed=t);}});Ke.prototype.destroy=FA.destroy;Ke.prototype._undestroy=FA.undestroy;Ke.prototype._destroy=function(e,t){t(e);};Ke.prototype.push=function(e,t){var r=this._readableState,n;return r.objectMode?n=true:typeof e=="string"&&(t=t||r.defaultEncoding,t!==r.encoding&&(e=Z0.from(e,t),t=""),n=true),X7(this,e,t,false,n)};Ke.prototype.unshift=function(e){return X7(this,e,null,true,false)};function X7(e,t,r,n,i){je("readableAddChunk",t);var s=e._readableState;if(t===null)s.reading=false,w2e(e,s);else {var o;if(i||(o=g2e(s,t)),o)$f(e,o);else if(s.objectMode||t&&t.length>0)if(typeof t!="string"&&!s.objectMode&&Object.getPrototypeOf(t)!==Z0.prototype&&(t=o2e(t)),n)s.endEmitted?$f(e,new p2e):LA(e,s,t,true);else if(s.ended)$f(e,new f2e);else {if(s.destroyed)return false;s.reading=false,s.decoder&&!r?(t=s.decoder.write(t),s.objectMode||t.length!==0?LA(e,s,t,false):MA(e,s)):LA(e,s,t,false);}else n||(s.reading=false,MA(e,s));}return !s.ended&&(s.length<s.highWaterMark||s.length===0)}function LA(e,t,r,n){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&tw(e)),MA(e,t);}function g2e(e,t){var r;return !a2e(t)&&typeof t!="string"&&t!==void 0&&!e.objectMode&&(r=new d2e("chunk",["string","Buffer","Uint8Array"],t)),r}Ke.prototype.isPaused=function(){return this._readableState.flowing===false};Ke.prototype.setEncoding=function(e){gl||(gl=AA().StringDecoder);var t=new gl(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,n="";r!==null;)n+=t.write(r.data),r=r.next;return this._readableState.buffer.clear(),n!==""&&this._readableState.buffer.push(n),this._readableState.length=n.length,this};var K7=1073741824;function y2e(e){return e>=K7?e=K7:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function Y7(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=y2e(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=true,0))}Ke.prototype.read=function(e){je("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(e!==0&&(t.emittedReadable=false),e===0&&t.needReadable&&((t.highWaterMark!==0?t.length>=t.highWaterMark:t.length>0)||t.ended))return je("read: emitReadable",t.length,t.ended),t.length===0&&t.ended?DA(this):tw(this),null;if(e=Y7(e,t),e===0&&t.ended)return t.length===0&&DA(this),null;var n=t.needReadable;je("need readable",n),(t.length===0||t.length-e<t.highWaterMark)&&(n=true,je("length less than watermark",n)),t.ended||t.reading?(n=false,je("reading or ended",n)):n&&(je("do read"),t.reading=true,t.sync=true,t.length===0&&(t.needReadable=true),this._read(t.highWaterMark),t.sync=false,t.reading||(e=Y7(r,t)));var i;return e>0?i=tJ(e,t):i=null,i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=true),r!==e&&t.ended&&DA(this)),i!==null&&this.emit("data",i),i};function w2e(e,t){if(je("onEofChunk"),!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length);}t.ended=true,t.sync?tw(e):(t.needReadable=false,t.emittedReadable||(t.emittedReadable=true,Z7(e)));}}function tw(e){var t=e._readableState;je("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=false,t.emittedReadable||(je("emitReadable",t.flowing),t.emittedReadable=true,process.nextTick(Z7,e));}function Z7(e){var t=e._readableState;je("emitReadable_",t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit("readable"),t.emittedReadable=false),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,$A(e);}function MA(e,t){t.readingMore||(t.readingMore=true,process.nextTick(v2e,e,t));}function v2e(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var r=t.length;if(je("maybeReadMore read 0"),e.read(0),r===t.length)break}t.readingMore=false;}Ke.prototype._read=function(e){$f(this,new h2e("_read()"));};Ke.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e);break}n.pipesCount+=1,je("pipe count=%d opts=%j",n.pipesCount,t);var i=(!t||t.end!==false)&&e!==process.stdout&&e!==process.stderr,s=i?a:f;n.endEmitted?process.nextTick(s):r.once("end",s),e.on("unpipe",o);function o(g,y){je("onunpipe"),g===r&&y&&y.hasUnpiped===false&&(y.hasUnpiped=true,u());}function a(){je("onend"),e.end();}var c=_2e(r);e.on("drain",c);var l=false;function u(){je("cleanup"),e.removeListener("close",p),e.removeListener("finish",h),e.removeListener("drain",c),e.removeListener("error",m),e.removeListener("unpipe",o),r.removeListener("end",a),r.removeListener("end",f),r.removeListener("data",d),l=true,n.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c();}r.on("data",d);function d(g){je("ondata");var y=e.write(g);je("dest.write",y),y===false&&((n.pipesCount===1&&n.pipes===e||n.pipesCount>1&&rJ(n.pipes,e)!==-1)&&!l&&(je("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause());}function m(g){je("onerror",g),f(),e.removeListener("error",m),Q7(e,"error")===0&&$f(e,g);}m2e(e,"error",m);function p(){e.removeListener("finish",h),f();}e.once("close",p);function h(){je("onfinish"),e.removeListener("close",p),f();}e.once("finish",h);function f(){je("unpipe"),r.unpipe(e);}return e.emit("pipe",r),n.flowing||(je("pipe resume"),r.resume()),e};function _2e(e){return function(){var r=e._readableState;je("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,r.awaitDrain===0&&Q7(e,"data")&&(r.flowing=true,$A(e));}}Ke.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:false};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=false,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=false;for(var s=0;s<i;s++)n[s].emit("unpipe",this,{hasUnpiped:false});return this}var o=rJ(t.pipes,e);return o===-1?this:(t.pipes.splice(o,1),t.pipesCount-=1,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,r),this)};Ke.prototype.on=function(e,t){var r=qf.prototype.on.call(this,e,t),n=this._readableState;return e==="data"?(n.readableListening=this.listenerCount("readable")>0,n.flowing!==false&&this.resume()):e==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=true,n.flowing=false,n.emittedReadable=false,je("on readable",n.length,n.reading),n.length?tw(this):n.reading||process.nextTick(S2e,this)),r};Ke.prototype.addListener=Ke.prototype.on;Ke.prototype.removeListener=function(e,t){var r=qf.prototype.removeListener.call(this,e,t);return e==="readable"&&process.nextTick(eJ,this),r};Ke.prototype.removeAllListeners=function(e){var t=qf.prototype.removeAllListeners.apply(this,arguments);return (e==="readable"||e===void 0)&&process.nextTick(eJ,this),t};function eJ(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=true:e.listenerCount("data")>0&&e.resume();}function S2e(e){je("readable nexttick read 0"),e.read(0);}Ke.prototype.resume=function(){var e=this._readableState;return e.flowing||(je("resume"),e.flowing=!e.readableListening,b2e(this,e)),e.paused=false,this};function b2e(e,t){t.resumeScheduled||(t.resumeScheduled=true,process.nextTick(E2e,e,t));}function E2e(e,t){je("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=false,e.emit("resume"),$A(e),t.flowing&&!t.reading&&e.read(0);}Ke.prototype.pause=function(){return je("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==false&&(je("pause"),this._readableState.flowing=false,this.emit("pause")),this._readableState.paused=true,this};function $A(e){var t=e._readableState;for(je("flow",t.flowing);t.flowing&&e.read()!==null;);}Ke.prototype.wrap=function(e){var t=this,r=this._readableState,n=false;e.on("end",function(){if(je("wrapped end"),r.decoder&&!r.ended){var o=r.decoder.end();o&&o.length&&t.push(o);}t.push(null);}),e.on("data",function(o){if(je("wrapped data"),r.decoder&&(o=r.decoder.write(o)),!(r.objectMode&&o==null)&&!(!r.objectMode&&(!o||!o.length))){var a=t.push(o);a||(n=true,e.pause());}});for(var i in e)this[i]===void 0&&typeof e[i]=="function"&&(this[i]=(function(a){return function(){return e[a].apply(e,arguments)}})(i));for(var s=0;s<jA.length;s++)e.on(jA[s],this.emit.bind(this,jA[s]));return this._read=function(o){je("wrapped _read",o),n&&(n=false,e.resume());},this};typeof Symbol=="function"&&(Ke.prototype[Symbol.asyncIterator]=function(){return CA===void 0&&(CA=H7()),CA(this)});Object.defineProperty(Ke.prototype,"readableHighWaterMark",{enumerable:false,get:function(){return this._readableState.highWaterMark}});Object.defineProperty(Ke.prototype,"readableBuffer",{enumerable:false,get:function(){return this._readableState&&this._readableState.buffer}});Object.defineProperty(Ke.prototype,"readableFlowing",{enumerable:false,get:function(){return this._readableState.flowing},set:function(t){this._readableState&&(this._readableState.flowing=t);}});Ke._fromList=tJ;Object.defineProperty(Ke.prototype,"readableLength",{enumerable:false,get:function(){return this._readableState.length}});function tJ(e,t){if(t.length===0)return null;var r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(t.decoder?r=t.buffer.join(""):t.buffer.length===1?r=t.buffer.first():r=t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r}function DA(e){var t=e._readableState;je("endReadable",t.endEmitted),t.endEmitted||(t.ended=true,process.nextTick(T2e,t,e));}function T2e(e,t){if(je("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=true,t.readable=false,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy();}}typeof Symbol=="function"&&(Ke.from=function(e,t){return NA===void 0&&(NA=W7()),NA(Ke,e,t)});function rJ(e,t){for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return -1}});var qA=c((M7e,sJ)=>{sJ.exports=Zi;var rw=Qs().codes,R2e=rw.ERR_METHOD_NOT_IMPLEMENTED,P2e=rw.ERR_MULTIPLE_CALLBACK,k2e=rw.ERR_TRANSFORM_ALREADY_TRANSFORMING,x2e=rw.ERR_TRANSFORM_WITH_LENGTH_0,nw=aa();Ws()(Zi,nw);function A2e(e,t){var r=this._transformState;r.transforming=false;var n=r.writecb;if(n===null)return this.emit("error",new P2e);r.writechunk=null,r.writecb=null,t!=null&&this.push(t),n(e);var i=this._readableState;i.reading=false,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark);}function Zi(e){if(!(this instanceof Zi))return new Zi(e);nw.call(this,e),this._transformState={afterTransform:A2e.bind(this),needTransform:false,transforming:false,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=true,this._readableState.sync=false,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.on("prefinish",I2e);}function I2e(){var e=this;typeof this._flush=="function"&&!this._readableState.destroyed?this._flush(function(t,r){iJ(e,t,r);}):iJ(this,null,null);}Zi.prototype.push=function(e,t){return this._transformState.needTransform=false,nw.prototype.push.call(this,e,t)};Zi.prototype._transform=function(e,t,r){r(new R2e("_transform()"));};Zi.prototype._write=function(e,t,r){var n=this._transformState;if(n.writecb=r,n.writechunk=e,n.writeencoding=t,!n.transforming){var i=this._readableState;(n.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark);}};Zi.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=true,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=true;};Zi.prototype._destroy=function(e,t){nw.prototype._destroy.call(this,e,function(r){t(r);});};function iJ(e,t,r){if(t)return e.emit("error",t);if(r!=null&&e.push(r),e._writableState.length)throw new x2e;if(e._transformState.transforming)throw new k2e;return e.push(null)}});var cJ=c((F7e,aJ)=>{aJ.exports=Uf;var oJ=qA();Ws()(Uf,oJ);function Uf(e){if(!(this instanceof Uf))return new Uf(e);oJ.call(this,e);}Uf.prototype._transform=function(e,t,r){r(null,e);};});var hJ=c(($7e,fJ)=>{var UA;function O2e(e){var t=false;return function(){t||(t=true,e.apply(void 0,arguments));}}var dJ=Qs().codes,C2e=dJ.ERR_MISSING_ARGS,N2e=dJ.ERR_STREAM_DESTROYED;function lJ(e){if(e)throw e}function j2e(e){return e.setHeader&&typeof e.abort=="function"}function L2e(e,t,r,n){n=O2e(n);var i=false;e.on("close",function(){i=true;}),UA===void 0&&(UA=Q0()),UA(e,{readable:t,writable:r},function(o){if(o)return n(o);i=true,n();});var s=false;return function(o){if(!i&&!s){if(s=true,j2e(e))return e.abort();if(typeof e.destroy=="function")return e.destroy();n(o||new N2e("pipe"));}}}function uJ(e){e();}function D2e(e,t){return e.pipe(t)}function M2e(e){return !e.length||typeof e[e.length-1]!="function"?lJ:e.pop()}function F2e(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=M2e(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new C2e("streams");var i,s=t.map(function(o,a){var c=a<t.length-1,l=a>0;return L2e(o,c,l,function(u){i||(i=u),u&&s.forEach(uJ),!c&&(s.forEach(uJ),n(i));})});return t.reduce(D2e)}fJ.exports=F2e;});var pJ=c((_n,Hf)=>{var Bf=a("stream");process.env.READABLE_STREAM==="disable"&&Bf?(Hf.exports=Bf.Readable,Object.assign(Hf.exports,Bf),Hf.exports.Stream=Bf):(_n=Hf.exports=RA(),_n.Stream=Bf||_n,_n.Readable=_n,_n.Writable=bA(),_n.Duplex=aa(),_n.Transform=qA(),_n.PassThrough=cJ(),_n.finished=Q0(),_n.pipeline=hJ());});var yJ=c((q7e,gJ)=>{gJ.exports=mJ;function mJ(e,t){if(e&&t)return mJ(e)(t);if(typeof e!="function")throw new TypeError("need wrapper function");return Object.keys(e).forEach(function(n){r[n]=e[n];}),r;function r(){for(var n=new Array(arguments.length),i=0;i<n.length;i++)n[i]=arguments[i];var s=e.apply(this,n),o=n[n.length-1];return typeof s=="function"&&s!==o&&Object.keys(o).forEach(function(a){s[a]=o[a];}),s}}});var _J=c((U7e,BA)=>{var wJ=yJ();BA.exports=wJ(iw);BA.exports.strict=wJ(vJ);iw.proto=iw(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return iw(this)},configurable:true}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return vJ(this)},configurable:true});});function iw(e){var t=function(){return t.called?t.value:(t.called=true,t.value=e.apply(this,arguments))};return t.called=false,t}function vJ(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=true,t.value=e.apply(this,arguments)},r=e.name||"Function wrapped with `once`";return t.onceError=r+" shouldn't be called more than once",t.called=false,t}});var EJ=c((B7e,bJ)=>{var $2e=_J(),q2e=function(){},U2e=global.Bare?queueMicrotask:process.nextTick.bind(process),B2e=function(e){return e.setHeader&&typeof e.abort=="function"},H2e=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},SJ=function(e,t,r){if(typeof t=="function")return SJ(e,null,t);t||(t={}),r=$2e(r||q2e);var n=e._writableState,i=e._readableState,s=t.readable||t.readable!==false&&e.readable,o=t.writable||t.writable!==false&&e.writable,a=false,c=function(){e.writable||l();},l=function(){o=false,s||r.call(e);},u=function(){s=false,o||r.call(e);},d=function(g){r.call(e,g?new Error("exited with error code: "+g):null);},m=function(g){r.call(e,g);},p=function(){U2e(h);},h=function(){if(!a){if(s&&!(i&&i.ended&&!i.destroyed))return r.call(e,new Error("premature close"));if(o&&!(n&&n.ended&&!n.destroyed))return r.call(e,new Error("premature close"))}},f=function(){e.req.on("finish",l);};return B2e(e)?(e.on("complete",l),e.on("abort",p),e.req?f():e.on("request",f)):o&&!n&&(e.on("end",c),e.on("close",c)),H2e(e)&&e.on("exit",d),e.on("end",u),e.on("finish",l),t.error!==false&&e.on("error",m),e.on("close",p),function(){a=true,e.removeListener("complete",l),e.removeListener("abort",p),e.removeListener("request",f),e.req&&e.req.removeListener("finish",l),e.removeListener("end",c),e.removeListener("close",c),e.removeListener("finish",l),e.removeListener("exit",d),e.removeListener("end",u),e.removeListener("error",m),e.removeListener("close",p);}};bJ.exports=SJ;});var RJ=c((H7e,TJ)=>{TJ.exports=G2e;function G2e(e){var t=e._readableState;return t?t.objectMode||typeof e._duplexState=="number"?e.read():e.read(z2e(t)):null}function z2e(e){if(e.buffer.length){var t=e.bufferIndex||0;if(e.buffer.head)return e.buffer.head.data.length;if(e.buffer.length-t>0&&e.buffer[t])return e.buffer[t].length}return e.length}});var IJ=c((G7e,AJ)=>{var sw=pJ(),PJ=EJ(),V2e=Ws(),W2e=RJ(),kJ=Buffer.from&&Buffer.from!==Uint8Array.from?Buffer.from([0]):new Buffer([0]),HA=function(e,t){e._corked?e.once("uncork",t):t();},K2e=function(e,t){e._autoDestroy&&e.destroy(t);},xJ=function(e,t){return function(r){r?K2e(e,r.message==="premature close"?null:r):t&&!e._ended&&e.end();}},Y2e=function(e,t){if(!e||e._writableState&&e._writableState.finished)return t();if(e._writableState)return e.end(t);e.end(),t();},Q2e=function(){},J2e=function(e){return new sw.Readable({objectMode:true,highWaterMark:16}).wrap(e)},ir=function(e,t,r){if(!(this instanceof ir))return new ir(e,t,r);sw.Duplex.call(this,r),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!r||r.autoDestroy!==false,this._forwardDestroy=!r||r.destroy!==false,this._forwardEnd=!r||r.end!==false,this._corked=1,this._ondrain=null,this._drained=false,this._forwarding=false,this._unwrite=null,this._unread=null,this._ended=false,this.destroyed=false,e&&this.setWritable(e),t&&this.setReadable(t);};V2e(ir,sw.Duplex);ir.obj=function(e,t,r){return r||(r={}),r.objectMode=true,r.highWaterMark=16,new ir(e,t,r)};ir.prototype.cork=function(){++this._corked===1&&this.emit("cork");};ir.prototype.uncork=function(){this._corked&&--this._corked===0&&this.emit("uncork");};ir.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===false){this.end();return}var t=this,r=PJ(e,{writable:true,readable:false},xJ(this,this._forwardEnd)),n=function(){var s=t._ondrain;t._ondrain=null,s&&s();},i=function(){t._writable.removeListener("drain",n),r();};this._unwrite&&process.nextTick(n),this._writable=e,this._writable.on("drain",n),this._unwrite=i,this.uncork();};ir.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===false){this.push(null),this.resume();return}var t=this,r=PJ(e,{writable:false,readable:true},xJ(this)),n=function(){t._forward();},i=function(){t.push(null);},s=function(){t._readable2.removeListener("readable",n),t._readable2.removeListener("end",i),r();};this._drained=true,this._readable=e,this._readable2=e._readableState?e:J2e(e),this._readable2.on("readable",n),this._readable2.on("end",i),this._unread=s,this._forward();};ir.prototype._read=function(){this._drained=true,this._forward();};ir.prototype._forward=function(){if(!(this._forwarding||!this._readable2||!this._drained)){this._forwarding=true;for(var e;this._drained&&(e=W2e(this._readable2))!==null;)this.destroyed||(this._drained=this.push(e));this._forwarding=false;}};ir.prototype.destroy=function(e,t){if(t||(t=Q2e),this.destroyed)return t(null);this.destroyed=true;var r=this;process.nextTick(function(){r._destroy(e),t(null);});};ir.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit("error",e);}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close");};ir.prototype._write=function(e,t,r){if(!this.destroyed){if(this._corked)return HA(this,this._write.bind(this,e,t,r));if(e===kJ)return this._finish(r);if(!this._writable)return r();this._writable.write(e)===false?this._ondrain=r:this.destroyed||r();}};ir.prototype._finish=function(e){var t=this;this.emit("preend"),HA(this,function(){Y2e(t._forwardEnd&&t._writable,function(){t._writableState.prefinished===false&&(t._writableState.prefinished=true),t.emit("prefinish"),HA(t,e);});});};ir.prototype.end=function(e,t,r){return typeof e=="function"?this.end(null,null,e):typeof t=="function"?this.end(e,null,t):(this._ended=true,e&&this.write(e),!this._writableState.ending&&!this._writableState.destroyed&&this.write(kJ),sw.Writable.prototype.end.call(this,r))};AJ.exports=ir;});var jJ=c((z7e,aw)=>{var{ServerResponse:X2e}=a("http"),{PassThrough:OJ}=a("stream"),{randomBytes:Z2e}=a("crypto"),eqe=tf(),CJ=u7(),NJ=IJ(),fa=Symbol("ws-socket"),ow=Symbol("ws-head"),tqe=/HTTP\/1.1 (\d+)/u;function GA(e,t,r){e.decorateRequest("ws",null);let n=p;if(t.errorHandler){if(typeof t.errorHandler!="function")return r(new Error("invalid errorHandler function"));n=t.errorHandler;}let i=d;if(t?.preClose){if(typeof t.preClose!="function")return r(new Error("invalid preClose function"));i=t.preClose;}if(t.options?.noServer)return r(new Error("fastify-websocket doesn't support the ws noServer option. If you want to create a websocket server detatched from fastify, use the ws library directly."));let s=Object.assign({noServer:true},t.options);s.path&&e.log.warn("ws server path option shouldn't be provided, use a route instead");let o=s.server||e.server;delete s.server;let a=new CJ.Server(s);e.decorate("websocketServer",a);async function c(h="/",f={},g={}){let y=new OJ,_=new OJ,v=new NJ(y,_),w=new NJ(_,y),E=new CJ(null,void 0,{isServer:false}),R=Buffer.from([]),P,b,O=new Promise((N,M)=>{P=N,b=M;});typeof g.onInit=="function"&&g.onInit(E),E.on("open",()=>{typeof g.onOpen=="function"&&g.onOpen(E),w.removeListener("data",F),P(E);});let F=N=>{if(N.toString().includes("HTTP/1.1 101 Switching Protocols"))E._isServer=false,E.setSocket(w,R,{maxPayload:0});else {w.removeListener("data",F);let M=Number(tqe.exec(N.toString())[1]);b(new Error("Unexpected server response: "+M));}};w.on("data",F);let j={...f,method:"GET",headers:{...f.headers,connection:"upgrade",upgrade:"websocket","sec-websocket-version":13,"sec-websocket-key":Z2e(16).toString("base64")},httpVersion:"1.1",url:h,[fa]:v,[ow]:R};return o.emit("upgrade",j,j[fa],j[ow]),O}e.decorate("injectWS",c);function l(h,f,g){h[fa]=f,h[ow]=g;let y=new X2e(h);try{y.assignSocket(f),e.routing(h,y);}catch(_){e.log.warn({err:_},"websocket upgrade failed");}}o.on("upgrade",l);let u=(h,f)=>{a.handleUpgrade(h,h[fa],h[ow],g=>{a.emit("connection",g,h),g.on("error",y=>{e.log.error(y);}),f(g);});};e.addHook("onRequest",(h,f,g)=>{h.raw[fa]?h.ws=true:h.ws=false,g();}),e.addHook("onResponse",(h,f,g)=>{h.ws&&h.raw[fa].destroy(),g();}),e.addHook("onRoute",h=>{let f=false,g=h.wsHandler,y=h.handler;if(h.websocket||h.wsHandler){if(h.method==="HEAD")return;if(h.method!=="GET")throw new Error("websocket handler can only be declared in GET method");if(f=true,h.websocket&&(h.schema||(h.schema={}),h.schema.hide=true,g=h.handler,y=function(_,v){v.code(404).send();}),typeof g!="function")throw new TypeError("invalid wsHandler function")}h.handler=function(_,v){if(_.raw[fa])v.hijack(),u(_.raw,w=>{let E;try{f?E=g.call(this,w,_):E=m.call(this,w,_);}catch(R){return n.call(this,R,w,_,v)}E&&typeof E.catch=="function"&&E.catch(R=>n.call(this,R,w,_,v));});else return y.call(this,_,v)};}),e.addHook("preClose",i);function d(h){let f=this.websocketServer;if(f.clients)for(let g of f.clients)g.close();e.server.removeListener("upgrade",l),f.close(h),h();}function m(h,f){this.log.info({path:f.url},"closed incoming websocket connection for path with no websocket handler"),h.close();}function p(h,f,g){g.log.error(h),f.terminate();}r();}aw.exports=eqe(GA,{fastify:"5.x",name:"@fastify/websocket"});aw.exports.default=GA;aw.exports.fastifyWebsocket=GA;});var mX=256*1024,k1=1024*1024,I1='{"events":[',O1='],"type":"events.batch","version":3}',gX=I1.length+O1.length,x1=new WeakMap,A1=new WeakMap;function Ow(e){let t=x1.get(e);if(t!==void 0)return t;let r=JSON.stringify(e),n={byteLength:Buffer$1.byteLength(r),data:r};return x1.set(e,n),n}function yX(e){return Ow(e)}function Cw(e){return Ow(e).byteLength}function wX(e,t,r,n){return e.length!==n-r?false:e.every((i,s)=>i===t[r+s])}function vX(e,t){let r=Math.min(t+ng,e.length),n=t,i=gX,s=[];for(;n<r;n+=1){let f=e[n];if(f===void 0)throw new RangeError("Event batch must contain defined events");let g=Ow(f);if(g.byteLength>og$1){if(n===t)return;break}let y=i+g.byteLength+(n===t?0:1);if(y>pg$1)break;i=y,s.push(g);}let o=e[t];if(o===void 0)throw new RangeError("Event batch must contain at least one event");let a=n-t,c=A1.get(o),l=c?.get(a);if(l!==void 0&&wX(l.events,e,t,n))return l;let u=e.slice(t,n),d=`${I1}${s.map(f=>f.data).join(",")}${O1}`,p={events:u,message:{byteLength:i,data:d}},h=c??new Map;return h.set(a,p),c===void 0&&A1.set(o,h),p}function C1(e,t,r,n){if(e.readyState!==1)return false;if(e.bufferedAmount>k1)return n(),e.close(1013,"Client is too slow; refresh the snapshot"),false;let i=t();if(i===void 0||i.byteLength>pg$1)return e.close(1009,"Event frame is too large; refresh the snapshot"),false;let s=e.bufferedAmount+i.byteLength;return s>k1?(n(),e.close(1013,"Client is too slow; refresh the snapshot"),false):(s>mX&&r(),e.send(i.data),true)}function N1(e,t,r,n){return C1(e,()=>{if(!(t.type==="events.batch"&&t.events.some(i=>Cw(i)>og$1)))return yX(t)},r,n)}function j1(e,t,r,n){for(let i=0;i<t.length;){let s=i;if(!C1(e,()=>{let o=vX(t,i);if(o!==void 0)return s+=o.events.length,o.message},r,n))return false;i=s;}return true}var _X=16,SX=og$1,bX=4*1048576,EX=32;function TX(e){return e.type==="command.output_delta"||e.type==="file_change.updated"||e.type==="message.delta"||e.type==="plan.delta"||e.type==="reasoning.delta"||e.type==="tool.progress"}function L1(e){let t=e.type==="reasoning.delta"?`${e.payload.field}:${String(e.payload.sectionIndex??-1)}`:"value";return JSON.stringify([e.taskId,e.turnId,e.itemId,e.type,t])}function RX(e,t){return e.type==="command.output_delta"&&t.type==="command.output_delta"||e.type==="message.delta"&&t.type==="message.delta"||e.type==="plan.delta"&&t.type==="plan.delta"||e.type==="reasoning.delta"&&t.type==="reasoning.delta"?{...e,payload:{...e.payload,delta:e.payload.delta+t.payload.delta}}:t}var Tl=class{#e;#t;#n;#r=new Set;#i;#o;#f;#l=[];#s;#p;#h;#d=0;#c=false;#a=0;#m=0;#y=0;#g;#k=0;#b=0;#T=0;#R=0;#v=0;#w=0;#E=false;constructor(t){let r=t.capacity??1e3;if(!Number.isInteger(r)||r<=0)throw new RangeError("Agent Event capacity must be a positive integer");let n=t.coalescingWindowMs??_X,i=t.maxEventBytes??SX,s=t.maxRetainedBytes??bX,o=t.pressureCoalescingWindowMs??EX;if(!Number.isFinite(n)||n<=0)throw new RangeError("Agent Event coalescing window must be a positive number");if(!Number.isFinite(o)||o<n)throw new RangeError("Agent Event pressure coalescing window must not be shorter than the normal window");if(!Number.isSafeInteger(i)||i<0)throw new RangeError("Agent Event maxEventBytes must be a non-negative safe integer");if(!Number.isSafeInteger(s)||s<0)throw new RangeError("Agent Event maxRetainedBytes must be a non-negative safe integer");this.#e=r,this.#t=n,this.#n=new Array(r),this.#i=i,this.#o=s,this.#f=t.now??(()=>new Date),this.#s=o,this.#p=t.provider,this.#h=t.sessionId;}get checkpoint(){return this.#_(),{sequence:this.#w,sessionId:this.#h}}get metrics(){return {backpressureSignals:this.#d,coalescedEvents:this.#a,pendingDeltas:this.#l.length,providerEventsReceived:this.#b,publishedEvents:this.#T,retainedEvents:this.#m,retentionEvictions:this.#v}}publish(t){if(this.#c)return;if(this.#b+=1,!TX(t)){this.#_(),this.#u(t);return}if(this.#g===void 0){this.#u(t),this.#O();return}let r=this.#l.length-1,n=this.#l[r];n===void 0||L1(n)!==L1(t)?this.#l.push(t):(this.#l[r]=RX(n,t),this.#a+=1);}noteBackpressure(){this.#c||(this.#d+=1,this.#E=true);}replayAfter(t){if(this.#_(),t>this.#w)return {latestSequence:this.#w,reason:"session_changed",type:"resync"};let r=this.#I();return t<this.#k?{latestSequence:this.#w,reason:"event_retention_exceeded",type:"resync"}:{events:r.filter(n=>n.sequence>t),type:"events"}}subscribe(t){return this.#c?()=>{}:(this.#r.add(t),()=>{this.#r.delete(t);})}close(){this.#c||(this.#_(),this.#c=true,this.#r.clear());}#_(){if(this.#g!==void 0&&(clearTimeout(this.#g),this.#g=void 0),this.#l.length===0)return;let t=this.#l.splice(0);for(let r of t)this.#u(r);}#u(t){this.#w+=1;let r={...t,provider:this.#p,sequence:this.#w,sessionId:this.#h,timestamp:this.#f().toISOString(),version:2};this.#P(r),this.#T+=1;for(let n of this.#r)n(r);}#P(t){let r=Cw(t);if(r>this.#i||r>this.#o){for(;this.#m>0;)this.#x();this.#k=t.sequence,this.#v+=1;return}for(this.#m===this.#e&&this.#x();this.#m>0&&this.#R+r>this.#o;)this.#x();let n=(this.#y+this.#m)%this.#e;this.#n[n]={event:t,retainedBytes:r},this.#m+=1,this.#R+=r;}#I(){let t=[];for(let r=0;r<this.#m;r+=1){let n=this.#n[(this.#y+r)%this.#e];n!==void 0&&t.push(n.event);}return t}#x(){let t=this.#n[this.#y];t!==void 0&&(this.#n[this.#y]=void 0,this.#y=(this.#y+1)%this.#e,this.#m-=1,this.#R-=t.retainedBytes,this.#k=t.event.sequence,this.#v+=1);}#O(){if(this.#g!==void 0)return;let t=this.#E?this.#s:this.#t;this.#E=false,this.#g=setTimeout(()=>{this.#g=void 0,this.#_();},t);}};var OH=e(gT(),1),yT=new WeakMap,E_e=3e3;function wT(e,t){yT.set(e,t);}var nd=class extends OH.LogController{incomingRequest(){}routeNotFound(){}requestCompleted(t,r,n){let i=r.routeOptions.url,s=yT.get(r)??(t?"REQUEST_FAILED":void 0);yT.delete(r);let o=r.params,a={durationMs:n.elapsedTime,...s===void 0?{}:{errorCode:s},method:r.method,requestId:r.id,route:i,statusCode:n.statusCode,...Object.fromEntries(["projectId","taskId","turnId"].filter(c=>typeof o?.[c]=="string").map(c=>[c,o?.[c]]))};t||n.statusCode>=500?r.log.error(a,"request completed"):i?.startsWith("/v1/")&&i!=="/v1/health"&&(n.statusCode>=400?r.log.warn(a,"request rejected"):n.elapsedTime>=E_e&&!r.ws?r.log.warn(a,"slow request completed"):["POST","PUT","PATCH","DELETE"].includes(r.method)&&r.log.info(a,"operation completed"));}};var vT=e(k(),1);vT.default.configure;var CH=vT.default;function qe(e,t){return e instanceof Error&&e.message.length>0?e.message:typeof e=="string"&&e.length>0?e:t}var L=class extends Error{constructor(r,n,i,s=false){super(n);this.code=r;this.statusCode=i;this.retryable=s;this.name="MutationHttpError";}code;statusCode;retryable};function Vm(e){let t=e instanceof Error&&e.message.trim().length>0?e.message:"MCP provider request failed";return new L("PROVIDER_ERROR",t,502,true)}var DH=64*1024;function MH(e){return e==="image"?Fb:e==="text"?Ib:Db}function jH(e){return [...e].sort((t,r)=>t.id.localeCompare(r.id,"en"))}function Mi(e,t,r="workspace-write"){let n=jH(e),i=n.find(a=>a.id===t?.model)??n.find(a=>a.isDefault)??n[0];if(i===void 0)throw new L("PROVIDER_ERROR","No Agent models are available",502,true);let s=jH(i.supportedReasoningEfforts),o=s.find(a=>a.id===t?.reasoningEffort)?.id??s.find(a=>a.id===i.defaultReasoningEffort)?.id??s[0]?.id;if(o===void 0)throw new L("PROVIDER_ERROR","The selected Agent model has no reasoning effort",502,true);return {model:i.id,reasoningEffort:o,sandboxMode:t?.sandboxMode??r}}function Km(e,t){let r=Mi(e,t);if(r.model!==t.model||r.reasoningEffort!==t.reasoningEffort)throw new L("INVALID_REQUEST","Model and reasoning effort combination is invalid",400)}function FH(e,t={}){return {id:e.id,pinned:e.pinned,projectId:e.projectId,...e.threadConfiguration===void 0?{}:{threadConfiguration:e.threadConfiguration},title:t.title??e.title,updatedAt:e.updatedAt,...e.workspacePath===void 0?{}:{workspacePath:e.workspacePath}}}function $H(e,t){return async()=>{let r=await e.readProviderConnection(),n,i;try{n=await e.listModels();}catch(o){i=o instanceof Error?o:new Error("Model catalog unavailable");}if(n===void 0||n.data.length===0){if(r.mode!=="custom")throw i??new L("PROVIDER_ERROR","No Agent models are available",502,true);let o$1=await t.readProviderConnection().catch(()=>{});if(o$1?.mode==="custom"&&r.customBaseUrl?.replace(/\/+$/u,"")===o$1.customBaseUrl?.replace(/\/+$/u,"")&&o$1.customModels!==null&&o$1.customModels.data.length>0)return o(o$1.customModels);throw i??new L("PROVIDER_ERROR","No Agent models are available",502,true)}let s=r.mode==="custom"?o(n):n;return await t.writeProviderConnection({customBaseUrl:r.customBaseUrl,customModels:r.mode==="custom"?{data:s.data.map(o=>({...o,supportedReasoningEfforts:[...o.supportedReasoningEfforts]})),nextCursor:s.nextCursor}:null,mode:r.mode,updatedAt:new Date().toISOString()}).catch(()=>{}),s}}var Wm=class{#e;#t;#n;#r;#i=0;#o;constructor(t,r){this.#e=t,this.#t=r.maxBytes,this.#n=r.ttlMs;}read(){let t=this.#r;if(t!==void 0&&t.expiresAt>Date.now())return Promise.resolve(t.page);if(this.#r=void 0,this.#o!==void 0)return this.#o;let r=this.#i,n=this.#e().then(i=>{let s=Buffer$1.byteLength(JSON.stringify(i),"utf8");return r===this.#i&&s<=this.#t&&(this.#r={expiresAt:Date.now()+this.#n,page:i}),i}).finally(()=>{this.#o===n&&(this.#o=void 0);});return this.#o=n,n}clear(){this.#i+=1,this.#r=void 0,this.#o=void 0;}replace(t){this.#i+=1,this.#o=void 0;let r=Buffer$1.byteLength(JSON.stringify(t),"utf8");this.#r=r<=this.#t?{expiresAt:Date.now()+this.#n,page:t}:void 0;}},qH=1e3,UH=600*1e3,BH=6e4,HH=1*1024*1024,GH=3e4,T_e=55e3,R_e={additionalProperties:false,properties:{message:{maxLength:1e4,minLength:1,type:"string"}},required:["message"],type:"object"};function _c(e){let t=CH(e);if(t===void 0)throw new TypeError("Payload must be JSON-serializable");return t}function zH(e){switch(e.code){case "not_found":return new L("PENDING_REQUEST_NOT_FOUND","Pending request not found",404);case "expired":return new L("PENDING_REQUEST_EXPIRED","Pending request expired",409);case "resolved":return new L("PENDING_REQUEST_ALREADY_RESOLVED","Pending request already resolved",409);case "mismatch":return new L("PENDING_REQUEST_MISMATCH","Pending request identity does not match",409)}}function VH(e,t){if(e.repositoryMode!=="root")throw new L("GIT_REPOSITORY_UNAVAILABLE","Git commits require the project root to be a repository",409);if(e.snapshot!==t.expectedSnapshot)throw new L("GIT_STATUS_CHANGED","Git changes changed before the request completed",409);let r=new Set([...e.staged,...e.unstaged].map(n=>n.path));if(t.paths.some(n=>!r.has(n)))throw new L("GIT_PATH_UNAVAILABLE","A selected file is no longer available",409)}function LH(e,t){if(e.status!=="completed")throw new L("COMMIT_MESSAGE_GENERATION_FAILED",e.error??"Commit message generation did not complete",502,true);let r=t;for(let n of [...e.items].reverse())if(n.type==="message"&&n.role==="assistant"){r=n.text;break}if(r===void 0)throw new L("COMMIT_MESSAGE_GENERATION_FAILED","Codex returned no commit message",502,true);try{let n=JSON.parse(r);if(typeof n!="object"||n===null||Object.keys(n).length!==1||!("message"in n)||typeof n.message!="string"||n.message.trim().length===0||n.message.length>1e4)throw new Error("Invalid structured output");return n.message.trim()}catch{throw new L("COMMIT_MESSAGE_GENERATION_FAILED","Codex returned an invalid commit message",502,true)}}async function WH(e,t,r){let n=await e.startTask({ephemeral:true}),i=new Map,s,o=false,a,c;try{let l=new Promise((m,p)=>{c=e.subscribeEvents(h=>{h.taskId===n.id&&(h.type==="item.completed"&&h.payload.item.type==="message"&&h.payload.item.role==="assistant"?i.set(h.turnId,h.payload.item.text):h.type==="turn.completed"?(o=!0,m(h.payload.turn)):h.type==="provider.error"&&!h.payload.willRetry&&p(new Error(h.payload.message)));},{includeEphemeral:!0}),a=setTimeout(()=>{p(new Error("Commit message generation timed out"));},T_e);}),u=await e.startTurn(n.id,{files:[],images:[],outputSchema:R_e,skills:[],text:t,textAttachments:[]},{...r,approvalPolicy:"never",approvalsReviewer:"user",sandboxMode:"read-only"});if(s=u.id,u.status!=="running")return o=!0,LH(u);let d=await l;return LH(d,i.get(d.id))}catch(l){throw l instanceof L?l:new L("COMMIT_MESSAGE_GENERATION_FAILED",qe(l,"Codex could not generate a commit message"),502,true)}finally{a!==void 0&&clearTimeout(a),c?.(),!o&&s!==void 0&&await e.interruptTurn(n.id,s).catch(()=>{}),await e.unsubscribeTask(n.id).catch(()=>{});}}function KH(e){let t=e.code==="GIT_COMMIT_FAILED"?502:409;return new L(e.code,e.message,t)}function YH(e,t,r){let n={...t,...r},i=Mi(e,n,n.sandboxMode??"workspace-write"),s=Mi(e,{model:t?.commitMessageModel??rd,sandboxMode:"read-only"},"read-only"),o=n.approvalPolicy??"on-request",a=n.approvalsReviewer??"user";return {approvalPolicy:o,approvalsReviewer:a,commitMessageModel:s.model,commitMessagePrompt:t?.commitMessagePrompt??"",modelContextWindow:r.modelContextWindow??null,defaultOpenAppId:t?.defaultOpenAppId??null,fastMode:r.fastMode??t?.fastMode??false,followUpBehavior:t?.followUpBehavior??"queue",pet:t?.pet??{enabled:false,selectedPetId:null},...i}}var ge={additionalProperties:false,properties:{projectId:{minLength:1,type:"string"}},required:["projectId"],type:"object"},QH={additionalProperties:false,properties:{kind:Qb$1,projectId:{minLength:1,type:"string"}},required:["kind","projectId"],type:"object"},JH={additionalProperties:false,properties:{kind:xa,projectId:{minLength:1,type:"string"}},required:["kind","projectId"],type:"object"},XH={additionalProperties:false,properties:{attachmentId:{minLength:1,type:"string"},projectId:{minLength:1,type:"string"}},required:["attachmentId","projectId"],type:"object"},Fe={additionalProperties:false,properties:{projectId:{minLength:1,type:"string"},taskId:{minLength:1,type:"string"}},required:["projectId","taskId"],type:"object"},_T={additionalProperties:false,properties:{projectId:{minLength:1,type:"string"},taskId:{minLength:1,type:"string"},turnId:{minLength:1,type:"string"}},required:["projectId","taskId","turnId"],type:"object"},ST={additionalProperties:false,properties:{projectId:{minLength:1,type:"string"},queuedSubmissionId:{minLength:1,type:"string"},taskId:{minLength:1,type:"string"}},required:["projectId","taskId","queuedSubmissionId"],type:"object"},ZH={additionalProperties:false,properties:{projectId:{minLength:1,type:"string"},taskId:{minLength:1,type:"string"},terminalId:{minLength:1,type:"string"}},required:["projectId","taskId","terminalId"],type:"object"},bT={additionalProperties:false,properties:{attachmentId:{minLength:1,type:"string"},projectId:{minLength:1,type:"string"},taskId:{minLength:1,type:"string"}},required:["attachmentId","projectId","taskId"],type:"object"},eG={additionalProperties:false,properties:{projectId:{minLength:1,type:"string"},requestId:{minLength:1,type:"string"},taskId:{minLength:1,type:"string"}},required:["projectId","taskId","requestId"],type:"object"},X={properties:{"idempotency-key":{minLength:1,type:"string"}},required:["idempotency-key"],type:"object"},tG={additionalProperties:false,properties:{archived:{const:true,type:"boolean"},completed:{const:true,type:"boolean"},cursor:{minLength:1,type:"string"},limit:{maximum:100,minimum:1,type:"integer"},pinned:{const:true,type:"boolean"},searchTerm:{maxLength:200,minLength:1,type:"string"}},type:"object"},rG={additionalProperties:false,properties:{cursor:{maxLength:8192,minLength:1,type:"string"},summary:{type:"boolean"}},type:"object"};var nG={additionalProperties:false,properties:{afterSequence:{minimum:0,type:"integer"}},required:["afterSequence"],type:"object"},le={additionalProperties:false,properties:{code:{minLength:1,type:"string"},message:{minLength:1,type:"string"}},required:["code","message"],type:"object"};var iG=(e,t,r)=>{e.post("/v1/history/compress",{schema:{body:{type:"object",additionalProperties:false},headers:X,response:{200:Eg$1,502:Xf,503:Xf}}},n=>t.runIdempotent(["compress-history"],n.headers["idempotency-key"],n.body,async()=>{let i=t.provider.historyStorage;if(i===void 0)throw new L("PROVIDER_ERROR","History compression is unavailable",503,true);try{return await i.compress()}catch(s){throw new L("PROVIDER_ERROR",s instanceof Error?s.message:"History compression request failed",502,true)}})),r();};var Ym=class{#e=new Set;subscribe(t){return this.#e.add(t),()=>{this.#e.delete(t);}}publish(t){for(let r of this.#e)r(t);}publishAgentEvent(t,r){(r.type==="turn.started"||r.type==="turn.completed"||r.type==="item.completed"&&r.payload.item.type==="message"&&(r.payload.item.questions?.length??0)>0)&&this.publish({type:"async-questions.changed",projectId:t,taskId:r.taskId});}};var cn="codexly_session";function Qm(e,t){return {authenticated:e,mode:t,version:1}}var sG=(e,t,r)=>{let{access:n,service:i}=t,s=n===void 0?"local":"lan";e.get("/v1/access",{schema:{response:{200:Zd$1}}},o=>Qm(s==="local"||i?.validate(o.cookies[cn])===true,s)),e.post("/v1/access/pair",{schema:{body:_d$1,response:{200:Zd$1}}},(o,a)=>{if(n===void 0||i===void 0)return Qm(true,"local");let c=i.pair(o.body.code,o.ip);return c.status!=="paired"?a.code(c.status==="rate_limited"?429:403).send({code:c.status==="rate_limited"?"PAIRING_RATE_LIMITED":"PAIRING_FAILED",message:"Pairing request failed",retryable:c.status==="rate_limited"}):(a.setCookie(cn,c.sessionId,{...c.expiresAt===null||n.sessionTtlMs===void 0?{}:{expires:new Date(c.expiresAt),maxAge:Math.ceil(n.sessionTtlMs/1e3)},httpOnly:true,path:"/",sameSite:"strict",secure:false}),Qm(true,"lan"))}),e.post("/v1/access/logout",{schema:{response:{200:Zd$1}}},(o,a)=>(i?.logout(o.cookies[cn]),a.clearCookie(cn,{path:"/",sameSite:"strict"}),Qm(s==="local",s))),r();};var P_e=2147483647;function ET(e,t){let r,n=()=>{let i=t-Date.now();if(i<=0){e.close(1008,"Access session expired");return}r=setTimeout(n,Math.min(i,P_e)),r.unref();};return n(),()=>{r!==void 0&&clearTimeout(r);}}var oG=(e,t,r)=>{let{accessService:n,getProjectContext:i,projectContexts:s}=t;e.get("/v1/projects/:projectId/events",{async preValidation(o,a){if(await i(o.params.projectId)===void 0)return await a.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"})},schema:{params:ge,querystring:nG},websocket:true},(o,a)=>{let c=n?.expiresAt(a.cookies[cn]);if(n!==void 0&&c===void 0){o.close(1008,"Access session expired");return}let l=s.get(a.params.projectId);if(l===void 0){o.close(1008,"Project not found");return}let u=l.eventStream;l.transportMetrics.activeClients+=1;let d=false,m=false,p=[],h=()=>{},f=()=>{},g=c==null?()=>{}:ET(o,c),y=()=>{d||(d=true,p.length=0,g(),f(),h(),l.transportMetrics.activeClients-=1);};if(o.once("close",y),o.once("error",y),f=n?.onInvalidated(a.cookies[cn],()=>{y(),o.close(1008,"Access session expired");})??(()=>{}),o.readyState!==o.OPEN)return;let _=j=>N1(o,j,()=>{u.noteBackpressure();},()=>{l.transportMetrics.slowClientDisconnects+=1;}),v=j=>j1(o,j,()=>{u.noteBackpressure();},()=>{l.transportMetrics.slowClientDisconnects+=1;}),w=()=>{if(m=false,d||p.length===0)return;let j=p.splice(0);v(j);},E=j=>{if(p.push(j),p.length>=ng){w();return}m||(m=true,queueMicrotask(()=>{m&&w();}));},R=u.replayAfter(a.query.afterSequence);if(R.type==="resync"){_({latestSequence:R.latestSequence,reason:R.reason,sessionId:u.checkpoint.sessionId,type:"resync.required",version:3})&&o.close(1e3,"Snapshot resync required");return}let P=u.checkpoint,b=[],O=true;h=u.subscribe(j=>{if(O){b.push(j);return}E(j);}),_({latestSequence:P.sequence,sessionId:P.sessionId,type:"connection.ready",version:3})&&v(R.events)&&(O=false,v(b));}),r();};function aG(e,t){TT(e,t,"/v1/workbench/events",{type:"workbench.ready"},r=>t.workbenchChanges.subscribe(r));}function TT(e,t,r,n,i){e.get(r,{websocket:true},(s,o)=>{let a=t.accessService?.expiresAt(o.cookies[cn]);if(t.accessService!==void 0&&a===void 0){s.close(1008,"Access session expired");return}let c=a==null?()=>{}:ET(s,a),l=new Set,u=false,d=y=>{if(!(u||s.readyState!==1)){if(s.bufferedAmount>65536){s.close(1013,"Slow client");return}s.send(y,_=>{_&&s.terminate();});}},m=i(y=>{if(u)return;let _=l.size>0;if(l.add(JSON.stringify(y)),l.size>256){s.close(1013,"Too many changes");return}_||queueMicrotask(()=>{for(let v of l)d(v);l.clear();});}),p=true;s.on("pong",()=>{p=true;});let h=setInterval(()=>{if(!p){s.terminate();return}p=false,s.ping();},3e4);h.unref();let f=()=>{},g=()=>{u||(u=true,m(),l.clear(),c(),f(),clearInterval(h));};s.once("close",g),s.once("error",g),f=t.accessService?.onInvalidated(o.cookies[cn],()=>{g(),s.close(1008,"Access session expired");})??(()=>{}),d(JSON.stringify(n));});}var KJ=e(gT(),1);function RT(e,t){return `${e}\0${t}`}var Jm=class{#e=new Map;retain(t,r,n){this.#e.set(RT(t,r),new Set(n));}take(t,r){let n=RT(t,r),i=[...this.#e.get(n)??[]];return this.#e.delete(n),i}replace(t,r,n){let i=RT(t,r),s=this.#e.get(i)??new Set,o=new Set(n);return this.#e.set(i,o),[...s].filter(a=>!o.has(a))}hasAttachment(t){return [...this.#e.values()].some(r=>r.has(t))}deleteAttachment(t){for(let[r,n]of this.#e)n.delete(t),n.size===0&&this.#e.delete(r);}clearProject(t){let r=`${t}\0`;for(let n of this.#e.keys())n.startsWith(r)&&this.#e.delete(n);}};var M_e=1800*1e3,F_e=1500,$_e=Hb+Eb$1,q_e=new Map([["image/gif",".gif"],["image/jpeg",".jpg"],["image/png",".png"],["image/webp",".webp"]]),er=class extends Error{constructor(){super("Attachment was not found or has expired"),this.name="AttachmentNotFoundError";}};function U_e(e){return e==="image"?Fb:e==="text"?Ib:Db}function B_e(e){if(e.name.length===0||e.name.length>255||e.mediaType.length>255)throw new TypeError("Attachment metadata is invalid");if(e.kind==="image"){let r=q_e.get(e.mediaType);if(r===void 0)throw new TypeError("Attachment image type is unsupported");return r}if(e.kind==="text"){if(e.mediaType!=="text/plain")throw new TypeError("Generated text attachment must use text/plain");return ".txt"}return extname(e.name).toLowerCase()}async function hG(e,t){let r=await open(e,"r");try{let n=Buffer$1.alloc(t),{bytesRead:i}=await r.read(n,0,t,0);return n.subarray(0,i)}finally{await r.close();}}async function H_e(e){let t=await open(e,"r"),r=13,n=0,i=async o=>{let a=Buffer$1.alloc(o),{bytesRead:c}=await t.read(a,0,o,r);if(c===o)return r+=o,a},s=async()=>{for(;;){let o=(await i(1))?.[0];if(o===void 0)return false;if(o===0)return true;if(await i(o)===void 0)return false}};try{let o=await hG(e,13),a=o[10];if(o.length<13||a===void 0)return !1;for((a&128)!==0&&(r+=3*2**((a&7)+1));;){let c=(await i(1))?.[0];if(c===void 0||c===59)return n>1;if(c===33){if(await i(1)===void 0||!await s())return !1;continue}if(c!==44)return !1;if(n+=1,n>1)return !0;let l=await i(9);if(l===void 0)return !1;let u=l[8]??0;if((u&128)!==0&&(r+=3*2**((u&7)+1)),await i(1)===void 0||!await s())return !1}}finally{await t.close();}}async function G_e(e,t){let r=await hG(e,12);if(!(t==="image/png"&&r.subarray(0,8).equals(Buffer$1.from("89504e470d0a1a0a","hex"))||t==="image/jpeg"&&r[0]===255&&r[1]===216&&r[2]===255||t==="image/webp"&&r.subarray(0,4).toString("ascii")==="RIFF"&&r.subarray(8,12).toString("ascii")==="WEBP"||t==="image/gif"&&/^GIF8[79]a$/u.test(r.subarray(0,6).toString("ascii")))||t==="image/gif"&&await H_e(e))throw new TypeError("Attachment image content is invalid or animated")}async function z_e(e){let t=new TextDecoder$1("utf-8",{fatal:true});for await(let r of createReadStream(e))t.decode(r,{stream:true});t.decode();}async function uG(e){try{await unlink(e);}catch(t){if(!(t instanceof Error&&"code"in t&&t.code==="ENOENT"))throw t}}var Xm=class{#e;#t;#n;#r=new Map;#i=new Jm;#o;#f;#l;#s;#p=0;#h=0;constructor(t={}){this.#e=t.attachmentDirectory??join(tmpdir(),`codexly-attachments-${randomUUID()}`),this.#t=t.clock??Date.now,this.#n=t.createId??randomUUID,this.#o=t.maxBytes,this.#f=t.maxEntries??F_e,this.#l=t.maxTotalBytes??$_e,this.#s=t.ttlMs??M_e;}async add(t,r){await this.#c();let n=B_e(r),i=this.#o??U_e(r.kind);if(this.#r.size+this.#p>=this.#f)throw new RangeError("Attachment store capacity exceeded");this.#p+=1;let s;try{let o=this.#n();s=join(this.#e,`${Buffer$1.from(o).toString("base64url")}${n}`);let a=createHash("sha256"),c=0,l=new Transform({transform(d,m,p){let h=Buffer$1.isBuffer(d)?d:Buffer$1.from(d);if(c+=h.byteLength,c>i){p(new RangeError("Attachment exceeds the maximum size"));return}a.update(h),p(null,h);}});if(await mkdir(this.#e,{recursive:!0}),await pipeline(r.content,l,createWriteStream(s,{flags:"wx"})),c===0)throw new RangeError("Attachment must not be empty");r.kind==="image"?await G_e(s,r.mediaType):r.kind==="text"&&await z_e(s);let u={id:o,kind:r.kind,mediaType:r.mediaType,name:r.name,size:c};if(this.#h+c>this.#l)throw new RangeError("Attachment store capacity exceeded");return this.#r.set(o,{attachment:u,expiresAt:this.#t()+this.#s,path:s,projectId:t}),this.#h+=c,{attachment:u,contentDigest:a.digest("hex")}}catch(o){throw s!==void 0&&await uG(s),o}finally{this.#p-=1;}}async resolve(t,r){await this.#c();let n=r.map(s=>{let o=this.#r.get(s);if(o?.projectId!==t||o.consumedTurnId!==void 0)throw new er;return o}),i=[];for(let s of n){let{attachment:o,path:a}=s;if(o.kind==="file")i.push({kind:"file",mediaType:o.mediaType,name:o.name,path:a,size:o.size});else if(o.kind==="image"){let c=o.mediaType;i.push({kind:"image",mediaType:c,path:a,size:o.size});}else {let c=await readFile(a);i.push({kind:"text",mediaType:"text/plain",name:o.name,size:o.size,text:new TextDecoder$1("utf-8",{fatal:true}).decode(c)});}}return i}async read(t,r){await this.#c();let n=this.#r.get(r);if(n?.projectId!==t||n.consumedTurnId!==void 0)throw new er;return {attachment:n.attachment,content:await readFile(n.path)}}async readSubmitted(t,r){await this.#c();let n=this.#r.get(r);if(n?.projectId!==t||n.consumedTurnId===void 0)throw new er;return {attachment:n.attachment,content:await readFile(n.path)}}async consume(t,r,n){for(let i of new Set(r)){let s=this.#r.get(i);s?.projectId===t&&(n!==void 0?(s.consumedTurnId=n,s.expiresAt=this.#t()+this.#s):await this.#d(i));}}async retainQueue(t,r,n,i=false){let s=[...new Set(r)];for(let a of s){let c=this.#r.get(a);if(c?.projectId!==t||c.consumedTurnId!==void 0)throw new er;c.expiresAt=this.#t()+this.#s;}if(!i){this.#i.retain(t,n,s);return}let o=this.#i.replace(t,n,s);await Promise.all(o.map(a=>this.#d(a)));}startQueue(t,r,n){for(let i of this.#i.take(t,r)){let s=this.#r.get(i);s?.projectId===t&&(s.consumedTurnId=n,s.expiresAt=this.#t()+this.#s);}return Promise.resolve()}async releaseQueue(t,r){let n=this.#i.take(t,r);await Promise.all(n.map(async i=>{let s=this.#r.get(i);s?.projectId===t&&s.consumedTurnId===void 0&&await this.#d(i);}));}async discard(t){await this.#d(t);}async releaseTurn(t,r){for(let[n,i]of this.#r)i.projectId===t&&i.consumedTurnId===r&&await this.#d(n);}async releaseProject(t){this.#i.clearProject(t);let r=[...this.#r].filter(([,n])=>n.projectId===t).map(([n])=>n);await Promise.all(r.map(n=>this.#d(n)));}async releaseProjectRuntime(t){let r=[...this.#r].filter(([n,i])=>i.projectId===t&&!this.#i.hasAttachment(n)).map(([n])=>n);await Promise.all(r.map(n=>this.#d(n)));}async clear(){await Promise.all([...this.#r.keys()].map(t=>this.#d(t)));}async dispose(){await this.clear(),await rm$1(this.#e,{force:true,recursive:true});}async#d(t){let r=this.#r.get(t);r!==void 0&&(this.#r.delete(t),this.#i.deleteAttachment(t),this.#h-=r.attachment.size,await uG(r.path));}async#c(){let t=this.#t();for(let[r,n]of this.#r)n.expiresAt<=t&&!this.#i.hasAttachment(r)&&await this.#d(r);}};var kT=new WeakMap;function id(...e){let t=new String(e);return kT.set(t,e),t}function ti(e){return e instanceof String&&kT.has(e)}function bc(e){return kT.get(e)??[]}var yg=e(PG(),1),wg=e(OT(),1),As=e(kG(),1);function*xG(e,t){let r=t==="global";for(let n of e)n.isGlobal===r&&(yield n);}var bSe=new Set(["--add","--edit","--remove-section","--rename-section","--replace-all","--unset","--unset-all","-e"]),ESe=new Set(["--get","--get-all","--get-color","--get-colorbool","--get-regexp","--get-urlmatch","--list","-l"]),TSe=new Set(["edit","remove-section","rename-section","set","unset"]),RSe=new Set(["get","get-color","get-colorbool","list"]);function PSe(e,t){for(let{name:n}of xG(e,"task")){if(bSe.has(n))return kc(true,t);if(ESe.has(n))return kc(false,t)}let r=t.at(0)?.toLowerCase();return r===void 0?null:TSe.has(r)?kc(true,t.slice(1)):RSe.has(r)?kc(false,t.slice(1)):t.length===1?kc(false,t):kc(true,t)}function kc(e=false,t=[]){let r=t.at(0)?.toLowerCase();return r===void 0?null:{isWrite:e,isRead:!e,key:r,value:t.at(1)}}function kSe(e,t){return t.isWrite&&t.value!==void 0?{key:t.key,value:t.value,scope:e}:{key:t.key,scope:e}}function xSe(e){let t=e?.indexOf("=")||-1;return !e||t<0?null:{key:e.slice(0,t).trim().toLowerCase(),value:e.slice(t+1)}}function ASe(e){for(let{name:t}of xG(e,"task"))switch(t){case "--global":return "global";case "--system":return "system";case "--worktree":return "worktree";case "--local":return "local";case "--file":case "-f":return "file"}return "local"}function ISe({name:e}){if(e==="-c"||e==="--config")return "inline";if(e==="--config-env")return "env"}function*OSe(e){for(let t of e){let r=ISe(t),n=r&&xSe(t.value);n&&(yield {...n,scope:r});}}function CSe(e,t,r){let n={read:[],write:[...OSe(t)]};return e==="config"&&NSe(n,ASe(t),PSe(t,r)),n}function NSe(e,t,r){if(r===null)return;let n=kSe(t,r);r.isWrite?e.write.push(n):e.read.push(n);}var AG={short:new Map([["c",true]])},jSe={short:new Map([["C",true],["P",false],["h",false],["p",false],["v",false],...AG.short.entries()]),long:new Set(["attr-source","config-env","exec-path","git-dir","list-cmds","namespace","super-prefix","work-tree"])},LSe={clone:{short:new Map([["b",true],["j",true],["l",false],["n",false],["o",true],["q",false],["s",false],["u",true]]),long:new Set(["branch","config","jobs","origin","upload-pack","u","template"])},commit:{short:new Map([["C",true],["F",true],["c",true],["m",true],["t",true]]),long:new Set(["file","message","reedit-message","reuse-message","template"])},config:{short:new Map([["e",false],["f",true],["l",false]]),long:new Set(["blob","comment","default","file","type","value"])},fetch:{short:new Map,long:new Set(["upload-pack"])},init:{short:new Map,long:new Set(["template"])},pull:{short:new Map,long:new Set(["upload-pack"])},push:{short:new Map,long:new Set(["exec","receive-pack"])},rebase:{short:new Map([["X",true],["f",false],["i",false],["k",false],["m",false],["n",false],["q",false],["r",false],["s",true],["v",false],["x",true]]),long:new Set(["exec","onto","strategy","strategy-option"])}},DSe={short:new Map,long:new Set};function MSe(e){let t=LSe[e??""]??DSe;return {short:new Map([...AG.short.entries(),...t.short.entries()]),long:t.long}}function IG(e,t=jSe){if(e.startsWith("--")){let r=e.indexOf("=");if(r>2)return [{name:e.slice(0,r),value:e.slice(r+1),needsNext:false}];let n=e.slice(2);return [{name:e,needsNext:t.long.has(n)}]}if(e.length===2){let r=e.charAt(1),n=t.short.get(r);return [{name:e,needsNext:n===true}]}return FSe(e,t.short)}function FSe(e,t){let r=e.slice(1).split(""),n=[];for(let i=0;i<r.length;i++){let s=r[i],o=t.get(s);if(o===void 0)return [{name:e,needsNext:false}];if(o){let a=r.slice(i+1).join("");if(a&&![...a].every(c=>t.has(c)))return n.push({name:`-${s}`,value:a,needsNext:false}),n}n.push({name:`-${s}`,needsNext:o});}return n}function $Se(e,t=[]){let r=0;for(;r<e.length;){let n=String(e[r]);if(!n.startsWith("-")||n.length<2)break;let i=IG(n),s=r+1;for(let o of i){let a={name:o.name,value:o.value,absorbedNext:false,isGlobal:true};o.needsNext&&a.value===void 0&&s<e.length&&(a.value=String(e[s]),a.absorbedNext=true,s++),t.push(a);}r=s;}return {flags:t,taskIndex:r}}function qSe(e,t,r=[]){let n=MSe(t),i=[],s=[],o=0;for(;o<e.length;){let a=e[o];if(ti(a)){s.push(...bc(a)),o++;continue}let c=String(a);if(c==="--"){for(let d=o+1;d<e.length;d++){let m=e[d];ti(m)?s.push(...bc(m)):s.push(String(m));}break}if(!c.startsWith("-")||c.length<2){i.push(c),o++;continue}let l=IG(c,n),u=o+1;for(let d of l){let m={name:d.name,value:d.value,absorbedNext:false,isGlobal:false};d.needsNext&&m.value===void 0&&u<e.length&&!ti(e[u])&&(m.value=String(e[u]),m.absorbedNext=true,u++),r.push(m);}o=u;}return {flags:r,positionals:i,pathspecs:s}}function*USe({write:e}){for(let t of e)for(let r of BSe){let n=r(t.key);n&&(yield n);}}function Lr(e,t,r=String(e)){let n=typeof e=="string"?new RegExp(`\\s*${e.toLowerCase()}`):e;return function(i){if(n.test(i))return {category:t,message:`Configuring ${r} is not permitted without enabling ${t}`}}}function Ct(e,t){let r=new RegExp(`\\s*${e.toLowerCase().replace(/\./g,"(..+)?.")}`);return Lr(r,t,e)}var BSe=[Lr("alias","allowUnsafeAlias"),Lr("core.askPass","allowUnsafeAskPass"),Lr("core.editor","allowUnsafeEditor"),Lr("core.fsmonitor","allowUnsafeFsMonitor"),Lr("core.gitProxy","allowUnsafeGitProxy"),Lr("core.hooksPath","allowUnsafeHooksPath"),Lr("core.pager","allowUnsafePager"),Lr("core.sshCommand","allowUnsafeSshCommand"),Ct("credential.helper","allowUnsafeCredentialHelper"),Ct("diff.command","allowUnsafeDiffExternal"),Lr("diff.external","allowUnsafeDiffExternal"),Ct("difftool.cmd","allowUnsafeDiffExternal"),Ct("diff.textconv","allowUnsafeDiffTextConv"),Ct("filter.clean","allowUnsafeFilter"),Ct("filter.process","allowUnsafeFilter"),Ct("filter.smudge","allowUnsafeFilter"),Ct("gpg.program","allowUnsafeGpgProgram"),Lr("include.path","allowUnsafeInclude"),Ct("includeIf","allowUnsafeInclude"),Lr("init.templateDir","allowUnsafeTemplateDir"),Ct("pager.","allowUnsafePager"),Ct("merge.driver","allowUnsafeMergeDriver"),Ct("mergetool.path","allowUnsafeMergeDriver"),Ct("mergetool.cmd","allowUnsafeMergeDriver"),Ct("protocol.allow","allowUnsafeProtocolOverride"),Ct("remote.receivepack","allowUnsafePack"),Ct("remote.uploadpack","allowUnsafePack"),Lr("uploadpack.packObjectsHook","allowUnsafePack"),Lr("sequence.editor","allowUnsafeEditor"),Ct("submodule.update","allowUnsafeSubmodule"),Ct("tar.command","allowUnsafeCommandBinaries"),Ct("trailer.cmd","allowUnsafeCommandBinaries"),Ct("trailer.command","allowUnsafeCommandBinaries"),Ct("url.insteadOf","allowUnsafeUrlRewrite")];function*HSe(e,t){for(let r of t)for(let n of GSe){let i=n(e,r);i&&(yield i);}}function ri(e,t,r,{name:n=String(t),globalOnly:i=false,withValue:s=false}={}){let o=typeof t=="string"?new RegExp(`\\s*${t.toLowerCase()}`):t,a=`Use of ${e?`${e} with option `:""}${n} is not permitted without enabling ${r}`;return function(c,l){if(!(e&&c!==e)&&!(i&&!l.isGlobal)&&!(s&&l.value===void 0)&&o.test(l.name))return {category:r,message:a}}}var sg={globalOnly:true,withValue:true},GSe=[ri(null,/--(upload|receive)-pack/,"allowUnsafePack",{name:"--upload-pack or --receive-pack"}),ri("clone",/^-\w*u/,"allowUnsafePack"),ri("clone","--u","allowUnsafePack"),ri("push",/^--exec$/,"allowUnsafePack",{name:"--exec"}),ri("rebase",/^(-x|--ex(ec?)?)$/,"allowUnsafeExec",{name:"-x or --exec"}),ri(null,"--template","allowUnsafeTemplateDir"),ri(null,"--exec-path","allowUnsafeExec",sg),ri(null,"--git-dir","allowUnsafeConfigPaths",sg),ri(null,"--work-tree","allowUnsafeConfigPaths",sg),ri(null,/^-C$/,"allowUnsafeConfigPaths",{...sg,name:"-C"})];function OG(e,t,r){return [...HSe(e,t),...USe(r)]}function zSe(...e){let{flags:t,taskIndex:r}=$Se(e),n=r<e.length?String(e[r]).toLowerCase():null,i=n!==null?e.slice(r+1):[],{positionals:s,pathspecs:o}=qSe(i,n,t),a=CSe(n,t,s);return {task:n,flags:t.map(WSe),paths:o,config:a,vulnerabilities:VSe(OG(n,t,a))}}function VSe(e){return Object.defineProperty(e,"vulnerabilities",{value:e})}function WSe({value:e,name:t}){return e!==void 0?{name:t,value:e}:{name:t}}var CG={editor:"allowUnsafeEditor",git_askpass:"allowUnsafeAskPass",git_config_global:"allowUnsafeConfigPaths",git_config_system:"allowUnsafeConfigPaths",git_config_count:"allowUnsafeConfigEnvCount",git_config_parameters:"allowUnsafeConfigEnvCount",git_config:"allowUnsafeConfigPaths",git_editor:"allowUnsafeEditor",git_exec_path:"allowUnsafeExec",git_external_diff:"allowUnsafeDiffExternal",git_pager:"allowUnsafePager",git_proxy_command:"allowUnsafeGitProxy",git_template_dir:"allowUnsafeTemplateDir",git_sequence_editor:"allowUnsafeEditor",git_ssh:"allowUnsafeSshCommand",git_ssh_command:"allowUnsafeSshCommand",pager:"allowUnsafePager",prefix:"allowUnsafeConfigPaths",ssh_askpass:"allowUnsafeAskPass",visual:"allowUnsafeEditor"};function*KSe(e){let t=parseInt(e.git_config_count??"0",10);for(let r=0;r<t;r++){let n=e[`git_config_key_${r}`],i=e[`git_config_value_${r}`];n!==void 0&&(yield {key:n.toLowerCase().trim(),value:i,scope:"env"});}}function*YSe(e){for(let t of Object.keys(e))if(og(t)){let r=CG[t];yield {category:r,message:`Use of "${t.toUpperCase()}" is not permitted without enabling ${r}`};}}function og(e){return Object.hasOwn(CG,e)}function QSe(e){let t={};for(let[r,n]of Object.entries(e)){let i=r.toLowerCase().trim();(og(i)||i.startsWith("git"))&&(t[i]=String(n));}return t}function JSe(e){let t=QSe(e),r={read:[],write:[...KSe(t)]},n=[...YSe(t),...OG(null,[],r)];return {config:r,vulnerabilities:n}}function NG(e,t){return [...zSe(...e).vulnerabilities,...JSe(t).vulnerabilities]}var In=class extends Error{constructor(t,r){super(r),this.task=t,Object.setPrototypeOf(this,new.target.prototype);}},FT=class extends In{constructor(t,r){super(void 0,r),this.config=t;}},Fi=class extends In{constructor(t,r,n){super(t,n),this.task=t,this.plugin=r,Object.setPrototypeOf(this,new.target.prototype);}},ad=class extends In{constructor(t,r){super(void 0,r||String(t)),this.git=t;}},$T=class extends In{constructor(t){super(void 0,t);}},lg="\0",vg=()=>{};function tbe(e){return typeof e!="function"?vg:e}function rbe(e){return typeof e=="function"&&e!==vg}function nbe(e,t){let r=e.indexOf(t);return r<=0?[e,""]:[e.substr(0,r),e.substr(r+1)]}function ibe(e,t=0){return JG(e)&&e.length>t?e[t]:void 0}function xc(e,t=0){if(JG(e)&&e.length>t)return e[e.length-1-t]}function JG(e){return e3(e)}function _g(e="",t=true,r=`
|
|
530
530
|
`){return e.split(r).reduce((n,i)=>{let s=t?i.trim():i;return s&&n.push(s),n},[])}function sR(e,t){return _g(e,true).map(r=>t(r))}function XG(e){return (0, yg.exists)(e,yg.FOLDER)}function On(e,t){return Array.isArray(e)?e.includes(t)||e.push(t):e.add(t),t}function sbe(e,t){return Array.isArray(e)&&!e.includes(t)&&e.push(t),e}function oR(e,t){if(Array.isArray(e)){let r=e.indexOf(t);r>=0&&e.splice(r,1);}else e.delete(t);return t}var aR=Object.prototype.toString.call.bind(Object.prototype.toString);function Gr(e){return Array.isArray(e)?e:[e]}function ZG(e){return e.replace(/[\s-]+(.)/g,(t,r)=>r.toUpperCase())}function cd(e){return Gr(e).map(t=>t instanceof String?t:String(t))}function dt(e,t=0){if(e==null)return t;let r=parseInt(e,10);return Number.isNaN(r)?t:r}function ug(e,t){let r=[];for(let n=0,i=e.length;n<i;n++)r.push(t,e[n]);return r}function dg(e){return (Array.isArray(e)?Buffer.concat(e):e).toString("utf-8")}function obe(e){return e?Buffer.isBuffer(e)?e.length:Buffer.byteLength(e):0}function abe(e,t){let r={};return t.forEach(n=>{e[n]!==void 0&&(r[n]=e[n]);}),r}function jG(e=0){return new Promise(t=>setTimeout(t,e))}function LG(e){if(e!==false)return e}function ft(e,t,r){return t(e)?e:arguments.length>2?r:void 0}var Sg=e=>Array.isArray(e);function qT(e,t){let r=ti(e)?"string":typeof e;return /number|string|boolean/.test(r)&&(!t||!t.includes(r))}var et=e=>typeof e=="string"||ti(e),cbe=e=>et(e)||Buffer.isBuffer(e),fg=e=>et(e)||Array.isArray(e)&&e.every(et);function cR(e){return !!e&&aR(e)==="[object Object]"}function lbe(e){return typeof e=="function"}var e3=e=>e==null||"number|boolean|function".includes(typeof e)?false:typeof e.length=="number",bg=(e=>(e[e.SUCCESS=0]="SUCCESS",e[e.ERROR=1]="ERROR",e[e.NOT_FOUND=-2]="NOT_FOUND",e[e.UNCLEAN=128]="UNCLEAN",e))(bg||{}),hg=class e{constructor(t,r){this.stdOut=t,this.stdErr=r;}asStrings(){return new e(this.stdOut.toString("utf8"),this.stdErr.toString("utf8"))}};function ube(){throw new Error("LineParser:useMatches not implemented")}var be=class{constructor(t,r){this.matches=[],this.useMatches=ube,this.parse=(n,i)=>(this.resetMatches(),this._regExp.every((s,o)=>this.addMatch(s,o,n(o)))?this.useMatches(i,this.prepareMatches())!==false:false),this._regExp=Array.isArray(t)?t:[t],r&&(this.useMatches=r);}resetMatches(){this.matches.length=0;}prepareMatches(){return this.matches}addMatch(t,r,n){let i=n&&t.exec(n);return i&&this.pushMatch(r,i),!!i}pushMatch(t,r){this.matches.push(...r.slice(1));}},Is=class extends be{addMatch(t,r,n){return /^remote:\s/.test(String(n))&&super.addMatch(t,r,n)}pushMatch(t,r){(t>0||r.length>1)&&super.pushMatch(t,r);}},dbe={binary:"git",maxConcurrentProcesses:5,config:[],trimmed:false};function fbe(...e){let t=process.cwd(),r=Object.assign({baseDir:t,...dbe},...e.filter(n=>typeof n=="object"&&n));return r.baseDir=r.baseDir||t,r.trimmed=r.trimmed===true,r}function t3(e,t=[]){return cR(e)?Object.keys(e).reduce((r,n)=>{let i=e[n];if(ti(i))r.push(i);else if(qT(i,["boolean"]))r.push(n+"="+i);else if(Array.isArray(i))for(let s of i)qT(s,["string","number"])||r.push(n+"="+s);else r.push(n);return r},t):t}function Ge(e,t=0,r=false){let n=[];for(let i=0,s=t<0?e.length:t;i<s;i++)"string|number".includes(typeof e[i])&&n.push(String(e[i]));return t3(lR(e),n),r||n.push(...hbe(e)),n}function hbe(e){let t=typeof xc(e)=="function";return cd(ft(xc(e,t?1:0),Sg,[]))}function lR(e){let t=lbe(xc(e));return ft(xc(e,t?1:0),cR)}function fe(e,t=true){let r=tbe(xc(e));return t||rbe(r)?r:void 0}function DG(e,t){return e(t.stdOut,t.stdErr)}function zr(e,t,r,n=true){return Gr(r).forEach(i=>{for(let s=_g(i,n),o=0,a=s.length;o<a;o++){let c=(l=0)=>{if(!(o+l>=a))return s[o+l]};t.some(({parse:l})=>l(c,e));}}),e}var uR=({exitCode:e},t,r,n)=>{if(e===bg.UNCLEAN&&ybe(t))return r(Buffer.from("false"));n(t);},r3=e=>e.trim()==="true";function pbe(e){switch(e){case "bare":return gbe();case "root":return mbe()}return {commands:["rev-parse","--is-inside-work-tree"],format:"utf-8",onError:uR,parser:r3}}function mbe(){return {commands:["rev-parse","--git-dir"],format:"utf-8",onError:uR,parser(e){return /^\.(git)?$/.test(e.trim())}}}function gbe(){return {commands:["rev-parse","--is-bare-repository"],format:"utf-8",onError:uR,parser:r3}}function ybe(e){return /(Not a git repository|Kein Git-Repository)/i.test(String(e))}var UT=class{constructor(t){this.paths=[],this.files=[],this.folders=[],this.dryRun=t;}},wbe=/^[a-z]+\s*/i,vbe=/^[a-z]+\s+[a-z]+\s*/i,_be=/\/$/;function Sbe(e,t){let r=new UT(e),n=e?vbe:wbe;return _g(t).forEach(i=>{let s=i.replace(n,"");r.paths.push(s),(_be.test(s)?r.folders:r.files).push(s);}),r}var n3=[];function bbe(e){return {commands:n3,format:"empty",parser:e}}function Dt(e){return {commands:n3,format:"empty",parser(){throw typeof e=="string"?new $T(e):e}}}function ht(e,t=false){return {commands:e,format:"utf-8",parser(r){return t?String(r).trim():r}}}function i3(e){return {commands:e,format:"buffer",parser(t){return t}}}function Ebe(e){return e.format==="buffer"}function MG(e){return e.format==="empty"||!e.commands.length}var Tbe="Git clean interactive mode is not supported",Rbe='Git clean mode parameter ("n" or "f") is required',Pbe="Git clean unknown option found in: ",s3=(e=>(e.DRY_RUN="n",e.FORCE="f",e.IGNORED_INCLUDED="x",e.IGNORED_ONLY="X",e.EXCLUDING="e",e.QUIET="q",e.RECURSIVE="d",e))(s3||{}),o3=new Set(["i",...cd(Object.values(s3))]);function kbe(e,t){let{cleanMode:r,options:n,valid:i}=Ibe(e);return r?i.options?(n.push(...t),n.some(Nbe)?Dt(Tbe):xbe(r,n)):Dt(Pbe+JSON.stringify(e)):Dt(Rbe)}function xbe(e,t){return {commands:["clean",`-${e}`,...t],format:"utf-8",parser(r){return Sbe(e==="n",r)}}}function Abe(e){return Array.isArray(e)&&e.every(t=>o3.has(t))}function Ibe(e){let t,r=[],n={cleanMode:false,options:true};return e.replace(/[^a-z]i/g,"").split("").forEach(i=>{Obe(i)?(t=i,n.cleanMode=true):n.options=n.options&&Cbe(r[r.length]=`-${i}`);}),{cleanMode:t,options:r,valid:n}}function Obe(e){return e==="f"||e==="n"}function Cbe(e){return /^-[a-z]$/i.test(e)&&o3.has(e.charAt(1))}function Nbe(e){return /^-[^\-]/.test(e)?e.indexOf("i")>0:e==="--interactive"}var BT=class{constructor(){this.files=[],this.values=Object.create(null);}get all(){return this._all||(this._all=this.files.reduce((t,r)=>Object.assign(t,this.values[r]),{})),this._all}addFile(t){if(!(t in this.values)){let r=xc(this.files);this.values[t]=r?Object.create(this.values[r]):{},this.files.push(t);}return this.values[t]}addValue(t,r,n){let i=this.addFile(t);Object.hasOwn(i,r)?Array.isArray(i[r])?i[r].push(n):i[r]=[i[r],n]:i[r]=n,this._all=void 0;}};function jbe(e){let t=new BT;for(let r of a3(e))t.addValue(r.file,String(r.key),r.value);return t}function Lbe(e,t){let r=null,n=[],i=new Map;for(let s of a3(e,t))s.key===t&&(n.push(r=s.value),i.has(s.file)||i.set(s.file,[]),i.get(s.file).push(r));return {key:t,paths:Array.from(i.keys()),scopes:i,value:r,values:n}}function Dbe(e){return e.replace(/^(file):/,"")}function*a3(e,t=null){let r=e.split("\0");for(let n=0,i=r.length-1;n<i;){let s=Dbe(r[n++]),o=r[n++],a=t;if(o.includes(`
|
|
531
531
|
`)){let c=nbe(o,`
|
|
532
532
|
`);a=c[0],o=c[1];}yield {file:s,key:a,value:o};}}var c3=(e=>(e.system="system",e.global="global",e.local="local",e.worktree="worktree",e))(c3||{});function NT(e,t){return typeof e=="string"&&Object.hasOwn(c3,e)?e:t}function Mbe(e,t,r,n){let i=["config",`--${n}`];return r&&i.push("--add"),i.push(e,t),{commands:i,format:"utf-8",parser(s){return s}}}function Fbe(e,t){let r=["config","--null","--show-origin","--get-all",e];return t&&r.splice(1,0,`--${t}`),{commands:r,format:"utf-8",parser(n){return Lbe(n,e)}}}function $be(e){let t=["config","--list","--show-origin","--null"];return e&&t.push(`--${e}`),{commands:t,format:"utf-8",parser(r){return jbe(r)}}}function qbe(){return {addConfig(e,t,...r){return this._runTask(Mbe(e,t,r[0]===true,NT(r[1],"local")),fe(arguments))},getConfig(e,t){return this._runTask(Fbe(e,NT(t,void 0)),fe(arguments))},listConfig(...e){return this._runTask($be(NT(e[0],void 0)),fe(arguments))}}}var l3=(e=>(e.ADDED="A",e.COPIED="C",e.DELETED="D",e.MODIFIED="M",e.RENAMED="R",e.CHANGED="T",e.UNMERGED="U",e.UNKNOWN="X",e.BROKEN="B",e))(l3||{}),Ube=new Set(Object.values(l3));function Bbe(e){return Ube.has(e)}var FG,Hbe=["-h"],ag=Symbol("grepQuery"),HT=class{constructor(){this[FG]=[];}*[(FG=ag,Symbol.iterator)](){for(let t of this[ag])yield t;}and(...t){return t.length&&this[ag].push("--and","(",...ug(t,"-e"),")"),this}param(...t){return this[ag].push(...ug(t,"-e")),this}};function Gbe(...e){return new HT().param(...e)}function zbe(e){let t=new Set,r={};return sR(e,n=>{let[i,s,o]=n.split(lg);t.add(i),(r[i]=r[i]||[]).push({line:dt(s),path:i,preview:o});}),{paths:t,results:r}}function Vbe(){return {grep(e){let t=fe(arguments),r=Ge(arguments);for(let i of Hbe)if(r.includes(i))return this._runTask(Dt(`git.grep: use of "${i}" is not supported.`),t);typeof e=="string"&&(e=Gbe().param(e));let n=["grep","--null","-n","--full-name",...r,...e];return this._runTask({commands:n,format:"utf-8",parser(i){return zbe(i)}},t)}}}var u3=(e=>(e.MIXED="mixed",e.SOFT="soft",e.HARD="hard",e.MERGE="merge",e.KEEP="keep",e))(u3||{}),Wbe=cd(Object.values(u3));function Kbe(e,t){let r=["reset"];return d3(e)&&r.push(`--${e}`),r.push(...t),ht(r)}function Ybe(e){if(d3(e))return e;switch(typeof e){case "string":case "undefined":return "soft"}}function d3(e){return typeof e=="string"&&Wbe.includes(e)}wg.default.formatters.L=e=>String(e3(e)?e.length:"-");wg.default.formatters.B=e=>Buffer.isBuffer(e)?e.toString("utf8"):aR(e);function Qbe(){return (0, wg.default)("simple-git")}function $G(e,t,r){return !t||!String(t).replace(/\s*/,"")?r?(n,...i)=>{e(n,...i),r(n,...i);}:e:(n,...i)=>{e(`%s ${n}`,t,...i),r&&r(n,...i);}}function Jbe(e,t,{namespace:r}){if(typeof e=="string")return e;let n=t&&t.namespace||"";return n.startsWith(r)?n.substr(r.length+1):n||r}function Ac(e,t,r,n=Qbe()){let i=e&&`[${e}]`||"",s=[],o=typeof t=="string"?n.extend(t):t,a=Jbe(ft(t,et),o,n);return l(r);function c(u,d){return On(s,Ac(e,a.replace(/^[^:]+/,u),d,n))}function l(u){let d=u&&`[${u}]`||"",m=o&&$G(o,d)||vg,p=$G(n,`${i} ${d}`,m);return Object.assign(o?m:p,{label:e,sibling:c,info:p,step:l})}}var f3=class GT{constructor(t="GitExecutor"){this.logLabel=t,this._queue=new Map;}withProgress(t){return this._queue.get(t)}createProgress(t){let r=GT.getName(t.commands[0]),n=Ac(this.logLabel,r);return {task:t,logger:n,name:r}}push(t){let r=this.createProgress(t);return r.logger("Adding task to the queue, commands = %o",t.commands),this._queue.set(t,r),r}fatal(t){for(let[r,{logger:n}]of Array.from(this._queue.entries()))r===t.task?(n.info("Failed %o",t),n("Fatal exception, any as-yet un-started tasks run through this executor will not be attempted")):n.info("A fatal exception occurred in a previous task, the queue has been purged: %o",t.message),this.complete(r);if(this._queue.size!==0)throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`)}complete(t){this.withProgress(t)&&this._queue.delete(t);}attempt(t){let r=this.withProgress(t);if(!r)throw new In(void 0,"TasksPendingQueue: attempt called for an unknown task");return r.logger("Starting task"),r}static getName(t="empty"){return `task:${t}:${++GT.counter}`}};f3.counter=0;var Xbe=f3,zT=class{constructor(t,r,n){this._executor=t,this._scheduler=r,this._plugins=n,this._chain=Promise.resolve(),this._queue=new Xbe;}get cwd(){return this._cwd||this._executor.cwd}set cwd(t){this._cwd=t;}get env(){return this._executor.env}get outputHandler(){return this._executor.outputHandler}chain(){return this}push(t){return this._queue.push(t),this._chain=this._chain.then(()=>this.attemptTask(t))}async attemptTask(t){let r=await this._scheduler.next(),n=()=>this._queue.complete(t);try{let{logger:i}=this._queue.attempt(t);return await(MG(t)?this.attemptEmptyTask(t,i):this.attemptRemoteTask(t,i))}catch(i){throw this.onFatalException(t,i)}finally{n(),r();}}onFatalException(t,r){let n=r instanceof In?Object.assign(r,{task:t}):new In(t,r&&String(r));return this._chain=Promise.resolve(),this._queue.fatal(n),n}async attemptRemoteTask(t,r){let n=this._plugins.exec("spawn.binary","",this.taskContext(t,t.commands)),i=this._plugins.exec("spawn.args",[...t.commands],this.taskContext(t,t.commands)),s=await this.gitResponse(t,n,i,this.outputHandler,r.step("SPAWN")),o=await this.handleTaskData(t,i,s,r.step("HANDLE"));return r("passing response to task's parser as a %s",t.format),Ebe(t)?DG(t.parser,o):DG(t.parser,o.asStrings())}async attemptEmptyTask(t,r){return r("empty task bypassing child process to call to task's parser"),t.parser(this)}handleTaskData(t,r,n,i){let{exitCode:s,rejection:o,stdOut:a,stdErr:c}=n;return new Promise((l,u)=>{i("Preparing to handle process response exitCode=%d stdOut=",s);let{error:d}=this._plugins.exec("task.error",{error:o},{...this.taskContext(t,r),...n});if(d&&t.onError)return i.info("exitCode=%s handling with custom error handler"),t.onError(n,d,m=>{i.info("custom error handler treated as success"),i("custom error returned a %s",aR(m)),l(new hg(Array.isArray(m)?Buffer.concat(m):m,Buffer.concat(c)));},u);if(d)return i.info("handling as error: exitCode=%s stdErr=%s rejection=%o",s,c.length,o),u(d);i.info("retrieving task output complete"),l(new hg(Buffer.concat(a),Buffer.concat(c)));})}async gitResponse(t,r,n,i,s){let o=s.sibling("output"),a=this._plugins.exec("spawn.options",{cwd:this.cwd,env:this.env,windowsHide:true},this.taskContext(t,t.commands));return new Promise(c=>{let l=[],u=[];s.info("%s %o",r,n),s("%O",a);let d=this._beforeSpawn(t,n);if(d)return c({stdOut:l,stdErr:u,exitCode:9901,rejection:d});this._plugins.exec("spawn.before",void 0,{...this.taskContext(t,n),kill(p){d=p||d;}});let m=spawn(r,n,a);m.stdout.on("data",qG(l,"stdOut",s,o.step("stdOut"))),m.stderr.on("data",qG(u,"stdErr",s,o.step("stdErr"))),m.on("error",Zbe(u,s)),i&&(s("Passing child process stdOut/stdErr to custom outputHandler"),i(r,m.stdout,m.stderr,[...n])),this._plugins.exec("spawn.after",void 0,{...this.taskContext(t,n),spawned:m,close(p,h){c({stdOut:l,stdErr:u,exitCode:p,rejection:d||h});},kill(p){m.killed||(d=p,m.kill("SIGINT"));}});})}_beforeSpawn(t,r){let n;return this._plugins.exec("spawn.before",void 0,{...this.taskContext(t,r),kill(i){n=i||n;}}),n}taskContext(t,r){return {method:String(ibe(t.commands)||""),commands:r,env:{...this.env},input:MG(t)?void 0:t.input}}};function Zbe(e,t){return r=>{t("[ERROR] child process exception %o",r),e.push(Buffer.from(String(r.stack),"ascii"));}}function qG(e,t,r,n){return i=>{r("%s received %L bytes",t,i),n("%B",i),e.push(i);}}var VT=class{constructor(t,r,n){this.cwd=t,this._scheduler=r,this._plugins=n,this._chain=this.chain();}chain(){return new zT(this,this._scheduler,this._plugins)}push(t){return this._chain.push(t)}};function eEe(e,t,r=vg){let n=s=>{r(null,s);},i=s=>{s?.task===e&&r(s,void 0);};t.then(n,i);}function UG(e,t){return bbe(r=>{if(!XG(e))throw new Error(`Git.cwd: cannot change to non-directory "${e}"`);return (t||r).cwd=e})}function jT(e){let t=["checkout",...e];return t[1]==="-b"&&t.includes("-B")&&(t[1]=oR(t,"-B")),ht(t)}function tEe(){return {checkout(){return this._runTask(jT(Ge(arguments,1)),fe(arguments))},checkoutBranch(e,t){return this._runTask(jT(["-b",e,t,...Ge(arguments)]),fe(arguments))},checkoutLocalBranch(e){return this._runTask(jT(["-b",e,...Ge(arguments)]),fe(arguments))}}}var h3=(e,t,r)=>{let n=["clone",...r];return et(e)&&n.push(id(e)),et(t)&&n.push(id(t)),ht(n)},rEe=(e,t,r)=>(On(r,"--mirror"),h3(e,t,r));function BG(e,t,r,...n){return et(r)?t(r,ft(n[0],et),Ge(arguments)):Dt(`git.${e}() requires a string 'repoPath'`)}function nEe(){return {clone(e,...t){return this._runTask(BG("clone",h3,ft(e,et),...t),fe(arguments))},mirror(e,...t){return this._runTask(BG("mirror",rEe,ft(e,et),...t),fe(arguments))}}}var iEe=[new be(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/,(e,[t,r,n])=>{e.branch=t,e.commit=n,e.root=!!r;}),new be(/\s*Author:\s(.+)/i,(e,[t])=>{let r=t.split("<"),n=r.pop();!n||!n.includes("@")||(e.author={email:n.substr(0,n.length-1),name:r.join("<").trim()});}),new be(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g,(e,[t,r,n])=>{e.summary.changes=parseInt(t,10)||0,e.summary.insertions=parseInt(r,10)||0,e.summary.deletions=parseInt(n,10)||0;}),new be(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/,(e,[t,r,n])=>{e.summary.changes=parseInt(t,10)||0;let i=parseInt(r,10)||0;n==="-"?e.summary.deletions=i:n==="+"&&(e.summary.insertions=i);})];function sEe(e){return zr({author:null,branch:"",commit:"",root:false,summary:{changes:0,insertions:0,deletions:0}},iEe,e)}function oEe(e,t,r){return {commands:["-c","core.abbrev=40","commit",...ug(e,"-m"),...t,...r],format:"utf-8",parser:sEe}}function aEe(){return {commit(t,...r){let n=fe(arguments),i=e(t)||oEe(Gr(t),Gr(ft(r[0],fg,[])),[...cd(ft(r[1],Sg,[])),...Ge(arguments,0,true)]);return this._runTask(i,n)}};function e(t){return !fg(t)&&Dt("git.commit: requires the commit message to be supplied as a string/string[]")}}function cEe(){return {count:0,garbage:0,inPack:0,packs:0,prunePackable:0,size:0,sizeGarbage:0,sizePack:0}}var lEe=new be(/([a-z-]+): (\d+)$/,(e,[t,r])=>{let n=ZG(t);Object.hasOwn(e,n)&&(e[n]=dt(r));});function uEe(){return {countObjects(){return this._runTask({commands:["count-objects","--verbose"],format:"utf-8",parser(e){return zr(cEe(),[lEe],e)}})}}}function dEe(){return {firstCommit(){return this._runTask(ht(["rev-list","--max-parents=0","HEAD"],true),fe(arguments))}}}function fEe(e,t){let r=["hash-object",e];return t&&r.push("-w"),ht(r,true)}var sd=class{constructor(t,r,n,i){this.bare=t,this.path=r,this.existing=n,this.gitDir=i;}},hEe=/^Init.+ repository in (.+)$/,pEe=/^Rein.+ in (.+)$/;function mEe(e,t,r){let n=String(r).trim(),i;if(i=hEe.exec(n))return new sd(e,t,false,i[1]);if(i=pEe.exec(n))return new sd(e,t,true,i[1]);let s="",o=n.split(" ");for(;o.length;)if(o.shift()==="in"){s=o.join(" ");break}return new sd(e,t,/^re/i.test(n),s)}var p3="--bare";function gEe(e){return e.includes(p3)}function yEe(e=false,t,r){let n=["init",...r];return e&&!gEe(n)&&n.splice(1,0,p3),{commands:n,format:"utf-8",parser(i){return mEe(n.includes("--bare"),t,i)}}}function wEe(e){return e===void 0?Dt("interpretTrailers called without input content"):{format:"utf-8",parser(t){return Object.fromEntries(sR(t,r=>{let n=r.indexOf(":");return [ZG(r.substring(0,n).toLowerCase()),r.substring(n+2).trim()]}))},commands:["interpret-trailers","--parse"],input:e}}function vEe(){return {interpretTrailers(e){return this._runTask(wEe(ft(e,cbe)),fe(arguments))}}}var ni=(e=>(e.NONE="",e.STAT="--stat",e.NUM_STAT="--numstat",e.NAME_ONLY="--name-only",e.NAME_STATUS="--name-status",e))(ni||{}),m3=/^--(stat|numstat|name-only|name-status)(=|$)/;function dR(e){for(let t=0;t<e.length;t++){let r=m3.exec(e[t]);if(r)return `--${r[1]}`}return ""}function _Ee(e){return m3.test(e)}var WT=class{constructor(){this.changed=0,this.deletions=0,this.insertions=0,this.files=[];}},HG=[new be(/^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/,(e,[t,r,n=""])=>{e.files.push({file:t.trim(),changes:dt(r),insertions:n.replace(/[^+]/g,"").length,deletions:n.replace(/[^-]/g,"").length,binary:false});}),new be(/^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,(e,[t,r,n])=>{e.files.push({file:t.trim(),before:dt(r),after:dt(n),binary:true});}),new be(/^(.+)\s+\|\s+Bin\s*$/,(e,[t])=>{e.files.push({file:t.trim(),before:0,after:0,binary:true});}),new be(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/,(e,[t,r])=>{let n=/(\d+) i/.exec(r),i=/(\d+) d/.exec(r);e.changed=dt(t),e.insertions=dt(n?.[1]),e.deletions=dt(i?.[1]);})],SEe=[new be(/(\d+)\t(\d+)\t(.+)$/,(e,[t,r,n])=>{let i=dt(t),s=dt(r);e.changed++,e.insertions+=i,e.deletions+=s,e.files.push({file:n,changes:i+s,insertions:i,deletions:s,binary:false});}),new be(/-\t-\t(.+)$/,(e,[t])=>{e.changed++,e.files.push({file:t,after:0,before:0,binary:true});})],bEe=[new be(/(.+)$/,(e,[t])=>{e.changed++,e.files.push({file:t,changes:0,insertions:0,deletions:0,binary:false});})],EEe=[new be(/([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/,(e,[t,r,n,i,s])=>{e.changed++,e.files.push({file:s??n,changes:0,insertions:0,deletions:0,binary:false,status:LG(Bbe(t)&&t),from:LG(!!s&&n!==s&&n),similarity:dt(r)});})],TEe={[ni.NONE]:HG,[ni.STAT]:HG,[ni.NUM_STAT]:SEe,[ni.NAME_STATUS]:EEe,[ni.NAME_ONLY]:bEe};function g3(e=ni.NONE){let t=TEe[e];return r=>zr(new WT,t,r,false)}var y3="\xF2\xF2\xF2\xF2\xF2\xF2 ",w3=" \xF2\xF2",v3=" \xF2 ",REe=["hash","date","message","refs","author_name","author_email"];function PEe(e,t){return t.reduce((r,n,i)=>(r[n]=e[i]||"",r),Object.create({diff:null}))}function _3(e=v3,t=REe,r=ni.NONE){let n=g3(r);return function(i){let s=_g(i.trim(),false,y3).map(function(o){let a=o.split(w3),c=PEe(a[0].split(e),t);return a.length>1&&a[1].trim()&&(c.diff=n(a[1])),c});return {all:s,latest:s.length&&s[0]||null,total:s.length}}}function kEe(e){let t=dR(e),r=["diff"];return t===ni.NONE&&(t=ni.STAT,r.push("--stat=4096")),r.push(...e),fR(r)||{commands:r,format:"utf-8",parser:g3(t)}}function fR(e){let t=e.filter(_Ee);if(t.length>1)return Dt(`Summary flags are mutually exclusive - pick one of ${t.join(",")}`);if(t.length&&e.includes("-z"))return Dt(`Summary flag ${t} parsing is not compatible with null termination option '-z'`)}var S3=(e=>(e[e["--pretty"]=0]="--pretty",e[e["max-count"]=1]="max-count",e[e.maxCount=2]="maxCount",e[e.n=3]="n",e[e.file=4]="file",e[e.format=5]="format",e[e.from=6]="from",e[e.to=7]="to",e[e.splitter=8]="splitter",e[e.symmetric=9]="symmetric",e[e.mailMap=10]="mailMap",e[e.multiLine=11]="multiLine",e[e.strictDate=12]="strictDate",e))(S3||{});function xEe(e,t){let r=[],n=[];return Object.keys(e).forEach(i=>{r.push(i),n.push(String(e[i]));}),[r,n.join(t)]}function AEe(e){return Object.keys(e).reduce((t,r)=>(r in S3||(t[r]=e[r]),t),{})}function b3(e={},t=[]){let r=ft(e.splitter,et,v3),n=cR(e.format)?e.format:{hash:"%H",date:e.strictDate===false?"%ai":"%aI",message:"%s",refs:"%D",body:e.multiLine?"%B":"%b",author_name:e.mailMap!==false?"%aN":"%an",author_email:e.mailMap!==false?"%aE":"%ae"},[i,s]=xEe(n,r),o=[],a=[`--pretty=format:${y3}${s}${w3}`,...t],c=e.n||e["max-count"]||e.maxCount;if(c&&a.push(`--max-count=${c}`),e.from||e.to){let l=e.symmetric!==false?"...":"..";o.push(`${e.from||""}${l}${e.to||""}`);}return et(e.file)&&a.push("--follow",id(e.file)),t3(AEe(e),a),{fields:i,splitter:r,commands:[...a,...o]}}function IEe(e,t,r){let n=_3(e,t,dR(r));return {commands:["log",...r],format:"utf-8",parser:n}}function OEe(){return {log(...r){let n=fe(arguments),i=b3(lR(arguments),cd(ft(arguments[0],Sg,[]))),s=t(...r)||fR(i.commands)||e(i);return this._runTask(s,n)}};function e(r){return IEe(r.splitter,r.fields,r.commands)}function t(r,n){return et(r)&&et(n)&&Dt("git.log(string, string) should be replaced with git.log({ from: string, to: string })")}}var od=class{constructor(t,r=null,n){this.reason=t,this.file=r,this.meta=n;}toString(){return `${this.file}:${this.reason}`}},KT=class{constructor(){this.conflicts=[],this.merges=[],this.result="success";}get failed(){return this.conflicts.length>0}get reason(){return this.result}toString(){return this.conflicts.length?`CONFLICTS: ${this.conflicts.join(", ")}`:"OK"}},pg=class{constructor(){this.remoteMessages={all:[]},this.created=[],this.deleted=[],this.files=[],this.deletions={},this.insertions={},this.summary={changes:0,deletions:0,insertions:0};}},YT=class{constructor(){this.remote="",this.hash={local:"",remote:""},this.branch={local:"",remote:""},this.message="";}toString(){return this.message}};function LT(e){return e.objects=e.objects||{compressing:0,counting:0,enumerating:0,packReused:0,reused:{count:0,delta:0},total:{count:0,delta:0}}}function GG(e){let t=/^\s*(\d+)/.exec(e),r=/delta (\d+)/i.exec(e);return {count:dt(t&&t[1]||"0"),delta:dt(r&&r[1]||"0")}}var CEe=[new Is(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i,(e,[t,r])=>{let n=t.toLowerCase(),i=LT(e.remoteMessages);Object.assign(i,{[n]:dt(r)});}),new Is(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i,(e,[t,r])=>{let n=t.toLowerCase(),i=LT(e.remoteMessages);Object.assign(i,{[n]:dt(r)});}),new Is(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i,(e,[t,r,n])=>{let i=LT(e.remoteMessages);i.total=GG(t),i.reused=GG(r),i.packReused=dt(n);})],NEe=[new Is(/^remote:\s*(.+)$/,(e,[t])=>(e.remoteMessages.all.push(t.trim()),false)),...CEe,new Is([/create a (?:pull|merge) request/i,/\s(https?:\/\/\S+)$/],(e,[t])=>{e.remoteMessages.pullRequestUrl=t;}),new Is([/found (\d+) vulnerabilities.+\(([^)]+)\)/i,/\s(https?:\/\/\S+)$/],(e,[t,r,n])=>{e.remoteMessages.vulnerabilities={count:dt(t),summary:r,url:n};})];function E3(e,t){return zr({remoteMessages:new QT},NEe,t)}var QT=class{constructor(){this.all=[];}},jEe=/^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/,LEe=/(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/,DEe=/^(create|delete) mode \d+ (.+)/,MEe=[new be(jEe,(e,[t,r,n])=>{e.files.push(t),r&&(e.insertions[t]=r.length),n&&(e.deletions[t]=n.length);}),new be(LEe,(e,[t,,r,,n])=>r!==void 0||n!==void 0?(e.summary.changes=+t||0,e.summary.insertions=+r||0,e.summary.deletions=+n||0,true):false),new be(DEe,(e,[t,r])=>{On(e.files,r),On(t==="create"?e.created:e.deleted,r);})],FEe=[new be(/^from\s(.+)$/i,(e,[t])=>{e.remote=t;}),new be(/^fatal:\s(.+)$/,(e,[t])=>{e.message=t;}),new be(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/,(e,[t,r,n,i])=>{e.branch.local=n,e.hash.local=t,e.branch.remote=i,e.hash.remote=r;})],$Ee=(e,t)=>zr(new pg,MEe,[e,t]),T3=(e,t)=>Object.assign(new pg,$Ee(e,t),E3(e,t));function qEe(e,t){let r=zr(new YT,FEe,[e,t]);return r.message&&r}var UEe=[new be(/^Auto-merging\s+(.+)$/,(e,[t])=>{e.merges.push(t);}),new be(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/,(e,[t,r])=>{e.conflicts.push(new od(t,r));}),new be(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/,(e,[t,r,n])=>{e.conflicts.push(new od(t,r,{deleteRef:n}));}),new be(/^CONFLICT\s+\((.+)\):/,(e,[t])=>{e.conflicts.push(new od(t,null));}),new be(/^Automatic merge failed;\s+(.+)$/,(e,[t])=>{e.result=t;})],BEe=(e,t)=>Object.assign(HEe(e),T3(e,t)),HEe=e=>zr(new KT,UEe,e);function zG(e){return e.length?{commands:["merge",...e],format:"utf-8",parser(t,r){let n=BEe(t,r);if(n.failed)throw new ad(n);return n}}:Dt("Git.merge requires at least one option")}function GEe(e,t,r){let n=r.includes("deleted"),i=r.includes("tag")||/^refs\/tags/.test(e),s=!r.includes("new");return {deleted:n,tag:i,branch:!i,new:!s,alreadyUpdated:s,local:e,remote:t}}var zEe=[new be(/^Pushing to (.+)$/,(e,[t])=>{e.repo=t;}),new be(/^updating local tracking ref '(.+)'/,(e,[t])=>{e.ref={...e.ref||{},local:t};}),new be(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/,(e,[t,r,n])=>{e.pushed.push(GEe(t,r,n));}),new be(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,(e,[t,r,n])=>{e.branch={...e.branch||{},local:t,remote:r,remoteName:n};}),new be(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/,(e,[t,r,n,i])=>{e.update={head:{local:t,remote:r},hash:{from:n,to:i}};})],VEe=(e,t)=>{let r=WEe(e,t),n=E3(e,t);return {...r,...n}},WEe=(e,t)=>zr({pushed:[]},zEe,[e,t]);function KEe(e={},t){return On(t,"--tags"),R3(e,t)}function R3(e={},t){let r=["push",...t];return e.branch&&r.splice(1,0,e.branch),e.remote&&r.splice(1,0,e.remote),oR(r,"-v"),On(r,"--verbose"),On(r,"--porcelain"),{commands:r,format:"utf-8",parser:VEe}}function YEe(){return {showBuffer(){let e=["show",...Ge(arguments,1)];return e.includes("--binary")||e.splice(1,0,"--binary"),this._runTask(i3(e),fe(arguments))},show(){let e=["show",...Ge(arguments,1)];return this._runTask(ht(e),fe(arguments))}}}var QEe=/^(.+)\0(.+)$/,JT=class{constructor(t,r,n){if(this.path=t,this.index=r,this.working_dir=n,r==="R"||n==="R"){let i=QEe.exec(t)||[null,t,t];this.from=i[2]||"",this.path=i[1]||"";}}},XT=class{constructor(){this.not_added=[],this.conflicted=[],this.created=[],this.deleted=[],this.ignored=void 0,this.modified=[],this.renamed=[],this.files=[],this.staged=[],this.ahead=0,this.behind=0,this.current=null,this.tracking=null,this.detached=false,this.isClean=()=>!this.files.length;}};function VG(e){let[t,r]=e.split(lg);return {from:r||t,to:t}}function Hr(e,t,r){return [`${e}${t}`,r]}function DT(e,...t){return t.map(r=>Hr(e,r,(n,i)=>n.conflicted.push(i)))}var JEe=new Map([Hr(" ","A",(e,t)=>e.created.push(t)),Hr(" ","D",(e,t)=>e.deleted.push(t)),Hr(" ","M",(e,t)=>e.modified.push(t)),Hr("A"," ",(e,t)=>{e.created.push(t),e.staged.push(t);}),Hr("A","M",(e,t)=>{e.created.push(t),e.staged.push(t),e.modified.push(t);}),Hr("D"," ",(e,t)=>{e.deleted.push(t),e.staged.push(t);}),Hr("M"," ",(e,t)=>{e.modified.push(t),e.staged.push(t);}),Hr("M","M",(e,t)=>{e.modified.push(t),e.staged.push(t);}),Hr("R"," ",(e,t)=>{e.renamed.push(VG(t));}),Hr("R","M",(e,t)=>{let r=VG(t);e.renamed.push(r),e.modified.push(r.to);}),Hr("!","!",(e,t)=>{(e.ignored=e.ignored||[]).push(t);}),Hr("?","?",(e,t)=>e.not_added.push(t)),...DT("A","A","U"),...DT("D","D","U"),...DT("U","A","D","U"),["##",(e,t)=>{let r=/ahead (\d+)/,n=/behind (\d+)/,i=/^(.+?(?=(?:\.{3}|\s|$)))/,s=/\.{3}(\S*)/,o=/\son\s(\S+?)(?=\.{3}|$)/,a=r.exec(t);e.ahead=a&&+a[1]||0,a=n.exec(t),e.behind=a&&+a[1]||0,a=i.exec(t),e.current=ft(a?.[1],et,null),a=s.exec(t),e.tracking=ft(a?.[1],et,null),a=o.exec(t),a&&(e.current=ft(a?.[1],et,e.current)),e.detached=/\(no branch\)/.test(t);}]]),XEe=function(e){let t=e.split(lg),r=new XT;for(let n=0,i=t.length;n<i;){let s=t[n++].trim();s&&(s.charAt(0)==="R"&&(s+=lg+(t[n++]||"")),ZEe(r,s));}return r};function ZEe(e,t){let r=t.trim();switch(" "){case r.charAt(2):return n(r.charAt(0),r.charAt(1),r.slice(3));case r.charAt(1):return n(" ",r.charAt(0),r.slice(2));default:return}function n(i,s,o){let a=`${i}${s}`,c=JEe.get(a);c&&c(e,o),a!=="##"&&a!=="!!"&&e.files.push(new JT(o,i,s));}}var eTe=["--null","-z"];function tTe(e){return {format:"utf-8",commands:["status","--porcelain","-b","-u","--null",...e.filter(t=>!eTe.includes(t))],parser(t){return XEe(t)}}}var P3="installed=false";function mg(e=0,t=0,r=0,n="",i=true){return Object.defineProperty({major:e,minor:t,patch:r,agent:n,installed:i},"toString",{value(){return `${this.major}.${this.minor}.${this.patch}`},configurable:false,enumerable:false})}function rTe(){return mg(0,0,0,"",false)}function nTe(){return {version(){return this._runTask({commands:["--version"],format:"utf-8",parser:sTe,onError(e,t,r,n){if(e.exitCode===bg.NOT_FOUND)return r(Buffer.from(P3));n(t);}})}}}var iTe=[new be(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/,(e,[t,r,n,i=""])=>{Object.assign(e,mg(dt(t),dt(r),dt(n),i));}),new be(/version (\d+)\.(\d+)\.(\D+)(.+)?$/,(e,[t,r,n,i=""])=>{Object.assign(e,mg(dt(t),dt(r),n,i));})];function sTe(e){return e===P3?rTe():zr(mg(0,0,0,e),iTe,e)}var gg=class{constructor(t){this._executor=t;}_runTask(t,r){let n=this._executor.chain(),i=n.push(t);return r&&eEe(t,i,r),Object.create(this,{then:{value:i.then.bind(i)},catch:{value:i.catch.bind(i)},_executor:{value:n}})}add(t){return this._runTask(ht(["add",...Gr(t)]),fe(arguments))}cwd(t){let r=fe(arguments);return typeof t=="string"?this._runTask(UG(t,this._executor),r):typeof t?.path=="string"?this._runTask(UG(t.path,t.root&&this._executor||void 0),r):this._runTask(Dt("Git.cwd: workingDirectory must be supplied as a string"),r)}hashObject(t,r){return this._runTask(fEe(t,r===true),fe(arguments))}init(t){return this._runTask(yEe(t===true,this._executor.cwd,Ge(arguments)),fe(arguments))}merge(){return this._runTask(zG(Ge(arguments)),fe(arguments))}mergeFromTo(t,r){return et(t)&&et(r)?this._runTask(zG([t,r,...Ge(arguments)]),fe(arguments,false)):this._runTask(Dt("Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings"))}outputHandler(t){return this._executor.outputHandler=t,this}push(){let t=R3({remote:ft(arguments[0],et),branch:ft(arguments[1],et)},Ge(arguments));return this._runTask(t,fe(arguments))}stash(){return this._runTask(ht(["stash",...Ge(arguments)]),fe(arguments))}status(){return this._runTask(tTe(Ge(arguments)),fe(arguments))}};Object.assign(gg.prototype,tEe(),nEe(),aEe(),qbe(),uEe(),dEe(),Vbe(),vEe(),OEe(),YEe(),nTe());var oTe=(()=>{let e=0;return ()=>{e++;let{promise:t,done:r}=(0, As.createDeferred)();return {promise:t,done:r,id:e}}})(),ZT=class{constructor(t=2){this.concurrency=t,this.logger=Ac("","scheduler"),this.pending=[],this.running=[],this.logger("Constructed, concurrency=%s",t);}schedule(){if(!this.pending.length||this.running.length>=this.concurrency){this.logger("Schedule attempt ignored, pending=%s running=%s concurrency=%s",this.pending.length,this.running.length,this.concurrency);return}let t=On(this.running,this.pending.shift());this.logger("Attempting id=%s",t.id),t.done(()=>{this.logger("Completing id=",t.id),oR(this.running,t),this.schedule();});}next(){let{promise:t,id:r}=On(this.pending,oTe());return this.logger("Scheduling id=%s",r),this.schedule(),t}};function aTe(e,t){return ht(["apply",...t,...e])}var k3=(e=>(e.CURRENT="*",e.LINKED="+",e))(k3||{}),eR=class{constructor(){this.all=[],this.branches={},this.current="",this.detached=false;}push(t,r,n,i,s){t==="*"&&(this.detached=r,this.current=n),this.all.push(n),this.branches[n]={current:t==="*",linkedWorkTree:t==="+",name:n,commit:i,label:s};}},cTe=[new be(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/,(e,[t,r,n,i])=>{e.push(WG(t),true,r,n,i);}),new be(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s,(e,[t,r,n,i])=>{e.push(WG(t),false,r,n,i);})],lTe=new be(/^(\S+)$/s,(e,[t])=>{e.push(k3.CURRENT,false,t,"","");});function WG(e){return e?e.charAt(0):""}function x3(e,t=false){return zr(new eR,t?[lTe]:cTe,e)}var tR=class{constructor(){this.all=[],this.branches={},this.errors=[];}get success(){return !this.errors.length}};function uTe(e,t){return {branch:e,hash:t,success:true}}function dTe(e){return {branch:e,hash:null,success:false}}var fTe=/(\S+)\s+\(\S+\s([^)]+)\)/,A3=/^error[^']+'([^']+)'/m,hTe=[new be(fTe,(e,[t,r])=>{let n=uTe(t,r);e.all.push(n),e.branches[t]=n;}),new be(A3,(e,[t])=>{let r=dTe(t);e.errors.push(r),e.all.push(r),e.branches[t]=r;})],hR=(e,t)=>zr(new tR,hTe,[e,t]);function I3(e,t){return t===bg.ERROR&&A3.test(e)}function pTe(e){let t=["-d","-D","--delete"];return e.some(r=>t.includes(r))}function mTe(e){let t=pTe(e),r=e.includes("--show-current"),n=["branch",...e];return n.length===1&&n.push("-a"),n.includes("-v")||n.splice(1,0,"-v"),{format:"utf-8",commands:n,parser(i,s){return t?hR(i,s).all[0]:x3(i,r)}}}function gTe(){return {format:"utf-8",commands:["branch","-v"],parser(e){return x3(e)}}}function yTe(e,t=false){return {format:"utf-8",commands:["branch","-v",t?"-D":"-d",...e],parser(r,n){return hR(r,n)},onError({exitCode:r,stdOut:n},i,s,o){if(!I3(String(i),r))return o(i);s(n);}}}function wTe(e,t=false){let r={format:"utf-8",commands:["branch","-v",t?"-D":"-d",e],parser(n,i){return hR(n,i).branches[e]},onError({exitCode:n,stdErr:i,stdOut:s},o,a,c){if(!I3(String(o),n))return c(o);throw new ad(r.parser(dg(s),dg(i)),String(o))}};return r}function vTe(e){return {commands:["check-ignore",...e],format:"utf-8",parser:_Te}}function _Te(e){return e.split(/\n/g).map(STe).filter(Boolean)}function STe(e){let t=e.trim().replace(/^["']|["']$/g,"");return t&&normalize(t)}var bTe=[new be(/From (.+)$/,(e,[t])=>{e.remote=t;}),new be(/\* \[new branch]\s+(\S+)\s*-> (.+)$/,(e,[t,r])=>{e.branches.push({name:t,tracking:r});}),new be(/\* \[new tag]\s+(\S+)\s*-> (.+)$/,(e,[t,r])=>{e.tags.push({name:t,tracking:r});}),new be(/- \[deleted]\s+\S+\s*-> (.+)$/,(e,[t])=>{e.deleted.push({tracking:t});}),new be(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/,(e,[t,r,n,i])=>{e.updated.push({name:n,tracking:i,to:r,from:t});})];function ETe(e,t){return zr({raw:e,remote:null,branches:[],tags:[],updated:[],deleted:[]},bTe,[e,t])}function TTe(e){return /^--upload-pack(=|$)/.test(e)}function RTe(e,t,r){let n=["fetch",...r];return e&&t&&n.push(e,t),n.find(TTe)?Dt("git.fetch: potential exploit argument blocked."):{commands:n,format:"utf-8",parser:ETe}}var PTe=[new be(/^Renaming (.+) to (.+)$/,(e,[t,r])=>{e.moves.push({from:t,to:r});})];function kTe(e){return zr({moves:[]},PTe,e)}function xTe(e,t){return {commands:["mv","-v",...Gr(e),t],format:"utf-8",parser:kTe}}function ATe(e,t,r){let n=["pull",...r];return e&&t&&n.splice(1,0,e,t),{commands:n,format:"utf-8",parser(i,s){return T3(i,s)},onError(i,s,o,a){let c=qEe(dg(i.stdOut),dg(i.stdErr));if(c)return a(new ad(c));a(s);}}}function ITe(e){let t={};return O3(e,([r])=>t[r]={name:r}),Object.values(t)}function OTe(e){let t={};return O3(e,([r,n,i])=>{Object.hasOwn(t,r)||(t[r]={name:r,refs:{fetch:"",push:""}}),i&&n&&(t[r].refs[i.replace(/[^a-z]/g,"")]=n);}),Object.values(t)}function O3(e,t){sR(e,r=>t(r.split(/\s+/)));}function CTe(e,t,r){return ht(["remote","add",...r,e,t])}function NTe(e){let t=["remote"];return e&&t.push("-v"),{commands:t,format:"utf-8",parser:e?OTe:ITe}}function jTe(e){let t=[...e];return t[0]!=="ls-remote"&&t.unshift("ls-remote"),ht(t)}function LTe(e){let t=[...e];return t[0]!=="remote"&&t.unshift("remote"),ht(t)}function DTe(e){return ht(["remote","remove",e])}function MTe(e={},t){let r=b3(e),n=["stash","list",...r.commands,...t],i=_3(r.splitter,r.fields,dR(n));return fR(n)||{commands:n,format:"utf-8",parser:i}}function FTe(e,t){return Eg(["add",e,t])}function $Te(e){return Eg(["init",...e])}function Eg(e){let t=[...e];return t[0]!=="submodule"&&t.unshift("submodule"),ht(t)}function qTe(e){return Eg(["update",...e])}var rR=class{constructor(t,r){this.all=t,this.latest=r;}},UTe=function(e,t=false){let r=e.split(`
|
|
@@ -562,7 +562,7 @@ ${s}
|
|
|
562
562
|
`)||process.platform==="win32"&&(gke.test(r)||r.split("").some(l=>l.charCodeAt(0)<32)))throw new TypeError("Project file name is invalid");let{absolutePath:n,resolvedRoot:i,directory:s}=await Lz(e,t),o=resolve(dirname(n),r);AR(i,o);try{await Oz(n,o,s);}catch(l){throw ["EEXIST","ENOTEMPTY"].includes(l.code??"")?new TypeError("Project file rename target already exists",{cause:l}):l}let a=t.lastIndexOf("/");return {path:a===-1?r:`${t.slice(0,a)}/${r}`}}async function Mz(e,t){let{absolutePath:r}=await Lz(e,t);return await rm$1(r,{recursive:true}),{path:t,status:"deleted"}}var Ske=20*1024*1024;function qz(e){return e===".."||e.startsWith(`..${sep}`)||isAbsolute(e)}function bke(e){return e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?"image/png":e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":/^GIF8[79]a$/u.test(e.subarray(0,6).toString("ascii"))?"image/gif":e.subarray(0,4).toString("ascii")==="RIFF"&&e.subarray(8,12).toString("ascii")==="WEBP"?"image/webp":null}async function Uz(e,t){if(!isAbsolute(e)||t.length===0)throw new TypeError("Project root and image path must be valid");let r=await realpath(e),n=isAbsolute(t),i=n?t:resolve(r,t),s=relative(r,i);if(!n&&(s.length===0||qz(s)))throw new TypeError("Project image file is outside the project root");if(!n){let u=r;for(let d of s.split(sep))if(u=resolve(u,d),(await lstat(u)).isSymbolicLink())throw new TypeError("Project image file is outside the project root")}let o=await realpath(i);if(!n&&qz(relative(r,o)))throw new TypeError("Project image file is outside the project root");let a=await stat(o);if(!a.isFile()||a.size===0||a.size>Ske)throw new TypeError("Unsupported project image file");let c=await readFile(o),l=bke(c);if(l===null)throw new TypeError("Unsupported project image file");return {content:c,mediaType:l,path:n?o:relative(r,o).split(sep).join("/")}}var kke=256*1024,xke=4e3,Ake=4;function Ike(e){return e===".."||e.startsWith(`..${sep}`)||isAbsolute(e)}async function Gz(e,t,r=0){if(!isAbsolute(e)||t.length===0||!Number.isSafeInteger(r)||r<0)throw new TypeError("Project root and source path must be valid");let n=await realpath(e),i=isAbsolute(t),s=i?t:resolve(n,t),o=await realpath(s),a=relative(n,o);if(!i&&Ike(a))throw new TypeError("Source file is outside the project root");let c=await stat(o);if(!c.isFile())throw new TypeError("Source path is not a regular file");if(r>c.size)throw new TypeError("Source cursor is outside the file");let l=Math.min(c.size-r,kke),u=Buffer.alloc(l),d=await open(o,"r");try{let _=0;for(;_<l;){let{bytesRead:v}=await d.read(u,_,l-_,r+_);if(v===0)break;_+=v;}if(_!==l)throw new TypeError("Source file changed while it was being read")}finally{await d.close();}if(u.includes(0))throw new TypeError("Binary source files cannot be previewed");let m=u.length,p=0;for(let _=0;_<u.length;_+=1)if(u[_]===10&&(p+=1,p===xke)){m=_+1;break}let h=new TextDecoder("utf-8",{fatal:true}),f,g=Math.max(0,m-(Ake-1));for(let _=m;_>=g;_-=1)try{f=h.decode(u.subarray(0,_)),m=_;break}catch{}if(f===void 0||m===0&&u.length>0)throw new TypeError("Source file is not valid UTF-8 text");let y=r+m;return {content:f,nextCursor:y<c.size?y:null,path:i?o:a.split(sep).join("/")}}function zz(e,t){return async(r,n,i,s)=>{let o=n.attachments.map(m=>m.id);if(new Set(o).size!==o.length)throw new L("INVALID_REQUEST","Duplicate attachments are not allowed",400);let a=[],c=[];for(let m of o){try{let[y]=await e.resolve(r,[m]);if(y!==void 0){a.push(m),c.push(y);continue}}catch(y){if(!(y instanceof er))throw y}let p=await t?.(r,m),h=p===void 0?i===void 0||s===void 0?void 0:await i.readTaskAttachment(s,m):{...p.attachment,content:p.content};if(h===void 0)throw new L("ATTACHMENT_NOT_FOUND","Attachment was not found or has expired",404);let f=await e.add(r,{content:Readable.from([h.content]),kind:h.kind,mediaType:h.mediaType,name:h.name}),[g]=await e.resolve(r,[f.attachment.id]);g!==void 0&&(a.push(f.attachment.id),c.push(g));}let l=c.reduce((m,p)=>m+(p.kind==="image"?p.size:0),0),u=c.reduce((m,p)=>m+(p.kind==="image"?0:p.size),0);if(c.filter(m=>m.kind==="image").length>Gb||l>Hb)throw new L("INVALID_REQUEST","Image input limit exceeded",400);if(u>Eb$1)throw new L("INVALID_REQUEST","File input limit exceeded",400);return {attachmentIds:a,providerInput:{files:c.flatMap(m=>m.kind==="file"?[{mediaType:m.mediaType,name:m.name,path:m.path}]:[]),images:c.flatMap(m=>m.kind==="image"?[{detail:"auto",mediaType:m.mediaType,path:m.path}]:[]),skills:n.skills,text:n.text,textAttachments:c.flatMap(m=>m.kind==="text"?[{name:m.name,text:m.text}]:[])}}}}var Vz=500;function Do(e,t){for(let r of t){let n=e[r];if(n!==void 0&&n.length>0)return n;let i=Object.entries(e).find(([s,o])=>s.toLowerCase()===r.toLowerCase()&&o!==void 0)?.[1];if(i!==void 0&&i.length>0)return i}}async function un(e,t){for(let r of e)if(r!==void 0&&await t(r))return r}async function Wz(e,t,r,n){let i=Do(r,["PATH"]);if(i===void 0)return;let s=t==="win32"?win32:posix,o=t==="win32"?";":":";return un(i.split(o).filter(Boolean).map(a=>s.join(a,e)),n)}function bt(e,t,r,n,i={}){r!==void 0&&e.set(t.id,{app:t,args:n,file:r,observeEarlyExit:i.observeEarlyExit??true,targetTypes:i.targetTypes??["directory","file"]});}function Cke(e,t){return [posix.join("/Applications",`${t}.app`),...e===void 0?[]:[posix.join(e,"Applications",`${t}.app`)]]}async function Kz(e,t){let r=new Map,n=await un(["/usr/bin/open"],t);if(n===void 0)return r;let i=Do(e,["HOME"]),s=c=>un(Cke(i,c),t),o=async(c,l,u)=>{let d=await s(l);bt(r,{id:c,kind:u,name:l},d===void 0?void 0:n,m=>["-a",l,u==="terminal"?m.directoryPath:m.absolutePath]);};await o("zed","Zed","editor"),await o("windsurf","Windsurf","editor"),await o("visual-studio-code","Visual Studio Code","editor"),bt(r,{id:"system-default",kind:"system-default",name:"\u7CFB\u7EDF\u9ED8\u8BA4\u5E94\u7528"},n,c=>[c.absolutePath],{targetTypes:["file"]}),bt(r,{id:"finder",kind:"file-manager",name:"Finder"},n,c=>c.type==="file"?["-R",c.absolutePath]:[c.absolutePath]);let a=await un(["/System/Applications/Utilities/Terminal.app","/Applications/Utilities/Terminal.app"],t);return bt(r,{id:"terminal",kind:"terminal",name:"Terminal"},a===void 0?void 0:n,c=>["-a","Terminal",c.directoryPath]),await o("ghostty","Ghostty","terminal"),await o("xcode","Xcode","editor"),await o("android-studio","Android Studio","editor"),r}async function Yz(e,t){let r=new Map,n=o=>Wz(o,"linux",e,t);bt(r,{id:"zed",kind:"editor",name:"Zed"},await n("zed"),o=>[o.absolutePath]),bt(r,{id:"windsurf",kind:"editor",name:"Windsurf"},await n("windsurf"),o=>[o.absolutePath]),bt(r,{id:"visual-studio-code",kind:"editor",name:"Visual Studio Code"},await n("code"),o=>[o.absolutePath]);let i=await n("xdg-open");bt(r,{id:"system-default",kind:"system-default",name:"\u7CFB\u7EDF\u9ED8\u8BA4\u5E94\u7528"},i,o=>[o.absolutePath],{targetTypes:["file"]}),bt(r,{id:"file-manager",kind:"file-manager",name:"\u6587\u4EF6\u7BA1\u7406\u5668"},i,o=>[o.directoryPath]),bt(r,{id:"ghostty",kind:"terminal",name:"Ghostty"},await n("ghostty"),o=>[`--working-directory=${o.directoryPath}`]),bt(r,{id:"gnome-terminal",kind:"terminal",name:"GNOME Terminal"},await n("gnome-terminal"),o=>[`--working-directory=${o.directoryPath}`]),bt(r,{id:"konsole",kind:"terminal",name:"Konsole"},await n("konsole"),o=>["--workdir",o.directoryPath]),bt(r,{id:"xfce-terminal",kind:"terminal",name:"Xfce Terminal"},await n("xfce4-terminal"),o=>["--working-directory",o.directoryPath]);let s=await un(["/opt/android-studio/bin/studio.sh",await n("android-studio"),await n("studio.sh")],t);return bt(r,{id:"android-studio",kind:"editor",name:"Android Studio"},s,o=>[o.absolutePath]),r}async function Qz(e,t){let r=new Map,n=Do(e,["SystemRoot","WINDIR"]),i=Do(e,["LOCALAPPDATA"]),s=Do(e,["ProgramFiles"]),o=Do(e,["ProgramFiles(x86)"]),a=f=>Wz(f,"win32",e,t),c=await un([i===void 0?void 0:win32.join(i,"Programs","Zed","Zed.exe"),await a("Zed.exe")],t);bt(r,{id:"zed",kind:"editor",name:"Zed"},c,f=>[f.absolutePath]);let l=await un([i===void 0?void 0:win32.join(i,"Programs","Windsurf","Windsurf.exe"),await a("Windsurf.exe")],t);bt(r,{id:"windsurf",kind:"editor",name:"Windsurf"},l,f=>[f.absolutePath]);let u=await un([i===void 0?void 0:win32.join(i,"Programs","Microsoft VS Code","Code.exe"),s===void 0?void 0:win32.join(s,"Microsoft VS Code","Code.exe"),o===void 0?void 0:win32.join(o,"Microsoft VS Code","Code.exe"),await a("Code.exe")],t);bt(r,{id:"visual-studio-code",kind:"editor",name:"Visual Studio Code"},u,f=>[f.absolutePath]);let d=await un([n===void 0?void 0:win32.join(n,"explorer.exe"),await a("explorer.exe")],t);bt(r,{id:"system-default",kind:"system-default",name:"\u7CFB\u7EDF\u9ED8\u8BA4\u5E94\u7528"},d,f=>[f.absolutePath],{observeEarlyExit:false,targetTypes:["file"]}),bt(r,{id:"explorer",kind:"file-manager",name:"\u6587\u4EF6\u8D44\u6E90\u7BA1\u7406\u5668"},d,f=>f.type==="file"?["/select,",f.absolutePath]:[f.absolutePath],{observeEarlyExit:false});let m=await un([i===void 0?void 0:win32.join(i,"Microsoft","WindowsApps","wt.exe"),await a("wt.exe")],t);bt(r,{id:"windows-terminal",kind:"terminal",name:"Windows Terminal"},m,f=>["-w","new","-d",f.directoryPath]);let p=await un([Do(e,["COMSPEC"]),n===void 0?void 0:win32.join(n,"System32","cmd.exe")],t);bt(r,{id:"command-prompt",kind:"terminal",name:"\u547D\u4EE4\u63D0\u793A\u7B26"},p,()=>["/d","/k"]);let h=await un([s===void 0?void 0:win32.join(s,"Android","Android Studio","bin","studio64.exe"),o===void 0?void 0:win32.join(o,"Android","Android Studio","bin","studio64.exe"),await a("studio64.exe")],t);return bt(r,{id:"android-studio",kind:"editor",name:"Android Studio"},h,f=>[f.absolutePath]),r}var Ns=class extends Error{constructor(t){super(`Project open app is unavailable: ${t}`),this.name="ProjectOpenAppUnavailableError";}},gr=class extends Error{constructor(){super("Project open target is invalid"),this.name="ProjectOpenTargetInvalidError";}};function t5(e=process.platform){return {getCapabilities:()=>Promise.resolve({apps:[],platform:e}),open:(t,r)=>Promise.reject(new Ns(r))}}function Xz(e){return e===".."||e.startsWith(`..${sep}`)||isAbsolute(e)}async function $ke(e,t){if(t===void 0)return {absolutePath:e,directoryPath:e,projectRoot:e,type:"directory"};try{if(!isAbsolute(e))throw new gr;let r=await realpath(e);if(isAbsolute(t)){let l=await realpath(t),u=await stat(l);if(!u.isDirectory()&&!u.isFile())throw new gr;await access(l,constants.R_OK);let d=u.isDirectory()?"directory":"file";return {absolutePath:l,directoryPath:d==="directory"?l:dirname(l),projectRoot:r,type:d}}let n=t;if(Xz(n)||n.endsWith("/")||n.includes("\\")||n.includes("//")||/^[A-Za-z]:/u.test(n))throw new gr;let i=n.split("/");if(i.some(l=>l===""||l==="."||l===".."))throw new gr;let s=r,o;for(let l of i)if(s=resolve(s,l),o=await lstat(s),o.isSymbolicLink())throw new gr;let a=await realpath(s);if(Xz(relative(r,a)))throw new gr;if(o===void 0||!o.isDirectory()&&!o.isFile())throw new gr;let c=o.isDirectory()?"directory":"file";return {absolutePath:a,directoryPath:c==="directory"?a:dirname(a),projectRoot:r,type:c}}catch(r){throw r instanceof gr?r:new gr}}async function qke(e){try{return await access(e,constants.X_OK),!0}catch{return false}}function Uke(e,t,r,n){return new Promise((i,s)=>{let{observeEarlyExit:o,...a}=r,c=spawn(e,[...t],{...a,detached:true,stdio:"ignore"}),l=false,u,d=m=>{l||(l=true,u!==void 0&&clearTimeout(u),m());};c.once("error",m=>{d(()=>{s(m);});}),c.once("spawn",()=>{if(!o){d(()=>{c.unref(),i();});return}u=setTimeout(()=>{d(()=>{c.unref(),i();});},n);}),c.once("exit",(m,p)=>{if(m===0){d(i);return}let h=p?`signal ${p}`:`code ${String(m)}`;d(()=>{s(new Error(`${e} exited with ${h}`));});});})}function r5(e={}){let t=e.platform??process.platform,r=e.environment??process.env,n=e.pathExists??qke,i=e.launchConfirmationMs??Vz,s=e.spawnDetached??((a,c,l)=>Uke(a,c,l,i)),o=()=>{switch(t){case "darwin":return Kz(r,n);case "linux":return Yz(r,n);case "win32":return Qz(r,n)}};return {async getCapabilities(){return {apps:[...(await o()).values()].map(c=>c.app),platform:t}},async open(a,c,l){let u=(await o()).get(c);if(u===void 0)throw new Ns(c);let d=await $ke(a,l);if(!u.targetTypes.includes(d.type))throw new gr;await s(u.file,u.args(d),{cwd:u.app.kind==="terminal"?d.directoryPath:d.projectRoot,observeEarlyExit:u.observeEarlyExit,shell:false,windowsHide:false});}}}var Ue=class extends Error{constructor(r,n){super(n);this.code=r;this.name="SkillMarketError";}code};var n5="https://clawhub.ai",Bke="24";function dn(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new Ue("SKILL_MARKET_INVALID_RESPONSE",`${t} is invalid`);return e}function si(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function md(e){return typeof e=="number"&&Number.isSafeInteger(e)?e:0}function i5(e){let t=dn(e,"ClawHub package");if(t.family!==void 0&&t.family!=="skill")return;let r=si(t.name??t.slug),n=si(t.ownerHandle),i=si(t.latestVersion);if(r===void 0||n===void 0||i===void 0)return;let s=dn(t.stats??{},"ClawHub package stats"),o=Array.isArray(t.topics)?t.topics.filter(a=>typeof a=="string").slice(0,8):[];return {canonicalUrl:`${n5}/${n}/skills/${r}`,displayName:si(t.displayName)??r,downloads:md(s.downloads),id:`${n}/${r}`,latestVersion:i,owner:n,slug:r,stars:md(s.stars),summary:typeof t.summary=="string"?t.summary:"",topics:o,updatedAt:md(t.updatedAt),versionCount:md(s.versions)}}function s5(e,t,r){let n=e.trim(),i=new URL(n.length===0?"/api/v1/packages":"/api/v1/packages/search",n5);return i.searchParams.set("family","skill"),i.searchParams.set("limit",Bke),n.length===0?(i.searchParams.set("sort",r==="downloads"||r==="updated"?r:"recommended"),t!==null&&t.length>0&&i.searchParams.set("cursor",t)):i.searchParams.set("q",n.slice(0,120)),i}function o5(e,t){let r=dn(e,"ClawHub catalog"),n=r[t?"results":"items"];if(!Array.isArray(n))throw new Ue("SKILL_MARKET_INVALID_RESPONSE","ClawHub catalog items are invalid");return {items:n.flatMap(o=>{let a=t?dn(o,"ClawHub search result").package:o,c=i5(a);return c===void 0?[]:[c]}),nextCursor:t?null:si(r.nextCursor)??null}}function a5(e,t,r,n){let i=dn(e,"ClawHub skill detail"),s=dn(i.skill,"ClawHub skill"),o=dn(i.latestVersion,"ClawHub latest version"),a=si(dn(i.owner,"ClawHub owner").handle),c=si(s.slug),l=si(o.version);if(a===void 0||c===void 0||l===void 0)throw new Ue("SKILL_MARKET_INVALID_RESPONSE","ClawHub skill identity is invalid");let u=i5({...s,family:"skill",latestVersion:l,name:c,ownerHandle:a});if(u===void 0)throw new Ue("SKILL_MARKET_INVALID_RESPONSE","ClawHub skill summary is invalid");let d=dn(t,"ClawHub versions").items;if(!Array.isArray(d))throw new Ue("SKILL_MARKET_INVALID_RESPONSE","ClawHub versions are invalid");let m=dn(dn(r,"ClawHub scan").security??{},"ClawHub security");return {...u,changelog:typeof o.changelog=="string"?o.changelog:"",hasWarnings:m.hasWarnings===true,readme:n,scanStatus:si(m.status)??"not-run",versions:d.flatMap(p=>{let h=dn(p,"ClawHub version"),f=si(h.version);return f===void 0?[]:[{changelog:typeof h.changelog=="string"?h.changelog:"",createdAt:md(h.createdAt),version:f}]}).slice(0,20)}}var X8=e(Q8(),1),gCe=["openclaw","clawdbot","clawdis"],yCe=["primaryEnv","envVars","install","nix","config","skillKey"],wCe=["env","bins","anyBins","config"];function Ny(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function J8(e){return e==null||e===false?false:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:true}function vCe(e){let t=e.replace(/^\uFEFF/,"");return /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(t)?.[1]}function _Ce(e){if(e.always===true||yCe.some(r=>J8(e[r])))return true;let t=Ny(e.requires);return t!==void 0&&wCe.some(r=>J8(t[r]))}function jy(e){let t=vCe(e);if(t===void 0)return false;let r;try{r=Ny((0,X8.parse)(t));}catch{return false}if(r===void 0||typeof r.name!="string"||r.name.trim().length===0||typeof r.description!="string"||r.description.trim().length===0)return false;let n=Ny(r.metadata);return !gCe.some(i=>{let s=Ny(n?.[i]);return s!==void 0&&_Ce(s)})}var SCe="https://clawhub.ai",bCe=512*1024,ECe=256*1024,Z8=50*1024*1024,TCe=18e3,e6=3;function yk(e){return e===429?new Ue("SKILL_MARKET_RATE_LIMITED","ClawHub rate limit reached"):e===404?new Ue("SKILL_MARKET_NOT_FOUND","Skill package was not found"):new Ue("SKILL_MARKET_NETWORK","ClawHub request failed")}async function Dy(e,t){let r=t;for(let n=0;n<=e6;n+=1){let i;try{i=await e(r,{headers:{"user-agent":ia},redirect:"manual",signal:AbortSignal.timeout(TCe)});}catch{throw new Ue("SKILL_MARKET_NETWORK","ClawHub request failed")}if(i.status>=300&&i.status<400){let s=i.headers.get("location");if(s===null||n===e6||(r=new URL(s,r),r.protocol!=="https:"))throw yk(i.status);continue}if(!i.ok)throw yk(i.status);return i}throw new Ue("SKILL_MARKET_NETWORK","ClawHub redirected too many times")}async function My(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new Ue("SKILL_MARKET_INVALID_RESPONSE","ClawHub response is too large");if(e.body===null)return new Uint8Array;let n=e.body.getReader(),i=[],s=0;for(;;){let c=await n.read();if(c.done)break;let l=c.value;if(l===void 0)throw new Ue("SKILL_MARKET_INVALID_RESPONSE","ClawHub response is invalid");if(s+=l.byteLength,s>t)throw await n.cancel(),new Ue("SKILL_MARKET_INVALID_RESPONSE","ClawHub response is too large");i.push(l);}let o=new Uint8Array(s),a=0;for(let c of i)o.set(c,a),a+=c.byteLength;return o}async function Ly(e,t){try{return JSON.parse(new TextDecoder().decode(await My(await Dy(e,t),bCe)))}catch(r){throw r instanceof Ue?r:new Ue("SKILL_MARKET_INVALID_RESPONSE","ClawHub JSON is invalid")}}function Vd(e,t,r){if(![t,r].every(s=>s.length>0&&s.length<=100&&/^[A-Za-z0-9_-]+$/.test(s)))throw new Ue("SKILL_MARKET_INVALID_RESPONSE","Skill identity is invalid");let i=new URL(e,SCe);return i.searchParams.set("ownerHandle",t),i}async function RCe(e,t,r){let n=Vd(`/api/v1/skills/${r}/file`,t,r);n.searchParams.set("path","SKILL.md"),n.searchParams.set("tag","latest"),n.searchParams.set("preview","1");let i=new TextDecoder().decode(await My(await Dy(e,n),ECe));try{let s=JSON.parse(i);if(typeof s!="object"||s===null||Array.isArray(s))throw new Error;let o=s,a=o.content,c=o.file,l=typeof c=="object"&&c!==null&&!Array.isArray(c)?c.content:void 0;if(typeof a=="string")return a;if(typeof l=="string")return l;throw new Error}catch{if(i.trimStart().startsWith("---"))return i;throw new Ue("SKILL_MARKET_INVALID_RESPONSE","Skill content is invalid")}}function t6(e={}){let t=e.fetch??globalThis.fetch;return {async listSkills(r,n,i){let s=s5(r,n,i);return o5(await Ly(t,s),r.trim().length>0)},async getSkill(r,n){let[i,s,o,a]=await Promise.all([Ly(t,Vd(`/api/v1/skills/${n}`,r,n)),Ly(t,Vd(`/api/v1/skills/${n}/versions`,r,n)),Ly(t,Vd(`/api/v1/skills/${n}/scan`,r,n)),RCe(t,r,n)]);if(!jy(a))throw new Ue("SKILL_MARKET_INCOMPATIBLE","Skill is not compatible with Codex");return a5(i,s,o,a)},async downloadArchive(r,n,i){let s=Vd("/api/v1/download",r,n);s.searchParams.set("slug",n),s.searchParams.set("version",i);let o=await Dy(t,s),a=await My(o,Z8);if(!o.headers.get("content-type")?.includes("json"))return {bytes:a,contentHash:null,sourcePath:null};let c;try{let m=JSON.parse(new TextDecoder().decode(a));if(typeof m!="object"||m===null||Array.isArray(m))throw new Error;c=m;}catch{throw new Ue("SKILL_MARKET_INVALID_ARCHIVE","Archive handoff is invalid")}let l=typeof c.archiveUrl=="string"?new URL(c.archiveUrl):void 0,u=c.contentHash,d=c.path;if(c.sourceRef!=="public-github"||l?.protocol!=="https:"||l.hostname!=="github.com"&&l.hostname!=="codeload.github.com"||typeof d!="string"||d.length===0||d.length>512||typeof u!="string"||!/^[A-Fa-f0-9]{64}$/.test(u))throw new Ue("SKILL_MARKET_INVALID_ARCHIVE","Archive handoff is invalid");return {bytes:await My(await Dy(t,l),Z8),contentHash:u.toLowerCase(),sourcePath:d}}}}var kCe=createRequire$1("/"),Kc,$y,vk,xCe=";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global";try{Kc=kCe("worker_threads"),$y=Kc.Worker,vk=Kc.isMarkedAsUntransferable;}catch{}var ACe=$y?function(e,t,r,n,i){var s=false,o=new $y(e+xCe,{eval:true}).on("error",function(a){return i(a,null)}).on("message",function(a){return i(null,a)}).on("exit",function(a){a&&!s&&i(new Error("exited with code "+a),null);});return vk&&(n=n.filter(function(a){return !vk(a)})),o.postMessage(r,n),o.terminate=function(){return s=true,$y.prototype.terminate.call(o)},o}:function(e,t,r,n,i){setImmediate(function(){return i(new Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"),null)});var s=function(){};return {terminate:s,postMessage:s}},Tr=Uint8Array,Ho=Uint16Array,i6=Int32Array,Sk=new Tr([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),bk=new Tr([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),s6=new Tr([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),o6=function(e,t){for(var r=new Ho(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];for(var i=new i6(r[30]),n=1;n<30;++n)for(var s=r[n];s<r[n+1];++s)i[s]=s-r[n]<<5|n;return {b:r,r:i}},Kc=o6(Sk,2),Ek=Kc.b,ICe=Kc.r;Ek[28]=258,ICe[258]=28;var a6=o6(bk,0),c6=a6.b,By=new Ho(32768);for(Qe=0;Qe<32768;++Qe)Bi=(Qe&43690)>>1|(Qe&21845)<<1,Bi=(Bi&52428)>>2|(Bi&13107)<<2,Bi=(Bi&61680)>>4|(Bi&3855)<<4,By[Qe]=((Bi&65280)>>8|(Bi&255)<<8)>>1;var Bi,Qe,Yc=(function(e,t,r){for(var n=e.length,i=0,s=new Ho(t);i<n;++i)e[i]&&++s[e[i]-1];var o=new Ho(t);for(i=1;i<t;++i)o[i]=o[i-1]+s[i-1]<<1;var a;if(r){a=new Ho(1<<t);var c=15-t;for(i=0;i<n;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,m=d|(1<<u)-1;d<=m;++d)a[By[d]>>c]=l;}else for(a=new Ho(n),i=0;i<n;++i)e[i]&&(a[i]=By[o[e[i]-1]++]>>15-e[i]);return a}),Wd=new Tr(288);for(Qe=0;Qe<144;++Qe)Wd[Qe]=8;var Qe;for(Qe=144;Qe<256;++Qe)Wd[Qe]=9;var Qe;for(Qe=256;Qe<280;++Qe)Wd[Qe]=7;var Qe;for(Qe=280;Qe<288;++Qe)Wd[Qe]=8;var Qe,l6=new Tr(32);for(Qe=0;Qe<32;++Qe)l6[Qe]=5;var Qe;var u6=Yc(Wd,9,1);var d6=Yc(l6,5,1),qy=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},hn=function(e,t,r){var n=t/8|0;return (e[n]|e[n+1]<<8)>>(t&7)&r},Uy=function(e,t){var r=t/8|0;return (e[r]|e[r+1]<<8|e[r+2]<<16)>>(t&7)},f6=function(e){return (e+7)/8|0},Hy=function(e,t,r){return (t==null||t<0)&&(t=0),(r==null||r>e.length)&&(r=e.length),new Tr(e.subarray(t,r))};var h6=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],yr=function(e,t,r){var n=new Error(t||h6[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,yr),!r)throw n;return n},p6=function(e,t,r,n){var i=e.length,s=n?n.length:0;if(!i||t.f&&!t.l)return r||new Tr(0);var o=!r,a=o||t.i!=2,c=t.i;o&&(r=new Tr(i*3));var l=function(D){var $=r.length;if(D>$){var V=new Tr(Math.max($*2,D));V.set(r),r=V;}},u=t.f||0,d=t.p||0,m=t.b||0,p=t.l,h=t.d,f=t.m,g=t.n,y=i*8;do{if(!p){u=hn(e,d,1);var _=hn(e,d+1,3);if(d+=3,_)if(_==1)p=u6,h=d6,f=9,g=5;else if(_==2){var R=hn(e,d,31)+257,P=hn(e,d+10,15)+4,b=R+hn(e,d+5,31)+1;d+=14;for(var O=new Tr(b),F=new Tr(19),j=0;j<P;++j)F[s6[j]]=hn(e,d+j*3,7);d+=P*3;for(var N=qy(F),M=(1<<N)-1,q=Yc(F,N,1),j=0;j<b;){var z=q[hn(e,d,M)];d+=z&15;var v=z>>4;if(v<16)O[j++]=v;else {var W=0,H=0;for(v==16?(H=3+hn(e,d,3),d+=2,W=O[j-1]):v==17?(H=3+hn(e,d,7),d+=3):v==18&&(H=11+hn(e,d,127),d+=7);H--;)O[j++]=W;}}var J=O.subarray(0,R),ce=O.subarray(R);f=qy(J),g=qy(ce),p=Yc(J,f,1),h=Yc(ce,g,1);}else yr(1);else {var v=f6(d)+4,w=e[v-4]|e[v-3]<<8,E=v+w;if(E>i){c&&yr(0);break}a&&l(m+w),r.set(e.subarray(v,E),m),t.b=m+=w,t.p=d=E*8,t.f=u;continue}if(d>y){c&&yr(0);break}}a&&l(m+131072);for(var he=(1<<f)-1,Te=(1<<g)-1,ue=d;;ue=d){var W=p[Uy(e,d)&he],B=W>>4;if(d+=W&15,d>y){c&&yr(0);break}if(W||yr(2),B<256)r[m++]=B;else if(B==256){ue=d,p=null;break}else {var de=B-254;if(B>264){var j=B-257,we=Sk[j];de=hn(e,d,(1<<we)-1)+Ek[j],d+=we;}var ie=h[Uy(e,d)&Te],U=ie>>4;ie||yr(3),d+=ie&15;var ce=c6[U];if(U>3){var we=bk[U];ce+=Uy(e,d)&(1<<we)-1,d+=we;}if(d>y){c&&yr(0);break}a&&l(m+131072);var Q=m+de;if(m<ce){var x=s-ce,A=Math.min(ce,Q);for(x+m<0&&yr(3);m<A;++m)r[m]=n[x+m];}for(;m<Q;++m)r[m]=r[m-ce];}}t.l=p,t.p=ue,t.b=m,t.f=u,p&&(u=1,t.m=f,t.d=h,t.n=g);}while(!u);return m!=r.length&&o?Hy(r,0,m):r.subarray(0,m)};var OCe=new Tr(0);var CCe=function(e,t){var r={};for(var n in e)r[n]=e[n];for(var n in t)r[n]=t[n];return r},r6=function(e,t,r){for(var n=e(),i=e.toString(),s=i.slice(i.indexOf("[")+1,i.lastIndexOf("]")).replace(/\s+/g,"").split(","),o=0;o<n.length;++o){var a=n[o],c=s[o];if(typeof a=="function"){t+=";"+c+"=";var l=a.toString();if(a.prototype)if(l.indexOf("[native code]")!=-1){var u=l.indexOf(" ",8)+1;t+=l.slice(u,l.indexOf("(",u));}else {t+=l;for(var d in a.prototype)t+=";"+c+".prototype."+d+"="+a.prototype[d].toString();}else t+=l;}else r[c]=a;}return t},Fy=[],NCe=function(e){var t=[];for(var r in e)e[r].buffer&&t.push((e[r]=new e[r].constructor(e[r])).buffer);return t},jCe=function(e,t,r,n){if(!Fy[r]){for(var i="",s={},o=e.length-1,a=0;a<o;++a)i=r6(e[a],i,s);Fy[r]={c:r6(e[o],i,s),e:s};}var c=CCe({},Fy[r].e);return ACe(Fy[r].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+t.toString()+"}",r,c,NCe(c),n)},LCe=function(){return [Tr,Ho,i6,Sk,bk,s6,Ek,c6,u6,d6,By,h6,Yc,qy,hn,Uy,f6,Hy,yr,p6,Tk,m6,g6]};var m6=function(e){return postMessage(e,[e.buffer])},g6=function(e){return e&&{out:e.size&&new Tr(e.size),dictionary:e.dictionary}},DCe=function(e,t,r,n,i,s){var o=jCe(r,n,i,function(a,c){o.terminate(),s(a,c);});return o.postMessage([e,t],t.consume?[e.buffer]:[]),function(){o.terminate();}};var ci=function(e,t){return e[t]|e[t+1]<<8},pn=function(e,t){return (e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},wk=function(e,t){return pn(e,t)+pn(e,t+4)*4294967296};function MCe(e,t,r){return r||(r=t,t={}),typeof r!="function"&&yr(7),DCe(e,t,[LCe],function(n){return m6(Tk(n.data[0],g6(n.data[1])))},1,r)}function Tk(e,t){return p6(e,{i:2},t&&t.out,t&&t.dictionary)}var _k=typeof TextDecoder<"u"&&new TextDecoder,FCe=0;try{_k.decode(OCe,{stream:!0}),FCe=1;}catch{}var $Ce=function(e){for(var t="",r=0;;){var n=e[r++],i=(n>127)+(n>223)+(n>239);if(r+i>e.length)return {s:t,r:Hy(e,r-1)};i?i==3?(n=((n&15)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,t+=String.fromCharCode(55296|n>>10,56320|n&1023)):i&1?t+=String.fromCharCode((n&31)<<6|e[r++]&63):t+=String.fromCharCode((n&15)<<12|(e[r++]&63)<<6|e[r++]&63):t+=String.fromCharCode(n);}};function qCe(e,t){if(t){for(var r="",n=0;n<e.length;n+=16384)r+=String.fromCharCode.apply(null,e.subarray(n,n+16384));return r}else {if(_k)return _k.decode(e);var i=$Ce(e),s=i.s,r=i.r;return r.length&&yr(8),s}}var UCe=function(e,t){return t+30+ci(e,t+26)+ci(e,t+28)},BCe=function(e,t,r){var n=ci(e,t+28),i=ci(e,t+30),s=qCe(e.subarray(t+46,t+46+n),!(ci(e,t+8)&2048)),o=t+46+n,a=HCe(e,o,i,r,pn(e,t+20),pn(e,t+24),pn(e,t+42)),c=a[0],l=a[1],u=a[2];return [ci(e,t+10),c,l,s,o+i+ci(e,t+32),u]},HCe=function(e,t,r,n,i,s,o){var a=i==4294967295,c=s==4294967295,l=o==4294967295,u=t+r,d=a+c+l;if(n&&d){for(;t+4<u;t+=4+ci(e,t+2))if(ci(e,t)==1)return [a?wk(e,t+4+8*c):i,c?wk(e,t+4):s,l?wk(e,t+4+8*(c+a)):o,1];n<2&&yr(13);}return [i,s,o,0]};var n6=typeof queueMicrotask=="function"?queueMicrotask:typeof setTimeout=="function"?setTimeout:function(e){e();};function y6(e,t,r){r||(r=t,t={}),typeof r!="function"&&yr(7);var n=[],i=function(){for(var g=0;g<n.length;++g)n[g]();},s={},o=function(g,y){n6(function(){r(g,y);});};n6(function(){o=r;});for(var a=e.length-22;pn(e,a)!=101010256;--a)if(!a||e.length-a>65558)return o(yr(13,0,1),null),i;var c=ci(e,a+8);if(c){var l=c,u=pn(e,a+16),d=pn(e,a-20)==117853008;if(d){var m=pn(e,a-12);d=pn(e,m)==101075792,d&&(l=c=pn(e,m+32),u=pn(e,m+48));}for(var p=t&&t.filter,h=function(g){var y=BCe(e,u,d),_=y[0],v=y[1],w=y[2],E=y[3],R=y[4],P=y[5],b=UCe(e,P);u=R;var O=function(j,N){j?(i(),o(j,null)):(N&&(s[E]=N),--c||o(null,s));};if(!p||p({name:E,size:v,originalSize:w,compression:_}))if(!_)O(null,Hy(e,b,b+v));else if(_==8){var F=e.subarray(b,b+v);if(w<524288||v>.8*w)try{O(null,Tk(F,{out:new Tr(w)}));}catch(j){O(j,null);}else n.push(MCe(F,{size:w},O));}else O(yr(14,"unknown compression type "+_,1),null);else O(null,null);},f=0;f<l;++f)h(f);}else o(null,{});return i}var YCe=2048,v6=50*1024*1024;function Hi(e){return new Ue("SKILL_MARKET_INVALID_ARCHIVE",e)}function _6(e){if(e.length===0||e.includes("\0")||e.startsWith("/")||/^[A-Za-z]:/.test(e))return;let t=e.replaceAll("\\","/").split("/").filter(r=>r.length>0);return t.length>0&&t.every(r=>r!=="."&&r!=="..")?t:void 0}function S6(e,t){let r=_6(e);if(r===void 0)return;if(t===null)return r.join("/");let n=_6(t);if(n===void 0)throw Hi("Skill source path is invalid");let i=r.slice(1);if(!n.every((o,a)=>i[a]===o))return "";let s=i.slice(n.length);return s.length===0?"":s.join("/")}function QCe(e,t){return new Promise((r,n)=>{let i=0,s=0,o;y6(e,{filter(a){s+=1,i+=a.originalSize;let c=S6(a.name,t);return s>YCe||i>v6||c===void 0?(o=Hi("Skill archive exceeds safety limits"),false):c.length>0}},(a,c)=>{if(a!==null){n(Hi("Skill archive cannot be decompressed"));return}if(o!==void 0){n(o);return}let l=new Map,u=0;for(let[d,m]of Object.entries(c)){let p=S6(d,t);if(p===void 0){n(Hi("Skill archive path is invalid"));return}if(!(p.length===0||d.endsWith("/"))){if(u+=m.byteLength,u>v6){n(Hi("Skill archive is too large"));return}l.set(p,m);}}if(l.size===0){n(Hi("Skill archive is empty"));return}r(l);});})}async function JCe(e,t){let r=await QCe(e.bytes,e.sourcePath);await Promise.all([...r].map(async([s,o])=>{let a=join(t,...s.split("/"));await mkdir(dirname(a),{recursive:true}),await writeFile(a,o);}));let n=join(t,"SKILL.md");if(await b6(n))return t;let i=await readdir(t,{withFileTypes:true});if(i.length===1&&i[0]?.isDirectory()){let s=join(t,i[0].name);if(await b6(join(s,"SKILL.md")))return s}throw Hi("Skill archive does not contain SKILL.md")}async function b6(e){try{return (await stat(e)).isFile()}catch{return false}}async function XCe(e){try{let t=JSON.parse(await readFile(join(e,".clawhub/origin.json"),"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))return;let r=t;return r.version!==1||typeof r.fingerprint!="string"||typeof r.installedVersion!="string"||typeof r.ownerHandle!="string"||typeof r.slug!="string"?void 0:r}catch{return}}async function P6(e,t,r){for(let n of await readdir(t,{withFileTypes:true})){if(t===e&&n.name===".clawhub")continue;let i=join(t,n.name),s=await lstat(i);if(s.isSymbolicLink())throw Hi("Skill symlinks are not allowed");s.isDirectory()?await P6(e,i,r):s.isFile()&&r.push(i);}}async function xk(e){let t=[];await P6(e,e,t),t.sort((n,i)=>relative(e,n).localeCompare(relative(e,i)));let r=createHash("sha256");for(let[n,i]of t.entries()){let s=await readFile(i),o=relative(e,i).split(sep).join("/"),a=createHash("sha256").update(s).digest("hex");n>0&&r.update(`
|
|
563
563
|
`),r.update(o).update("\0").update(String(s.byteLength)).update("\0").update(a);}return r.digest("hex")}async function k6(e,t,r,n,i){await mkdir(t,{recursive:true});let s=join(t,n),o=await XCe(s),a=await stat(s).then(()=>true,()=>false);if(a&&(o===void 0||o.ownerHandle!==r||o.slug!==n))throw new Ue("SKILL_MARKET_CONFLICT","Skill directory contains unrelated files");if(a&&o!==void 0&&await xk(s)!==o.fingerprint)throw new Ue("SKILL_MARKET_CONFLICT","Skill directory contains local changes");if(o?.installedVersion===i)return {path:s,status:"current",version:i};let c=[String(process.pid),randomUUID()].join("-"),l=join(t,`.${n}.codexly-${c}`),u=join(t,`.${n}.backup-${c}`);try{let d=await JCe(e,l);if(e.contentHash!==null&&await xk(d)!==e.contentHash)throw Hi("Skill archive content hash does not match");let m=await readFile(join(d,"SKILL.md"),"utf8");if(!jy(m))throw new Ue("SKILL_MARKET_INCOMPATIBLE","Skill is not compatible with Codex");let p=await xk(d);await mkdir(join(d,".clawhub"),{recursive:!0}),await writeFile(join(d,".clawhub/origin.json"),`${JSON.stringify({fingerprint:p,installedVersion:i,ownerHandle:r,registry:"https://clawhub.ai",slug:n,version:1},null,2)}
|
|
564
564
|
`),a&&await rename(s,u);try{await rename(d,s);}catch(h){throw a&&await rename(u,s).catch(()=>{}),h}return a&&await rm$1(u,{force:!0,recursive:!0}),d!==l&&await rm$1(l,{force:!0,recursive:!0}),{path:s,status:a?"updated":"installed",version:i}}catch(d){throw await rm$1(l,{force:true,recursive:true}).catch(()=>{}),d instanceof Ue?d:new Ue("SKILL_MARKET_FILESYSTEM",`Skill installation failed for ${basename(s)}`)}}var i1e=64*1024;async function s1e(e){try{let t=join(dirname(e),".clawhub/origin.json");if((await stat(t)).size>i1e)return;let r=JSON.parse(await readFile(t,"utf8"));if(typeof r!="object"||r===null||Array.isArray(r))return;let n=r;return typeof n.installedVersion=="string"&&typeof n.ownerHandle=="string"&&typeof n.slug=="string"?{installedVersion:n.installedVersion,owner:n.ownerHandle,slug:n.slug}:void 0}catch{return}}async function x6(e){let t=Ic(32);return Promise.all(e.map(r=>t(async()=>{let n=await s1e(r.path);return n===void 0?r:{...r,marketplace:n,source:"clawhub"}})))}function Kd(e){return new Ue("SKILL_MARKET_FILESYSTEM",e)}function I6(e){let t=e.homeDirectory??homedir(),r=async n=>{let i=await e.projectRepository.list();return {page:await e.provider.listInstalledSkills(i,n),projects:i}};return {getSkill:(n,i)=>e.catalog.getSkill(n,i),getOfficialPlugin:(n,i,s)=>e.provider.getOfficialPlugin(n,i,s),async installSkill(n,i,s){let o=await e.catalog.getSkill(n,i);if(o.scanStatus!=="clean")throw new Ue("SKILL_MARKET_UNSAFE","Skill package failed the security scan");let a=await e.projectRepository.list(),c;if(s.scope==="user")c=join(t,".agents/skills");else {let p=a.find(h=>h.id===s.projectId)?.roots.find(h=>h.path===s.rootPath);if(p===void 0)throw Kd("Skill project root is invalid");c=join(p.path,".agents/skills");}let l=await e.catalog.downloadArchive(n,i,o.latestVersion),u=await k6(l,c,n,i,o.latestVersion),d=await e.provider.listInstalledSkills(a,true);return {...u,installedSkills:{...d,data:await x6(d.data)}}},installOfficialPlugin:(n,i,s,o)=>e.provider.installOfficialPlugin(n,i,s,o),listConfiguredMcpServers:()=>e.provider.listConfiguredMcpServers(),async listInstalledSkills(n){let{page:i}=await r(n);return {...i,data:await x6(i.data)}},reconcileOfficialPlugins:()=>e.provider.reconcileOfficialPlugins(),async listOfficialPlugins(n){let i=await e.projectRepository.list();return e.provider.listOfficialPlugins(i,n)},listSkills:(n,i,s)=>e.catalog.listSkills(n,i,s),async openSkillDirectory(n){let{page:i}=await r(false);if(!i.data.some(c=>c.path===n))throw Kd("Skill path was not discovered");let s;try{s=await realpath(n);}catch{throw Kd("Skill path is unavailable")}if(basename(s)!=="SKILL.md")throw Kd("Skill path is invalid");let a=(await e.projectOpenService.getCapabilities()).apps.find(c=>c.kind==="file-manager");if(a===void 0)throw Kd("File manager is unavailable");return await e.projectOpenService.open(dirname(s),a.id,s),{status:"opened"}},setMcpServerEnabled:(n,i)=>e.provider.setMcpServerEnabled(n,i),setSkillEnabled:(n,i)=>e.provider.setSkillEnabled(n,i),uninstallOfficialPlugin:n=>e.provider.uninstallOfficialPlugin(n)}}function O6(e){let t=new Tl({...e.eventBufferSize===void 0?{}:{capacity:e.eventBufferSize},provider:e.eventProvider,sessionId:e.eventSessionId??randomUUID()}),{attachmentStore:r,onAttachmentReleaseError:n,provider:i,scope:s}=e;return {eventStream:t,provider:i,scope:s,transportMetrics:{activeClients:0,slowClientDisconnects:0},unsubscribe:i.subscribeEvents(o=>{e.onActivity(),o.type==="turn.completed"&&(r.releaseTurn(s.id,o.payload.turn.id).catch(n),e.onTurnCompleted?.({eventStream:t,projectId:s.id,provider:i,taskId:o.taskId}).catch(n)),o.type==="project.git_metadata_changed"&&K3(o.payload.rootPath),t.publish(o),e.workbenchChanges?.publishAgentEvent(s.id,o);})}}var Gy=class{#e=new Map;#t;#n;#r;#i;#o;#f;#l=false;#s;constructor(t){for(let[r,n]of [["cleanupIntervalMs",t.cleanupIntervalMs],["idleTtlMs",t.idleTtlMs]])if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`${r} must be a positive safe integer`);this.#n=t.clock??Date.now,this.#r=t.contexts,this.#i=t.idleTtlMs,this.#o=t.onReleaseError??(()=>{}),this.#f=t.release,this.#t=setInterval(()=>{this.#p();},t.cleanupIntervalMs),this.#t.unref();}touch(t){this.#l||this.#e.set(t,this.#n());}forget(t){this.#e.delete(t);}async close(){this.#l||(this.#l=true,clearInterval(this.#t)),await this.#s,this.#e.clear();}#p(){return this.#l?Promise.resolve():(this.#s??=this.#h().finally(()=>{this.#s=void 0;}),this.#s)}async#h(){let t=this.#n();for(let[r,n]of this.#r){let i=this.#e.get(r);if(i===void 0){this.#e.set(r,t);continue}if(!(n.transportMetrics.activeClients>0||i+this.#i>t||this.#r.get(r)!==n))try{await this.#f(r),this.#r.has(r)||this.#e.delete(r);}catch(s){this.#o(s,r);}}}};var zy=class{#e=new Map;async run(t,r){let n=this.#e.get(t)??Promise.resolve(),i,s=new Promise(o=>{i=o;});this.#e.set(t,s),await n.catch(()=>{});try{return await r()}finally{i(),this.#e.get(t)===s&&this.#e.delete(t);}}};var li=class extends Error{constructor(){super("Task queue is blocked by an edited or unresolved submission"),this.name="TaskQueueBlockedError";}},Go=class extends Error{constructor(){super("Queued submission was not found"),this.name="TaskQueueItemNotFoundError";}},Vy=class{#e;#t=new Map;#n=new Map;#r;#i;#o;constructor(t){this.#e=t.attachmentStore,this.#r=t.readTaskSettings,this.#i=t.repository,this.#o=t.resolveProviderInput;}async add(t,r,n){return this.#d(t,async()=>{let{attachmentIds:i}=await this.#o(t.projectId,r,t.provider,t.taskId),s={...r,attachments:i.map(a=>({id:a}))},o=await this.#i.addQueue({clientUserMessageId:n,id:randomUUID(),input:s,projectId:t.projectId,status:"queued",taskId:t.taskId});return await this.#e.retainQueue(t.projectId,i,o.id),this.#s(t),this.#l(o)})}async delete(t,r){return this.#d(t,async()=>{let n=await this.#i.deleteQueue(t.projectId,t.taskId,r);return n&&(this.#n.delete(r),await this.#e.releaseQueue(t.projectId,r),this.#s(t)),n})}async list(t){let r=await this.#i.listQueue(t.projectId,t.taskId);return Promise.all(r.map(n=>this.#l(n)))}async reorder(t,r){await this.#d(t,async()=>{await this.#i.reorderQueue(t.projectId,t.taskId,r),this.#s(t);});}async start(t,r){let n=await this.#d(t,()=>this.#p(t,r));if(n===void 0)throw new Go;return n}async startNext(t){await this.#d(t,()=>this.#f(t));}async#f(t){let[r]=await this.#i.listQueue(t.projectId,t.taskId);r?.status==="queued"&&await this.#p(t,r.id,false);}async update(t,r,n,i){return this.#d(t,async()=>{if((await this.#i.listQueue(t.projectId,t.taskId)).find(u=>u.id===r)?.execution!==void 0)throw new li;let{attachmentIds:o}=await this.#o(t.projectId,n,t.provider,t.taskId),a={...n,attachments:o.map(u=>({id:u}))},c=await this.#i.updateQueue(t.projectId,t.taskId,r,a,i);if(c===void 0)throw new Go;await this.#e.retainQueue(t.projectId,o,r,true),this.#s(t);let l=await this.#l(c);return i==="queued"&&await this.#f(t),l})}async#l(t){return {attachments:await Promise.all(t.input.attachments.map(async({id:n})=>(await this.#e.read(t.projectId,n)).attachment)),clientUserMessageId:t.clientUserMessageId,id:t.id,skills:t.input.skills,status:t.status,text:t.input.text}}#s(t){t.eventStream.publish({payload:{},taskId:t.taskId,type:"queue.changed"});}async#p(t,r,n=true){let i=await this.#i.listQueue(t.projectId,t.taskId),s=r===void 0?0:i.findIndex(h=>h.id===r);if(s<0)return;let o=i.findIndex(h=>h.status==="editing");if(o>=0&&s>=o)throw new li;let a=i[s];if(a?.status!=="queued")throw new li;let c=a.execution?.state==="started"?a.execution.turn:this.#n.get(a.id);if(c!==void 0)return this.#h(t,a,c);if(a.execution!==void 0)throw new li;let u=(await t.provider.readTask(t.taskId))?.turns.find(h=>h.status==="running");if(u!==void 0&&!n)return;let{providerInput:d}=await this.#o(t.projectId,a.input,t.provider,t.taskId),m=await this.#r(t.projectId,t.taskId);if(this.#n.size>=1e3)throw new li;if(!await this.#i.setQueueExecution(a,{state:"starting"}))throw new li;let p;return u!==void 0?(await t.provider.steerTurn(t.taskId,u.id,d),p=u):p=await t.provider.startTurn(t.taskId,d,m),this.#n.set(a.id,p),this.#h(t,a,p)}async#h(t,r,n){if(!await this.#i.setQueueExecution(r,{state:"started",turn:n}))throw new Go;return this.#n.delete(r.id),await this.#e.startQueue(t.projectId,r.id,n.id),await this.#i.deleteQueue(t.projectId,t.taskId,r.id),this.#s(t),n}async#d(t,r){let n=`${t.projectId}\0${t.taskId}`,i=this.#t.get(n)??Promise.resolve(),s,o=new Promise(c=>{s=c;}),a=i.then(()=>o);this.#t.set(n,a),await i;try{return await r()}finally{s(),this.#t.get(n)===a&&this.#t.delete(n);}}};function C6(){let e=new Map,t=(r,n)=>`${r}\0${n}`;return {setQueueExecution(r,n){let i=e.get(t(r.projectId,r.taskId))??[],s=i.findIndex(a=>a.id===r.id),o=i[s];return o===void 0||n.state==="starting"&&o.execution!==void 0?Promise.resolve(false):(i[s]={...o,execution:n},Promise.resolve(true))},addQueue(r){let n=e.get(t(r.projectId,r.taskId))??[];return n.push(r),e.set(t(r.projectId,r.taskId),n),Promise.resolve(r)},deleteQueue(r,n,i){let s=e.get(t(r,n))??[],o=s.findIndex(a=>a.id===i);return o<0?Promise.resolve(false):(s.splice(o,1),Promise.resolve(true))},listQueue(r,n){return Promise.resolve([...e.get(t(r,n))??[]])},reorderQueue(r,n,i){let s=e.get(t(r,n))??[],o=new Map(s.map(a=>[a.id,a]));if(i.length!==s.length||new Set(i).size!==s.length||i.some(a=>!o.has(a)))throw new Error("Task queue order must contain every queued submission exactly once");return e.set(t(r,n),i.map(a=>o.get(a))),Promise.resolve()},updateQueue(r,n,i,s,o){let a=e.get(t(r,n))??[],c=a.findIndex(d=>d.id===i),l=a[c];if(l===void 0||l.execution!==void 0)return Promise.resolve(void 0);let u={...l,input:s,status:o};return a[c]=u,Promise.resolve(u)}}}var Vr=class extends Error{constructor(r,n,i){super(r,i);this.reason=n;this.name="ProjectDirectoryBrowserError";}reason};function m1e(e,t){let r=relative(e,t);return r===""||!r.startsWith(`..${sep}`)&&r!==".."&&!isAbsolute(r)}async function L6(e){return e===void 0?[]:Promise.all(e.map(async t=>{if(!isAbsolute(t))throw new Vr("Workspace root path must be absolute","invalid-directory");let r=await realpath(t);if(!(await lstat(r)).isDirectory())throw new Vr("Workspace root path must identify a directory","invalid-directory");return r}))}function Ck(e){let t=e.code,r=t==="EACCES"||t==="EPERM";return new Vr(r?"Project directory is not accessible":"Project directory is invalid",r?"directory-unavailable":"invalid-directory",{cause:e instanceof Error?e:void 0})}function g1e(e,t){return e.name.localeCompare(t.name,"en",{sensitivity:"base"})||e.name.localeCompare(t.name,"en")}async function jk(e,t={}){let r;try{r=await L6(t.workspaceRoots);}catch(i){throw i instanceof Vr?i:Ck(i)}let n=e??r[0]??t.homePath??homedir();if(!isAbsolute(n))throw new Vr("Project directory path must be absolute","invalid-directory");try{let i=await realpath(n);if(!(await lstat(i)).isDirectory())throw new Vr("Project directory path must identify a directory","invalid-directory");if(r.length>0&&!r.some(s=>m1e(s,i)))throw new Vr("Project directory is outside the configured workspace roots","invalid-directory");return i}catch(i){throw i instanceof Vr?i:Ck(i)}}async function D6(e,t={}){let[r,n]=await Promise.all([jk(e,t),L6(t.workspaceRoots)]),i=n.length>0?n.map(a=>({name:basename(a),path:a})):await(t.filesystemRoots??jg)(),s;try{let a=await readdir(r,{withFileTypes:!0});s=(await Lc(r,a.filter(l=>t.includeHidden===!0||!l.name.startsWith(".")))).filter(({type:l})=>l==="directory").map(({entry:l})=>l).sort(g1e).map(l=>({name:l.name,path:join(r,l.name)}));}catch(a){throw Ck(a)}let o=dirname(r);return {entries:s,parentPath:o===r||n.some(a=>a===r)?null:o,path:r,roots:i}}var mt=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ProjectRootScopeError";}code};async function Lk(e,t,r){let n=await e.read(t);if(n===void 0)throw new mt("PROJECT_NOT_FOUND","Project not found");let i=r===void 0?n.roots[0]:n.roots.find(s=>s.path===r);if(i!==void 0)return i;if(r!==void 0)for(let s of n.roots)try{let o=await Ng(s.path,r);return {id:createHash("sha256").update(o.path).digest("hex").slice(0,32),path:o.path}}catch{}throw new mt("PROJECT_ROOT_INVALID","Project root is invalid")}async function ui(e,t,r){return (await Lk(e,t,r)).path}async function Gs(e,t,r,n,i){try{return await Wy(e,t,r,n)}catch(s){if(s instanceof mt){let o=s.code==="PROJECT_NOT_FOUND"?404:400;await i.code(o).send({code:s.code,message:s.message});return}throw s}}async function Wy(e,t,r,n){if(r===we){let i=(await t(r))?.scope.rootPath;if(i===void 0)throw new mt("PROJECT_NOT_FOUND","Project not found");return {id:we,path:i}}if(n===void 0)throw new mt("PROJECT_ROOT_INVALID","Project root is required");return Lk(e,r,n)}function b1e(e,t){let r=/^bytes=(\d*)-(\d*)$/u.exec(e);if(r===null||r[1]===""&&r[2]==="")return null;let n=r[1]===""?Math.max(0,t-Number(r[2])):Number(r[1]),i=r[1]===""||r[2]===""?t-1:Math.min(Number(r[2]),t-1);return Number.isSafeInteger(n)&&Number.isSafeInteger(i)&&n<=i&&n<t?{start:n,end:i}:null}async function M6(e,t,r,n){let i=isAbsolute(r)?r:resolve(t,r),s=await open(i,"r"),o=false;try{let a=await s.stat(),c=Buffer.alloc(5);if(await s.read(c,0,c.length,0),!a.isFile()||c.toString("ascii")!=="%PDF-")throw new TypeError("Invalid PDF file");e.type("application/pdf").header("content-disposition",Dc(basename(i)).replace(/^attachment/u,"inline")).header("cache-control","private, no-cache").header("accept-ranges","bytes");let l=n===void 0?void 0:b1e(n,a.size);if(l===null){await e.code(416).header("content-range",`bytes */${String(a.size)}`).send();return}l!==void 0&&e.code(206).header("content-range",`bytes ${String(l.start)}-${String(l.end)}/${String(a.size)}`),e.header("content-length",l===void 0?a.size:l.end-l.start+1);let u=s.createReadStream(l);o=!0,await e.send(u);}finally{o||await s.close();}}function F6(e,t){e.get("/v1/projects/:projectId/files/pdf",{schema:{params:ge,querystring:xb,response:{400:le,404:le}}},async(r,n)=>{let i=await Gs(t.projectRepository,t.getProjectContext,r.params.projectId,r.query.rootPath,n);if(i!==void 0)try{await M6(n,i.path,r.query.path,r.headers.range);}catch{return n.code(404).send({code:"PROJECT_PDF_NOT_FOUND",message:"Project PDF is unavailable"})}});}function $6(e,t){return e.header("x-content-type-options","nosniff").type(t.attachment.mediaType).send(Buffer$1.from(t.content))}var k1e=20,x1e=50,A1e=new Set([".git",".next",".turbo","build","coverage","dist","node_modules"]);function I1e(e){if(e.startsWith("/")||e.includes("\\")||/^[A-Za-z]:/u.test(e))return;let t=e.split("/");if(!(t.length>k1e||t.some(r=>r===""||r==="."||r===".."||A1e.has(r))))return t}async function O1e(e,t){let r=e;try{for(let[n,i]of t.entries()){r=resolve(r,i);let s=await lstat(r);if(s.isSymbolicLink()||(n<t.length-1?!s.isDirectory():!s.isFile()))return !1}return !0}catch{return false}}async function q6(e,t){if(t.data.length===0)return {data:[]};let r=await realpath(e),n=[],i=new Set,s=await Promise.all(t.data.slice(0,x1e).map(async o=>{if(o.rootPath!==e||o.name===".DS_Store")return;let a=I1e(o.path);if(a?.at(-1)===o.name)return await O1e(r,a)?o:void 0}));for(let o of s){if(o===void 0)continue;let a=o.path;i.has(a)||(i.add(a),n.push(o));}return {data:n}}var Qc=class extends Error{constructor(r,n){super(n);this.code=r;}code},zi=()=>new Qc("TEXT_FILE_UNSUPPORTED","Only project UTF-8 text files up to 2 MiB with consistent line endings can be edited"),Mk=()=>new Qc("TEXT_FILE_CONFLICT","File changed on disk; reload before saving"),$1e=new Set([".doc",".docx",".odt",".rtf",".xls",".xlsx",".ppt",".pptx",".pdf",".zip",".png",".jpg",".jpeg",".gif",".webp",".woff",".woff2"]),Ky=new Map,V6=e=>createHash("sha256").update(e).digest("hex"),Gi=e=>createHash("sha256").update([e.dev,e.ino,e.size,e.mtimeNs,e.ctimeNs,e.birthtimeNs].join(":")).digest("hex");async function W6(e,t){let{target:r}=await Yy(e,t),n=await lstat(r,{bigint:true});if(!n.isFile()||n.size>BigInt(_g$1))throw zi();return {revision:Gi(n)}}async function Yy(e,t){let r=await realpath(e),n=isAbsolute(t)?relative(t.startsWith(`${resolve(e)}${sep}`)?resolve(e):r,t):t,i=n.split(/[\\/]/u);if(!n||isAbsolute(n)||i.some(o=>!o||o==="."||o===".."||o.toLowerCase()===".git"||o.includes(":")))throw zi();let s=r;for(let o of i)if(s=resolve(s,o),(await lstat(s)).isSymbolicLink())throw zi();if($1e.has(extname(s).toLowerCase()))throw zi();return {target:s,path:relative(r,s).split(sep).join("/")}}function K6(e){if(e.length>_g$1)throw zi();let t;try{t=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(e);}catch{throw zi()}if(e.some(r=>r<=8||r===11||r===12||r>=14&&r<=31)||/\r(?!\n)/u.test(t)||t.includes(`\r
|
|
565
|
-
`)&&/(?<!\r)\n/u.test(t))throw zi();return t}async function Fk(e){let t=await open(e,"r");try{let r=await t.stat({bigint:!0});if(!r.isFile()||r.size>BigInt(_g$1))throw zi();let n=Buffer.alloc(Number(r.size)+1),i=0;for(;i<n.length;){let{bytesRead:a}=await t.read(n,i,n.length-i,i);if(!a)break;i+=a;}let s=await t.stat({bigint:!0});if(BigInt(i)!==r.size||Gi(s)!==Gi(r)||Gi(await lstat(e,{bigint:!0}))!==Gi(r))throw Mk();let o=n.subarray(0,i);return {content:K6(o),version:V6(o),revision:Gi(r),mode:Number(r.mode),ino:r.ino,dev:r.dev}}finally{await t.close();}}async function Y6(e,t){let r=await Yy(e,t),n=await Fk(r.target);return {path:r.path,content:n.content,version:n.version,revision:n.revision}}async function Q6(e,t){let{target:r}=await Yy(e,t.path),n=Buffer.from(t.content,"utf8");if(K6(n)!==t.content)throw zi();let s=(Ky.get(r)??Promise.resolve()).catch(()=>{}).then(async()=>{let o=await Fk(r);if(o.version!==t.expectedVersion)throw Mk();let a=join(dirname(r),`.codexly-edit-${randomUUID()}.tmp`),c=await open(a,"wx",384);try{await c.writeFile(n),await c.chmod(o.mode&511),await c.sync();let l=await c.stat({bigint:!0});await Yy(e,t.path);let u=await Fk(r);if(u.version!==o.version||u.ino!==o.ino||u.dev!==o.dev)throw Mk();await rename(a,r);let d=await c.stat({bigint:!0}).catch(()=>null),m=await lstat(r,{bigint:!0}).catch(()=>null);return {version:V6(n),...d!==null&&m!==null&&d.size===l.size&&d.mtimeNs===l.mtimeNs&&Gi(d)===Gi(m)?{revision:Gi(d)}:{}}}finally{await c.close(),await unlink(a).catch(l=>{if(l.code!=="ENOENT")throw l});}});Ky.set(r,s);try{return await s}finally{Ky.get(r)===s&&Ky.delete(r);}}function $k(e,t){return t instanceof Qc?e.code(t.code==="TEXT_FILE_CONFLICT"?409:400).send({code:t.code,message:t.message,retryable:false}):t instanceof mt?e.code(t.code==="PROJECT_NOT_FOUND"?404:400).send({code:t.code,message:t.message,retryable:false}):e.code(404).send({code:"TEXT_FILE_UNAVAILABLE",message:"Text file is unavailable",retryable:false})}function J6(e,t){let r={400:Xf,404:Xf,409:Xf};e.get("/v1/projects/:projectId/files/text/revision",{schema:{params:ge,querystring:xb,response:{200:$g$1,...r}}},async(n,i)=>{try{let s=await t(n.params.projectId,n.query.rootPath);return i.header("cache-control","no-store"),await W6(s.path,n.query.path)}catch(s){return $k(i,s)}}),e.get("/v1/projects/:projectId/files/text",{schema:{params:ge,querystring:xb,response:{200:ah,...r}}},async(n,i)=>{try{let s=await t(n.params.projectId,n.query.rootPath);return i.header("cache-control","no-store"),await Y6(s.path,n.query.path)}catch(s){return $k(i,s)}}),e.post("/v1/projects/:projectId/files/text",{bodyLimit:_g$1*6+8192,schema:{params:ge,querystring:Y,body:bh,response:{200:ch,...r}}},async(n,i)=>{try{let s=await t(n.params.projectId,n.query.rootPath);return await Q6(s.path,n.body)}catch(s){return $k(i,s)}});}function X6(e){if(e instanceof mt)throw new L(e.code==="PROJECT_NOT_FOUND"?"PROJECT_NOT_FOUND":"INVALID_REQUEST",e.message,e.code==="PROJECT_NOT_FOUND"?404:400);if(e.code==="ENOENT")throw new L("PROJECT_FILE_NOT_FOUND","Project file was not found",404);if(e instanceof TypeError){let r=e.message.includes("already exists");throw new L(r?"PROJECT_FILE_CONFLICT":"INVALID_REQUEST",r?"A file or directory with that name already exists":"Project file request is invalid",r?409:400)}throw new L("PROJECT_FILE_MUTATION_FAILED","Project file mutation failed",500)}var Z6={400:Xf,404:Xf,409:Xf,500:Xf,503:Xf};function eW(e){let t=posix.dirname(e);return t==="."?void 0:t}function tW(e,t,r){let{deleteProjectFile:n,readFileTree:i,renameProjectFile:s,runIdempotent:o}=t;J6(e,r),e.post("/v1/projects/:projectId/files/rename",{schema:{body:tb,headers:X,params:ge,querystring:Y,response:{200:ub,...Z6}}},async a=>o(["rename-project-file",a.params.projectId,a.query.rootPath,a.body.path],a.headers["idempotency-key"],a.body,async()=>{try{let c=await r(a.params.projectId,a.query.rootPath),l=await s(c.path,a.body.path,a.body.name),u=await i(c.path,eW(a.body.path));return {...l,tree:u}}catch(c){X6(c);}})),e.post("/v1/projects/:projectId/files/delete",{schema:{body:vb,headers:X,params:ge,querystring:Y,response:{200:wb,...Z6}}},async a=>o(["delete-project-file",a.params.projectId,a.query.rootPath,a.body.path],a.headers["idempotency-key"],a.body,async()=>{try{let c=await r(a.params.projectId,a.query.rootPath),l=await n(c.path,a.body.path),u=await i(c.path,eW(a.body.path));return {...l,tree:u}}catch(c){X6(c);}}));}function Jy(e,t,r,n){let{content:i,mediaType:s}=t,o=`"${createHash("sha256").update(i).digest("hex")}"`;return e.header("cache-control",`private, max-age=${String(r)}`).header("etag",o).header("x-content-type-options","nosniff").type(s),n?.split(",").some(c=>{let l=c.trim().replace(/^W\//u,"");return l===o||l==="*"})?e.code(304).send():e.send(Buffer.from(i.buffer,i.byteOffset,i.byteLength))}function rW(e,t){let{attachmentStore:r,getProjectContext:n,maximumAttachmentBytes:i,multipartEnvelopeBytes:s,projectRepository:o,readFileTree:a,readFileDownload:c,searchProjectFiles:l,readImageFile:u,readSourceFile:d,runIdempotent:m,resolveHostAttachment:p,stopProjectFileSearch:h}=t;tW(e,t,(f,g)=>Wy(o,n,f,g)),e.get("/v1/projects/:projectId/files/download",{schema:{params:ge,querystring:xb,response:{400:le,404:le}}},async(f,g)=>{let y=await Gs(o,n,f.params.projectId,f.query.rootPath,g);if(y!==void 0)try{let _=await c(y.path,f.query.path);return await g.header("content-disposition",Dc(_.name)).header("x-content-type-options","nosniff").type("application/octet-stream").send(_.content)}catch{return g.code(404).send({code:"PROJECT_FILE_NOT_FOUND",message:"Project file is unavailable"})}}),e.get("/v1/projects/:projectId/files/tree",{schema:{params:ge,querystring:qb$1,response:{200:rb$1,400:le,404:le,500:le}}},async(f,g)=>{let y=await Gs(o,n,f.params.projectId,f.query.rootPath,g);if(y!==void 0)try{return await a(y.path,f.query.path)}catch{return g.code(500).send({code:"PROJECT_FILE_TREE_UNAVAILABLE",message:"Project file tree is unavailable"})}}),e.get("/v1/projects/:projectId/files/search",{schema:{params:ge,querystring:ma,response:{200:oa,400:le,404:le,500:le}}},async(f,g)=>{let y=await Gs(o,n,f.params.projectId,f.query.rootPath,g);if(y!==void 0)try{let _=await l({projectId:f.params.projectId,query:f.query.query,roots:[y.path],sessionId:f.query.sessionId,signal:f.signal});return {data:(await q6(y.path,_)).data.map(w=>({name:w.name,path:w.path,rootId:y.id,rootPath:y.path}))}}catch(_){if(f.signal.aborted||_ instanceof Error&&_.name==="AbortError")throw _;return g.code(500).send({code:"PROJECT_FILE_SEARCH_UNAVAILABLE",message:"Project file search is unavailable"})}}),e.post("/v1/projects/:projectId/files/search/stop",{schema:{body:pa,headers:X,params:ge,response:{200:qa,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async f=>m(["project-file-search-stop",f.params.projectId,f.body.sessionId],f.headers["idempotency-key"],f.body,async()=>{try{await Wy(o,n,f.params.projectId,f.body.rootPath);}catch(g){throw g instanceof mt?new L(g.code==="PROJECT_NOT_FOUND"?"PROJECT_NOT_FOUND":"INVALID_REQUEST",g.message,g.code==="PROJECT_NOT_FOUND"?404:400):g}try{await h(f.params.projectId,f.body.sessionId);}catch{throw new L("PROVIDER_ERROR","Project file search is unavailable",502,true)}return {}})),e.get("/v1/projects/:projectId/files/image",{schema:{params:ge,querystring:xb,response:{400:le,404:le}}},async(f,g)=>{let y=await Gs(o,n,f.params.projectId,f.query.rootPath,g);if(y!==void 0)try{let _=await u(y.path,f.query.path);return await Jy(g,_,60,f.headers["if-none-match"])}catch{return g.code(404).send({code:"PROJECT_IMAGE_NOT_FOUND",message:"Project image is unavailable"})}}),e.get("/v1/projects/:projectId/files/source",{schema:{params:ge,querystring:xb,response:{200:yb,400:le,404:le}}},async(f,g)=>{let y=await Gs(o,n,f.params.projectId,f.query.rootPath,g);if(y!==void 0)try{return await d(y.path,f.query.path,f.query.cursor??0)}catch{return g.code(404).send({code:"SOURCE_FILE_NOT_FOUND",message:"Source file is unavailable"})}}),e.post("/v1/projects/:projectId/attachments/:kind/host",{schema:{body:Ba$1,headers:X,params:JH,response:{201:dd$1,400:Xf,404:Xf,409:Xf,413:Xf,502:Xf,503:Xf}}},async(f,g)=>{if(await n(f.params.projectId)===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let y;try{let _=await p(f.params.kind,f.body.path);y=await r.add(f.params.projectId,_);let v=y,w=await m(["import-host-attachment",f.params.projectId],f.headers["idempotency-key"],{contentDigest:y.contentDigest,kind:y.attachment.kind,mediaType:y.attachment.mediaType,name:y.attachment.name,size:y.attachment.size},()=>v.attachment);return w.id!==y.attachment.id&&await r.discard(y.attachment.id),await g.code(201).send({attachment:w})}catch(_){throw y!==void 0&&await r.discard(y.attachment.id),_ instanceof RangeError?new L("INVALID_REQUEST","Attachment is too large",413):_ instanceof mr||_ instanceof TypeError?new L("INVALID_REQUEST","Host attachment is invalid",400):_}}),e.post("/v1/projects/:projectId/attachments/:kind",{schema:{headers:X,params:QH,response:{201:dd$1,400:Xf,409:Xf,413:Xf,502:Xf,503:Xf}}},async(f,g)=>{let y=i(f.params.kind),_=Number(f.headers["content-length"]);if(Number.isFinite(_)&&_>y+s)throw new L("INVALID_REQUEST","Attachment is too large",413);if(await n(f.params.projectId)===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if(!f.isMultipart())throw new L("INVALID_REQUEST","Attachment must use multipart/form-data",400);let v;try{let w=await f.file({limits:{fields:0,files:1,fileSize:y,parts:1}});if(w?.fieldname!=="attachment")throw new TypeError("Attachment file part is missing");if(v=await r.add(f.params.projectId,{content:w.file,kind:f.params.kind,mediaType:w.mimetype,name:w.filename}),w.file.truncated)throw new RangeError("Attachment exceeds the maximum size");let E=v,R=await m(["upload-attachment",f.params.projectId],f.headers["idempotency-key"],{contentDigest:v.contentDigest,kind:f.params.kind,mediaType:v.attachment.mediaType,name:v.attachment.name,size:v.attachment.size},()=>E.attachment);return R.id!==v.attachment.id&&await r.discard(v.attachment.id),await g.code(201).send({attachment:R})}catch(w){throw v!==void 0&&await r.discard(v.attachment.id),w instanceof RangeError||w instanceof e.multipartErrors.RequestFileTooLargeError?new L("INVALID_REQUEST","Attachment is too large",413):w instanceof TypeError?new L("INVALID_REQUEST","Attachment is invalid",400):w}}),e.get("/v1/projects/:projectId/attachments/:attachmentId",{schema:{params:XH,response:{404:le}}},async(f,g)=>{try{let y=await r.read(f.params.projectId,f.params.attachmentId);return await g.header("x-content-type-options","nosniff").type(y.attachment.mediaType).send(y.content)}catch(y){if(y instanceof er){let _=await t.projectTodoRepository?.readProjectTodoAttachment(f.params.projectId,f.params.attachmentId)??await t.readScheduledTaskAttachment(f.params.projectId,f.params.attachmentId);return _!==void 0?$6(g,_):g.code(404).send({code:"ATTACHMENT_NOT_FOUND",message:"Attachment not found"})}throw y}});}async function Yd(e,t,r,n){try{return await ui(e,t,r)}catch(i){if(i instanceof mt){let s=i.code==="PROJECT_NOT_FOUND"?404:400;await n.code(s).send({code:i.code,message:i.message});return}throw i}}async function zo(e,t,r){try{return await ui(e,t,r)}catch(n){throw n instanceof mt?new L(n.code==="PROJECT_NOT_FOUND"?"PROJECT_NOT_FOUND":"INVALID_REQUEST",n.message,n.code==="PROJECT_NOT_FOUND"?404:400):n}}function Qd(e){let{rootPath:t,...r}=e;return r}function nW(e,t,r){let{projectRepository:n,runIdempotent:i,activeGitMutations:s,pushProjectCommits:o,toGitCommitHttpError:a}=t;e.post("/v1/projects/:projectId/git/push",{schema:{body:lb,headers:X,params:ge,querystring:Y,response:{200:nb$1,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async c=>{let l=await zo(n,c.params.projectId,c.query.rootPath),u=`${c.params.projectId}\0${l}`;return i(["push-project-commits",u],c.headers["idempotency-key"],{request:c.body,rootPath:l},async()=>{let d=c.body.action!=="inspect";d&&(r(u),s.add(u));try{return await o(l,c.body)}catch(m){throw m instanceof pr?a(m):new L("GIT_PUSH_FAILED",qe(m,"Git push failed"),502)}finally{d&&s.delete(u);}})});}function qk(e){switch(e.code){case "SNAPSHOT_MISMATCH":return new L("GIT_STATUS_CHANGED","Git working tree changed",409,true);case "ALREADY_ACTIVE":return new L("GIT_WORKTREE_ALREADY_ACTIVE",e.message,409,true);case "WORKTREE_NOT_FOUND":return new L("GIT_WORKTREE_NOT_FOUND",e.message,409,true);case "INVALID_BRANCH_NAME":return new L("GIT_BRANCH_INVALID",e.message,400,false);case "REPOSITORY_READ_ONLY":return new L("GIT_REPOSITORY_READ_ONLY",e.message,409,true);case "CREATE_FAILED":return new L("GIT_WORKTREE_CREATE_FAILED",e.message,502,true)}}function sW(e,t){let{activeGitMutations:r,createProjectWorktree:n,projectRepository:i,readProjectGitStatus:s,readProjectWorktrees:o,resolveProjectWorktree:a,runIdempotent:c}=t,l=m=>{if(r.has(m))throw new L("GIT_MUTATION_IN_PROGRESS","Another Git mutation is already in progress",409,true)},u=async(m,p)=>{try{return await ui(i,m,p)}catch(h){throw h instanceof mt?new L(h.code==="PROJECT_NOT_FOUND"?"PROJECT_NOT_FOUND":"INVALID_REQUEST",h.message,h.code==="PROJECT_NOT_FOUND"?404:400):h}},d=async m=>{let[p,h]=await Promise.all([i.list(),o(m)]);return {projects:{data:p,nextCursor:null},worktrees:h}};e.get("/v1/projects/:projectId/git/worktrees",{schema:{params:ge,querystring:Y,response:{200:cb,400:le,404:le,500:le}}},async(m,p)=>{try{let h=await ui(i,m.params.projectId,m.query.rootPath);return await o(h)}catch(h){if(h instanceof mt){let f=h.code==="PROJECT_NOT_FOUND"?404:400;return p.code(f).send({code:h.code,message:h.message})}return p.code(500).send({code:"GIT_WORKTREE_LIST_FAILED",message:qe(h,"Git worktree list failed")})}}),e.post("/v1/projects/:projectId/git/task-worktrees",{schema:{body:db$1,headers:X,params:ge,querystring:Y,response:{200:hb,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async m=>{let p=await u(m.params.projectId,m.query.rootPath),h=`${m.params.projectId}\0${p}`;return c(["create-task-worktree",h],m.headers["idempotency-key"],{request:m.body,rootPath:p},async()=>{l(h),r.add(h);try{return {worktree:await n(p,m.body)}}catch(f){throw f instanceof Gt?qk(f):new L("GIT_WORKTREE_CREATE_FAILED",qe(f,"Git worktree creation failed"),502,true)}finally{r.delete(h);}})}),e.post("/v1/projects/:projectId/git/worktrees",{schema:{body:db$1,headers:X,params:ge,querystring:Y,response:{200:gb,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async m=>{let p=await u(m.params.projectId,m.query.rootPath),h=`${m.params.projectId}\0${p}`;return c(["create-project-worktree",h],m.headers["idempotency-key"],{request:m.body,rootPath:p},async()=>{l(h),r.add(h);try{let f=await n(p,m.body),g=await i.register({idempotencyKey:m.headers["idempotency-key"],name:basename(f.path),roots:[{path:f.path}]}),[y,_]=await Promise.all([d(p),s(p)]);return {project:g,...y,status:_,worktree:f}}catch(f){throw f instanceof Gt?qk(f):new L("GIT_WORKTREE_CREATE_FAILED",qe(f,"Git worktree creation failed"),502,true)}finally{r.delete(h);}})}),e.post("/v1/projects/:projectId/git/worktree",{schema:{body:eb,headers:X,params:ge,querystring:Y,response:{200:fb,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async m=>{let p=await u(m.params.projectId,m.query.rootPath);return c(["switch-project-worktree",m.params.projectId,p],m.headers["idempotency-key"],{request:m.body,rootPath:p},async()=>{try{let h=await a(p,m.body.path);return {project:await i.register({idempotencyKey:m.headers["idempotency-key"],name:basename(h.path),roots:[{path:h.path}]}),...await d(p),worktree:h}}catch(h){throw h instanceof Gt?qk(h):new L("PROVIDER_ERROR",qe(h,"Git worktree switch failed"),502,true)}})});}function Uk(e){switch(e.code){case "SNAPSHOT_MISMATCH":return new L("GIT_STATUS_CHANGED","Git working tree changed",409,true);case "ALREADY_ACTIVE":return new L("GIT_BRANCH_ALREADY_ACTIVE",e.message,409,true);case "BRANCH_ALREADY_EXISTS":return new L("GIT_BRANCH_ALREADY_EXISTS",e.message,409,true);case "BRANCH_NOT_FOUND":return new L("GIT_BRANCH_NOT_FOUND",e.message,409,true);case "INVALID_BRANCH_NAME":return new L("GIT_BRANCH_INVALID",e.message,400,false);case "REPOSITORY_READ_ONLY":return new L("GIT_REPOSITORY_READ_ONLY",e.message,409,true);case "SWITCH_FAILED":return new L("GIT_BRANCH_SWITCH_FAILED",e.message,502,true);case "CREATE_FAILED":return new L("GIT_BRANCH_CREATE_FAILED",e.message,502,true)}}function oW(e,t){let{activeGitMutations:r,assertCommitSelection:n,buildCommitMessagePrompt:i,commitProjectChanges:s,createProjectBranch:o,generateCommitMessageWithCodex:a,getProjectContext:c,listModels:l,projectRepository:u,readEffectiveGlobalSettings:d,readProjectGitHistory:m,readProjectGitCommitFiles:p,readProjectGitCommitFileDiff:h,readProjectGitStatus:f,runIdempotent:g,switchProjectBranch:y,toGitCommitHttpError:_}=t;sW(e,t);let v=E=>{if(r.has(E))throw new L("GIT_MUTATION_IN_PROGRESS","Another Git mutation is already in progress",409,true)};nW(e,t,v),e.get("/v1/projects/:projectId/git/status",{schema:{params:ge,querystring:Sa,response:{200:Ra,400:le,404:le,500:le}}},async(E,R)=>{let P=await Yd(u,E.params.projectId,E.query.rootPath,R);if(P!==void 0)try{return await f(P,Qd(E.query))}catch(b){return b instanceof jo?R.code(404).send({code:"GIT_REPOSITORY_NOT_FOUND",message:b.message}):R.code(500).send({code:"GIT_STATUS_UNAVAILABLE",message:qe(b,"Git working tree status is unavailable")})}}),e.get("/v1/projects/:projectId/git/history",{schema:{params:ge,querystring:Ua,response:{200:Va,400:le,404:le,500:le}}},async(E,R)=>{let P=await Yd(u,E.params.projectId,E.query.rootPath,R);if(P!==void 0)try{return await m(P,Qd(E.query))}catch(b){return b instanceof Cs&&b.code==="INVALID_CURSOR"?R.code(400).send({code:"INVALID_REQUEST",message:b.message}):b instanceof Cs&&b.code==="REPOSITORY_NOT_FOUND"?R.code(404).send({code:"GIT_REPOSITORY_NOT_FOUND",message:b.message}):R.code(500).send({code:"GIT_HISTORY_UNAVAILABLE",message:qe(b,"Git history is unavailable")})}});let w=(E,R)=>E instanceof Cn&&E.code==="INVALID_CURSOR"?R.code(400).send({code:"INVALID_REQUEST",message:E.message}):E instanceof Cn&&E.code==="REPOSITORY_NOT_FOUND"?R.code(404).send({code:"GIT_REPOSITORY_NOT_FOUND",message:E.message}):R.code(500).send({code:"GIT_COMMIT_REVIEW_UNAVAILABLE",message:qe(E,"Git commit review is unavailable")});e.get("/v1/projects/:projectId/git/commit-files",{schema:{params:ge,querystring:Wa,response:{200:Ya,400:le,404:le,500:le}}},async(E,R)=>{let P=await Yd(u,E.params.projectId,E.query.rootPath,R);if(P!==void 0)try{return await p(P,Qd(E.query))}catch(b){return w(b,R)}}),e.get("/v1/projects/:projectId/git/commit-diff",{schema:{params:ge,querystring:Za,response:{200:_a,400:le,404:le,500:le}}},async(E,R)=>{let P=await Yd(u,E.params.projectId,E.query.rootPath,R);if(P!==void 0)try{return await h(P,Qd(E.query))}catch(b){return w(b,R)}}),e.post("/v1/projects/:projectId/git/branch",{schema:{body:$a,headers:X,params:ge,querystring:Y,response:{200:Ra,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async E=>{let R=await zo(u,E.params.projectId,E.query.rootPath),P=`${E.params.projectId}\0${R}`;return g(["switch-project-branch",P],E.headers["idempotency-key"],{request:E.body,rootPath:R},async()=>{v(P),r.add(P);try{return await y(R,E.body)}catch(b){throw b instanceof Er?Uk(b):new L("GIT_BRANCH_SWITCH_FAILED",qe(b,"Git branch switch failed"),502,true)}finally{r.delete(P);}})}),e.post("/v1/projects/:projectId/git/branches",{schema:{body:ab,headers:X,params:ge,querystring:Y,response:{200:Ra,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async E=>{let R=await zo(u,E.params.projectId,E.query.rootPath),P=`${E.params.projectId}\0${R}`;return g(["create-project-branch",P],E.headers["idempotency-key"],{request:E.body,rootPath:R},async()=>{v(P),r.add(P);try{return await o(R,E.body)}catch(b){throw b instanceof Er?Uk(b):new L("GIT_BRANCH_CREATE_FAILED",qe(b,"Git branch creation failed"),502,true)}finally{r.delete(P);}})}),e.post("/v1/projects/:projectId/git/commit-message",{schema:{body:ib,headers:X,params:ge,querystring:Y,response:{200:jb,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async E=>{let R=await c(E.params.projectId);if(R===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let P=await zo(u,E.params.projectId,E.query.rootPath);return g(["generate-commit-message",E.params.projectId,P],E.headers["idempotency-key"],{request:E.body,rootPath:P},async()=>{let b=await f(P,{includeDiff:true,...E.body.repository===void 0?{}:{repository:E.body.repository}}).catch(q=>{throw new L("GIT_REPOSITORY_UNAVAILABLE",qe(q,"Git repository is unavailable"),409)});n(b,E.body);let O=await l(),F=await d(O),N={approvalPolicy:"never",approvalsReviewer:"user",...Mi(O,{model:F.commitMessageModel,sandboxMode:"read-only"},"read-only")};return {message:await a(R.provider,i(b,E.body,F.commitMessagePrompt),N),snapshot:b.snapshot}})}),e.post("/v1/projects/:projectId/git/commits",{schema:{body:kb,headers:X,params:ge,querystring:Y,response:{201:ob,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(E,R)=>{let P=await zo(u,E.params.projectId,E.query.rootPath),b=`${E.params.projectId}\0${P}`,O=await g(["commit-project-changes",b],E.headers["idempotency-key"],{request:E.body,rootPath:P},async()=>{v(b),r.add(b);try{let F=await s(P,E.body),j=E.body.repository,[N,M]=await Promise.all([m(P,j?{repository:j}:{}),f(P,j?{repository:j}:{})]);return {...F,history:N,status:M}}catch(F){throw F instanceof pr?_(F):new L("GIT_COMMIT_FAILED",qe(F,"Git commit failed"),502)}finally{r.delete(b);}});return R.code(201).send(O)});}function aW(e,t){e.post("/v1/project-directories",{schema:{body:_,headers:X,response:{200:$,400:Xf,409:Xf}}},async r=>t.runIdempotent(["create-project-directory"],r.headers["idempotency-key"],r.body,async()=>{if(!Z(r.body.name))throw new L("INVALID_REQUEST","Invalid folder name",400);try{let n=await t.resolveProjectDirectory(r.body.parentPath),i=join(n,r.body.name);try{return await mkdir(i),{path:i,status:"created"}}catch(s){if(s.code!=="EEXIST")throw s;let o=await lstat(i);return {path:i,status:o.isDirectory()?"exists-directory":"exists-file"}}}catch{throw new L("INVALID_REQUEST","Folder could not be created; check the parent directory and permissions",400)}}));}var cW=(e,t,r)=>{aW(e,t);let{assertValidProjectDefaults:n,getProjectContext:i,listModels:s,projectOpenService:o,projectRepository:a,readEffectiveProjectDefaults:c,readHostFileDirectory:l,readProjectDirectory:u,releaseProjectContext:d,runIdempotent:m,resolveProjectDirectory:p,settingsRepository:h}=t,f=async()=>({data:await a.list(),nextCursor:null});e.get("/v1/projects",{schema:{response:{200:Ce}}},f),e.get("/v1/host-files",{schema:{querystring:ya$1,response:{200:Aa,400:Xf}}},async g=>{try{return await l(g.query.kind,g.query.path,{...g.query.includeHidden===void 0?{}:{includeHidden:g.query.includeHidden}})}catch(y){throw y instanceof mr?new L("INVALID_REQUEST",y.message,400):y}}),e.get("/v1/project-directories",{schema:{querystring:ta,response:{200:wa,400:Xf}}},async g=>{try{return await u(g.query.path,{...g.query.includeHidden===void 0?{}:{includeHidden:g.query.includeHidden}})}catch(y){throw y instanceof Vr?new L("INVALID_REQUEST",y.message,400):y}}),e.get("/v1/projects/:projectId/open-capabilities",{schema:{params:ge,response:{200:Ia,404:le}}},async(g,y)=>await a.read(g.params.projectId)===void 0?y.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):o.getCapabilities()),e.post("/v1/projects/:projectId/open",{schema:{body:Ja$1,headers:X,params:ge,querystring:Y,response:{200:Ka,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async g=>m(["open-project",g.params.projectId],g.headers["idempotency-key"],{request:g.body,rootPath:g.query.rootPath},async()=>{let y;try{y=await ui(a,g.params.projectId,g.query.rootPath);}catch(_){throw _ instanceof mt?new L(_.code==="PROJECT_NOT_FOUND"?"PROJECT_NOT_FOUND":"INVALID_REQUEST",_.message,_.code==="PROJECT_NOT_FOUND"?404:400):_}try{await o.open(y,g.body.appId,g.body.path);}catch(_){throw _ instanceof Ns?new L("INVALID_REQUEST","Project open app is unavailable",409):_ instanceof gr?new L("INVALID_REQUEST","Project open target is invalid",400):new L("PROVIDER_ERROR","Project could not be opened",502,true)}return g.body})),e.put("/v1/projects/order",{schema:{body:La,headers:X,response:{200:De,400:Xf,409:Xf,502:Xf,503:Xf}}},async g=>m(["reorder-projects"],g.headers["idempotency-key"],g.body,async()=>{let y=await a.list(),_=new Set(y.map(w=>w.id));if(!(g.body.projectIds.length===y.length&&g.body.projectIds.every(w=>_.has(w))))throw new L("INVALID_REQUEST","Project order must contain every project exactly once",409);return {data:await a.reorder(g.body.projectIds),nextCursor:null}})),e.get("/v1/projects/:projectId/skills",{schema:{params:ge,response:{200:Ge$1,404:le}}},async(g,y)=>{let _=await i(g.params.projectId);return _===void 0?y.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):_.provider.listSkills()}),e.get("/v1/projects/:projectId/defaults",{schema:{params:ge,response:{200:Ed,404:le}}},async(g,y)=>await i(g.params.projectId)===void 0?y.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):{settings:await c(g.params.projectId)}),e.put("/v1/projects/:projectId/defaults",{schema:{body:Dd$1,headers:X,params:ge,response:{200:Ed,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async g=>m(["update-project-defaults",g.params.projectId],g.headers["idempotency-key"],g.body,async()=>{if(await i(g.params.projectId)===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);return n(await s(),g.body),{settings:await h.writeProjectDefaults(g.params.projectId,g.body)}})),e.post("/v1/projects",{schema:{body:Ca,headers:X,response:{200:Da,400:Xf,409:Xf,502:Xf,503:Xf}}},async g=>m(["add-project"],g.headers["idempotency-key"],g.body,async()=>{let y;try{y=await Promise.all(g.body.roots.map(v=>p(v.path)));}catch(v){throw v instanceof Vr?new L("INVALID_REQUEST",v.message,400):v}return {project:await a.register({idempotencyKey:g.headers["idempotency-key"],name:basename(y[0]??""),roots:y.map(v=>({path:v}))}),projects:await f()}})),e.post("/v1/projects/:projectId/rename",{schema:{body:Ma,headers:X,params:ge,response:{200:Na,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async g=>m(["rename-project",g.params.projectId],g.headers["idempotency-key"],g.body,async()=>{let y=await a.rename(g.params.projectId,g.body.name.trim());if(y===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);return {project:y,projects:await f()}})),e.post("/v1/projects/:projectId/remove",{schema:{body:Oa,headers:X,params:ge,response:{200:Pa,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async g=>m(["remove-project",g.params.projectId],g.headers["idempotency-key"],g.body,async()=>{if(!await a.remove(g.params.projectId))throw new L("PROJECT_NOT_FOUND","Project not found",404);return await d(g.params.projectId),{projectId:g.params.projectId,projects:await f(),status:"removed"}})),oW(e,t),rW(e,t),F6(e,t),r();};function lW(e){return e.trim().replace(/\/+$/u,"")}function V1e(e,t){return e!==null&&lW(e)===lW(t)}function W1e(e){return {data:e.data.map(t=>({...t,supportedReasoningEfforts:[...t.supportedReasoningEfforts]})),nextCursor:e.nextCursor}}async function uW(e,t){if(e.models!==void 0&&e.models.length>0)return;let r=await t.readProviderConnection().catch(()=>{});if(r?.mode==="custom"&&V1e(r.customBaseUrl,e.baseUrl)&&r.customModels!==null&&r.customModels.data.length>0)return o(W1e(r.customModels))}var Xy={400:Xf,409:Xf,502:Xf,503:Xf},dW=(e,t,r)=>{let{modelCatalogCache:n,provider:i,providerConnectionRepository:s,runIdempotent:o}=t;e.get("/v1/provider-connection",{schema:{response:{200:Ne}}},()=>i.readProviderConnection()),e.post("/v1/provider-connection/official-login",{schema:{body:Oe,headers:X,response:{200:Pe,...Xy}}},a=>o(["start-official-provider-login"],a.headers["idempotency-key"],a.body,async()=>{let c=await i.startOfficialProviderLogin();return await s.writeProviderConnection({customBaseUrl:null,customModels:null,mode:"official",updatedAt:new Date().toISOString()}),n.clear(),c})),e.post("/v1/provider-connection/official-login/cancel",{schema:{body:Se$1,headers:X,response:{200:Te,...Xy}}},a=>o(["cancel-provider-login",a.body.loginId],a.headers["idempotency-key"],a.body,()=>i.cancelProviderLogin(a.body.loginId))),e.put("/v1/provider-connection/custom",{schema:{body:Qe$1,headers:X,response:{200:Re,...Xy}}},a=>o(["configure-custom-provider"],a.headers["idempotency-key"],a.body,async()=>{let c=await i.configureCustomProvider(a.body,()=>uW(a.body,s));return await s.writeProviderConnection({customBaseUrl:c.status.customBaseUrl,customModels:c.models,mode:"custom",updatedAt:new Date().toISOString()}),n.replace(c.models),c})),e.post("/v1/provider-connection/logout",{schema:{body:Oe,headers:X,response:{200:Te,...Xy}}},a=>o(["logout-provider"],a.headers["idempotency-key"],a.body,async()=>{let c=await i.logoutProvider();return n.clear(),c})),r();};var Y1e={additionalProperties:false,properties:{assetId:{pattern:"^[a-f0-9]{64}$",type:"string"}},required:["assetId"],type:"object"},fW=(e,{petProvider:t,runIdempotent:r},n)=>{e.get("/v1/pets",{schema:{response:{200:fa,500:le}}},async(i,s)=>{try{return {data:await t.listPets()}}catch{return s.code(500).send({code:"PET_CATALOG_UNAVAILABLE",message:"Pet catalog is unavailable"})}}),e.get("/v1/pets/assets/:assetId",{schema:{params:Y1e,response:{404:le,422:le,500:le}}},async(i,s)=>{try{let o=await t.openPetAsset(i.params.assetId);return o===void 0?await s.code(404).send({code:"PET_NOT_FOUND",message:"Pet asset not found"}):(s.header("Cache-Control","private, no-cache").header("Cross-Origin-Resource-Policy","same-origin").header("ETag",o.etag).header("X-Content-Type-Options","nosniff"),i.headers["if-none-match"]===o.etag?await s.code(304).send():await s.type(o.contentType).send(Buffer$1.from(o.content)))}catch(o){return o instanceof a$1&&o.code==="invalid"?await s.code(422).send({code:"PET_ASSET_INVALID",message:"Pet asset is invalid"}):await s.code(500).send({code:"PET_ASSET_UNAVAILABLE",message:"Pet asset is unavailable"})}}),e.post("/v1/pets/downloads",{schema:{body:ga,headers:X,response:{200:ha,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async i=>r(["download-workbench-pet",i.body.petId],i.headers["idempotency-key"],i.body,async()=>{try{return await t.ensurePetAsset(i.body.petId),{pets:{data:await t.listPets()}}}catch(s){if(s instanceof a$1){if(s.code==="not_found")throw new L("PET_NOT_FOUND","Pet not found",404);if(s.code==="invalid")throw new L("PET_ASSET_INVALID","Pet cannot be downloaded",400)}throw new L("PET_DOWNLOAD_FAILED","Pet asset download failed",502,true)}})),n();};var J1e=["approvalPolicy","approvalsReviewer","model","modelContextWindow","reasoningEffort","sandboxMode","fastMode"];function hW(e){let t=Promise.resolve();return r=>{let n=t.catch(()=>{}).then(async()=>{let i=await e.readEffectiveGlobalSettings(),s=Object.fromEntries(J1e.filter(o=>!isDeepStrictEqual(i[o],r[o])).map(o=>[o,r[o]]));return Object.keys(s).length>0&&await e.provider.updateDefaultSettings(s),await e.settingsRepository.writeGlobalSettings(r),e.readEffectiveGlobalSettings()});return t=n,n}}var Bk="https://www.bing.com",X1e=`${Bk}/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN`,pW=1e4,Z1e=64*1024,eNe=20*1024*1024;function tNe(e,t){return globalThis.fetch(e,t)}async function Jd(e,t,r){if(!e.ok||e.body===null)throw new Error(`Bing wallpaper ${r} request failed`);let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>t)throw new Error(`Bing wallpaper ${r} response is too large`);let i=[],s=0,o=e.body.getReader(),a=await o.read();for(;!a.done;){let c=a.value;if(s+=c.byteLength,s>t)throw await o.cancel(),new Error(`Bing wallpaper ${r} response is too large`);i.push(Buffer.from(c)),a=await o.read();}return Buffer.concat(i,s)}function rNe(e){let t;try{t=JSON.parse(e.toString("utf8"));}catch{throw new Error("Bing wallpaper returned invalid metadata")}let r=mW(t)?t.images:null,n=Array.isArray(r)?r[0]:null,i=mW(n)?n.url:null;if(typeof i!="string"||!i.startsWith("/"))throw new Error("Bing wallpaper returned an invalid image URL");let s=new URL(i,Bk);if(s.origin!==Bk||s.pathname!=="/th")throw new Error("Bing wallpaper returned an invalid image URL");return s.toString()}function mW(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function nNe(e){let t=await e(X1e,{headers:{"user-agent":ia},redirect:"error",signal:AbortSignal.timeout(pW)});if(!t.headers.get("content-type")?.startsWith("application/json"))throw new Error("Bing wallpaper returned invalid metadata content type");let r=await Jd(t,Z1e,"metadata"),n=rNe(r),i=await e(n,{headers:{"user-agent":ia},redirect:"error",signal:AbortSignal.timeout(pW)});if(!i.headers.get("content-type")?.startsWith("image/jpeg"))throw new Error("Bing wallpaper returned invalid image content type");let s=await Jd(i,eNe,"image");if(s.length<4||s[0]!==255||s[1]!==216||s[2]!==255)throw new Error("Bing wallpaper returned invalid JPEG content");return {body:s,contentType:"image/jpeg"}}function gW({fetcher:e=tNe}={}){let t=null,r=null,n=0;return {read(i){if(t?.day===i)return Promise.resolve(t.wallpaper);if(r?.day===i)return r.promise;let s=++n,o=nNe(e).then(c=>(s===n&&(t={day:i,wallpaper:c}),c));r={day:i,promise:o};let a=()=>{r?.promise===o&&(r=null);};return o.then(a,a),o}}}var Hk="https://www.bing.com",iNe=`${Hk}/HPImageArchive.aspx?format=js&idx=0&n=8&mkt=zh-CN`;function sNe(e){if(!e||typeof e!="object"||!("images"in e)||!Array.isArray(e.images))throw new Error("Invalid Bing wallpaper catalog");return e.images.slice(0,9).map(t=>{if(!t||typeof t!="object"||!("startdate"in t)||typeof t.startdate!="string"||!/^\d{8}$/u.test(t.startdate)||!("url"in t)||typeof t.url!="string"||!t.url.startsWith("/"))throw new Error("Invalid Bing wallpaper entry");let r=new URL(t.url,Hk);if(r.origin!==Hk||r.pathname!=="/th")throw new Error("Invalid Bing wallpaper URL");return {day:`${t.startdate.slice(0,4)}-${t.startdate.slice(4,6)}-${t.startdate.slice(6)}`,title:"title"in t&&typeof t.title=="string"?t.title:"",copyright:"copyright"in t&&typeof t.copyright=="string"?t.copyright:"",url:r.toString()}})}function yW(e=(t,r)=>fetch(t,r)){let t=[],r=0,n,i=new Map,s=()=>Date.now()<r?Promise.resolve(t):n||(n=(async()=>{let o=await e(iNe,{headers:{"user-agent":ia},redirect:"error",signal:AbortSignal.timeout(1e4)});if(!o.headers.get("content-type")?.startsWith("application/json"))throw new Error("Invalid Bing metadata content type");let a=sNe(JSON.parse((await Jd(o,64*1024,"catalog")).toString("utf8")));return t=a,r=Date.now()+60*6e4,i.clear(),a})().finally(()=>{n=void 0;}),n);return {async list(){return (await s()).map(({day:o,title:a,copyright:c})=>({day:o,title:a,copyright:c}))},async read(o,a){let l=(await s()).find(p=>p.day===o);if(!l)throw Object.assign(new Error("Bing wallpaper is no longer available"),{statusCode:404});let u=`${o}:${String(a)}`,d=i.get(u);if(d)return d;let m=(async()=>{let p=new URL(l.url);a&&(p.searchParams.set("w","480"),p.searchParams.set("h","270"));let h=await e(p.toString(),{headers:{"user-agent":ia},redirect:"error",signal:AbortSignal.timeout(1e4)});if(!h.headers.get("content-type")?.startsWith("image/jpeg"))throw new Error("Invalid Bing image content type");let f=await Jd(h,a?2*1024*1024:20*1024*1024,"image");if(f.length<4||f[0]!==255||f[1]!==216||f[2]!==255)throw new Error("Invalid Bing JPEG content");return f})();return i.set(u,m),m.then(()=>{a||i.delete(u);},()=>{i.delete(u);}),m}}}var oNe=15e4,aNe={additionalProperties:false,properties:{day:{pattern:"^\\d{4}-\\d{2}-\\d{2}$",type:"string"}},required:["day"],type:"object"},wW=(e,t,r)=>{let n=gW(),i=yW();e.get("/v1/workbench-background/bing/catalog",{schema:{response:{200:Gg}}},()=>i.list()),e.get("/v1/workbench-background/bing/image",{schema:{querystring:{type:"object",additionalProperties:false,required:["day"],properties:{day:{type:"string",pattern:"^\\d{4}-\\d{2}-\\d{2}$"},thumbnail:{type:"boolean"}}}}},async(g,y)=>y.type("image/jpeg").send(await i.read(g.query.day,g.query.thumbnail??false)));let{assertValidProjectDefaults:s,capabilities:o,installAppUpdate:a,listModels:c,modelCatalogCache:l,projectContexts:u,readAppInfo:d,readAppUpdateProgress:m,readEffectiveGlobalSettings:p,runIdempotent:h}=t,f=hW(t);e.get("/v1/health",{schema:{response:{200:He}}},()=>({status:"ok",version:1})),e.get("/v1/app-info",{schema:{response:{200:pc}}},()=>d()),e.get("/v1/app-update/progress",{schema:{response:{200:oc}}},()=>m()),e.get("/v1/workbench-background/bing",{schema:{querystring:aNe}},async(g,y)=>{let _=await n.read(g.query.day);return y.type(_.contentType).send(_.body)}),e.post("/v1/app-update",{handlerTimeout:oNe,schema:{body:qc,headers:X,response:{200:rc,400:Xf,409:Xf,502:Xf,503:Xf}}},async g=>h(["install-app-update"],g.headers["idempotency-key"],g.body,async()=>{try{return await a(g.body.version)}catch(y){let _=typeof y=="object"&&y!==null&&"code"in y&&(y.code==="UPDATE_NOT_AVAILABLE"||y.code==="UPDATE_CHECK_FAILED"||y.code==="UPDATE_INSTALL_FAILED")?y.code:"UPDATE_INSTALL_FAILED";throw new L(_,y instanceof Error?y.message:"Failed to install the Codexly update",_==="UPDATE_NOT_AVAILABLE"?409:502,_!=="UPDATE_NOT_AVAILABLE")}})),e.get("/v1/metrics/events",{schema:{response:{200:xg$1}}},()=>({projects:[...u.values()].map(g=>({...g.eventStream.metrics,activeClients:g.transportMetrics.activeClients,projectId:g.scope.id,slowClientDisconnects:g.transportMetrics.slowClientDisconnects})),version:1})),e.get("/v1/capabilities",{schema:{response:{200:Ie}}},()=>o),e.get("/v1/models",{schema:{response:{200:Fe$1}}},()=>l.read()),e.get("/v1/settings",{schema:{response:{200:Cd}}},async()=>({settings:await p()})),e.put("/v1/settings",{preValidation:(g,y,_)=>{let v=g.body?.modelContextWindow;if(v!=null&&(typeof v!="number"||!Number.isSafeInteger(v)||v<1))throw new L("INVALID_REQUEST","modelContextWindow must be a positive safe integer or null",400);_();},schema:{body:Bd,headers:X,response:{200:Cd,400:Xf,409:Xf,502:Xf,503:Xf}}},async g=>h(["update-global-settings"],g.headers["idempotency-key"],g.body,async()=>(s(await c(),g.body),{settings:await f(g.body)}))),r();};async function vW(e,t,r,n){let i$1=e.asyncQuestionRepository;if(i$1===void 0)return n;let s=await i$1.listAsyncQuestions(t,r);return i(n,s)}function _W(e,t){let{assertValidProjectDefaults:r,getProjectContext:n,listModels:i,readEffectiveTaskSettings:s,runIdempotent:o,settingsRepository:a}=t;e.get("/v1/projects/:projectId/tasks/:taskId/settings",{schema:{params:Fe,response:{200:Fd,404:le}}},async(c,l)=>{let u=await n(c.params.projectId);return u===void 0?l.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):(await u.provider.readTask(c.params.taskId))?.projectId!==u.scope.id?l.code(404).send({code:"TASK_NOT_FOUND",message:"Task not found"}):{settings:await s(c.params.projectId,c.params.taskId)}}),e.put("/v1/projects/:projectId/tasks/:taskId/settings",{schema:{body:zd,headers:X,params:Fe,response:{200:Fd,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async c=>o(["update-task-settings",c.params.projectId,c.params.taskId],c.headers["idempotency-key"],c.body,async()=>{let l=await n(c.params.projectId);if(l===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let u=await l.provider.readTask(c.params.taskId);if(u?.projectId!==l.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let d=c.body;r(await i(),d);let m=u.turns.findLast(p=>p.status==="running");return m!==void 0&&(await s(c.params.projectId,c.params.taskId)).approvalsReviewer!==d.approvalsReviewer&&await l.provider.updateTurnApprovalsReviewer(c.params.taskId,m.id,d.approvalsReviewer),{settings:await a.writeTaskSettings(c.params.projectId,c.params.taskId,d)}})),e.post("/v1/projects/:projectId/tasks/:taskId/mcp-servers/retry",{schema:{body:Df,headers:X,params:Fe,response:{200:Ef,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async c=>o(["reload-task-mcp-servers",c.params.projectId,c.params.taskId],c.headers["idempotency-key"],c.body,async()=>{let l=await n(c.params.projectId);if(l===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await l.provider.readTask(c.params.taskId))?.projectId!==l.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);try{return await l.provider.reloadMcpServers(c.params.taskId)}catch(d){throw Vm(d)}})),e.post("/v1/projects/:projectId/tasks/:taskId/review",{schema:{body:xf$1,headers:X,params:Fe,response:{201:yf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(c,l)=>{let u=await o(["review-task",c.params.projectId,c.params.taskId],c.headers["idempotency-key"],c.body,async()=>{let d=await n(c.params.projectId);if(d===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await d.provider.readTask(c.params.taskId))?.projectId!==d.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return d.provider.startReview(c.params.taskId,c.body.target)});return l.code(201).send({taskId:c.params.taskId,turn:u})}),e.post("/v1/projects/:projectId/tasks/:taskId/compact",{schema:{body:zf,headers:X,params:Fe,response:{202:Af,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(c,l)=>{let u=await o(["compact-task",c.params.projectId,c.params.taskId],c.headers["idempotency-key"],c.body,async()=>{let d=await n(c.params.projectId);if(d===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await d.provider.readTask(c.params.taskId))?.projectId!==d.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return await d.provider.compactTask(c.params.taskId),{status:"compacting",taskId:c.params.taskId}});return l.code(202).send(u)}),e.post("/v1/projects/:projectId/tasks/:taskId/fork",{schema:{body:Bf,headers:X,params:Fe,response:{201:Cf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(c,l)=>{let u=await o(["fork-task",c.params.projectId,c.params.taskId],c.headers["idempotency-key"],c.body,async()=>{let d=await n(c.params.projectId);if(d===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await d.provider.readTask(c.params.taskId))?.projectId!==d.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return d.provider.forkTask(c.params.taskId,c.body.lastTurnId)});return l.code(201).send({task:u})}),e.post("/v1/projects/:projectId/tasks/:taskId/feedback",{schema:{body:Ff,headers:X,params:Fe,response:{200:Gf$1,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async c=>o(["feedback-task",c.params.projectId,c.params.taskId],c.headers["idempotency-key"],c.body,async()=>{let l=await n(c.params.projectId);if(l===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await l.provider.readTask(c.params.taskId))?.projectId!==l.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return await l.provider.uploadFeedback(c.params.taskId,c.body),{status:"sent",taskId:c.params.taskId}}));}function bW(e,{attachmentStore:t,getProjectContext:r,projectOpenService:n,runIdempotent:i}){e.get("/v1/projects/:projectId/tasks/:taskId/attachments/:attachmentId",{schema:{params:bT,response:{404:le}}},async(s,o)=>{let a=await r(s.params.projectId);if(a===void 0)return o.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"});let c=await a.provider.readTaskAttachment(s.params.taskId,s.params.attachmentId);if(c===void 0){if((await a.provider.readTask(s.params.taskId))?.projectId!==a.scope.id)return o.code(404).send({code:"TASK_NOT_FOUND",message:"Task not found"});try{let m=await t.readSubmitted(s.params.projectId,s.params.attachmentId);c={...m.attachment,content:m.content};}catch(m){if(m instanceof er)return o.code(404).send({code:"ATTACHMENT_NOT_FOUND",message:"Attachment not found"});throw m}}let l=Buffer$1.from(c.content),u=(c.mediaType==="application/pdf"||/\.pdf$/iu.test(c.name))&&l.subarray(0,5).toString("ascii")==="%PDF-";return u&&o.header("content-disposition",Dc(c.name).replace(/^attachment/u,"inline")),Jy(o,{content:l,mediaType:u?"application/pdf":c.mediaType},300,s.headers["if-none-match"])}),e.post("/v1/projects/:projectId/tasks/:taskId/attachments/:attachmentId/open",{schema:{body:Ub,headers:X,params:bT,response:{200:Vb,400:Xf,404:Xf,409:Xf,502:Xf}}},async s=>i(["open-task-attachment",s.params.projectId,s.params.taskId,s.params.attachmentId],s.headers["idempotency-key"],{},async()=>{let o=await r(s.params.projectId);if(o===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let a=await o.provider.readTask(s.params.taskId);if(a?.projectId!==o.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let c=await o.provider.readTaskAttachment(s.params.taskId,s.params.attachmentId),l=a.turns.flatMap(u=>u.items).filter(u=>u.type==="message").flatMap(u=>u.attachments??[]).find(u=>u.id===s.params.attachmentId)?.kind;if(c===void 0)try{let u=await t.readSubmitted(s.params.projectId,s.params.attachmentId);c={...u.attachment,content:u.content},l=u.attachment.kind;}catch(u){throw u instanceof er?new L("INVALID_REQUEST","Attachment not found",404):u}if(l!=="file")throw new L("INVALID_REQUEST","Attachment cannot be opened",400);try{let u=await t.add(s.params.projectId,{content:Readable.from([Buffer$1.from(c.content)]),kind:"file",mediaType:c.mediaType,name:c.name}),[d]=await t.resolve(s.params.projectId,[u.attachment.id]);if(d?.kind!=="file")throw new TypeError("Attachment copy is not a file");await n.open(o.scope.rootPath,"system-default",d.path);}catch(u){throw u instanceof Ns?new L("INVALID_REQUEST","System application is unavailable",409):u instanceof gr||u instanceof TypeError?new L("INVALID_REQUEST","Attachment cannot be opened",400):new L("PROVIDER_ERROR","Attachment could not be opened",502,true)}return {attachmentId:s.params.attachmentId,status:"opened"}}));}function EW(e,t){let{getProjectContext:r,runIdempotent:n}=t;e.put("/v1/projects/:projectId/tasks/:taskId/goal",{schema:{body:te,headers:X,params:Fe,response:{200:ue,400:Xf,404:Xf,502:Xf,503:Xf}}},async i=>n(["update-goal",i.params.projectId,i.params.taskId],i.headers["idempotency-key"],i.body,async()=>{let s=await r(i.params.projectId);if(s===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await s.provider.readTask(i.params.taskId))?.projectId!==s.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return {goal:await s.provider.updateGoal(i.params.taskId,i.body)}})),e.delete("/v1/projects/:projectId/tasks/:taskId/goal",{schema:{body:{additionalProperties:false,properties:{},type:"object"},headers:X,params:Fe,response:{200:ve,400:Xf,404:Xf,502:Xf,503:Xf}}},async i=>n(["clear-goal",i.params.projectId,i.params.taskId],i.headers["idempotency-key"],i.body,async()=>{let s=await r(i.params.projectId);if(s===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await s.provider.readTask(i.params.taskId))?.projectId!==s.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return await s.provider.clearGoal(i.params.taskId),{cleared:true}}));}function TW(e,t){e.delete("/v1/projects/:projectId/tasks/archived",{schema:{params:ge,headers:X,body:jc$1,response:{200:kc$1,400:Xf,404:Xf}}},r=>t.runIdempotent(["delete-archived-tasks",r.params.projectId],r.headers["idempotency-key"],r.body,async()=>{let n=await t.getProjectContext(r.params.projectId);if(n===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);return j(n.provider,n.scope.id)}));}function RW(e,t){e.get("/v1/projects/:projectId/tasks/catalog",{schema:{params:ge,querystring:_if,response:{200:jf,404:le}}},async(r,n)=>{let i=await t.getProjectContext(r.params.projectId);return i===void 0?n.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):k$1(i.provider,i.scope.id,r.query)});}function PW(e,t){e.post("/v1/tasks/completed/query",{schema:{body:Yg,response:{200:Zg$1,400:le,404:le}}},async(r,n)=>{try{return await m$1(async i=>{let s=await t.getProjectContext(i);if(s===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);return s.provider},r.body)}catch(i){if(i instanceof l$1)return n.code(400).send({code:"INVALID_QUERY",message:i.message});throw i}});}function kW(e,t){e.put("/v1/projects/:projectId/tasks/:taskId/settings-and-defaults",{schema:{body:Gd,headers:X,params:Fe,response:{200:Hd,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},r=>t.runIdempotent(["update-task-settings-and-defaults",r.params.projectId,r.params.taskId],r.headers["idempotency-key"],r.body,async()=>{let n=await t.getProjectContext(r.params.projectId);if(n===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let i=await n.provider.readTask(r.params.taskId);if(i?.projectId!==n.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let{settings:s,fastMode:o}=r.body,a={...s,fastMode:o};t.assertValidProjectDefaults(await t.listModels(),a);let c=i.turns.findLast(d=>d.status==="running");c!==void 0&&(await t.readEffectiveTaskSettings(r.params.projectId,r.params.taskId)).approvalsReviewer!==s.approvalsReviewer&&await n.provider.updateTurnApprovalsReviewer(r.params.taskId,c.id,s.approvalsReviewer);let l=await t.settingsRepository.writeTaskSettings(r.params.projectId,r.params.taskId,s),u=await t.settingsRepository.writeProjectDefaults(r.params.projectId,a);return {settings:l,defaults:u}}));}var lNe=/thread.*(?:not loaded|not found|does not exist|deleted|archived)|no rollout found/iu;async function xW(e,t,r){let n=new Set,i;for(;;){let s=await e.listTasks({archived:true,limit:100,...r?{pinnedOnly:true}:{},...i===void 0?{}:{cursor:i}});if(s.data.some(o=>o.id===t))return true;if(s.nextCursor===null)return false;if(n.has(s.nextCursor))throw new Error("Task archive pagination did not advance");n.add(s.nextCursor),i=s.nextCursor;}}async function AW(e,t,r){let n;try{n=await e.readTask(r);}catch(i){let s=i instanceof Error?i.message:typeof i=="string"?i:"";if(lNe.test(s))return null;throw i}return n?.projectId!==t||await xW(e,r,false)||await xW(e,r,true)?null:n}function IW(e,t){e.get("/v1/projects/:projectId/tasks/:taskId/navigation",{schema:{params:Fe,response:{200:vg$1,404:le}}},async(r,n)=>{let i=await t.getProjectContext(r.params.projectId);if(i===void 0)return n.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"});let s=await AW(i.provider,i.scope.id,r.params.taskId);if(s===null)return {task:null};let o=await t.readEffectiveTaskSettings(r.params.projectId,r.params.taskId);return {task:{checkpoint:i.eventStream.checkpoint,snapshot:{...s,settings:o}}}});}var OW=(e,t,r)=>{let{getProjectContext:n,readEffectiveTaskSettings:i,runIdempotent:s,taskFromSnapshot:o}=t;e.get("/v1/projects/:projectId/tasks",{schema:{params:ge,querystring:tG,response:{200:Ee,404:le}}},async(a,c)=>{let l=await n(a.params.projectId);if(l===void 0)return c.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"});let u={...a.query.archived===true?{archived:true}:{},...a.query.completed===true?{completed:true}:{},...a.query.cursor===void 0?{}:{cursor:a.query.cursor},...a.query.limit===void 0?{}:{limit:a.query.limit},...a.query.pinned===true?{pinnedOnly:true}:{},...a.query.searchTerm===void 0?{}:{searchTerm:a.query.searchTerm}};return l.provider.listTasks(u)}),e.post("/v1/projects/:projectId/tasks/:taskId/unsubscribe",{schema:{params:Fe,response:{200:wf,404:le}}},async(a,c)=>{let l=await n(a.params.projectId);return l===void 0?c.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):{status:await l.provider.unsubscribeTask(a.params.taskId),taskId:a.params.taskId}}),e.get("/v1/projects/:projectId/tasks/:taskId",{schema:{params:Fe,querystring:rG,response:{200:ug$1,404:le}}},async(a,c)=>{let l=await n(a.params.projectId);if(l===void 0)return c.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"});let u=await l.provider.readTask(a.params.taskId,{...a.query.cursor===void 0?{}:{cursor:a.query.cursor}});if(u?.projectId!==l.scope.id)return c.code(404).send({code:"TASK_NOT_FOUND",message:"Task not found"});let d=await vW(t,a.params.projectId,a.params.taskId,u),m=l.eventStream.checkpoint,p=await i(a.params.projectId,a.params.taskId);return {checkpoint:m,snapshot:{...d,settings:p}}}),e.get("/v1/projects/:projectId/tasks/:taskId/mcp-servers",{schema:{params:Fe,response:{200:kd,404:le,502:Xf}}},async(a,c)=>{let l=await n(a.params.projectId);if(l===void 0)return c.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"});try{return await l.provider.listMcpServers(a.params.taskId)}catch(u){throw Vm(u)}}),e.get("/v1/projects/:projectId/tasks/:taskId/background-terminals",{schema:{params:Fe,response:{200:ac,404:le}}},async(a,c)=>{let l=await n(a.params.projectId);return l===void 0?c.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):l.provider.listBackgroundTerminals(a.params.taskId)}),e.post("/v1/projects/:projectId/tasks/:taskId/background-terminals/:terminalId/terminate",{schema:{body:{additionalProperties:false,properties:{},type:"object"},headers:X,params:ZH,response:{200:bc$1,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async a=>s(["terminate-background-terminal",a.params.projectId,a.params.taskId,a.params.terminalId],a.headers["idempotency-key"],a.body,async()=>{let c=await n(a.params.projectId);if(c===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await c.provider.readTask(a.params.taskId))?.projectId!==c.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);await c.provider.terminateBackgroundTerminal(a.params.taskId,a.params.terminalId);let u=await c.provider.listBackgroundTerminals(a.params.taskId);return {status:"terminated",terminalId:a.params.terminalId,terminals:u}})),e.put("/v1/projects/:projectId/tasks/:taskId/pin",{schema:{body:mf,headers:X,params:Fe,response:{200:nf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async a=>s(["pin-task",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>{let c=await n(a.params.projectId);if(c===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await c.provider.readTask(a.params.taskId))?.projectId!==c.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let u=await c.provider.pinTask(a.params.taskId,a.body.pinned);return {pinnedTasks:await k$1(c.provider,c.scope.id,{pinned:true}),task:u}})),e.post("/v1/projects/:projectId/tasks/:taskId/rename",{schema:{body:of,headers:X,params:Fe,response:{200:pf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async a=>s(["rename-task",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>{let c=await n(a.params.projectId);if(c===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let l=await c.provider.readTask(a.params.taskId);if(l?.projectId!==c.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let u=a.body.title.trim();await c.provider.renameTask(a.params.taskId,u);let d=o(l,{title:u}),m=await k$1(c.provider,c.scope.id);return {task:d,taskCatalog:m}})),e.post("/v1/projects/:projectId/tasks/:taskId/archive",{schema:{body:qf,headers:X,params:Fe,response:{200:rf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async a=>s(["archive-task",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>{let c=await n(a.params.projectId);if(c===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await c.provider.readTask(a.params.taskId))?.projectId!==c.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);await c.provider.archiveTask(a.params.taskId);let u=await c.provider.listTasks({limit:5});return {status:"archived",taskId:a.params.taskId,tasks:u}})),e.post("/v1/projects/:projectId/tasks/:taskId/unarchive",{schema:{body:sf,headers:X,params:Fe,response:{200:tf$1,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async a=>s(["unarchive-task",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>{let c=await n(a.params.projectId);if(c===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let l=await c.provider.unarchiveTask(a.params.taskId),u=await c.provider.listTasks({limit:5});return {task:l,tasks:u}})),e.delete("/v1/projects/:projectId/tasks/:taskId",{schema:{body:uf,headers:X,params:Fe,response:{200:vf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async a=>s(["delete-task",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>{let c=await n(a.params.projectId);if(c===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await c.provider.readTask(a.params.taskId))?.projectId!==c.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);await c.provider.deleteTask(a.params.taskId);let u=await c.provider.listTasks({limit:5});return {status:"deleted",taskId:a.params.taskId,tasks:u}})),_W(e,t),TW(e,t),RW(e,t),PW(e,t),kW(e,t),IW(e,t),bW(e,t),EW(e,t),r();};var CW=(e,t,r)=>{let{getProjectContext:n,projectRepository:i,provider:s}=t;e.get("/v1/search/tasks",{schema:{querystring:dc$1,response:{200:ic,503:le}}},async(o,a)=>{if(s.search===void 0)return a.code(503).send({code:"GLOBAL_SEARCH_UNAVAILABLE",message:"Global search is unavailable"});let c=await i.list(),l=[{id:we,kind:"temporary"},...c.map(u=>({id:u.id,kind:"project"}))];return s.search.searchTasks(o.query,l,o.signal)}),e.get("/v1/projects/:projectId/tasks/:taskId/search-occurrences",{schema:{params:Fe,querystring:gc,response:{200:hc,404:le,503:le}}},async(o,a)=>{let c=await n(o.params.projectId);return c===void 0?a.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):s.search===void 0?a.code(503).send({code:"GLOBAL_SEARCH_UNAVAILABLE",message:"Global search is unavailable"}):s.search.searchTaskOccurrences(o.params.taskId,o.query,c.scope,o.signal)}),r();};var NW=(e,t,r)=>{let{assertValidProjectDefaults:n,attachmentStore:i,fingerprintPayload:s,getProjectContext:o,idempotencyCacheSize:a,listModels:c,readInheritedTaskSettings:l,projectRepository:u,resolveProjectWorktree:d,resolveProviderTurnInput:m,runIdempotent:p,settingsRepository:h,taskStartRecoveries:f,toPendingRequestHttpError:g}=t;e.post("/v1/projects/:projectId/tasks",{schema:{body:kf,headers:X,params:ge,response:{201:lf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(y,_)=>{let v=await o(y.params.projectId);if(v===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let w=await p(["start-task",y.params.projectId],y.headers["idempotency-key"],y.body,async()=>{let E=JSON.stringify(["start-task",y.params.projectId,y.headers["idempotency-key"]]),R=s(y.body),P=f.get(E);if(P!==void 0&&P.fingerprint!==R)throw new L("IDEMPOTENCY_CONFLICT","Idempotency key was already used with another request",409);if(P===void 0){if(f.size>=a)throw new Error("Task creation recovery capacity is exhausted");let b=await l(y.params.projectId),O;if(y.body.worktreePath!==void 0){if(y.body.rootPath===void 0)throw new L("INVALID_REQUEST","Project root is required",400);try{let j=await ui(u,y.params.projectId,y.body.rootPath);O=(await d(j,y.body.worktreePath)).path;}catch(j){throw j instanceof Gt||j instanceof mt?new L("INVALID_REQUEST","Git worktree is invalid",400):j}}else if(y.body.rootPath!==void 0)throw new L("INVALID_REQUEST","Git worktree path is required",400);let F=O===void 0?await v.provider.startTask():await v.provider.startTask({workspacePath:O});P={fingerprint:R,settings:{...b},task:F},f.set(E,P);}return await h.writeTaskSettings(y.params.projectId,P.task.id,P.settings),f.delete(E),P.task});return _.code(201).send({task:w})}),e.post("/v1/projects/:projectId/tasks/:taskId/turns",{schema:{body:Hf,headers:X,params:Fe,response:{201:If,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(y,_)=>{let v=await p(["start-turn",y.params.projectId,y.params.taskId],y.headers["idempotency-key"],y.body,async()=>{let w=await o(y.params.projectId);if(w===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await w.provider.readTask(y.params.taskId))?.projectId!==w.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let{attachmentIds:R,providerInput:P}=await m(y.params.projectId,y.body.input,w.provider,y.params.taskId),b=y.body.options;n(await c(),b),await h.writeTaskSettings(y.params.projectId,y.params.taskId,b);let O=w.eventStream.checkpoint,F=await w.provider.startTurn(y.params.taskId,P,b);return await i.consume(y.params.projectId,R,F.status==="running"?F.id:void 0),{checkpoint:O,turn:F}});return _.code(201).send({checkpoint:v.checkpoint,taskId:y.params.taskId,turn:v.turn})}),e.post("/v1/projects/:projectId/tasks/:taskId/turns/:turnId/steer",{schema:{body:Jf,headers:X,params:_T,response:{202:Kf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(y,_)=>{let v=await p(["steer-turn",y.params.projectId,y.params.taskId,y.params.turnId],y.headers["idempotency-key"],y.body,async()=>{if(y.body.taskId!==y.params.taskId)throw new L("TASK_NOT_FOUND","Task not found",404);let w=await o(y.params.projectId);if(w===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let E=await w.provider.readTask(y.params.taskId);if(E?.projectId!==w.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let R=E.turns.find(O=>O.id===y.params.turnId);if(R===void 0)throw new L("TURN_NOT_FOUND","Turn not found",404);if(R.status!=="running")throw new L("TURN_NOT_RUNNING","Turn is not running",409);let{attachmentIds:P,providerInput:b}=await m(y.params.projectId,y.body.input,w.provider,y.params.taskId);return await w.provider.steerTurn(y.params.taskId,y.params.turnId,b),await i.consume(y.params.projectId,P,y.params.turnId),{status:"accepted",taskId:y.params.taskId,turnId:y.params.turnId}});return _.code(202).send(v)}),e.post("/v1/projects/:projectId/tasks/:taskId/turns/:turnId/interrupt",{schema:{body:Uf,headers:X,params:_T,response:{202:Vf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(y,_)=>{let v=await p(["interrupt-turn",y.params.projectId,y.params.taskId,y.params.turnId],y.headers["idempotency-key"],y.body,async()=>{if(y.body.taskId!==y.params.taskId)throw new L("TASK_NOT_FOUND","Task not found",404);let w=await o(y.params.projectId);if(w===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let E=await w.provider.readTask(y.params.taskId);if(E?.projectId!==w.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let R=E.turns.find(P=>P.id===y.params.turnId);if(R===void 0)throw new L("TURN_NOT_FOUND","Turn not found",404);if(R.status!=="running")throw new L("TURN_NOT_RUNNING","Turn is not running",409);return await w.provider.interruptTurn(y.params.taskId,y.params.turnId),{status:"interrupting",taskId:y.body.taskId,turnId:y.params.turnId}});return _.code(202).send(v)}),e.post("/v1/projects/:projectId/tasks/:taskId/pending-requests/:requestId/resolve",{schema:{body:pe,headers:X,params:eG,response:{200:qe$1,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async y=>{if(y.body.projectId!==y.params.projectId||y.body.taskId!==y.params.taskId)throw new L("PENDING_REQUEST_MISMATCH","Pending request identity does not match",409);let _=await o(y.params.projectId);if(_===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await _.provider.readTask(y.params.taskId))?.projectId!==_.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return {request:await p(["resolve-pending-request",y.params.projectId,y.params.taskId,y.params.requestId],y.headers["idempotency-key"],y.body,async()=>{try{return await _.provider.resolvePendingRequest({...y.body,requestId:y.params.requestId})}catch(E){throw E instanceof b?g(E):E}})}}),r();};function Zy(e){let t=new Map;return {readSubmission(r,n){return Promise.resolve(t.get(JSON.stringify([r,n])))},writeSubmission(r,n,i){let s=JSON.stringify([r,n]);if(!t.has(s)&&t.size>=e)throw new L("IDEMPOTENCY_CAPACITY_EXCEEDED","Submission recovery capacity is exhausted",503);return t.set(s,structuredClone(i)),Promise.resolve()}}}async function jW(e,t,r,n,i){let s=await e.getProjectContext(r);if(s===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let o;try{return await d$1(t,r,n,e.fingerprintPayload(i),i,{validate:async()=>{if(i.type==="prompt"&&e.assertValidProjectDefaults(await e.listModels(),i.options),i.taskId!==void 0&&(await s.provider.readTask(i.taskId))?.projectId!==s.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404)},createTask:()=>s.provider.startTask(),prepare:async a=>{let c=i.type==="prompt"?i.options:await e.readEffectiveTaskSettings(r,a);return await e.settingsRepository.writeTaskSettings(r,a,c),i.type==="prompt"&&(o=await e.resolveProviderTurnInput(r,i.input,s.provider,a)),o?.attachmentIds??[]},execute:async a=>{let c=s.eventStream.checkpoint;if(i.type==="review"){let u=await s.provider.startReview(a,i.target);return {taskId:a,turn:u,checkpoint:c}}if(o===void 0)throw new Error("Submission input is unavailable");let l=await s.provider.startTurn(a,o.providerInput,i.options);return {taskId:a,turn:l,checkpoint:c}},complete:async(a,c)=>{i.type==="prompt"&&await e.attachmentStore.consume(r,c,a.turn.status==="running"?a.turn.id:void 0);}})}catch(a){throw a instanceof c$2?new L(a.code,a.message,409):a}}var LW=(e,t,r)=>{e.post("/v1/projects/:projectId/submissions",{schema:{body:Hg$1,params:ge,headers:X,response:{201:Ig,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(n,i)=>{let s=await t.runIdempotent(["submit-task",n.params.projectId],n.headers["idempotency-key"],n.body,()=>jW(t,t.submissionRepository,n.params.projectId,n.headers["idempotency-key"],n.body));return i.code(201).send(s)}),r();};var DW=e=>createHash("sha256").update(e).digest("hex"),MW=e=>e.turns.filter(t=>t.status==="running").map(t=>t.id),e0=class{constructor(t){this.context=t;}context;#e=new Map;#t=new Map;#n=new Map;repository(){let t=this.context.asyncQuestionRepository;if(t===void 0)throw new L("PROVIDER_ERROR","Async question persistence is unavailable",503);return t}async task(t,r){let n=await this.context.getProjectContext(t);if(n===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let i=await n.provider.readTask(r);if(i?.projectId!==n.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return {runtime:n,task:i}}refresh(t,r){let n=JSON.stringify([t,r]),i=this.#t.get(n);if(i!==void 0)return i;let s=this.discover(t,r,n).finally(()=>{this.#t.delete(n);});return this.#t.set(n,s),s}async discover(t,r,n){let i=this.repository(),{runtime:s,task:o}=await this.task(t,r),a=this.#e.get(n),c=o.turns.at(-1)?.id,l=o,u=new Set,d=new Set(o.status==="running"&&a===c?this.#n.get(n):void 0);for(let m=0;;m++){for(let f of l.turns)f.status==="running"?d.add(f.id):d.delete(f.id);if(await i.discoverAsyncQuestions(t,r,g(l.turns,DW)),l.turnsNextCursor===null||l.turns.some(f=>f.id===a))break;let p=l.turnsNextCursor;if(m>=199||u.has(p))throw new L("PROVIDER_ERROR","Async question history scan limit exceeded",503);u.add(p);let h=await s.provider.readTask(r,{cursor:p});if(h?.projectId!==s.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);l=h;}if(c!==void 0){this.#e.delete(n),this.#e.set(n,c);let m=this.#e.keys().next().value;this.#e.size>128&&m!==void 0&&(this.#e.delete(m),this.#n.delete(m));}return this.#n.set(n,d),d}async list(t,r){let n=await this.refresh(t,r);return this.pending(t,r,n)}async pending(t,r,n){let i=n??new Set(MW((await this.task(t,r)).task));return {data:(await this.repository().listAsyncQuestions(t,r)).map(o=>o.group).filter(o=>i.has(o.turnId)&&(o.status==="pending"||o.status==="answering"))}}async dismiss(t,r,n){let{task:i}=await this.task(t,r);return await this.repository().dismissAsyncQuestions(t,r,n),this.context.workbenchChanges.publish({type:"async-questions.changed",projectId:t,taskId:r}),this.pending(t,r,new Set(MW(i)))}async answer(t,r,n,i){let s=this.repository(),{runtime:o,task:a}=await this.task(t,r),c=(await s.listAsyncQuestions(t,r)).find(y=>y.group.id===n);if(c===void 0)throw new L("ASYNC_QUESTION_NOT_FOUND","Async question not found",404);let l=DW(JSON.stringify(i.map(y=>y.trim())));if(c.fingerprint!==void 0&&c.fingerprint!==l)throw new L("ASYNC_QUESTION_RESOLVED","Async question already has another answer",409);if(c.group.status==="answered"&&c.result!==void 0)return c.result;if(c.group.status==="answering")throw this.unknownOutcome();if(c.group.status!=="pending")throw new L("ASYNC_QUESTION_RESOLVED","Async question is no longer pending",409);let u;try{u=h(c.group.questions,i);}catch{throw new L("INVALID_REQUEST","Invalid question answers",400)}let d={type:"prompt",text:u,attachments:[],skills:[]},m=a.turns.findLast(y=>y.status==="running"),p=await this.context.readEffectiveTaskSettings(t,r);m===void 0&&this.context.assertValidProjectDefaults(await this.context.listModels(),p);let h$1={group:{...c.group,status:"answering"},fingerprint:l};if(!await s.updateAsyncQuestion(t,r,h$1,"pending"))throw new L("ASYNC_QUESTION_RESOLVED","Async question is being resolved",409);let f=o.eventStream.checkpoint;this.context.workbenchChanges.publish({type:"async-questions.changed",projectId:t,taskId:r});let g={text:u,skills:[],files:[],images:[],textAttachments:[]};try{let y=m===void 0?await o.provider.startTurn(r,g,p):null;m!==void 0&&await o.provider.steerTurn(r,m.id,g);let _=y?.id??m?.id;if(_===void 0)throw new Error("Answer turn is unavailable");let v={...c.group,status:"answered"},w={question:v,input:d,messageId:randomUUID(),turnId:_,turn:y,checkpoint:f};if(!await s.updateAsyncQuestion(t,r,{group:v,fingerprint:l,result:w},"answering"))throw new Error("Answer state changed unexpectedly");return this.context.workbenchChanges.publish({type:"async-questions.changed",projectId:t,taskId:r}),w}catch{throw this.unknownOutcome()}}unknownOutcome(){return new L("SUBMISSION_OUTCOME_UNKNOWN","Answer delivery outcome is unknown; inspect the task before sending again",409)}};var Gk={400:Xf,404:Xf,409:Xf,502:Xf,503:Xf},FW=(e,t,r)=>{let n=new e0(t),i="/v1/projects/:projectId/tasks/:taskId/async-questions";e.get(i,{schema:{params:Fe,response:{200:Tg$1,...Gk}}},s=>n.list(s.params.projectId,s.params.taskId)),e.post(`${i}/:questionId/answer`,{schema:{params:R.Object({projectId:R.String({minLength:1}),taskId:R.String({minLength:1}),questionId:R.String({minLength:1,maxLength:128})}),headers:X,body:Ug,response:{200:Wg,...Gk}}},async s=>({...await t.runIdempotent(["answer-async-question",s.params.projectId,s.params.taskId,s.params.questionId],s.headers["idempotency-key"],s.body,()=>n.answer(s.params.projectId,s.params.taskId,s.params.questionId,s.body.answers)),questions:await n.pending(s.params.projectId,s.params.taskId)})),e.post(`${i}/dismiss`,{schema:{params:Fe,headers:X,body:Xg,response:{200:Tg$1,...Gk}}},s=>t.runIdempotent(["dismiss-async-questions",s.params.projectId,s.params.taskId],s.headers["idempotency-key"],s.body,()=>n.dismiss(s.params.projectId,s.params.taskId,s.body.ids))),r();};function Jc(e){if(e.projectTodoRepository===void 0)throw new L("PROVIDER_ERROR","Project todo persistence is unavailable",503);return e.projectTodoRepository}async function $W(e,t,r,n){return (await Jc(e).listProjectTodos(t)).find(s=>s.id===r)??await t0(e,t,n,r)}async function t0(e,t,r,n=randomUUID(),i=null){let s=Jc(e);return f(s,t,n,r,i,Date.now(),async()=>{let o=[];for(let a of r.attachments){let c;try{c=await e.attachmentStore.read(t,a.id);}catch(l){if(!(l instanceof er))throw l;c=await s.readProjectTodoAttachment(t,a.id);}if(c===void 0)throw new L("ATTACHMENT_NOT_FOUND","Project todo attachment not found",404);if(c.attachment.kind!==a.kind||c.attachment.name!==a.name||c.attachment.mediaType!==a.mediaType||c.attachment.size!==a.size)throw new L("INVALID_REQUEST","Project todo attachment metadata does not match",400);o.push({attachment:a,content:c.content});}return o})}function qW(e){throw e instanceof e$2?new L(e.code,e.message,e.code==="PROJECT_TODO_NOT_FOUND"?404:409):e}var zk=R.Object({projectId:R.String({minLength:1}),todoId:R.String({minLength:1})}),Xd={400:Xf,404:Xf,409:Xf,502:Xf,503:Xf},UW=(e,t,r)=>{let n=async o=>{if(await t.projectRepository.read(o)===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404)},i=async o=>({data:await Jc(t).listProjectTodos(o)}),s=async(o,a,c,l,u)=>(await n(o),t.runIdempotent(a,c,l,async()=>{try{let d=await u();return t.workbenchChanges.publish({type:"project-todos.changed",projectId:o}),d}catch(d){return qW(d)}}));e.get("/v1/projects/:projectId/todos",{schema:{params:ge,response:{200:Mg,...Xd}}},async o=>(await n(o.params.projectId),{data:await Jc(t).listProjectTodos(o.params.projectId)})),e.post("/v1/projects/:projectId/todos",{schema:{params:ge,headers:X,body:Kg,response:{201:Ng$1,...Xd}}},async(o,a)=>{let{projectId:c}=o.params,l=await s(c,["create-project-todo",c],o.headers["idempotency-key"],o.body,async()=>({todo:await t0(t,c,o.body),todos:await i(c)}));return a.code(201).send(l)}),e.post("/v1/projects/:projectId/todos/:todoId/import",{schema:{params:zk,headers:X,body:Kg,response:{200:Ng$1,...Xd}}},async o=>{let{projectId:a,todoId:c}=o.params;return s(a,["import-project-todo",a,c],o.headers["idempotency-key"],o.body,async()=>({todo:await $W(t,a,c,o.body),todos:await i(a)}))}),e.put("/v1/projects/:projectId/todos/:todoId",{schema:{params:zk,headers:X,body:Og,response:{200:Ng$1,...Xd}}},async o=>{let{projectId:a,todoId:c}=o.params;return s(a,["save-project-todo",a,c],o.headers["idempotency-key"],o.body,async()=>({todo:await t0(t,a,o.body.draft,c,o.body.expectedVersion),todos:await i(a)}))}),e.delete("/v1/projects/:projectId/todos/:todoId",{schema:{params:zk,headers:X,body:Pg$1,response:{200:Qg,...Xd}}},async o=>{let{projectId:a,todoId:c}=o.params;return s(a,["delete-project-todo",a,c],o.headers["idempotency-key"],o.body,async()=>({deleted:await Jc(t).deleteProjectTodo(a,c,o.body.expectedVersion),todos:await i(a)}))}),r();};function BW(e){throw e instanceof li?new L("TURN_NOT_RUNNING",e.message,409):e instanceof Go?new L("TASK_NOT_FOUND",e.message,404):e}var HW=(e,t,r)=>{let{getProjectContext:n,runIdempotent:i,taskQueue:s}=t,o=async a=>{let c=await n(a.projectId);if(c===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await c.provider.readTask(a.taskId))?.projectId!==c.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return {eventStream:c.eventStream,projectId:a.projectId,provider:c.provider,taskId:a.taskId}};e.get("/v1/projects/:projectId/tasks/:taskId/queue",{schema:{params:Fe,response:{200:qd$1,404:Xf}}},async a=>{let c=await o(a.params);return {data:await s.list(c)}}),e.post("/v1/projects/:projectId/tasks/:taskId/queue",{schema:{body:Lf,headers:X,params:Fe,response:{201:Mf,400:Xf}}},async(a,c)=>{let l=await o(a.params),u=await i(["queue-add",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>{let d=await s.add(l,a.body.input,a.body.clientUserMessageId);return await s.startNext(l).catch(m=>{a.log.error({err:m},"Failed to dispatch queued submission");}),d});return c.code(201).send({queue:{data:await s.list(l)},queuedSubmission:u})}),e.put("/v1/projects/:projectId/tasks/:taskId/queue/:queuedSubmissionId",{schema:{body:Nf,headers:X,params:ST,response:{200:Of,404:Xf,409:Xf}}},async a=>{let c=await o(a.params),l=await i(["queue-update",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],{...a.body,queuedSubmissionId:a.params.queuedSubmissionId},()=>s.update(c,a.params.queuedSubmissionId,a.body.input,a.body.status).catch(BW));return {queue:{data:await s.list(c)},queuedSubmission:l}}),e.delete("/v1/projects/:projectId/tasks/:taskId/queue/:queuedSubmissionId",{schema:{headers:X,params:ST,response:{200:Pf}}},async a=>{let c=await o(a.params);return {deleted:await i(["queue-delete",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],{queuedSubmissionId:a.params.queuedSubmissionId},()=>s.delete(c,a.params.queuedSubmissionId)),queue:{data:await s.list(c)}}}),e.put("/v1/projects/:projectId/tasks/:taskId/queue/reorder",{schema:{body:Qf,headers:X,params:Fe,response:{200:Rf}}},async a=>{let c=await o(a.params);return await i(["queue-reorder",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>(await s.reorder(c,a.body.queuedSubmissionIds),{status:"reordered"})),{queue:{data:await s.list(c)},status:"reordered"}}),e.post("/v1/projects/:projectId/tasks/:taskId/queue/start",{schema:{body:Sf,headers:X,params:Fe,response:{201:Tf}}},async(a,c)=>{let l=await o(a.params),u=await i(["queue-start",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>{try{return await s.start(l,a.body.queuedSubmissionId)}catch(d){BW(d);}});return c.code(201).send({queue:{data:await s.list(l)},taskId:a.params.taskId,turn:u})}),r();};var GW=R.Object({owner:R.String({maxLength:100,minLength:1,pattern:"^[A-Za-z0-9_-]+$"}),slug:R.String({maxLength:100,minLength:1,pattern:"^[A-Za-z0-9_-]+$"})},{additionalProperties:false}),hNe=R.Object({path:R.String({maxLength:4096,minLength:1})},{additionalProperties:false}),pNe=R.Object({enabled:R.Boolean(),path:R.String({maxLength:4096,minLength:1})},{additionalProperties:false}),mNe=R.Object({enabled:R.Boolean()},{additionalProperties:false}),gNe=R.Object({projectId:R.Optional(R.String({minLength:1})),rootPath:R.Optional(R.String({minLength:1})),scope:Bc$1},{additionalProperties:false}),yNe=R.Object({cursor:R.Optional(R.String({maxLength:2048})),query:R.Optional(R.String({maxLength:120})),sort:R.Optional(R.Union([R.Literal("recommended"),R.Literal("downloads"),R.Literal("updated")]))},{additionalProperties:false}),Vk=R.Object({marketplaceName:R.String({maxLength:160,minLength:1}),pluginName:R.String({maxLength:240,minLength:1})},{additionalProperties:false}),wNe=R.Object({marketplacePath:R.Optional(R.String({maxLength:4096,minLength:1}))},{additionalProperties:false}),vNe=R.Object({forceRefetch:R.Optional(R.Boolean())},{additionalProperties:false}),_Ne=R.Object({installAttemptId:R.String({maxLength:200,minLength:1}),marketplacePath:R.Union([R.String({maxLength:4096,minLength:1}),R.Null()])},{additionalProperties:false}),SNe=R.Object({pluginId:R.String({maxLength:300,minLength:1})},{additionalProperties:false});function Xc(e){if(!(e instanceof Ue))throw e;let t={SKILL_MARKET_CONFLICT:409,SKILL_MARKET_FILESYSTEM:500,SKILL_MARKET_INCOMPATIBLE:409,SKILL_MARKET_INVALID_ARCHIVE:409,SKILL_MARKET_INVALID_RESPONSE:502,SKILL_MARKET_NETWORK:502,SKILL_MARKET_NOT_FOUND:404,SKILL_MARKET_RATE_LIMITED:429,SKILL_MARKET_UNSAFE:409};throw new L(e.code,e.message,t[e.code],e.code==="SKILL_MARKET_NETWORK"||e.code==="SKILL_MARKET_RATE_LIMITED")}var Vi={400:Xf,404:Xf,409:Xf,429:Xf,500:Xf,502:Xf},zW=(e,t,r)=>{let{runIdempotent:n,skillMarketService:i}=t;e.post("/v1/plugins/official/reconcile",{schema:{body:R.Object({},{additionalProperties:false}),headers:X,response:{200:sc,...Vi}}},s=>n(["reconcile-official-plugins"],s.headers["idempotency-key"],s.body,()=>i.reconcileOfficialPlugins())),e.get("/v1/skills/installed",{schema:{response:{200:uc$1}}},()=>i.listInstalledSkills(false)),e.get("/v1/plugins/official",{schema:{querystring:vNe,response:{200:Lc$1}}},s=>i.listOfficialPlugins(s.query.forceRefetch??false)),e.get("/v1/plugins/official/:marketplaceName/:pluginName",{schema:{params:Vk,querystring:wNe,response:{200:Oc$1,...Vi}}},s=>i.getOfficialPlugin(s.params.marketplaceName,s.query.marketplacePath??null,s.params.pluginName)),e.post("/v1/plugins/official/:marketplaceName/:pluginName/install",{schema:{body:_Ne,headers:X,params:Vk,response:{200:Qc$1,...Vi}}},s=>n(["install-official-plugin",s.params.marketplaceName,s.params.pluginName],s.headers["idempotency-key"],s.body,async()=>({...await i.installOfficialPlugin(s.params.marketplaceName,s.body.marketplacePath,s.params.pluginName,s.body.installAttemptId),plugins:await i.listOfficialPlugins(true)}))),e.post("/v1/plugins/official/:marketplaceName/:pluginName/uninstall",{schema:{body:SNe,headers:X,params:Vk,response:{200:Sc,...Vi}}},s=>n(["uninstall-official-plugin",s.params.marketplaceName,s.params.pluginName],s.headers["idempotency-key"],s.body,async()=>(await i.uninstallOfficialPlugin(s.body.pluginId),{plugins:await i.listOfficialPlugins(true)}))),e.get("/v1/skills/market",{schema:{querystring:yNe,response:{200:yc}}},s=>i.listSkills(s.query.query??"",s.query.cursor??null,s.query.sort??"recommended").catch(Xc)),e.get("/v1/skills/market/:owner/:slug",{schema:{params:GW,response:{200:Ac$1,...Vi}}},s=>i.getSkill(s.params.owner,s.params.slug).catch(Xc)),e.get("/v1/mcp-servers/configured",{schema:{response:{200:wc}}},()=>i.listConfiguredMcpServers()),e.post("/v1/skills/open",{schema:{body:hNe,headers:X,response:{200:Ic$1,...Vi}}},s=>n(["open-skill"],s.headers["idempotency-key"],s.body,()=>i.openSkillDirectory(s.body.path).catch(Xc))),e.put("/v1/skills/enabled",{schema:{body:pNe,headers:X,response:{200:Fc,...Vi}}},s=>n(["set-skill-enabled",s.body.path],s.headers["idempotency-key"],s.body,async()=>({...await i.setSkillEnabled(s.body.path,s.body.enabled).catch(Xc),installedSkills:await i.listInstalledSkills(true)}))),e.put("/v1/mcp-servers/configured/:name/enabled",{schema:{body:mNe,headers:X,response:{200:Hc$1,...Vi}}},s=>n(["set-mcp-enabled",s.params.name],s.headers["idempotency-key"],s.body,async()=>({...await i.setMcpServerEnabled(s.params.name,s.body.enabled).catch(Xc),servers:await i.listConfiguredMcpServers()}))),e.post("/v1/skills/market/:owner/:slug/install",{schema:{body:gNe,headers:X,params:GW,response:{200:Dc$1,...Vi}}},s=>n(["install-skill",s.params.owner,s.params.slug],s.headers["idempotency-key"],s.body,()=>i.installSkill(s.params.owner,s.params.slug,s.body).catch(Xc))),r();};var zs=class extends Error{constructor(r,n){super(r==="unknown"?"Launch outcome is unknown; inspect the task before creating another schedule":r==="cleanup_pending"?"Launch confirmed; cleanup will be retried":"Scheduled task could not be launched");this.status=r;this.taskId=n;}status;taskId};function VW(e){return e.status==="unknown"||e.status==="cleanup_pending"}var ENe=4,TNe=1e3,Wk=0,Zd=class extends Error{constructor(){super("Scheduled task recurrence workers are busy");}};function RNe(e){if(e.length>1024||/[\r\n]/u.test(e))throw new Error("Scheduled task RRULE is too complex");let t=e.trim().replace(/^RRULE:/u,"").split(";"),r=new Set,n=1;for(let i of t){let[s,o]=i.split("=");if(!s||!o||r.has(s))throw new Error("Scheduled task RRULE is invalid");if(r.add(s),s==="FREQ"&&o==="SECONDLY")throw new Error("Scheduled task recurrence must be at least one minute");if(s.startsWith("BY")&&(n*=o.split(",").length),n>1024)throw new Error("Scheduled task RRULE is too complex")}}async function ef(e,t,r=5){if(!Number.isInteger(r)||r<1)throw new Error("Scheduled task preview limit is invalid");if(e.type==="once")return e.atUnixMs>t?[e.atUnixMs]:[];if(RNe(e.rrule),Wk>=ENe)throw new Zd;Wk+=1;let n,i;try{n=new Worker(new URL("./scheduled-task-recurrence-worker.js",import.meta.url),{execArgv:["--experimental-strip-types"],workerData:{schedule:e,afterUnixMs:t,limit:Math.min(r,5)},resourceLimits:{maxOldGenerationSizeMb:32}});let s=n;return await new Promise((o,a)=>{i=setTimeout(()=>{a(new Error("Scheduled task RRULE computation timed out"));},TNe),s.once("message",c=>{c.error!==void 0?a(new Error(c.error)):o(c.dates);}),s.once("error",a),s.once("exit",()=>{a(new Error("Scheduled task recurrence worker exited"));});})}finally{i!==void 0&&clearTimeout(i);try{await n?.terminate();}finally{Wk-=1;}}}async function r0(e,t){if(e.type==="once"){if(e.atUnixMs<=t)throw new Error("Scheduled task time must be in the future");return e.atUnixMs}let r=(await ef(e,t,1))[0];if(r===void 0)throw new Error("Scheduled task RRULE has no future occurrence");return r}async function Kk(e,t,r){let n=t.name.trim();if(n==="")throw new Error("Scheduled task name must not be empty");return {...t,createdAtUnixMs:r,id:e,lastRunAtUnixMs:null,lastRunStatus:null,name:n,nextRunAtUnixMs:t.enabled?await r0(t.schedule,r):null,runs:[],updatedAtUnixMs:r}}function KW(e,t){return [...e.runs,t].slice(-20)}async function YW(e,t){if(e.schedule.type==="once")return {enabled:false,nextRunAtUnixMs:null};try{return {enabled:!0,nextRunAtUnixMs:await r0(e.schedule,t)}}catch(r){if(r instanceof Zd)throw r;return {enabled:false,nextRunAtUnixMs:null}}}async function Yk(e,t,r,n){let i=[],s=[];for(let a of e)s.push(await o(a));return {claims:i,tasks:s};async function o(a){if(!(n===void 0?a.enabled&&a.nextRunAtUnixMs!==null&&a.nextRunAtUnixMs<=r:a.id===n))return a;if(t.has(a.id)){if(n!==void 0)return a;let d={error:"previous scheduled launch is still running",finishedAtUnixMs:r,id:randomUUID(),startedAtUnixMs:r,status:"skipped",taskId:null};return {...a,...await YW(a,r),lastRunAtUnixMs:r,lastRunStatus:"skipped",runs:KW(a,d),updatedAtUnixMs:r}}let l=randomUUID(),u={...a,...n===void 0?await YW(a,r):{},lastRunAtUnixMs:r,lastRunStatus:"running",runs:KW(a,{error:null,finishedAtUnixMs:null,id:l,startedAtUnixMs:r,status:"running",taskId:null}),updatedAtUnixMs:r};return i.push({runId:l,task:u}),u}}function QW(e,t,r,n){return e.map(i=>{if(i.id!==t.task.id)return i;let s=n.status==="rejected"&&n.reason instanceof zs?n.reason:void 0,o=n.status==="fulfilled"?"started":s?.status??"failed";return {...i,...o==="unknown"?{enabled:false,nextRunAtUnixMs:null}:{},lastRunStatus:o,runs:i.runs.map(a=>a.id===t.runId?{...a,error:n.status==="rejected"?s?.message??"Scheduled task could not be launched":null,finishedAtUnixMs:r,status:o,taskId:n.status==="fulfilled"?n.value:s?.taskId??null}:a),updatedAtUnixMs:r}})}function JW(e,t){return e.map(r=>r.runs.some(n=>n.status==="running")?{...r,enabled:false,nextRunAtUnixMs:null,lastRunStatus:"unknown",runs:r.runs.map(n=>n.status==="running"?{...n,error:"server exited before launch was confirmed",finishedAtUnixMs:t,status:"unknown"}:n),updatedAtUnixMs:t}:r)}var gn=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ScheduledTaskServiceError";}code};function XW(){let e=[];return {listScheduledTasks:()=>Promise.resolve(e),replaceScheduledTasks:t=>(e=[...t],Promise.resolve(e))}}var n0=class{#e=new Set;#t=new Set;#n;#r;#i;#o=new Set;#f=new Set;#l=new Set;#s=new Map;#p;#h;#d=false;#c=Promise.resolve();#a=[];#m;constructor(t){this.#n=t.now??Date.now,this.#r=t.repository,this.#i=t.prepareTaskResources,this.#p=t.startTask,this.#h=t.recoverTask;}async start(){await this.#P(async()=>{let t=await this.#r.listScheduledTasks(),r=await this.#k(t);this.#a=r,r.some((n,i)=>n!==t[i])&&await this.#r.replaceScheduledTasks(r),this.#w();});}list(){return this.#P(()=>[...this.#a].sort((t,r)=>(t.nextRunAtUnixMs??Number.MAX_SAFE_INTEGER)-(r.nextRunAtUnixMs??Number.MAX_SAFE_INTEGER)||t.createdAtUnixMs-r.createdAtUnixMs))}subscribe(t){return this.#e.add(t),()=>{this.#e.delete(t);}}create(t){return this.#P(async()=>{let r;try{r=await Kk(randomUUID(),t,this.#n());}catch(n){throw new gn("invalid",String(n))}return await this.#u([...this.#a,r],r),r})}update(t,r){return this.#P(async()=>{let n=this.#y(t);this.#b(n);let i;try{i={...await Kk(t,r,this.#n()),createdAtUnixMs:n.createdAtUnixMs,lastRunAtUnixMs:n.lastRunAtUnixMs,lastRunStatus:n.lastRunStatus,runs:n.runs};}catch(s){throw new gn("invalid",String(s))}return await this.#u(this.#a.map(s=>s.id===t?i:s),i),i})}delete(t){return this.#P(async()=>{let r=this.#y(t);if(this.#o.has(t)||r.runs.some(n=>n.status==="running"||n.status==="cleanup_pending"))throw new gn("busy","Scheduled task is running");await this.#_(this.#a.filter(n=>n.id!==t));})}setEnabled(t,r){return this.#P(async()=>{let n=this.#y(t);r&&this.#b(n);let i=n.nextRunAtUnixMs;if(r)try{i=await r0(n.schedule,this.#n());}catch(o){throw new gn("invalid",String(o))}let s={...n,enabled:r,nextRunAtUnixMs:i,updatedAtUnixMs:this.#n()};return await this.#_(this.#a.map(o=>o.id===t?s:o)),s})}runNow(t){return this.#P(async()=>{this.#b(this.#y(t));let r=await Yk(this.#a,this.#o,this.#n(),t),n=r.claims[0];if(n===void 0)throw new gn("busy","Scheduled task is already running");return await this.#_(r.tasks),await this.#r.claimScheduledTaskRun?.(n.runId),this.#f.add(n.runId),this.#o.add(t),this.#T(n),n.task})}async close(){this.#d=true,this.#e.clear(),this.#m!==void 0&&clearTimeout(this.#m),await Promise.allSettled(this.#t),await this.#c,this.#f.size>0&&this.#r.withScheduledTaskLock!==void 0&&await this.#r.withScheduledTaskLock(async()=>{for(let t of this.#f)await this.#r.releaseScheduledTaskRun?.(t);this.#f.clear();});}#y(t){let r=this.#a.find(n=>n.id===t);if(r===void 0)throw new gn("not_found","Scheduled task not found");return r}#g(t){return t.runs.some(r=>this.#l.has(r.id))}async#k(t){let r=t.filter(o=>!this.#o.has(o.id)&&!this.#g(o)),n=this.#h,i=n===void 0?JW(r,this.#n()):await Promise.all(r.map(n)),s=new Map(i.map(o=>[o.id,o]));return t.map(o=>s.get(o.id)??o)}#b(t){if(this.#o.has(t.id)||t.runs.some(r=>r.status==="running"||VW(r)))throw new gn("busy","Previous launch requires reconciliation")}#T(t){let r=Promise.resolve().then(()=>this.#p(t.task)).then(n=>({status:"fulfilled",value:n})).catch(n=>({reason:n,status:"rejected"})).then(n=>this.#P(async()=>{this.#s.set(t.task.id,{claim:t,finishedAtUnixMs:this.#n(),result:n}),await this.#R();})).catch(()=>{this.#v();}).finally(()=>this.#t.delete(r));this.#t.add(r);}async#R(){for(let[t,r]of this.#s)await this.#_(QW(this.#a,r.claim,r.finishedAtUnixMs,r.result)),await this.#r.releaseScheduledTaskRun?.(r.claim.runId),this.#f.delete(r.claim.runId),this.#s.delete(t),this.#o.delete(t);}#v(){this.#m!==void 0&&clearTimeout(this.#m),!this.#d&&(this.#m=setTimeout(()=>{this.#E().catch(()=>{this.#v();});},1e3),this.#m.unref());}#w(){if(this.#m!==void 0&&clearTimeout(this.#m),this.#d)return;let t=this.#a.filter(o=>o.enabled).flatMap(o=>o.nextRunAtUnixMs===null?[]:[o.nextRunAtUnixMs]).reduce((o,a)=>o===void 0?a:Math.min(o,a),void 0),r=this.#a.some(o=>o.runs.some(a=>a.status==="cleanup_pending")),n=t===void 0?1440*60*1e3:Math.max(1,t-this.#n()),i=this.#r.withScheduledTaskLock===void 0?2147483647:5e3,s=r||this.#s.size>0?1e3:i;this.#m=setTimeout(()=>{this.#E().catch(()=>{this.#v();});},Math.min(n,s)),this.#m.unref();}async#E(){await this.#P(async()=>{if(this.#d)return;await this.#R();let t=this.#a.filter(i=>!this.#o.has(i.id)&&!this.#g(i)&&i.runs.some(s=>s.status==="running"));if(t.length>0){let i=new Map((await this.#k(t)).map(s=>[s.id,s]));await this.#_(this.#a.map(s=>i.get(s.id)??s));}for(let i of this.#a){let s=i.runs.find(o=>o.status==="cleanup_pending");s===void 0||this.#o.has(i.id)||this.#g(i)||(this.#o.add(i.id),await this.#r.claimScheduledTaskRun?.(s.id),this.#f.add(s.id),this.#T({task:i,runId:s.id}));}let r=new Set([...this.#o,...this.#a.filter(i=>this.#g(i)).map(i=>i.id)]),n=await Yk(this.#a,r,this.#n());await this.#_(n.tasks);for(let i of n.claims)await this.#r.claimScheduledTaskRun?.(i.runId),this.#f.add(i.runId);for(let i of n.claims)this.#o.add(i.task.id);for(let i of n.claims)this.#T(i);});}async#_(t,r){if(t.length===this.#a.length&&t.every((n,i)=>n===this.#a[i])){this.#w();return}this.#a=await this.#r.replaceScheduledTasks(t,r),this.#w();for(let n of this.#e)n();}async#u(t,r){let n;try{n=await this.#i?.(r);}catch(i){throw new gn("invalid",String(i))}await this.#_(t,n);}#P(t){let r=this.#c.then(()=>this.#r.withScheduledTaskLock===void 0?t():this.#r.withScheduledTaskLock(async()=>(this.#a=await this.#r.listScheduledTasks(),this.#l=new Set(await this.#r.listActiveScheduledTaskRunIds?.()),t())));return this.#c=r.then(()=>{},()=>{}),r}};function ZW(e,t){TT(e,t,"/v1/scheduled-tasks/events",{type:"scheduled-tasks.changed"},r=>t.scheduledTaskService.subscribe(()=>{r({type:"scheduled-tasks.changed"});}));}var i0=R.Object({taskId:R.String({minLength:1})},{additionalProperties:false});function xNe(e){throw e instanceof gn?e.code==="not_found"?new L("TASK_NOT_FOUND",e.message,404):new L("INVALID_REQUEST",e.message,e.code==="busy"?409:400):e}var e9=(e,t,r)=>{ZW(e,t);let n=(o,a,c,l)=>t.runIdempotent(o,a,c,async()=>{try{return await l()}catch(u){xNe(u);}}),i={400:Xf,404:Xf,409:Xf,502:Xf,503:Xf},s=async o=>({...o,tasks:{data:await t.scheduledTaskService.list()}});e.post("/v1/scheduled-tasks/preview",{schema:{body:Od,response:{200:Pd$1,400:Xf}}},async o=>{try{return {dates:await ef(o.body.schedule,Date.now())}}catch(a){throw new L("INVALID_REQUEST",a instanceof Error?a.message:String(a),400)}}),e.get("/v1/scheduled-tasks",{schema:{response:{200:Ud}}},async()=>({data:await t.scheduledTaskService.list()})),e.post("/v1/scheduled-tasks",{schema:{body:Sd$1,headers:X,response:{...i,201:Vd$1}}},async(o,a)=>{let c=await n(["create-scheduled-task"],o.headers["idempotency-key"],o.body,async()=>s({task:await t.scheduledTaskService.create(o.body)}));return a.code(201).send(c)}),e.put("/v1/scheduled-tasks/:taskId",{schema:{body:Sd$1,headers:X,params:i0,response:{...i,200:Vd$1}}},o=>n(["update-scheduled-task",o.params.taskId],o.headers["idempotency-key"],o.body,async()=>s({task:await t.scheduledTaskService.update(o.params.taskId,o.body)}))),e.delete("/v1/scheduled-tasks/:taskId",{schema:{params:i0,headers:X,response:{...i,200:Wd$1}}},o=>n(["delete-scheduled-task",o.params.taskId],o.headers["idempotency-key"],{},async()=>(await t.scheduledTaskService.delete(o.params.taskId),s({status:"deleted",taskId:o.params.taskId})))),e.patch("/v1/scheduled-tasks/:taskId/enabled",{schema:{body:Xd$1,headers:X,params:i0,response:{...i,200:Vd$1}}},o=>n(["set-scheduled-task-enabled",o.params.taskId],o.headers["idempotency-key"],o.body,async()=>s({task:await t.scheduledTaskService.setEnabled(o.params.taskId,o.body.enabled)}))),e.post("/v1/scheduled-tasks/:taskId/run",{schema:{params:i0,headers:X,response:{...i,200:Vd$1}}},o=>n(["run-scheduled-task",o.params.taskId],o.headers["idempotency-key"],{},async()=>s({task:await t.scheduledTaskService.runNow(o.params.taskId)}))),r();};function INe(e,t){return e.id===t.id&&e.kind===t.kind&&e.mediaType===t.mediaType&&e.name===t.name&&e.size===t.size}var s0=class{#e;#t;constructor(t,r){this.#e=t,this.#t=r;}async prepare(t){let r=new Set(t.prompt.attachments.map(o=>o.id)),n=new Map(t.messageAttachments.map(o=>[o.id,o]));if(r.size!==t.prompt.attachments.length||n.size!==r.size||[...r].some(o=>!n.has(o)))throw new Error("Scheduled task attachment metadata is incomplete");let i=new Map((await this.#t.listScheduledTaskAttachments(t.id)).map(o=>[o.attachment.id,o]));return {attachments:await Promise.all(t.messageAttachments.map(async o=>{let a;try{let c=await this.#e.read(t.projectId,o.id);a={attachment:c.attachment,content:c.content};}catch(c){if(!(c instanceof er))throw c;let l=i.get(o.id);if(l===void 0)throw c;a={attachment:l.attachment,content:l.content};}if(!INe(a.attachment,o))throw new Error("Scheduled task attachment metadata does not match stored content");return a})),projectId:t.projectId,taskId:t.id}}read(t,r){return this.#t.readScheduledTaskAttachment(t,r)}async restorePrompt(t){if(t.prompt.attachments.length===0)return {prompt:t.prompt,restoredIds:[]};let r=new Map((await this.#t.listScheduledTaskAttachments(t.id)).map(i=>[i.attachment.id,i])),n=[];try{let i=[];for(let s of t.prompt.attachments){let o=r.get(s.id);if(o===void 0)throw new Error("Scheduled task attachment was not found");let a=await this.#e.add(t.projectId,{content:Readable.from([o.content]),kind:o.attachment.kind,mediaType:o.attachment.mediaType,name:o.attachment.name});n.push(a.attachment.id),i.push({id:a.attachment.id});}return {prompt:{...t.prompt,attachments:i},restoredIds:n}}catch(i){throw await this.discard(n),i}}async discard(t){await Promise.all(t.map(r=>this.#e.discard(r)));}};function t9(e,t,r,n,i,s,o){let a=new Map,c=d=>`scheduled:${d.id}`;async function l(d){let m=d.runs.findLast(v=>v.status==="running"||v.status==="cleanup_pending");if(m===void 0)throw new Error("Scheduled run is unavailable");let p=c(m),h={type:"prompt",input:d.prompt,options:d.turnOptions},f=_c(h),g,y,_;try{let v=a.get(p);v!==void 0&&await e.writeSubmission(d.projectId,p,v),y=await e.readSubmission(d.projectId,p);let w=await i(d.projectId);if(w===void 0)throw new Error("Scheduled task project was not found");_=y?.task;let E,R=await d$1(e,d.projectId,p,f,h,{validate:async()=>{Km(await s(),d.turnOptions),g=n===void 0?{prompt:d.prompt,restoredIds:[]}:await n.restorePrompt(d);},createTask:async()=>(_=await w.provider.startTask(),_),prepare:async P=>{if(await t.writeTaskSettings(d.projectId,P,d.turnOptions),g===void 0)throw new Error("Scheduled attachments are unavailable");return E=await o(d.projectId,g.prompt,w.provider,P),E.attachmentIds},execute:async P=>{if(E===void 0)throw new Error("Scheduled input is unavailable");let b=w.eventStream.checkpoint,O=await w.provider.startTurn(P,E.providerInput,d.turnOptions),F={taskId:P,turn:O,checkpoint:b,..._===void 0?{}:{createdTask:_}};return a.set(p,{fingerprint:f,stage:"started",result:F,attachmentIds:E.attachmentIds,..._===void 0?{}:{task:_}}),F},complete:(P,b)=>r.consume(d.projectId,b,P.turn.status==="running"?P.turn.id:void 0)});return a.delete(p),R.taskId}catch{let v=a.get(p);try{v??=await e.readSubmission(d.projectId,p);}catch{throw new zs(v?.result===void 0?"unknown":"cleanup_pending",v?.result?.taskId??_?.id??y?.task?.id??m.taskId)}let w=v?.result!==void 0?"cleanup_pending":v?.stage==="creating"||v?.stage==="starting"?"unknown":"failed";throw w==="failed"&&await n?.discard(g?.restoredIds??[]).catch(()=>{}),new zs(w,v?.result?.taskId??_?.id??v?.task?.id??m.taskId)}}async function u(d){if(!d.runs.some(p=>["running","unknown","cleanup_pending"].includes(p.status)))return d;let m=await Promise.all(d.runs.map(async p=>{if(!["running","unknown","cleanup_pending"].includes(p.status))return p;let h=await e.readSubmission(d.projectId,c(p)),f=h?.result?.taskId??h?.task?.id??p.taskId,g=h?.stage==="completed"?"started":h?.result!==void 0?"cleanup_pending":h?.stage==="ready"?"failed":"unknown";return {...p,status:g,taskId:f,finishedAtUnixMs:p.finishedAtUnixMs??Date.now(),error:g==="started"?null:new zs(g,f).message}}));return {...d,runs:m,lastRunStatus:m.at(-1)?.status??d.lastRunStatus,...m.some(p=>p.status==="unknown")?{enabled:false,nextRunAtUnixMs:null}:{}}}return {recoverTask:u,startTask:l}}async function r9(e,t,r,n,i){let s=e.scheduledTaskAttachmentRepository===void 0?void 0:new s0(t,e.scheduledTaskAttachmentRepository),o=new n0({...s===void 0?{}:{prepareTaskResources:a=>s.prepare(a)},repository:e.scheduledTaskRepository??XW(),...t9(e.submissionRepository??Zy(1e3),e.settingsRepository,t,s,r,n,i)});return await o.start(),{scheduledTaskAttachmentManager:s,scheduledTaskService:o}}var FJ=e(p9(),1),$J=e(fK(),1),qJ=e(iQ(),1),UJ=e(jJ(),1);var iqe=5,DJ=6e4,sqe=1e3,oqe=1e3;function aqe(e,t){let r=createHash("sha256").update(e,"utf8").digest(),n=createHash("sha256").update(t,"utf8").digest();return timingSafeEqual(r,n)}var Gf=class{#e=new Map;#t;#n;#r;#i;#o;#f;#l=new Map;#s;constructor(t,r={}){if(t.sessionTtlMs!==void 0&&(!Number.isSafeInteger(t.sessionTtlMs)||t.sessionTtlMs<=0))throw new Error("sessionTtlMs must be a positive safe integer");this.#i=t.pairingCode,this.#f=t.sessionTtlMs,this.#t=r.maxFailureWindows??sqe,this.#n=r.maxSessions??oqe,this.#r=r.now??Date.now,this.#o=r.randomBytes??randomBytes,this.#s=setInterval(()=>{this.#h(this.#r());},DJ),this.#s.unref();}pair(t,r){let n=this.#r();this.#h(n);let i=this.#e.get(r);if(i!==void 0&&i.count>=iqe)return {status:"rate_limited"};if(!aqe(this.#i,t)){this.#p(this.#e,this.#t);let a=this.#e.get(r);return a===void 0?this.#e.set(r,{count:1,startedAt:n}):a.count+=1,{status:"failed"}}this.#p(this.#l,this.#n,a=>{this.logout(a);});let s=this.#o(32).toString("base64url"),o=this.#f===void 0?null:n+this.#f;return this.#l.set(s,{createdAt:n,expiresAt:o,invalidationListeners:new Set}),{expiresAt:o,sessionId:s,status:"paired"}}validate(t){return this.expiresAt(t)!==void 0}expiresAt(t){if(t===void 0)return;let r=this.#l.get(t);if(r!==void 0){if(r.expiresAt!==null&&r.expiresAt<=this.#r()){this.logout(t);return}return r.expiresAt}}logout(t){if(t!==void 0){let r=this.#l.get(t);this.#l.delete(t);for(let n of r?.invalidationListeners??[])n();r?.invalidationListeners.clear();}}onInvalidated(t,r){let n=t===void 0?void 0:this.#l.get(t);return !this.validate(t)||n===void 0?(r(),()=>{}):(n.invalidationListeners.add(r),()=>{n.invalidationListeners.delete(r);})}diagnostics(){return {failureWindows:this.#e.size,sessions:this.#l.size}}close(){clearInterval(this.#s),this.#e.clear();for(let t of this.#l.keys())this.logout(t);}#p(t,r,n=i=>{t.delete(i);}){for(;t.size>=r;){let i=t.keys().next().value;if(i===void 0)return;n(i);}}#h(t){for(let[r,n]of this.#e)n.startedAt+DJ<=t&&this.#e.delete(r);for(let[r,n]of this.#l)n.expiresAt!==null&&n.expiresAt<=t&&this.logout(r);}};function dqe(e){let t="/v1/projects/";if(!e.startsWith(t))return false;let r=e.slice(t.length).split("/",1)[0];try{return decodeURIComponent(r??"")===we}catch{return false}}function fqe(e){if(e!==void 0)try{let t=new URL(`http://${e}`);return t.username===""&&t.password===""&&t.pathname==="/"&&t.search===""&&t.hash===""?t:void 0}catch{return}}var hqe=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;function BJ(e){let t=domainToASCII(e).toLowerCase(),r=t.split(".");if(e===""||e!==e.trim()||t.length>253||isIP(t)!==0||r.some(n=>!hqe.test(n)))throw new Error("Invalid allowed Host; expected a domain name without scheme, port, or wildcard");return t}function pqe(e,t,r){let n=e.hostname.toLowerCase(),i=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n;return n==="localhost"||i==="127.0.0.1"||i==="::1"||r.has(i)?true:t&&isIP(i)!==0}async function HJ(e,t){await e.register(UJ.default,{options:{maxPayload:64*1024}}),await e.register(FJ.default);let r=new Set((t.allowedHosts??[]).map(BJ)),n=t.access===void 0?void 0:new Gf(t.access);e.addHook("onRequest",async(s,o)=>{let a=s.originalUrl.split("?",1)[0]??s.originalUrl;if(dqe(a))return o.code(404).send({code:"NOT_FOUND",message:"Route not found"});let c=s.headers.upgrade?.toLowerCase()==="websocket",l=s.cookies[cn],u=fqe(s.headers.host);if(u===void 0||!pqe(u,t.access!==void 0,r))return o.code(403).send({code:"ACCESS_DENIED",message:"Access denied",retryable:false});let d=t.access===void 0||n?.validate(l)===true;if(!(!a.startsWith("/v1/")||s.method==="GET"&&(a==="/v1/health"||a==="/v1/access")||s.method==="POST"&&a==="/v1/access/pair")&&!d)return o.code(401).send({code:"ACCESS_DENIED",message:"Access denied",retryable:false});let p=!["GET","HEAD","OPTIONS"].includes(s.method)&&(l!==void 0||s.headers.origin!==void 0);if(c||p){let h=s.headers.origin;try{let f=h===void 0?void 0:new URL(h);if(f===void 0||f.protocol!=="http:"&&f.protocol!=="https:"||f.host!==u.host)throw new Error("Origin mismatch")}catch{return o.code(403).send({code:"ACCESS_DENIED",message:"Access denied",retryable:false})}}}),e.addHook("onSend",async(s,o,a)=>{let c=o.getHeader("content-type")==="application/pdf";if(o.headers({"Content-Security-Policy":`default-src 'self'; base-uri 'none'; connect-src 'self'; frame-src 'self'; frame-ancestors ${c?"'self'":"'none'"}; img-src 'self' blob: data:; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'`,"Permissions-Policy":"camera=(), geolocation=(), microphone=()","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff","X-Frame-Options":c?"SAMEORIGIN":"DENY"}),s.url.startsWith("/v1/pets/assets/"))o.header("Cache-Control","private, no-cache");else if(s.url.startsWith("/v1/")){let l=o.getHeader("cache-control");(o.statusCode>=400||typeof l!="string"||!l.startsWith("private,"))&&o.header("Cache-Control","no-store");}return a}),await e.register($J.default,{limits:{fields:0,files:1,fileSize:Db,parts:1}}),e.setErrorHandler((s,o,a)=>{if(s instanceof L)return wT(o,s.code),a.code(s.statusCode).send({code:s.code,message:s.message,retryable:s.retryable});if(typeof s=="object"&&s!==null&&"validation"in s){let l=o.headers["idempotency-key"],d=!(o.routeOptions.url==="/v1/access/pair"||o.routeOptions.url==="/v1/access/logout")&&(o.method==="POST"||o.method==="PUT")&&(l===void 0||l==="");return a.code(400).send({code:d?"IDEMPOTENCY_KEY_REQUIRED":"INVALID_REQUEST",message:d?"Idempotency-Key header is required":"Request is invalid",retryable:false})}let c=typeof s=="object"&&s!==null&&"statusCode"in s&&typeof s.statusCode=="number"&&Number.isInteger(s.statusCode)&&s.statusCode>=400&&s.statusCode<=599?s.statusCode:500;return c<500?a.code(c).send({code:"INVALID_REQUEST",message:c===413?"Request is too large":"Request is invalid",retryable:false}):(wT(o,"INTERNAL_ERROR"),a.code(c).send({code:"INTERNAL_ERROR",message:"Internal server error",retryable:false}))}),e.addHook("onClose",async()=>{n?.close(),await t.releaseResources();});let{staticRoot:i}=t;return i!==void 0&&(await e.register(qJ.default,{cacheControl:false,preCompressed:true,root:i,setHeaders:(s,o)=>{let[a]=relative(i,o).split(sep);s.header("Cache-Control",a==="assets"?"public, max-age=31536000, immutable":"public, max-age=0");},wildcard:false}),e.setNotFoundHandler((s,o)=>s.method==="GET"&&!s.url.startsWith("/v1/")?o.type("text/html; charset=utf-8").sendFile("index.html"):o.code(404).send({code:"NOT_FOUND",message:"Route not found"}))),n}async function GJ(e,t,r){let n=e.get(t);if(n!==void 0)return n;let i=Promise.resolve().then(r);e.set(t,i);try{return await i}finally{e.get(t)===i&&e.delete(t);}}async function zJ(e,t){if(e===we)return {provider:t.provider.forTemporary(t.standaloneCwd),scope:{id:we,kind:"temporary",rootPath:t.standaloneCwd,runtimeWorkspaceRoots:[t.standaloneCwd]}};let r=await t.projectRepository.read(e);if(r===void 0)return;let n=r.roots[0];if(n!==void 0)return {provider:t.provider.forProject(r),scope:{id:r.id,kind:"project",rootPath:n.path,runtimeWorkspaceRoots:r.roots.map(i=>i.path)}}}function VJ(e){let t=e.indexOf("?"),r=t<0?e:e.slice(0,t),n=t<0?"":e.slice(t);if(!r.startsWith(xe))return e;let i=r.slice(xe.length),s=i==="/tasks"||i.startsWith("/tasks/"),o=i.startsWith("/attachments/");return !s&&!o&&!(i==="/files/pdf"||i==="/files/download"||i==="/files/image"||i==="/files/source")&&!(i==="/open"||i==="/open-capabilities")&&i!=="/submissions"&&i!=="/events"&&i!=="/skills"?e:`/v1/projects/${we}${i}${n}`}var WJ=(e,t,r)=>{let n=()=>{if(!t.provider.personalization)throw new L("PROVIDER_ERROR","Personalization is unavailable",503,true);return t.provider.personalization},i={409:Xf,502:Xf,503:Xf},s=(o,a,c,l)=>t.runIdempotent([o],a,c,async()=>{try{return await l()}catch(u){throw u instanceof L?u:u instanceof Error&&"code"in u&&u.code==="GLOBAL_INSTRUCTIONS_CHANGED"?new L("GLOBAL_INSTRUCTIONS_CHANGED",u.message,409):new L("PROVIDER_ERROR",u instanceof Error?u.message:"Personalization request failed",502,true)}});e.get("/v1/personalization/instructions",{schema:{response:{200:yg$1}}},()=>n().getGlobalInstructions()),e.get("/v1/personalization/memories",{schema:{response:{200:Ag$1}}},()=>n().getMemorySettings()),e.get("/v1/personalization/agent",{schema:{response:{200:Cg$1}}},()=>n().getAgentPreferences()),e.put("/v1/personalization/instructions",{schema:{body:zg,headers:X,response:{200:yg$1,...i}}},o=>s("save-global-instructions",o.headers["idempotency-key"],o.body,()=>n().saveGlobalInstructions(o.body))),e.put("/v1/personalization/memories",{schema:{body:Bg,headers:X,response:{200:Ag$1,...i}}},o=>s("update-memory-settings",o.headers["idempotency-key"],o.body,()=>n().updateMemorySettings(o.body))),e.put("/v1/personalization/agent",{schema:{body:Cg$1,headers:X,response:{200:Cg$1,...i}}},o=>s("update-agent-preferences",o.headers["idempotency-key"],o.body,()=>n().updateAgentPreferences(o.body))),e.post("/v1/personalization/memories/reset",{schema:{body:{type:"object",additionalProperties:false},headers:X,response:{200:Dg,...i}}},o=>s("reset-memories",o.headers["idempotency-key"],o.body,async()=>(await n().resetMemories(),{success:!0}))),r();};async function yqe(e){let t=e.handlerTimeoutMs??BH,r=e.loggerEnabled===false?false:{level:"info",redact:{censor:"[Redacted]",paths:["req.headers.authorization","req.headers.cookie",'req.headers["x-api-key"]','res.headers["set-cookie"]']},...e.logDestination===void 0?{}:{stream:e.logDestination}},n=(0, KJ.default)({handlerTimeout:0,logController:new nd,logger:r,rewriteUrl:A=>VJ(A.url??"/")});n.addHook("onRoute",A=>{t>0&&A.websocket!==true&&(A.handlerTimeout??=t);});let i=e.readProjectGitStatus??Y3,s=e.commitProjectChanges??bR,o=e.readProjectFileTree??Rz,a=e.readProjectFileDownload??xz,c=e.provider.fileSearch,l=e.searchProjectFiles??(A=>c===void 0?Promise.reject(new Error("Provider file search is unavailable")):c.search(A)),u=e.stopProjectFileSearch??((A,D)=>c===void 0?Promise.reject(new Error("Provider file search is unavailable")):c.stop(A,D)),d=e.readProjectImageFile??Uz,m=e.readProjectSourceFile??Gz,p=e.access===void 0?e.projectOpenService??r5():t5(),h=e.workspaceRoots===void 0?{}:{workspaceRoots:e.workspaceRoots},f=e.readProjectDirectory??((A,D)=>D6(A,{...D,...h})),g=e.resolveProjectDirectory??(A=>jk(A,h)),y=e.skillMarketService??I6({catalog:t6(),projectOpenService:p,projectRepository:e.projectRepository,provider:e.provider}),_=new Xm,v=new Ym,w=zz(_,(A,D)=>e.projectTodoRepository?.readProjectTodoAttachment(A,D)??Promise.resolve(void 0)),E=await e.provider.getCapabilities(),R=e.modelCatalogCacheMaxBytes??HH,P=e.modelCatalogCacheTtlMs??GH;if(!Number.isInteger(R)||R<=0)throw new RangeError("Model catalog cache capacity must be a positive integer");if(!Number.isFinite(P)||P<=0)throw new RangeError("Model catalog cache TTL must be a positive number");let b=new Wm($H(e.provider,e.providerConnectionRepository),{maxBytes:R,ttlMs:P});e.preloadModelCatalog===true&&await b.read().catch(()=>{});let O=new Map,F=new Map,j=new zy,N=async A=>{let D=O.get(A);return D!==void 0?(q.touch(A),D):GJ(F,A,()=>j.run(A,async()=>{let $=O.get(A);if($!==void 0)return q.touch(A),$;let V=await zJ(A,e);if(V===void 0)return;let S=O6({attachmentStore:_,...e.eventBufferSize===void 0?{}:{eventBufferSize:e.eventBufferSize},eventProvider:E.provider,...e.eventSessionId===void 0?{}:{eventSessionId:e.eventSessionId},onActivity:()=>{q.touch(A);},onAttachmentReleaseError:()=>{n.log.warn({errorCode:"ATTACHMENT_CLEANUP_FAILED"},"Failed to release turn attachments");},onTurnCompleted:k=>he.startNext(k),workbenchChanges:v,provider:V.provider,scope:V.scope});return O.set(A,S),q.touch(A),S}))},M=async(A,D=false)=>j.run(A,async()=>{q.forget(A);let $=O.get(A);$!==void 0&&($.unsubscribe(),$.eventStream.close(),O.delete(A)),await Promise.all([e.provider.releaseProject(A,$?.provider),D?_.releaseProjectRuntime(A):_.releaseProject(A)]);}),q=new Gy({cleanupIntervalMs:e.projectRuntimeCleanupIntervalMs??6e4,contexts:O,idleTtlMs:e.projectRuntimeIdleTtlMs??18e5,onReleaseError:(A,D)=>{n.log.warn({errorCode:"PROJECT_RELEASE_FAILED",projectId:D},"Failed to release idle Project runtime");},release:A=>M(A,true)}),z=async()=>(await b.read()).data,W=async A=>{let D=A??await z(),$=await e.settingsRepository.readGlobalSettings(),V=await e.provider.readDefaultSettings();return YH(D,$,V)},H=async(A,D,$)=>{let V=D??await z(),S=await e.settingsRepository.readProjectDefaults(A),k=$??await W(V),C=S??k;return {approvalPolicy:C.approvalPolicy,approvalsReviewer:C.approvalsReviewer,fastMode:C.fastMode,...Mi(V,C,k.sandboxMode)}},J=async(A,D)=>{let $=D??await z(),V=await W($),S=await H(A,$,V);return {approvalPolicy:S.approvalPolicy,approvalsReviewer:S.approvalsReviewer,model:S.model,reasoningEffort:S.reasoningEffort,sandboxMode:S.sandboxMode}},ce=async(A,D,$)=>{let V=$??await z(),S=await e.settingsRepository.readTaskSettings(A,D);if(S===void 0)return J(A,V);let k=Mi(V,S,S.sandboxMode);return {approvalPolicy:S.approvalPolicy,approvalsReviewer:S.approvalsReviewer,...k}},he=new Vy({attachmentStore:_,readTaskSettings:ce,repository:e.queueRepository??C6(),resolveProviderInput:w}),{scheduledTaskAttachmentManager:Te,scheduledTaskService:ue}=await r9(e,_,N,z,w),B=new Set,de=new Map,we=e.idempotencyCacheSize??qH,ie=e.idempotencyTtlMs??UH,U=bz(we,ie),Q=await HJ(n,{...e.access===void 0?{}:{access:e.access},...e.allowedHosts===void 0?{}:{allowedHosts:e.allowedHosts},releaseResources:async()=>{await ue.close(),await q.close(),await Promise.all([...O.keys()].map(A=>M(A))),await _.dispose(),B.clear(),U.clear(),b.clear(),de.clear();},...e.staticRoot===void 0?{}:{staticRoot:e.staticRoot}}),x={workbenchChanges:v,...e.asyncQuestionRepository===void 0?{}:{asyncQuestionRepository:e.asyncQuestionRepository},...e.projectTodoRepository===void 0?{}:{projectTodoRepository:e.projectTodoRepository},submissionRepository:e.submissionRepository??Zy(we),...Q===void 0?{}:{accessService:Q},activeGitMutations:B,assertCommitSelection:VH,assertValidProjectDefaults:Km,attachmentStore:_,buildCommitMessagePrompt:oz,capabilities:E,commitProjectChanges:s,pushProjectCommits:e.pushProjectCommits??ez,createProjectBranch:e.createProjectBranch??uz,createProjectWorktree:e.createProjectWorktree??fz,fingerprintPayload:_c,generateCommitMessageWithCodex:WH,getProjectContext:N,idempotencyCacheSize:we,installAppUpdate:e.installAppUpdate,listModels:z,maximumAttachmentBytes:MH,modelCatalogCache:b,multipartEnvelopeBytes:DH,projectContexts:O,projectOpenService:p,projectRepository:e.projectRepository,provider:e.provider,petProvider:e.petProvider,providerConnectionRepository:e.providerConnectionRepository,readAppInfo:e.readAppInfo,readAppUpdateProgress:e.readAppUpdateProgress,readEffectiveGlobalSettings:W,readEffectiveProjectDefaults:H,readEffectiveTaskSettings:ce,readFileTree:o,readFileDownload:a,deleteProjectFile:e.deleteProjectFile??Mz,renameProjectFile:e.renameProjectFile??Dz,searchProjectFiles:l,stopProjectFileSearch:u,readHostFileDirectory:e.readHostFileDirectory??_z,readProjectDirectory:f,readImageFile:d,readInheritedTaskSettings:J,readProjectGitHistory:e.readProjectGitHistory??pz,readProjectGitCommitFiles:e.readProjectGitCommitFiles??TR,readProjectGitCommitFileDiff:e.readProjectGitCommitFileDiff??RR,readProjectGitStatus:i,readProjectWorktrees:e.readProjectWorktrees??Cg,readSourceFile:m,releaseProjectContext:M,resolveProviderTurnInput:w,runIdempotent:U.run,resolveProjectDirectory:g,resolveHostAttachment:e.resolveHostAttachment??Sz,readScheduledTaskAttachment:async(A,D)=>Te===void 0?void 0:Te.read(A,D),settingsRepository:e.settingsRepository,scheduledTaskService:ue,skillMarketService:y,taskFromSnapshot:FH,taskQueue:he,taskStartRecoveries:de,switchProjectBranch:e.switchProjectBranch??lz,resolveProjectWorktree:e.resolveProjectWorktree??Ng,toGitCommitHttpError:KH,toPendingRequestHttpError:zH};return await n.register(sG,{...e.access===void 0?{}:{access:e.access},...Q===void 0?{}:{service:Q}}),await n.register(wW,x),await n.register(WJ,x),await n.register(iG,x),await n.register(dW,x),await n.register(fW,x),await n.register(cW,x),await n.register(zW,x),await n.register(e9,x),await n.register(OW,x),await n.register(CW,x),await n.register(NW,x),await n.register(LW,x),await n.register(FW,x),await n.register(UW,x),aG(n,x),await n.register(HW,x),await n.register(oG,x),await n.ready(),n}var QJ=1e3,JJ=1024*1024,XJ={name:"create_provider_connection",sql:`
|
|
565
|
+
`)&&/(?<!\r)\n/u.test(t))throw zi();return t}async function Fk(e){let t=await open(e,"r");try{let r=await t.stat({bigint:!0});if(!r.isFile()||r.size>BigInt(_g$1))throw zi();let n=Buffer.alloc(Number(r.size)+1),i=0;for(;i<n.length;){let{bytesRead:a}=await t.read(n,i,n.length-i,i);if(!a)break;i+=a;}let s=await t.stat({bigint:!0});if(BigInt(i)!==r.size||Gi(s)!==Gi(r)||Gi(await lstat(e,{bigint:!0}))!==Gi(r))throw Mk();let o=n.subarray(0,i);return {content:K6(o),version:V6(o),revision:Gi(r),mode:Number(r.mode),ino:r.ino,dev:r.dev}}finally{await t.close();}}async function Y6(e,t){let r=await Yy(e,t),n=await Fk(r.target);return {path:r.path,content:n.content,version:n.version,revision:n.revision}}async function Q6(e,t){let{target:r}=await Yy(e,t.path),n=Buffer.from(t.content,"utf8");if(K6(n)!==t.content)throw zi();let s=(Ky.get(r)??Promise.resolve()).catch(()=>{}).then(async()=>{let o=await Fk(r);if(o.version!==t.expectedVersion)throw Mk();let a=join(dirname(r),`.codexly-edit-${randomUUID()}.tmp`),c=await open(a,"wx",384);try{await c.writeFile(n),await c.chmod(o.mode&511),await c.sync();let l=await c.stat({bigint:!0});await Yy(e,t.path);let u=await Fk(r);if(u.version!==o.version||u.ino!==o.ino||u.dev!==o.dev)throw Mk();await rename(a,r);let d=await c.stat({bigint:!0}).catch(()=>null),m=await lstat(r,{bigint:!0}).catch(()=>null);return {version:V6(n),...d!==null&&m!==null&&d.size===l.size&&d.mtimeNs===l.mtimeNs&&Gi(d)===Gi(m)?{revision:Gi(d)}:{}}}finally{await c.close(),await unlink(a).catch(l=>{if(l.code!=="ENOENT")throw l});}});Ky.set(r,s);try{return await s}finally{Ky.get(r)===s&&Ky.delete(r);}}function $k(e,t){return t instanceof Qc?e.code(t.code==="TEXT_FILE_CONFLICT"?409:400).send({code:t.code,message:t.message,retryable:false}):t instanceof mt?e.code(t.code==="PROJECT_NOT_FOUND"?404:400).send({code:t.code,message:t.message,retryable:false}):e.code(404).send({code:"TEXT_FILE_UNAVAILABLE",message:"Text file is unavailable",retryable:false})}function J6(e,t){let r={400:Xf,404:Xf,409:Xf};e.get("/v1/projects/:projectId/files/text/revision",{schema:{params:ge,querystring:xb,response:{200:$g$1,...r}}},async(n,i)=>{try{let s=await t(n.params.projectId,n.query.rootPath);return i.header("cache-control","no-store"),await W6(s.path,n.query.path)}catch(s){return $k(i,s)}}),e.get("/v1/projects/:projectId/files/text",{schema:{params:ge,querystring:xb,response:{200:ah,...r}}},async(n,i)=>{try{let s=await t(n.params.projectId,n.query.rootPath);return i.header("cache-control","no-store"),await Y6(s.path,n.query.path)}catch(s){return $k(i,s)}}),e.post("/v1/projects/:projectId/files/text",{bodyLimit:_g$1*6+8192,schema:{params:ge,querystring:Y,body:bh,response:{200:ch,...r}}},async(n,i)=>{try{let s=await t(n.params.projectId,n.query.rootPath);return await Q6(s.path,n.body)}catch(s){return $k(i,s)}});}function X6(e){if(e instanceof mt)throw new L(e.code==="PROJECT_NOT_FOUND"?"PROJECT_NOT_FOUND":"INVALID_REQUEST",e.message,e.code==="PROJECT_NOT_FOUND"?404:400);if(e.code==="ENOENT")throw new L("PROJECT_FILE_NOT_FOUND","Project file was not found",404);if(e instanceof TypeError){let r=e.message.includes("already exists");throw new L(r?"PROJECT_FILE_CONFLICT":"INVALID_REQUEST",r?"A file or directory with that name already exists":"Project file request is invalid",r?409:400)}throw new L("PROJECT_FILE_MUTATION_FAILED","Project file mutation failed",500)}var Z6={400:Xf,404:Xf,409:Xf,500:Xf,503:Xf};function eW(e){let t=posix.dirname(e);return t==="."?void 0:t}function tW(e,t,r){let{deleteProjectFile:n,readFileTree:i,renameProjectFile:s,runIdempotent:o}=t;J6(e,r),e.post("/v1/projects/:projectId/files/rename",{schema:{body:tb,headers:X,params:ge,querystring:Y,response:{200:ub,...Z6}}},async a=>o(["rename-project-file",a.params.projectId,a.query.rootPath,a.body.path],a.headers["idempotency-key"],a.body,async()=>{try{let c=await r(a.params.projectId,a.query.rootPath),l=await s(c.path,a.body.path,a.body.name),u=await i(c.path,eW(a.body.path));return {...l,tree:u}}catch(c){X6(c);}})),e.post("/v1/projects/:projectId/files/delete",{schema:{body:vb,headers:X,params:ge,querystring:Y,response:{200:wb,...Z6}}},async a=>o(["delete-project-file",a.params.projectId,a.query.rootPath,a.body.path],a.headers["idempotency-key"],a.body,async()=>{try{let c=await r(a.params.projectId,a.query.rootPath),l=await n(c.path,a.body.path),u=await i(c.path,eW(a.body.path));return {...l,tree:u}}catch(c){X6(c);}}));}function Jy(e,t,r,n){let{content:i,mediaType:s}=t,o=`"${createHash("sha256").update(i).digest("hex")}"`;return e.header("cache-control",`private, max-age=${String(r)}`).header("etag",o).header("x-content-type-options","nosniff").type(s),n?.split(",").some(c=>{let l=c.trim().replace(/^W\//u,"");return l===o||l==="*"})?e.code(304).send():e.send(Buffer.from(i.buffer,i.byteOffset,i.byteLength))}function rW(e,t){let{attachmentStore:r,getProjectContext:n,maximumAttachmentBytes:i,multipartEnvelopeBytes:s,projectRepository:o,readFileTree:a,readFileDownload:c,searchProjectFiles:l,readImageFile:u,readSourceFile:d,runIdempotent:m,resolveHostAttachment:p,stopProjectFileSearch:h}=t;tW(e,t,(f,g)=>Wy(o,n,f,g)),e.get("/v1/projects/:projectId/files/download",{schema:{params:ge,querystring:xb,response:{400:le,404:le}}},async(f,g)=>{let y=await Gs(o,n,f.params.projectId,f.query.rootPath,g);if(y!==void 0)try{let _=await c(y.path,f.query.path);return await g.header("content-disposition",Dc(_.name)).header("x-content-type-options","nosniff").type("application/octet-stream").send(_.content)}catch{return g.code(404).send({code:"PROJECT_FILE_NOT_FOUND",message:"Project file is unavailable"})}}),e.get("/v1/projects/:projectId/files/tree",{schema:{params:ge,querystring:qb$1,response:{200:rb$1,400:le,404:le,500:le}}},async(f,g)=>{let y=await Gs(o,n,f.params.projectId,f.query.rootPath,g);if(y!==void 0)try{return await a(y.path,f.query.path)}catch{return g.code(500).send({code:"PROJECT_FILE_TREE_UNAVAILABLE",message:"Project file tree is unavailable"})}}),e.get("/v1/projects/:projectId/files/search",{schema:{params:ge,querystring:ma,response:{200:oa,400:le,404:le,500:le}}},async(f,g)=>{let y=await Gs(o,n,f.params.projectId,f.query.rootPath,g);if(y!==void 0)try{let _=await l({projectId:f.params.projectId,query:f.query.query,roots:[y.path],sessionId:f.query.sessionId,signal:f.signal});return {data:(await q6(y.path,_)).data.map(w=>({name:w.name,path:w.path,rootId:y.id,rootPath:y.path}))}}catch(_){if(f.signal.aborted||_ instanceof Error&&_.name==="AbortError")throw _;return g.code(500).send({code:"PROJECT_FILE_SEARCH_UNAVAILABLE",message:"Project file search is unavailable"})}}),e.post("/v1/projects/:projectId/files/search/stop",{schema:{body:pa,headers:X,params:ge,response:{200:qa,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async f=>m(["project-file-search-stop",f.params.projectId,f.body.sessionId],f.headers["idempotency-key"],f.body,async()=>{try{await Wy(o,n,f.params.projectId,f.body.rootPath);}catch(g){throw g instanceof mt?new L(g.code==="PROJECT_NOT_FOUND"?"PROJECT_NOT_FOUND":"INVALID_REQUEST",g.message,g.code==="PROJECT_NOT_FOUND"?404:400):g}try{await h(f.params.projectId,f.body.sessionId);}catch{throw new L("PROVIDER_ERROR","Project file search is unavailable",502,true)}return {}})),e.get("/v1/projects/:projectId/files/image",{schema:{params:ge,querystring:xb,response:{400:le,404:le}}},async(f,g)=>{let y=await Gs(o,n,f.params.projectId,f.query.rootPath,g);if(y!==void 0)try{let _=await u(y.path,f.query.path);return await Jy(g,_,60,f.headers["if-none-match"])}catch{return g.code(404).send({code:"PROJECT_IMAGE_NOT_FOUND",message:"Project image is unavailable"})}}),e.get("/v1/projects/:projectId/files/source",{schema:{params:ge,querystring:xb,response:{200:yb,400:le,404:le}}},async(f,g)=>{let y=await Gs(o,n,f.params.projectId,f.query.rootPath,g);if(y!==void 0)try{return await d(y.path,f.query.path,f.query.cursor??0)}catch{return g.code(404).send({code:"SOURCE_FILE_NOT_FOUND",message:"Source file is unavailable"})}}),e.post("/v1/projects/:projectId/attachments/:kind/host",{schema:{body:Ba$1,headers:X,params:JH,response:{201:dd$1,400:Xf,404:Xf,409:Xf,413:Xf,502:Xf,503:Xf}}},async(f,g)=>{if(await n(f.params.projectId)===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let y;try{let _=await p(f.params.kind,f.body.path);y=await r.add(f.params.projectId,_);let v=y,w=await m(["import-host-attachment",f.params.projectId],f.headers["idempotency-key"],{contentDigest:y.contentDigest,kind:y.attachment.kind,mediaType:y.attachment.mediaType,name:y.attachment.name,size:y.attachment.size},()=>v.attachment);return w.id!==y.attachment.id&&await r.discard(y.attachment.id),await g.code(201).send({attachment:w})}catch(_){throw y!==void 0&&await r.discard(y.attachment.id),_ instanceof RangeError?new L("INVALID_REQUEST","Attachment is too large",413):_ instanceof mr||_ instanceof TypeError?new L("INVALID_REQUEST","Host attachment is invalid",400):_}}),e.post("/v1/projects/:projectId/attachments/:kind",{schema:{headers:X,params:QH,response:{201:dd$1,400:Xf,409:Xf,413:Xf,502:Xf,503:Xf}}},async(f,g)=>{let y=i(f.params.kind),_=Number(f.headers["content-length"]);if(Number.isFinite(_)&&_>y+s)throw new L("INVALID_REQUEST","Attachment is too large",413);if(await n(f.params.projectId)===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if(!f.isMultipart())throw new L("INVALID_REQUEST","Attachment must use multipart/form-data",400);let v;try{let w=await f.file({limits:{fields:0,files:1,fileSize:y,parts:1}});if(w?.fieldname!=="attachment")throw new TypeError("Attachment file part is missing");if(v=await r.add(f.params.projectId,{content:w.file,kind:f.params.kind,mediaType:w.mimetype,name:w.filename}),w.file.truncated)throw new RangeError("Attachment exceeds the maximum size");let E=v,R=await m(["upload-attachment",f.params.projectId],f.headers["idempotency-key"],{contentDigest:v.contentDigest,kind:f.params.kind,mediaType:v.attachment.mediaType,name:v.attachment.name,size:v.attachment.size},()=>E.attachment);return R.id!==v.attachment.id&&await r.discard(v.attachment.id),await g.code(201).send({attachment:R})}catch(w){throw v!==void 0&&await r.discard(v.attachment.id),w instanceof RangeError||w instanceof e.multipartErrors.RequestFileTooLargeError?new L("INVALID_REQUEST","Attachment is too large",413):w instanceof TypeError?new L("INVALID_REQUEST","Attachment is invalid",400):w}}),e.get("/v1/projects/:projectId/attachments/:attachmentId",{schema:{params:XH,response:{404:le}}},async(f,g)=>{try{let y=await r.read(f.params.projectId,f.params.attachmentId);return await g.header("x-content-type-options","nosniff").type(y.attachment.mediaType).send(y.content)}catch(y){if(y instanceof er){let _=await t.projectTodoRepository?.readProjectTodoAttachment(f.params.projectId,f.params.attachmentId)??await t.readScheduledTaskAttachment(f.params.projectId,f.params.attachmentId);return _!==void 0?$6(g,_):g.code(404).send({code:"ATTACHMENT_NOT_FOUND",message:"Attachment not found"})}throw y}});}async function Yd(e,t,r,n){try{return await ui(e,t,r)}catch(i){if(i instanceof mt){let s=i.code==="PROJECT_NOT_FOUND"?404:400;await n.code(s).send({code:i.code,message:i.message});return}throw i}}async function zo(e,t,r){try{return await ui(e,t,r)}catch(n){throw n instanceof mt?new L(n.code==="PROJECT_NOT_FOUND"?"PROJECT_NOT_FOUND":"INVALID_REQUEST",n.message,n.code==="PROJECT_NOT_FOUND"?404:400):n}}function Qd(e){let{rootPath:t,...r}=e;return r}function nW(e,t,r){let{projectRepository:n,runIdempotent:i,activeGitMutations:s,pushProjectCommits:o,toGitCommitHttpError:a}=t;e.post("/v1/projects/:projectId/git/push",{schema:{body:lb,headers:X,params:ge,querystring:Y,response:{200:nb$1,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async c=>{let l=await zo(n,c.params.projectId,c.query.rootPath),u=`${c.params.projectId}\0${l}`;return i(["push-project-commits",u],c.headers["idempotency-key"],{request:c.body,rootPath:l},async()=>{let d=c.body.action!=="inspect";d&&(r(u),s.add(u));try{return await o(l,c.body)}catch(m){throw m instanceof pr?a(m):new L("GIT_PUSH_FAILED",qe(m,"Git push failed"),502)}finally{d&&s.delete(u);}})});}function qk(e){switch(e.code){case "SNAPSHOT_MISMATCH":return new L("GIT_STATUS_CHANGED","Git working tree changed",409,true);case "ALREADY_ACTIVE":return new L("GIT_WORKTREE_ALREADY_ACTIVE",e.message,409,true);case "WORKTREE_NOT_FOUND":return new L("GIT_WORKTREE_NOT_FOUND",e.message,409,true);case "INVALID_BRANCH_NAME":return new L("GIT_BRANCH_INVALID",e.message,400,false);case "REPOSITORY_READ_ONLY":return new L("GIT_REPOSITORY_READ_ONLY",e.message,409,true);case "CREATE_FAILED":return new L("GIT_WORKTREE_CREATE_FAILED",e.message,502,true)}}function sW(e,t){let{activeGitMutations:r,createProjectWorktree:n,projectRepository:i,readProjectGitStatus:s,readProjectWorktrees:o,resolveProjectWorktree:a,runIdempotent:c}=t,l=m=>{if(r.has(m))throw new L("GIT_MUTATION_IN_PROGRESS","Another Git mutation is already in progress",409,true)},u=async(m,p)=>{try{return await ui(i,m,p)}catch(h){throw h instanceof mt?new L(h.code==="PROJECT_NOT_FOUND"?"PROJECT_NOT_FOUND":"INVALID_REQUEST",h.message,h.code==="PROJECT_NOT_FOUND"?404:400):h}},d=async m=>{let[p,h]=await Promise.all([i.list(),o(m)]);return {projects:{data:p,nextCursor:null},worktrees:h}};e.get("/v1/projects/:projectId/git/worktrees",{schema:{params:ge,querystring:Y,response:{200:cb,400:le,404:le,500:le}}},async(m,p)=>{try{let h=await ui(i,m.params.projectId,m.query.rootPath);return await o(h)}catch(h){if(h instanceof mt){let f=h.code==="PROJECT_NOT_FOUND"?404:400;return p.code(f).send({code:h.code,message:h.message})}return p.code(500).send({code:"GIT_WORKTREE_LIST_FAILED",message:qe(h,"Git worktree list failed")})}}),e.post("/v1/projects/:projectId/git/task-worktrees",{schema:{body:db$1,headers:X,params:ge,querystring:Y,response:{200:hb,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async m=>{let p=await u(m.params.projectId,m.query.rootPath),h=`${m.params.projectId}\0${p}`;return c(["create-task-worktree",h],m.headers["idempotency-key"],{request:m.body,rootPath:p},async()=>{l(h),r.add(h);try{return {worktree:await n(p,m.body)}}catch(f){throw f instanceof Gt?qk(f):new L("GIT_WORKTREE_CREATE_FAILED",qe(f,"Git worktree creation failed"),502,true)}finally{r.delete(h);}})}),e.post("/v1/projects/:projectId/git/worktrees",{schema:{body:db$1,headers:X,params:ge,querystring:Y,response:{200:gb,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async m=>{let p=await u(m.params.projectId,m.query.rootPath),h=`${m.params.projectId}\0${p}`;return c(["create-project-worktree",h],m.headers["idempotency-key"],{request:m.body,rootPath:p},async()=>{l(h),r.add(h);try{let f=await n(p,m.body),g=await i.register({idempotencyKey:m.headers["idempotency-key"],name:basename(f.path),roots:[{path:f.path}]}),[y,_]=await Promise.all([d(p),s(p)]);return {project:g,...y,status:_,worktree:f}}catch(f){throw f instanceof Gt?qk(f):new L("GIT_WORKTREE_CREATE_FAILED",qe(f,"Git worktree creation failed"),502,true)}finally{r.delete(h);}})}),e.post("/v1/projects/:projectId/git/worktree",{schema:{body:eb,headers:X,params:ge,querystring:Y,response:{200:fb,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async m=>{let p=await u(m.params.projectId,m.query.rootPath);return c(["switch-project-worktree",m.params.projectId,p],m.headers["idempotency-key"],{request:m.body,rootPath:p},async()=>{try{let h=await a(p,m.body.path);return {project:await i.register({idempotencyKey:m.headers["idempotency-key"],name:basename(h.path),roots:[{path:h.path}]}),...await d(p),worktree:h}}catch(h){throw h instanceof Gt?qk(h):new L("PROVIDER_ERROR",qe(h,"Git worktree switch failed"),502,true)}})});}function Uk(e){switch(e.code){case "SNAPSHOT_MISMATCH":return new L("GIT_STATUS_CHANGED","Git working tree changed",409,true);case "ALREADY_ACTIVE":return new L("GIT_BRANCH_ALREADY_ACTIVE",e.message,409,true);case "BRANCH_ALREADY_EXISTS":return new L("GIT_BRANCH_ALREADY_EXISTS",e.message,409,true);case "BRANCH_NOT_FOUND":return new L("GIT_BRANCH_NOT_FOUND",e.message,409,true);case "INVALID_BRANCH_NAME":return new L("GIT_BRANCH_INVALID",e.message,400,false);case "REPOSITORY_READ_ONLY":return new L("GIT_REPOSITORY_READ_ONLY",e.message,409,true);case "SWITCH_FAILED":return new L("GIT_BRANCH_SWITCH_FAILED",e.message,502,true);case "CREATE_FAILED":return new L("GIT_BRANCH_CREATE_FAILED",e.message,502,true)}}function oW(e,t){let{activeGitMutations:r,assertCommitSelection:n,buildCommitMessagePrompt:i,commitProjectChanges:s,createProjectBranch:o,generateCommitMessageWithCodex:a,getProjectContext:c,listModels:l,projectRepository:u,readEffectiveGlobalSettings:d,readProjectGitHistory:m,readProjectGitCommitFiles:p,readProjectGitCommitFileDiff:h,readProjectGitStatus:f,runIdempotent:g,switchProjectBranch:y,toGitCommitHttpError:_}=t;sW(e,t);let v=E=>{if(r.has(E))throw new L("GIT_MUTATION_IN_PROGRESS","Another Git mutation is already in progress",409,true)};nW(e,t,v),e.get("/v1/projects/:projectId/git/status",{schema:{params:ge,querystring:Sa,response:{200:Ra,400:le,404:le,500:le}}},async(E,R)=>{let P=await Yd(u,E.params.projectId,E.query.rootPath,R);if(P!==void 0)try{return await f(P,Qd(E.query))}catch(b){return b instanceof jo?R.code(404).send({code:"GIT_REPOSITORY_NOT_FOUND",message:b.message}):R.code(500).send({code:"GIT_STATUS_UNAVAILABLE",message:qe(b,"Git working tree status is unavailable")})}}),e.get("/v1/projects/:projectId/git/history",{schema:{params:ge,querystring:Ua,response:{200:Va,400:le,404:le,500:le}}},async(E,R)=>{let P=await Yd(u,E.params.projectId,E.query.rootPath,R);if(P!==void 0)try{return await m(P,Qd(E.query))}catch(b){return b instanceof Cs&&b.code==="INVALID_CURSOR"?R.code(400).send({code:"INVALID_REQUEST",message:b.message}):b instanceof Cs&&b.code==="REPOSITORY_NOT_FOUND"?R.code(404).send({code:"GIT_REPOSITORY_NOT_FOUND",message:b.message}):R.code(500).send({code:"GIT_HISTORY_UNAVAILABLE",message:qe(b,"Git history is unavailable")})}});let w=(E,R)=>E instanceof Cn&&E.code==="INVALID_CURSOR"?R.code(400).send({code:"INVALID_REQUEST",message:E.message}):E instanceof Cn&&E.code==="REPOSITORY_NOT_FOUND"?R.code(404).send({code:"GIT_REPOSITORY_NOT_FOUND",message:E.message}):R.code(500).send({code:"GIT_COMMIT_REVIEW_UNAVAILABLE",message:qe(E,"Git commit review is unavailable")});e.get("/v1/projects/:projectId/git/commit-files",{schema:{params:ge,querystring:Wa,response:{200:Ya,400:le,404:le,500:le}}},async(E,R)=>{let P=await Yd(u,E.params.projectId,E.query.rootPath,R);if(P!==void 0)try{return await p(P,Qd(E.query))}catch(b){return w(b,R)}}),e.get("/v1/projects/:projectId/git/commit-diff",{schema:{params:ge,querystring:Za,response:{200:_a,400:le,404:le,500:le}}},async(E,R)=>{let P=await Yd(u,E.params.projectId,E.query.rootPath,R);if(P!==void 0)try{return await h(P,Qd(E.query))}catch(b){return w(b,R)}}),e.post("/v1/projects/:projectId/git/branch",{schema:{body:$a,headers:X,params:ge,querystring:Y,response:{200:Ra,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async E=>{let R=await zo(u,E.params.projectId,E.query.rootPath),P=`${E.params.projectId}\0${R}`;return g(["switch-project-branch",P],E.headers["idempotency-key"],{request:E.body,rootPath:R},async()=>{v(P),r.add(P);try{return await y(R,E.body)}catch(b){throw b instanceof Er?Uk(b):new L("GIT_BRANCH_SWITCH_FAILED",qe(b,"Git branch switch failed"),502,true)}finally{r.delete(P);}})}),e.post("/v1/projects/:projectId/git/branches",{schema:{body:ab,headers:X,params:ge,querystring:Y,response:{200:Ra,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async E=>{let R=await zo(u,E.params.projectId,E.query.rootPath),P=`${E.params.projectId}\0${R}`;return g(["create-project-branch",P],E.headers["idempotency-key"],{request:E.body,rootPath:R},async()=>{v(P),r.add(P);try{return await o(R,E.body)}catch(b){throw b instanceof Er?Uk(b):new L("GIT_BRANCH_CREATE_FAILED",qe(b,"Git branch creation failed"),502,true)}finally{r.delete(P);}})}),e.post("/v1/projects/:projectId/git/commit-message",{schema:{body:ib,headers:X,params:ge,querystring:Y,response:{200:jb,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async E=>{let R=await c(E.params.projectId);if(R===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let P=await zo(u,E.params.projectId,E.query.rootPath);return g(["generate-commit-message",E.params.projectId,P],E.headers["idempotency-key"],{request:E.body,rootPath:P},async()=>{let b=await f(P,{includeDiff:true,...E.body.repository===void 0?{}:{repository:E.body.repository}}).catch(q=>{throw new L("GIT_REPOSITORY_UNAVAILABLE",qe(q,"Git repository is unavailable"),409)});n(b,E.body);let O=await l(),F=await d(O),N={approvalPolicy:"never",approvalsReviewer:"user",...Mi(O,{model:F.commitMessageModel,sandboxMode:"read-only"},"read-only")};return {message:await a(R.provider,i(b,E.body,F.commitMessagePrompt),N),snapshot:b.snapshot}})}),e.post("/v1/projects/:projectId/git/commits",{schema:{body:kb,headers:X,params:ge,querystring:Y,response:{201:ob,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(E,R)=>{let P=await zo(u,E.params.projectId,E.query.rootPath),b=`${E.params.projectId}\0${P}`,O=await g(["commit-project-changes",b],E.headers["idempotency-key"],{request:E.body,rootPath:P},async()=>{v(b),r.add(b);try{let F=await s(P,E.body),j=E.body.repository,[N,M]=await Promise.all([m(P,j?{repository:j}:{}),f(P,j?{repository:j}:{})]);return {...F,history:N,status:M}}catch(F){throw F instanceof pr?_(F):new L("GIT_COMMIT_FAILED",qe(F,"Git commit failed"),502)}finally{r.delete(b);}});return R.code(201).send(O)});}function aW(e,t){e.post("/v1/project-directories",{schema:{body:_,headers:X,response:{200:$,400:Xf,409:Xf}}},async r=>t.runIdempotent(["create-project-directory"],r.headers["idempotency-key"],r.body,async()=>{if(!Z(r.body.name))throw new L("INVALID_REQUEST","Invalid folder name",400);try{let n=await t.resolveProjectDirectory(r.body.parentPath),i=join(n,r.body.name);try{return await mkdir(i),{path:i,status:"created"}}catch(s){if(s.code!=="EEXIST")throw s;let o=await lstat(i);return {path:i,status:o.isDirectory()?"exists-directory":"exists-file"}}}catch{throw new L("INVALID_REQUEST","Folder could not be created; check the parent directory and permissions",400)}}));}var cW=(e,t,r)=>{aW(e,t);let{assertValidProjectDefaults:n,getProjectContext:i,listModels:s,projectOpenService:o,projectRepository:a,readEffectiveProjectDefaults:c,readHostFileDirectory:l,readProjectDirectory:u,releaseProjectContext:d,runIdempotent:m,resolveProjectDirectory:p,settingsRepository:h}=t,f=async()=>({data:await a.list(),nextCursor:null});e.get("/v1/projects",{schema:{response:{200:Ce}}},f),e.get("/v1/host-files",{schema:{querystring:ya$1,response:{200:Aa,400:Xf}}},async g=>{try{return await l(g.query.kind,g.query.path,{...g.query.includeHidden===void 0?{}:{includeHidden:g.query.includeHidden}})}catch(y){throw y instanceof mr?new L("INVALID_REQUEST",y.message,400):y}}),e.get("/v1/project-directories",{schema:{querystring:ta,response:{200:wa,400:Xf}}},async g=>{try{return await u(g.query.path,{...g.query.includeHidden===void 0?{}:{includeHidden:g.query.includeHidden}})}catch(y){throw y instanceof Vr?new L("INVALID_REQUEST",y.message,400):y}}),e.get("/v1/projects/:projectId/open-capabilities",{schema:{params:ge,response:{200:Ia,404:le}}},async(g,y)=>await a.read(g.params.projectId)===void 0?y.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):o.getCapabilities()),e.post("/v1/projects/:projectId/open",{schema:{body:Ja$1,headers:X,params:ge,querystring:Y,response:{200:Ka,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async g=>m(["open-project",g.params.projectId],g.headers["idempotency-key"],{request:g.body,rootPath:g.query.rootPath},async()=>{let y;try{y=await ui(a,g.params.projectId,g.query.rootPath);}catch(_){throw _ instanceof mt?new L(_.code==="PROJECT_NOT_FOUND"?"PROJECT_NOT_FOUND":"INVALID_REQUEST",_.message,_.code==="PROJECT_NOT_FOUND"?404:400):_}try{await o.open(y,g.body.appId,g.body.path);}catch(_){throw _ instanceof Ns?new L("INVALID_REQUEST","Project open app is unavailable",409):_ instanceof gr?new L("INVALID_REQUEST","Project open target is invalid",400):new L("PROVIDER_ERROR","Project could not be opened",502,true)}return g.body})),e.put("/v1/projects/order",{schema:{body:La,headers:X,response:{200:De,400:Xf,409:Xf,502:Xf,503:Xf}}},async g=>m(["reorder-projects"],g.headers["idempotency-key"],g.body,async()=>{let y=await a.list(),_=new Set(y.map(w=>w.id));if(!(g.body.projectIds.length===y.length&&g.body.projectIds.every(w=>_.has(w))))throw new L("INVALID_REQUEST","Project order must contain every project exactly once",409);return {data:await a.reorder(g.body.projectIds),nextCursor:null}})),e.get("/v1/projects/:projectId/skills",{schema:{params:ge,response:{200:Ge$1,404:le}}},async(g,y)=>{let _=await i(g.params.projectId);return _===void 0?y.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):_.provider.listSkills()}),e.get("/v1/projects/:projectId/defaults",{schema:{params:ge,response:{200:Ed,404:le}}},async(g,y)=>await i(g.params.projectId)===void 0?y.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):{settings:await c(g.params.projectId)}),e.put("/v1/projects/:projectId/defaults",{schema:{body:Dd$1,headers:X,params:ge,response:{200:Ed,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async g=>m(["update-project-defaults",g.params.projectId],g.headers["idempotency-key"],g.body,async()=>{if(await i(g.params.projectId)===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);return n(await s(),g.body),{settings:await h.writeProjectDefaults(g.params.projectId,g.body)}})),e.post("/v1/projects",{schema:{body:Ca,headers:X,response:{200:Da,400:Xf,409:Xf,502:Xf,503:Xf}}},async g=>m(["add-project"],g.headers["idempotency-key"],g.body,async()=>{let y;try{y=await Promise.all(g.body.roots.map(v=>p(v.path)));}catch(v){throw v instanceof Vr?new L("INVALID_REQUEST",v.message,400):v}return {project:await a.register({idempotencyKey:g.headers["idempotency-key"],name:basename(y[0]??""),roots:y.map(v=>({path:v}))}),projects:await f()}})),e.post("/v1/projects/:projectId/rename",{schema:{body:Ma,headers:X,params:ge,response:{200:Na,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async g=>m(["rename-project",g.params.projectId],g.headers["idempotency-key"],g.body,async()=>{let y=await a.rename(g.params.projectId,g.body.name.trim());if(y===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);return {project:y,projects:await f()}})),e.post("/v1/projects/:projectId/remove",{schema:{body:Oa,headers:X,params:ge,response:{200:Pa,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async g=>m(["remove-project",g.params.projectId],g.headers["idempotency-key"],g.body,async()=>{if(!await a.remove(g.params.projectId))throw new L("PROJECT_NOT_FOUND","Project not found",404);return await d(g.params.projectId),{projectId:g.params.projectId,projects:await f(),status:"removed"}})),oW(e,t),rW(e,t),F6(e,t),r();};function lW(e){return e.trim().replace(/\/+$/u,"")}function V1e(e,t){return e!==null&&lW(e)===lW(t)}function W1e(e){return {data:e.data.map(t=>({...t,supportedReasoningEfforts:[...t.supportedReasoningEfforts]})),nextCursor:e.nextCursor}}async function uW(e,t){if(e.models!==void 0&&e.models.length>0)return;let r=await t.readProviderConnection().catch(()=>{});if(r?.mode==="custom"&&V1e(r.customBaseUrl,e.baseUrl)&&r.customModels!==null&&r.customModels.data.length>0)return o(W1e(r.customModels))}var Xy={400:Xf,409:Xf,502:Xf,503:Xf},dW=(e,t,r)=>{let{modelCatalogCache:n,provider:i,providerConnectionRepository:s,runIdempotent:o}=t;e.get("/v1/provider-connection",{schema:{response:{200:Ne}}},()=>i.readProviderConnection()),e.post("/v1/provider-connection/official-login",{schema:{body:Oe,headers:X,response:{200:Pe,...Xy}}},a=>o(["start-official-provider-login"],a.headers["idempotency-key"],a.body,async()=>{let c=await i.startOfficialProviderLogin();return await s.writeProviderConnection({customBaseUrl:null,customModels:null,mode:"official",updatedAt:new Date().toISOString()}),n.clear(),c})),e.post("/v1/provider-connection/official-login/cancel",{schema:{body:Se$1,headers:X,response:{200:Te,...Xy}}},a=>o(["cancel-provider-login",a.body.loginId],a.headers["idempotency-key"],a.body,()=>i.cancelProviderLogin(a.body.loginId))),e.put("/v1/provider-connection/custom",{schema:{body:Qe$1,headers:X,response:{200:Re,...Xy}}},a=>o(["configure-custom-provider"],a.headers["idempotency-key"],a.body,async()=>{let c=await i.configureCustomProvider(a.body,()=>uW(a.body,s));return await s.writeProviderConnection({customBaseUrl:c.status.customBaseUrl,customModels:c.models,mode:"custom",updatedAt:new Date().toISOString()}),n.replace(c.models),c})),e.post("/v1/provider-connection/logout",{schema:{body:Oe,headers:X,response:{200:Te,...Xy}}},a=>o(["logout-provider"],a.headers["idempotency-key"],a.body,async()=>{let c=await i.logoutProvider();return n.clear(),c})),r();};var Y1e={additionalProperties:false,properties:{assetId:{pattern:"^[a-f0-9]{64}$",type:"string"}},required:["assetId"],type:"object"},fW=(e,{petProvider:t,runIdempotent:r},n)=>{e.get("/v1/pets",{schema:{response:{200:fa,500:le}}},async(i,s)=>{try{return {data:await t.listPets()}}catch{return s.code(500).send({code:"PET_CATALOG_UNAVAILABLE",message:"Pet catalog is unavailable"})}}),e.get("/v1/pets/assets/:assetId",{schema:{params:Y1e,response:{404:le,422:le,500:le}}},async(i,s)=>{try{let o=await t.openPetAsset(i.params.assetId);return o===void 0?await s.code(404).send({code:"PET_NOT_FOUND",message:"Pet asset not found"}):(s.header("Cache-Control","private, no-cache").header("Cross-Origin-Resource-Policy","same-origin").header("ETag",o.etag).header("X-Content-Type-Options","nosniff"),i.headers["if-none-match"]===o.etag?await s.code(304).send():await s.type(o.contentType).send(Buffer$1.from(o.content)))}catch(o){return o instanceof a$1&&o.code==="invalid"?await s.code(422).send({code:"PET_ASSET_INVALID",message:"Pet asset is invalid"}):await s.code(500).send({code:"PET_ASSET_UNAVAILABLE",message:"Pet asset is unavailable"})}}),e.post("/v1/pets/downloads",{schema:{body:ga,headers:X,response:{200:ha,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async i=>r(["download-workbench-pet",i.body.petId],i.headers["idempotency-key"],i.body,async()=>{try{return await t.ensurePetAsset(i.body.petId),{pets:{data:await t.listPets()}}}catch(s){if(s instanceof a$1){if(s.code==="not_found")throw new L("PET_NOT_FOUND","Pet not found",404);if(s.code==="invalid")throw new L("PET_ASSET_INVALID","Pet cannot be downloaded",400)}throw new L("PET_DOWNLOAD_FAILED","Pet asset download failed",502,true)}})),n();};var J1e=["approvalPolicy","approvalsReviewer","model","modelContextWindow","reasoningEffort","sandboxMode","fastMode"];function hW(e){let t=Promise.resolve();return r=>{let n=t.catch(()=>{}).then(async()=>{let i=await e.readEffectiveGlobalSettings(),s=Object.fromEntries(J1e.filter(o=>!isDeepStrictEqual(i[o],r[o])).map(o=>[o,r[o]]));return Object.keys(s).length>0&&await e.provider.updateDefaultSettings(s),await e.settingsRepository.writeGlobalSettings(r),e.readEffectiveGlobalSettings()});return t=n,n}}var Bk="https://www.bing.com",X1e=`${Bk}/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN`,pW=1e4,Z1e=64*1024,eNe=20*1024*1024;function tNe(e,t){return globalThis.fetch(e,t)}async function Jd(e,t,r){if(!e.ok||e.body===null)throw new Error(`Bing wallpaper ${r} request failed`);let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>t)throw new Error(`Bing wallpaper ${r} response is too large`);let i=[],s=0,o=e.body.getReader(),a=await o.read();for(;!a.done;){let c=a.value;if(s+=c.byteLength,s>t)throw await o.cancel(),new Error(`Bing wallpaper ${r} response is too large`);i.push(Buffer.from(c)),a=await o.read();}return Buffer.concat(i,s)}function rNe(e){let t;try{t=JSON.parse(e.toString("utf8"));}catch{throw new Error("Bing wallpaper returned invalid metadata")}let r=mW(t)?t.images:null,n=Array.isArray(r)?r[0]:null,i=mW(n)?n.url:null;if(typeof i!="string"||!i.startsWith("/"))throw new Error("Bing wallpaper returned an invalid image URL");let s=new URL(i,Bk);if(s.origin!==Bk||s.pathname!=="/th")throw new Error("Bing wallpaper returned an invalid image URL");return s.toString()}function mW(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function nNe(e){let t=await e(X1e,{headers:{"user-agent":ia},redirect:"error",signal:AbortSignal.timeout(pW)});if(!t.headers.get("content-type")?.startsWith("application/json"))throw new Error("Bing wallpaper returned invalid metadata content type");let r=await Jd(t,Z1e,"metadata"),n=rNe(r),i=await e(n,{headers:{"user-agent":ia},redirect:"error",signal:AbortSignal.timeout(pW)});if(!i.headers.get("content-type")?.startsWith("image/jpeg"))throw new Error("Bing wallpaper returned invalid image content type");let s=await Jd(i,eNe,"image");if(s.length<4||s[0]!==255||s[1]!==216||s[2]!==255)throw new Error("Bing wallpaper returned invalid JPEG content");return {body:s,contentType:"image/jpeg"}}function gW({fetcher:e=tNe}={}){let t=null,r=null,n=0;return {read(i){if(t?.day===i)return Promise.resolve(t.wallpaper);if(r?.day===i)return r.promise;let s=++n,o=nNe(e).then(c=>(s===n&&(t={day:i,wallpaper:c}),c));r={day:i,promise:o};let a=()=>{r?.promise===o&&(r=null);};return o.then(a,a),o}}}var Hk="https://www.bing.com",iNe=`${Hk}/HPImageArchive.aspx?format=js&idx=0&n=8&mkt=zh-CN`;function sNe(e){if(!e||typeof e!="object"||!("images"in e)||!Array.isArray(e.images))throw new Error("Invalid Bing wallpaper catalog");return e.images.slice(0,9).map(t=>{if(!t||typeof t!="object"||!("startdate"in t)||typeof t.startdate!="string"||!/^\d{8}$/u.test(t.startdate)||!("url"in t)||typeof t.url!="string"||!t.url.startsWith("/"))throw new Error("Invalid Bing wallpaper entry");let r=new URL(t.url,Hk);if(r.origin!==Hk||r.pathname!=="/th")throw new Error("Invalid Bing wallpaper URL");return {day:`${t.startdate.slice(0,4)}-${t.startdate.slice(4,6)}-${t.startdate.slice(6)}`,title:"title"in t&&typeof t.title=="string"?t.title:"",copyright:"copyright"in t&&typeof t.copyright=="string"?t.copyright:"",url:r.toString()}})}function yW(e=(t,r)=>fetch(t,r)){let t=[],r=0,n,i=new Map,s=()=>Date.now()<r?Promise.resolve(t):n||(n=(async()=>{let o=await e(iNe,{headers:{"user-agent":ia},redirect:"error",signal:AbortSignal.timeout(1e4)});if(!o.headers.get("content-type")?.startsWith("application/json"))throw new Error("Invalid Bing metadata content type");let a=sNe(JSON.parse((await Jd(o,64*1024,"catalog")).toString("utf8")));return t=a,r=Date.now()+60*6e4,i.clear(),a})().finally(()=>{n=void 0;}),n);return {async list(){return (await s()).map(({day:o,title:a,copyright:c})=>({day:o,title:a,copyright:c}))},async read(o,a){let l=(await s()).find(p=>p.day===o);if(!l)throw Object.assign(new Error("Bing wallpaper is no longer available"),{statusCode:404});let u=`${o}:${String(a)}`,d=i.get(u);if(d)return d;let m=(async()=>{let p=new URL(l.url);a&&(p.searchParams.set("w","480"),p.searchParams.set("h","270"));let h=await e(p.toString(),{headers:{"user-agent":ia},redirect:"error",signal:AbortSignal.timeout(1e4)});if(!h.headers.get("content-type")?.startsWith("image/jpeg"))throw new Error("Invalid Bing image content type");let f=await Jd(h,a?2*1024*1024:20*1024*1024,"image");if(f.length<4||f[0]!==255||f[1]!==216||f[2]!==255)throw new Error("Invalid Bing JPEG content");return f})();return i.set(u,m),m.then(()=>{a||i.delete(u);},()=>{i.delete(u);}),m}}}var oNe=15e4,aNe={additionalProperties:false,properties:{day:{pattern:"^\\d{4}-\\d{2}-\\d{2}$",type:"string"}},required:["day"],type:"object"},wW=(e,t,r)=>{let n=gW(),i=yW();e.get("/v1/workbench-background/bing/catalog",{schema:{response:{200:Gg}}},()=>i.list()),e.get("/v1/workbench-background/bing/image",{schema:{querystring:{type:"object",additionalProperties:false,required:["day"],properties:{day:{type:"string",pattern:"^\\d{4}-\\d{2}-\\d{2}$"},thumbnail:{type:"boolean"}}}}},async(g,y)=>y.type("image/jpeg").send(await i.read(g.query.day,g.query.thumbnail??false)));let{assertValidProjectDefaults:s,capabilities:o,installAppUpdate:a,listModels:c,modelCatalogCache:l,projectContexts:u,readAppInfo:d,readAppUpdateProgress:m,readEffectiveGlobalSettings:p,runIdempotent:h}=t,f=hW(t);e.get("/v1/health",{schema:{response:{200:He}}},()=>({status:"ok",version:1})),e.get("/v1/app-info",{schema:{response:{200:pc}}},()=>d()),e.get("/v1/app-update/progress",{schema:{response:{200:oc}}},()=>m()),e.get("/v1/workbench-background/bing",{schema:{querystring:aNe}},async(g,y)=>{let _=await n.read(g.query.day);return y.type(_.contentType).send(_.body)}),e.post("/v1/app-update",{handlerTimeout:oNe,schema:{body:qc,headers:X,response:{200:rc,400:Xf,409:Xf,502:Xf,503:Xf}}},async g=>h(["install-app-update"],g.headers["idempotency-key"],g.body,async()=>{try{return await a(g.body.version)}catch(y){let _=typeof y=="object"&&y!==null&&"code"in y&&(y.code==="UPDATE_NOT_AVAILABLE"||y.code==="UPDATE_CHECK_FAILED"||y.code==="UPDATE_INSTALL_FAILED")?y.code:"UPDATE_INSTALL_FAILED";throw new L(_,y instanceof Error?y.message:"Failed to install the Codexly update",_==="UPDATE_NOT_AVAILABLE"?409:502,_!=="UPDATE_NOT_AVAILABLE")}})),e.get("/v1/metrics/events",{schema:{response:{200:xg$1}}},()=>({projects:[...u.values()].map(g=>({...g.eventStream.metrics,activeClients:g.transportMetrics.activeClients,projectId:g.scope.id,slowClientDisconnects:g.transportMetrics.slowClientDisconnects})),version:1})),e.get("/v1/capabilities",{schema:{response:{200:Ie}}},()=>o),e.get("/v1/models",{schema:{response:{200:Fe$1}}},()=>l.read()),e.get("/v1/settings",{schema:{response:{200:Cd}}},async()=>({settings:await p()})),e.put("/v1/settings",{preValidation:(g,y,_)=>{let v=g.body?.modelContextWindow;if(v!=null&&(typeof v!="number"||!Number.isSafeInteger(v)||v<1))throw new L("INVALID_REQUEST","modelContextWindow must be a positive safe integer or null",400);_();},schema:{body:Bd,headers:X,response:{200:Cd,400:Xf,409:Xf,502:Xf,503:Xf}}},async g=>h(["update-global-settings"],g.headers["idempotency-key"],g.body,async()=>(s(await c(),g.body),{settings:await f(g.body)}))),r();};async function vW(e,t,r,n){let i$1=e.asyncQuestionRepository;if(i$1===void 0)return n;let s=await i$1.listAsyncQuestions(t,r);return i(n,s)}function _W(e,t){let{assertValidProjectDefaults:r,getProjectContext:n,listModels:i,readEffectiveTaskSettings:s,runIdempotent:o,settingsRepository:a}=t;e.get("/v1/projects/:projectId/tasks/:taskId/settings",{schema:{params:Fe,response:{200:Fd,404:le}}},async(c,l)=>{let u=await n(c.params.projectId);return u===void 0?l.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):(await u.provider.readTask(c.params.taskId))?.projectId!==u.scope.id?l.code(404).send({code:"TASK_NOT_FOUND",message:"Task not found"}):{settings:await s(c.params.projectId,c.params.taskId)}}),e.put("/v1/projects/:projectId/tasks/:taskId/settings",{schema:{body:zd,headers:X,params:Fe,response:{200:Fd,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async c=>o(["update-task-settings",c.params.projectId,c.params.taskId],c.headers["idempotency-key"],c.body,async()=>{let l=await n(c.params.projectId);if(l===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let u=await l.provider.readTask(c.params.taskId);if(u?.projectId!==l.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let d=c.body;r(await i(),d);let m=u.turns.findLast(p=>p.status==="running");return m!==void 0&&(await s(c.params.projectId,c.params.taskId)).approvalsReviewer!==d.approvalsReviewer&&await l.provider.updateTurnApprovalsReviewer(c.params.taskId,m.id,d.approvalsReviewer),{settings:await a.writeTaskSettings(c.params.projectId,c.params.taskId,d)}})),e.post("/v1/projects/:projectId/tasks/:taskId/mcp-servers/retry",{schema:{body:Df,headers:X,params:Fe,response:{200:Ef,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async c=>o(["reload-task-mcp-servers",c.params.projectId,c.params.taskId],c.headers["idempotency-key"],c.body,async()=>{let l=await n(c.params.projectId);if(l===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await l.provider.readTask(c.params.taskId))?.projectId!==l.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);try{return await l.provider.reloadMcpServers(c.params.taskId)}catch(d){throw Vm(d)}})),e.post("/v1/projects/:projectId/tasks/:taskId/review",{schema:{body:xf$1,headers:X,params:Fe,response:{201:yf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(c,l)=>{let u=await o(["review-task",c.params.projectId,c.params.taskId],c.headers["idempotency-key"],c.body,async()=>{let d=await n(c.params.projectId);if(d===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await d.provider.readTask(c.params.taskId))?.projectId!==d.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return d.provider.startReview(c.params.taskId,c.body.target)});return l.code(201).send({taskId:c.params.taskId,turn:u})}),e.post("/v1/projects/:projectId/tasks/:taskId/compact",{schema:{body:zf,headers:X,params:Fe,response:{202:Af,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(c,l)=>{let u=await o(["compact-task",c.params.projectId,c.params.taskId],c.headers["idempotency-key"],c.body,async()=>{let d=await n(c.params.projectId);if(d===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await d.provider.readTask(c.params.taskId))?.projectId!==d.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return await d.provider.compactTask(c.params.taskId),{status:"compacting",taskId:c.params.taskId}});return l.code(202).send(u)}),e.post("/v1/projects/:projectId/tasks/:taskId/fork",{schema:{body:Bf,headers:X,params:Fe,response:{201:Cf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(c,l)=>{let u=await o(["fork-task",c.params.projectId,c.params.taskId],c.headers["idempotency-key"],c.body,async()=>{let d=await n(c.params.projectId);if(d===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await d.provider.readTask(c.params.taskId))?.projectId!==d.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return d.provider.forkTask(c.params.taskId,c.body.lastTurnId)});return l.code(201).send({task:u})}),e.post("/v1/projects/:projectId/tasks/:taskId/feedback",{schema:{body:Ff,headers:X,params:Fe,response:{200:Gf$1,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async c=>o(["feedback-task",c.params.projectId,c.params.taskId],c.headers["idempotency-key"],c.body,async()=>{let l=await n(c.params.projectId);if(l===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await l.provider.readTask(c.params.taskId))?.projectId!==l.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return await l.provider.uploadFeedback(c.params.taskId,c.body),{status:"sent",taskId:c.params.taskId}}));}function bW(e,{attachmentStore:t,getProjectContext:r,projectOpenService:n,runIdempotent:i}){e.get("/v1/projects/:projectId/tasks/:taskId/attachments/:attachmentId",{schema:{params:bT,response:{404:le}}},async(s,o)=>{let a=await r(s.params.projectId);if(a===void 0)return o.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"});let c=await a.provider.readTaskAttachment(s.params.taskId,s.params.attachmentId);if(c===void 0){if((await a.provider.readTask(s.params.taskId))?.projectId!==a.scope.id)return o.code(404).send({code:"TASK_NOT_FOUND",message:"Task not found"});try{let m=await t.readSubmitted(s.params.projectId,s.params.attachmentId);c={...m.attachment,content:m.content};}catch(m){if(m instanceof er)return o.code(404).send({code:"ATTACHMENT_NOT_FOUND",message:"Attachment not found"});throw m}}let l=Buffer$1.from(c.content),u=(c.mediaType==="application/pdf"||/\.pdf$/iu.test(c.name))&&l.subarray(0,5).toString("ascii")==="%PDF-";return u&&o.header("content-disposition",Dc(c.name).replace(/^attachment/u,"inline")),Jy(o,{content:l,mediaType:u?"application/pdf":c.mediaType},300,s.headers["if-none-match"])}),e.post("/v1/projects/:projectId/tasks/:taskId/attachments/:attachmentId/open",{schema:{body:Ub,headers:X,params:bT,response:{200:Vb,400:Xf,404:Xf,409:Xf,502:Xf}}},async s=>i(["open-task-attachment",s.params.projectId,s.params.taskId,s.params.attachmentId],s.headers["idempotency-key"],{},async()=>{let o=await r(s.params.projectId);if(o===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let a=await o.provider.readTask(s.params.taskId);if(a?.projectId!==o.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let c=await o.provider.readTaskAttachment(s.params.taskId,s.params.attachmentId),l=a.turns.flatMap(u=>u.items).filter(u=>u.type==="message").flatMap(u=>u.attachments??[]).find(u=>u.id===s.params.attachmentId)?.kind;if(c===void 0)try{let u=await t.readSubmitted(s.params.projectId,s.params.attachmentId);c={...u.attachment,content:u.content},l=u.attachment.kind;}catch(u){throw u instanceof er?new L("INVALID_REQUEST","Attachment not found",404):u}if(l!=="file")throw new L("INVALID_REQUEST","Attachment cannot be opened",400);try{let u=await t.add(s.params.projectId,{content:Readable.from([Buffer$1.from(c.content)]),kind:"file",mediaType:c.mediaType,name:c.name}),[d]=await t.resolve(s.params.projectId,[u.attachment.id]);if(d?.kind!=="file")throw new TypeError("Attachment copy is not a file");await n.open(o.scope.rootPath,"system-default",d.path);}catch(u){throw u instanceof Ns?new L("INVALID_REQUEST","System application is unavailable",409):u instanceof gr||u instanceof TypeError?new L("INVALID_REQUEST","Attachment cannot be opened",400):new L("PROVIDER_ERROR","Attachment could not be opened",502,true)}return {attachmentId:s.params.attachmentId,status:"opened"}}));}function EW(e,t){let{getProjectContext:r,runIdempotent:n}=t;e.put("/v1/projects/:projectId/tasks/:taskId/goal",{schema:{body:te,headers:X,params:Fe,response:{200:ue,400:Xf,404:Xf,502:Xf,503:Xf}}},async i=>n(["update-goal",i.params.projectId,i.params.taskId],i.headers["idempotency-key"],i.body,async()=>{let s=await r(i.params.projectId);if(s===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await s.provider.readTask(i.params.taskId))?.projectId!==s.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return {goal:await s.provider.updateGoal(i.params.taskId,i.body)}})),e.delete("/v1/projects/:projectId/tasks/:taskId/goal",{schema:{body:{additionalProperties:false,properties:{},type:"object"},headers:X,params:Fe,response:{200:ve,400:Xf,404:Xf,502:Xf,503:Xf}}},async i=>n(["clear-goal",i.params.projectId,i.params.taskId],i.headers["idempotency-key"],i.body,async()=>{let s=await r(i.params.projectId);if(s===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await s.provider.readTask(i.params.taskId))?.projectId!==s.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return await s.provider.clearGoal(i.params.taskId),{cleared:true}}));}function TW(e,t){e.delete("/v1/projects/:projectId/tasks/archived",{schema:{params:ge,headers:X,body:jc$1,response:{200:kc$1,400:Xf,404:Xf}}},r=>t.runIdempotent(["delete-archived-tasks",r.params.projectId],r.headers["idempotency-key"],r.body,async()=>{let n=await t.getProjectContext(r.params.projectId);if(n===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);return j(n.provider,n.scope.id)}));}function RW(e,t){e.get("/v1/projects/:projectId/tasks/catalog",{schema:{params:ge,querystring:_if,response:{200:jf,404:le}}},async(r,n)=>{let i=await t.getProjectContext(r.params.projectId);return i===void 0?n.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):k$1(i.provider,i.scope.id,r.query)});}function PW(e,t){e.post("/v1/tasks/completed/query",{schema:{body:Yg,response:{200:Zg$1,400:le,404:le}}},async(r,n)=>{try{return await m$1(async i=>{let s=await t.getProjectContext(i);if(s===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);return s.provider},r.body)}catch(i){if(i instanceof l$1)return n.code(400).send({code:"INVALID_QUERY",message:i.message});throw i}});}function kW(e,t){e.put("/v1/projects/:projectId/tasks/:taskId/settings-and-defaults",{schema:{body:Gd,headers:X,params:Fe,response:{200:Hd,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},r=>t.runIdempotent(["update-task-settings-and-defaults",r.params.projectId,r.params.taskId],r.headers["idempotency-key"],r.body,async()=>{let n=await t.getProjectContext(r.params.projectId);if(n===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let i=await n.provider.readTask(r.params.taskId);if(i?.projectId!==n.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let{settings:s,fastMode:o}=r.body,a={...s,fastMode:o};t.assertValidProjectDefaults(await t.listModels(),a);let c=i.turns.findLast(d=>d.status==="running");c!==void 0&&(await t.readEffectiveTaskSettings(r.params.projectId,r.params.taskId)).approvalsReviewer!==s.approvalsReviewer&&await n.provider.updateTurnApprovalsReviewer(r.params.taskId,c.id,s.approvalsReviewer);let l=await t.settingsRepository.writeTaskSettings(r.params.projectId,r.params.taskId,s),u=await t.settingsRepository.writeProjectDefaults(r.params.projectId,a);return {settings:l,defaults:u}}));}var lNe=/thread.*(?:not loaded|not found|does not exist|deleted|archived)|no rollout found/iu;async function xW(e,t,r){let n=new Set,i;for(;;){let s=await e.listTasks({archived:true,limit:100,...r?{pinnedOnly:true}:{},...i===void 0?{}:{cursor:i}});if(s.data.some(o=>o.id===t))return true;if(s.nextCursor===null)return false;if(n.has(s.nextCursor))throw new Error("Task archive pagination did not advance");n.add(s.nextCursor),i=s.nextCursor;}}async function AW(e,t,r){let n;try{n=await e.readTask(r);}catch(i){let s=i instanceof Error?i.message:typeof i=="string"?i:"";if(lNe.test(s))return null;throw i}return n?.projectId!==t||await xW(e,r,false)||await xW(e,r,true)?null:n}function IW(e,t){e.get("/v1/projects/:projectId/tasks/:taskId/navigation",{schema:{params:Fe,response:{200:vg$1,404:le}}},async(r,n)=>{let i=await t.getProjectContext(r.params.projectId);if(i===void 0)return n.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"});let s=await AW(i.provider,i.scope.id,r.params.taskId);if(s===null)return {task:null};let o=await t.readEffectiveTaskSettings(r.params.projectId,r.params.taskId);return {task:{checkpoint:i.eventStream.checkpoint,snapshot:{...s,settings:o}}}});}var OW=(e,t,r)=>{let{getProjectContext:n,readEffectiveTaskSettings:i,runIdempotent:s,taskFromSnapshot:o}=t;e.get("/v1/projects/:projectId/tasks",{schema:{params:ge,querystring:tG,response:{200:Ee,404:le}}},async(a,c)=>{let l=await n(a.params.projectId);if(l===void 0)return c.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"});let u={...a.query.archived===true?{archived:true}:{},...a.query.completed===true?{completed:true}:{},...a.query.cursor===void 0?{}:{cursor:a.query.cursor},...a.query.limit===void 0?{}:{limit:a.query.limit},...a.query.pinned===true?{pinnedOnly:true}:{},...a.query.searchTerm===void 0?{}:{searchTerm:a.query.searchTerm}};return l.provider.listTasks(u)}),e.post("/v1/projects/:projectId/tasks/:taskId/unsubscribe",{schema:{params:Fe,response:{200:wf,404:le}}},async(a,c)=>{let l=await n(a.params.projectId);return l===void 0?c.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):{status:await l.provider.unsubscribeTask(a.params.taskId),taskId:a.params.taskId}}),e.get("/v1/projects/:projectId/tasks/:taskId",{schema:{params:Fe,querystring:rG,response:{200:ug$1,404:le}}},async(a,c)=>{let l=await n(a.params.projectId);if(l===void 0)return c.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"});let u=await l.provider.readTask(a.params.taskId,{...a.query.cursor===void 0?{}:{cursor:a.query.cursor},...a.query.summary===void 0?{}:{summary:a.query.summary}});if(u?.projectId!==l.scope.id)return c.code(404).send({code:"TASK_NOT_FOUND",message:"Task not found"});let d=await vW(t,a.params.projectId,a.params.taskId,u),m=l.eventStream.checkpoint,p=await i(a.params.projectId,a.params.taskId);return {checkpoint:m,snapshot:{...d,settings:p}}}),e.get("/v1/projects/:projectId/tasks/:taskId/mcp-servers",{schema:{params:Fe,response:{200:kd,404:le,502:Xf}}},async(a,c)=>{let l=await n(a.params.projectId);if(l===void 0)return c.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"});try{return await l.provider.listMcpServers(a.params.taskId)}catch(u){throw Vm(u)}}),e.get("/v1/projects/:projectId/tasks/:taskId/background-terminals",{schema:{params:Fe,response:{200:ac,404:le}}},async(a,c)=>{let l=await n(a.params.projectId);return l===void 0?c.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):l.provider.listBackgroundTerminals(a.params.taskId)}),e.post("/v1/projects/:projectId/tasks/:taskId/background-terminals/:terminalId/terminate",{schema:{body:{additionalProperties:false,properties:{},type:"object"},headers:X,params:ZH,response:{200:bc$1,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async a=>s(["terminate-background-terminal",a.params.projectId,a.params.taskId,a.params.terminalId],a.headers["idempotency-key"],a.body,async()=>{let c=await n(a.params.projectId);if(c===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await c.provider.readTask(a.params.taskId))?.projectId!==c.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);await c.provider.terminateBackgroundTerminal(a.params.taskId,a.params.terminalId);let u=await c.provider.listBackgroundTerminals(a.params.taskId);return {status:"terminated",terminalId:a.params.terminalId,terminals:u}})),e.put("/v1/projects/:projectId/tasks/:taskId/pin",{schema:{body:mf,headers:X,params:Fe,response:{200:nf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async a=>s(["pin-task",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>{let c=await n(a.params.projectId);if(c===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await c.provider.readTask(a.params.taskId))?.projectId!==c.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let u=await c.provider.pinTask(a.params.taskId,a.body.pinned);return {pinnedTasks:await k$1(c.provider,c.scope.id,{pinned:true}),task:u}})),e.post("/v1/projects/:projectId/tasks/:taskId/rename",{schema:{body:of,headers:X,params:Fe,response:{200:pf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async a=>s(["rename-task",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>{let c=await n(a.params.projectId);if(c===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let l=await c.provider.readTask(a.params.taskId);if(l?.projectId!==c.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let u=a.body.title.trim();await c.provider.renameTask(a.params.taskId,u);let d=o(l,{title:u}),m=await k$1(c.provider,c.scope.id);return {task:d,taskCatalog:m}})),e.post("/v1/projects/:projectId/tasks/:taskId/archive",{schema:{body:qf,headers:X,params:Fe,response:{200:rf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async a=>s(["archive-task",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>{let c=await n(a.params.projectId);if(c===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await c.provider.readTask(a.params.taskId))?.projectId!==c.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);await c.provider.archiveTask(a.params.taskId);let u=await c.provider.listTasks({limit:5});return {status:"archived",taskId:a.params.taskId,tasks:u}})),e.post("/v1/projects/:projectId/tasks/:taskId/unarchive",{schema:{body:sf,headers:X,params:Fe,response:{200:tf$1,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async a=>s(["unarchive-task",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>{let c=await n(a.params.projectId);if(c===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let l=await c.provider.unarchiveTask(a.params.taskId),u=await c.provider.listTasks({limit:5});return {task:l,tasks:u}})),e.delete("/v1/projects/:projectId/tasks/:taskId",{schema:{body:uf,headers:X,params:Fe,response:{200:vf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async a=>s(["delete-task",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>{let c=await n(a.params.projectId);if(c===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await c.provider.readTask(a.params.taskId))?.projectId!==c.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);await c.provider.deleteTask(a.params.taskId);let u=await c.provider.listTasks({limit:5});return {status:"deleted",taskId:a.params.taskId,tasks:u}})),_W(e,t),TW(e,t),RW(e,t),PW(e,t),kW(e,t),IW(e,t),bW(e,t),EW(e,t),r();};var CW=(e,t,r)=>{let{getProjectContext:n,projectRepository:i,provider:s}=t;e.get("/v1/search/tasks",{schema:{querystring:dc$1,response:{200:ic,503:le}}},async(o,a)=>{if(s.search===void 0)return a.code(503).send({code:"GLOBAL_SEARCH_UNAVAILABLE",message:"Global search is unavailable"});let c=await i.list(),l=[{id:we,kind:"temporary"},...c.map(u=>({id:u.id,kind:"project"}))];return s.search.searchTasks(o.query,l,o.signal)}),e.get("/v1/projects/:projectId/tasks/:taskId/search-occurrences",{schema:{params:Fe,querystring:gc,response:{200:hc,404:le,503:le}}},async(o,a)=>{let c=await n(o.params.projectId);return c===void 0?a.code(404).send({code:"PROJECT_NOT_FOUND",message:"Project not found"}):s.search===void 0?a.code(503).send({code:"GLOBAL_SEARCH_UNAVAILABLE",message:"Global search is unavailable"}):s.search.searchTaskOccurrences(o.params.taskId,o.query,c.scope,o.signal)}),r();};var NW=(e,t,r)=>{let{assertValidProjectDefaults:n,attachmentStore:i,fingerprintPayload:s,getProjectContext:o,idempotencyCacheSize:a,listModels:c,readInheritedTaskSettings:l,projectRepository:u,resolveProjectWorktree:d,resolveProviderTurnInput:m,runIdempotent:p,settingsRepository:h,taskStartRecoveries:f,toPendingRequestHttpError:g}=t;e.post("/v1/projects/:projectId/tasks",{schema:{body:kf,headers:X,params:ge,response:{201:lf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(y,_)=>{let v=await o(y.params.projectId);if(v===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let w=await p(["start-task",y.params.projectId],y.headers["idempotency-key"],y.body,async()=>{let E=JSON.stringify(["start-task",y.params.projectId,y.headers["idempotency-key"]]),R=s(y.body),P=f.get(E);if(P!==void 0&&P.fingerprint!==R)throw new L("IDEMPOTENCY_CONFLICT","Idempotency key was already used with another request",409);if(P===void 0){if(f.size>=a)throw new Error("Task creation recovery capacity is exhausted");let b=await l(y.params.projectId),O;if(y.body.worktreePath!==void 0){if(y.body.rootPath===void 0)throw new L("INVALID_REQUEST","Project root is required",400);try{let j=await ui(u,y.params.projectId,y.body.rootPath);O=(await d(j,y.body.worktreePath)).path;}catch(j){throw j instanceof Gt||j instanceof mt?new L("INVALID_REQUEST","Git worktree is invalid",400):j}}else if(y.body.rootPath!==void 0)throw new L("INVALID_REQUEST","Git worktree path is required",400);let F=O===void 0?await v.provider.startTask():await v.provider.startTask({workspacePath:O});P={fingerprint:R,settings:{...b},task:F},f.set(E,P);}return await h.writeTaskSettings(y.params.projectId,P.task.id,P.settings),f.delete(E),P.task});return _.code(201).send({task:w})}),e.post("/v1/projects/:projectId/tasks/:taskId/turns",{schema:{body:Hf,headers:X,params:Fe,response:{201:If,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(y,_)=>{let v=await p(["start-turn",y.params.projectId,y.params.taskId],y.headers["idempotency-key"],y.body,async()=>{let w=await o(y.params.projectId);if(w===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await w.provider.readTask(y.params.taskId))?.projectId!==w.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let{attachmentIds:R,providerInput:P}=await m(y.params.projectId,y.body.input,w.provider,y.params.taskId),b=y.body.options;n(await c(),b),await h.writeTaskSettings(y.params.projectId,y.params.taskId,b);let O=w.eventStream.checkpoint,F=await w.provider.startTurn(y.params.taskId,P,b);return await i.consume(y.params.projectId,R,F.status==="running"?F.id:void 0),{checkpoint:O,turn:F}});return _.code(201).send({checkpoint:v.checkpoint,taskId:y.params.taskId,turn:v.turn})}),e.post("/v1/projects/:projectId/tasks/:taskId/turns/:turnId/steer",{schema:{body:Jf,headers:X,params:_T,response:{202:Kf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(y,_)=>{let v=await p(["steer-turn",y.params.projectId,y.params.taskId,y.params.turnId],y.headers["idempotency-key"],y.body,async()=>{if(y.body.taskId!==y.params.taskId)throw new L("TASK_NOT_FOUND","Task not found",404);let w=await o(y.params.projectId);if(w===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let E=await w.provider.readTask(y.params.taskId);if(E?.projectId!==w.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let R=E.turns.find(O=>O.id===y.params.turnId);if(R===void 0)throw new L("TURN_NOT_FOUND","Turn not found",404);if(R.status!=="running")throw new L("TURN_NOT_RUNNING","Turn is not running",409);let{attachmentIds:P,providerInput:b}=await m(y.params.projectId,y.body.input,w.provider,y.params.taskId);return await w.provider.steerTurn(y.params.taskId,y.params.turnId,b),await i.consume(y.params.projectId,P,y.params.turnId),{status:"accepted",taskId:y.params.taskId,turnId:y.params.turnId}});return _.code(202).send(v)}),e.post("/v1/projects/:projectId/tasks/:taskId/turns/:turnId/interrupt",{schema:{body:Uf,headers:X,params:_T,response:{202:Vf,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(y,_)=>{let v=await p(["interrupt-turn",y.params.projectId,y.params.taskId,y.params.turnId],y.headers["idempotency-key"],y.body,async()=>{if(y.body.taskId!==y.params.taskId)throw new L("TASK_NOT_FOUND","Task not found",404);let w=await o(y.params.projectId);if(w===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let E=await w.provider.readTask(y.params.taskId);if(E?.projectId!==w.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);let R=E.turns.find(P=>P.id===y.params.turnId);if(R===void 0)throw new L("TURN_NOT_FOUND","Turn not found",404);if(R.status!=="running")throw new L("TURN_NOT_RUNNING","Turn is not running",409);return await w.provider.interruptTurn(y.params.taskId,y.params.turnId),{status:"interrupting",taskId:y.body.taskId,turnId:y.params.turnId}});return _.code(202).send(v)}),e.post("/v1/projects/:projectId/tasks/:taskId/pending-requests/:requestId/resolve",{schema:{body:pe,headers:X,params:eG,response:{200:qe$1,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async y=>{if(y.body.projectId!==y.params.projectId||y.body.taskId!==y.params.taskId)throw new L("PENDING_REQUEST_MISMATCH","Pending request identity does not match",409);let _=await o(y.params.projectId);if(_===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await _.provider.readTask(y.params.taskId))?.projectId!==_.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return {request:await p(["resolve-pending-request",y.params.projectId,y.params.taskId,y.params.requestId],y.headers["idempotency-key"],y.body,async()=>{try{return await _.provider.resolvePendingRequest({...y.body,requestId:y.params.requestId})}catch(E){throw E instanceof b?g(E):E}})}}),r();};function Zy(e){let t=new Map;return {readSubmission(r,n){return Promise.resolve(t.get(JSON.stringify([r,n])))},writeSubmission(r,n,i){let s=JSON.stringify([r,n]);if(!t.has(s)&&t.size>=e)throw new L("IDEMPOTENCY_CAPACITY_EXCEEDED","Submission recovery capacity is exhausted",503);return t.set(s,structuredClone(i)),Promise.resolve()}}}async function jW(e,t,r,n,i){let s=await e.getProjectContext(r);if(s===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let o;try{return await d$1(t,r,n,e.fingerprintPayload(i),i,{validate:async()=>{if(i.type==="prompt"&&e.assertValidProjectDefaults(await e.listModels(),i.options),i.taskId!==void 0&&(await s.provider.readTask(i.taskId))?.projectId!==s.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404)},createTask:()=>s.provider.startTask(),prepare:async a=>{let c=i.type==="prompt"?i.options:await e.readEffectiveTaskSettings(r,a);return await e.settingsRepository.writeTaskSettings(r,a,c),i.type==="prompt"&&(o=await e.resolveProviderTurnInput(r,i.input,s.provider,a)),o?.attachmentIds??[]},execute:async a=>{let c=s.eventStream.checkpoint;if(i.type==="review"){let u=await s.provider.startReview(a,i.target);return {taskId:a,turn:u,checkpoint:c}}if(o===void 0)throw new Error("Submission input is unavailable");let l=await s.provider.startTurn(a,o.providerInput,i.options);return {taskId:a,turn:l,checkpoint:c}},complete:async(a,c)=>{i.type==="prompt"&&await e.attachmentStore.consume(r,c,a.turn.status==="running"?a.turn.id:void 0);}})}catch(a){throw a instanceof c$2?new L(a.code,a.message,409):a}}var LW=(e,t,r)=>{e.post("/v1/projects/:projectId/submissions",{schema:{body:Hg$1,params:ge,headers:X,response:{201:Ig,400:Xf,404:Xf,409:Xf,502:Xf,503:Xf}}},async(n,i)=>{let s=await t.runIdempotent(["submit-task",n.params.projectId],n.headers["idempotency-key"],n.body,()=>jW(t,t.submissionRepository,n.params.projectId,n.headers["idempotency-key"],n.body));return i.code(201).send(s)}),r();};var DW=e=>createHash("sha256").update(e).digest("hex"),MW=e=>e.turns.filter(t=>t.status==="running").map(t=>t.id),e0=class{constructor(t){this.context=t;}context;#e=new Map;#t=new Map;#n=new Map;repository(){let t=this.context.asyncQuestionRepository;if(t===void 0)throw new L("PROVIDER_ERROR","Async question persistence is unavailable",503);return t}async task(t,r){let n=await this.context.getProjectContext(t);if(n===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);let i=await n.provider.readTask(r);if(i?.projectId!==n.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return {runtime:n,task:i}}refresh(t,r){let n=JSON.stringify([t,r]),i=this.#t.get(n);if(i!==void 0)return i;let s=this.discover(t,r,n).finally(()=>{this.#t.delete(n);});return this.#t.set(n,s),s}async discover(t,r,n){let i=this.repository(),{runtime:s,task:o}=await this.task(t,r),a=this.#e.get(n),c=o.turns.at(-1)?.id,l=o,u=new Set,d=new Set(o.status==="running"&&a===c?this.#n.get(n):void 0);for(let m=0;;m++){for(let f of l.turns)f.status==="running"?d.add(f.id):d.delete(f.id);if(await i.discoverAsyncQuestions(t,r,g(l.turns,DW)),l.turnsNextCursor===null||l.turns.some(f=>f.id===a))break;let p=l.turnsNextCursor;if(m>=199||u.has(p))throw new L("PROVIDER_ERROR","Async question history scan limit exceeded",503);u.add(p);let h=await s.provider.readTask(r,{cursor:p});if(h?.projectId!==s.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);l=h;}if(c!==void 0){this.#e.delete(n),this.#e.set(n,c);let m=this.#e.keys().next().value;this.#e.size>128&&m!==void 0&&(this.#e.delete(m),this.#n.delete(m));}return this.#n.set(n,d),d}async list(t,r){let n=await this.refresh(t,r);return this.pending(t,r,n)}async pending(t,r,n){let i=n??new Set(MW((await this.task(t,r)).task));return {data:(await this.repository().listAsyncQuestions(t,r)).map(o=>o.group).filter(o=>i.has(o.turnId)&&(o.status==="pending"||o.status==="answering"))}}async dismiss(t,r,n){let{task:i}=await this.task(t,r);return await this.repository().dismissAsyncQuestions(t,r,n),this.context.workbenchChanges.publish({type:"async-questions.changed",projectId:t,taskId:r}),this.pending(t,r,new Set(MW(i)))}async answer(t,r,n,i){let s=this.repository(),{runtime:o,task:a}=await this.task(t,r),c=(await s.listAsyncQuestions(t,r)).find(y=>y.group.id===n);if(c===void 0)throw new L("ASYNC_QUESTION_NOT_FOUND","Async question not found",404);let l=DW(JSON.stringify(i.map(y=>y.trim())));if(c.fingerprint!==void 0&&c.fingerprint!==l)throw new L("ASYNC_QUESTION_RESOLVED","Async question already has another answer",409);if(c.group.status==="answered"&&c.result!==void 0)return c.result;if(c.group.status==="answering")throw this.unknownOutcome();if(c.group.status!=="pending")throw new L("ASYNC_QUESTION_RESOLVED","Async question is no longer pending",409);let u;try{u=h(c.group.questions,i);}catch{throw new L("INVALID_REQUEST","Invalid question answers",400)}let d={type:"prompt",text:u,attachments:[],skills:[]},m=a.turns.findLast(y=>y.status==="running"),p=await this.context.readEffectiveTaskSettings(t,r);m===void 0&&this.context.assertValidProjectDefaults(await this.context.listModels(),p);let h$1={group:{...c.group,status:"answering"},fingerprint:l};if(!await s.updateAsyncQuestion(t,r,h$1,"pending"))throw new L("ASYNC_QUESTION_RESOLVED","Async question is being resolved",409);let f=o.eventStream.checkpoint;this.context.workbenchChanges.publish({type:"async-questions.changed",projectId:t,taskId:r});let g={text:u,skills:[],files:[],images:[],textAttachments:[]};try{let y=m===void 0?await o.provider.startTurn(r,g,p):null;m!==void 0&&await o.provider.steerTurn(r,m.id,g);let _=y?.id??m?.id;if(_===void 0)throw new Error("Answer turn is unavailable");let v={...c.group,status:"answered"},w={question:v,input:d,messageId:randomUUID(),turnId:_,turn:y,checkpoint:f};if(!await s.updateAsyncQuestion(t,r,{group:v,fingerprint:l,result:w},"answering"))throw new Error("Answer state changed unexpectedly");return this.context.workbenchChanges.publish({type:"async-questions.changed",projectId:t,taskId:r}),w}catch{throw this.unknownOutcome()}}unknownOutcome(){return new L("SUBMISSION_OUTCOME_UNKNOWN","Answer delivery outcome is unknown; inspect the task before sending again",409)}};var Gk={400:Xf,404:Xf,409:Xf,502:Xf,503:Xf},FW=(e,t,r)=>{let n=new e0(t),i="/v1/projects/:projectId/tasks/:taskId/async-questions";e.get(i,{schema:{params:Fe,response:{200:Tg$1,...Gk}}},s=>n.list(s.params.projectId,s.params.taskId)),e.post(`${i}/:questionId/answer`,{schema:{params:R.Object({projectId:R.String({minLength:1}),taskId:R.String({minLength:1}),questionId:R.String({minLength:1,maxLength:128})}),headers:X,body:Ug,response:{200:Wg,...Gk}}},async s=>({...await t.runIdempotent(["answer-async-question",s.params.projectId,s.params.taskId,s.params.questionId],s.headers["idempotency-key"],s.body,()=>n.answer(s.params.projectId,s.params.taskId,s.params.questionId,s.body.answers)),questions:await n.pending(s.params.projectId,s.params.taskId)})),e.post(`${i}/dismiss`,{schema:{params:Fe,headers:X,body:Xg,response:{200:Tg$1,...Gk}}},s=>t.runIdempotent(["dismiss-async-questions",s.params.projectId,s.params.taskId],s.headers["idempotency-key"],s.body,()=>n.dismiss(s.params.projectId,s.params.taskId,s.body.ids))),r();};function Jc(e){if(e.projectTodoRepository===void 0)throw new L("PROVIDER_ERROR","Project todo persistence is unavailable",503);return e.projectTodoRepository}async function $W(e,t,r,n){return (await Jc(e).listProjectTodos(t)).find(s=>s.id===r)??await t0(e,t,n,r)}async function t0(e,t,r,n=randomUUID(),i=null){let s=Jc(e);return f(s,t,n,r,i,Date.now(),async()=>{let o=[];for(let a of r.attachments){let c;try{c=await e.attachmentStore.read(t,a.id);}catch(l){if(!(l instanceof er))throw l;c=await s.readProjectTodoAttachment(t,a.id);}if(c===void 0)throw new L("ATTACHMENT_NOT_FOUND","Project todo attachment not found",404);if(c.attachment.kind!==a.kind||c.attachment.name!==a.name||c.attachment.mediaType!==a.mediaType||c.attachment.size!==a.size)throw new L("INVALID_REQUEST","Project todo attachment metadata does not match",400);o.push({attachment:a,content:c.content});}return o})}function qW(e){throw e instanceof e$2?new L(e.code,e.message,e.code==="PROJECT_TODO_NOT_FOUND"?404:409):e}var zk=R.Object({projectId:R.String({minLength:1}),todoId:R.String({minLength:1})}),Xd={400:Xf,404:Xf,409:Xf,502:Xf,503:Xf},UW=(e,t,r)=>{let n=async o=>{if(await t.projectRepository.read(o)===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404)},i=async o=>({data:await Jc(t).listProjectTodos(o)}),s=async(o,a,c,l,u)=>(await n(o),t.runIdempotent(a,c,l,async()=>{try{let d=await u();return t.workbenchChanges.publish({type:"project-todos.changed",projectId:o}),d}catch(d){return qW(d)}}));e.get("/v1/projects/:projectId/todos",{schema:{params:ge,response:{200:Mg,...Xd}}},async o=>(await n(o.params.projectId),{data:await Jc(t).listProjectTodos(o.params.projectId)})),e.post("/v1/projects/:projectId/todos",{schema:{params:ge,headers:X,body:Kg,response:{201:Ng$1,...Xd}}},async(o,a)=>{let{projectId:c}=o.params,l=await s(c,["create-project-todo",c],o.headers["idempotency-key"],o.body,async()=>({todo:await t0(t,c,o.body),todos:await i(c)}));return a.code(201).send(l)}),e.post("/v1/projects/:projectId/todos/:todoId/import",{schema:{params:zk,headers:X,body:Kg,response:{200:Ng$1,...Xd}}},async o=>{let{projectId:a,todoId:c}=o.params;return s(a,["import-project-todo",a,c],o.headers["idempotency-key"],o.body,async()=>({todo:await $W(t,a,c,o.body),todos:await i(a)}))}),e.put("/v1/projects/:projectId/todos/:todoId",{schema:{params:zk,headers:X,body:Og,response:{200:Ng$1,...Xd}}},async o=>{let{projectId:a,todoId:c}=o.params;return s(a,["save-project-todo",a,c],o.headers["idempotency-key"],o.body,async()=>({todo:await t0(t,a,o.body.draft,c,o.body.expectedVersion),todos:await i(a)}))}),e.delete("/v1/projects/:projectId/todos/:todoId",{schema:{params:zk,headers:X,body:Pg$1,response:{200:Qg,...Xd}}},async o=>{let{projectId:a,todoId:c}=o.params;return s(a,["delete-project-todo",a,c],o.headers["idempotency-key"],o.body,async()=>({deleted:await Jc(t).deleteProjectTodo(a,c,o.body.expectedVersion),todos:await i(a)}))}),r();};function BW(e){throw e instanceof li?new L("TURN_NOT_RUNNING",e.message,409):e instanceof Go?new L("TASK_NOT_FOUND",e.message,404):e}var HW=(e,t,r)=>{let{getProjectContext:n,runIdempotent:i,taskQueue:s}=t,o=async a=>{let c=await n(a.projectId);if(c===void 0)throw new L("PROJECT_NOT_FOUND","Project not found",404);if((await c.provider.readTask(a.taskId))?.projectId!==c.scope.id)throw new L("TASK_NOT_FOUND","Task not found",404);return {eventStream:c.eventStream,projectId:a.projectId,provider:c.provider,taskId:a.taskId}};e.get("/v1/projects/:projectId/tasks/:taskId/queue",{schema:{params:Fe,response:{200:qd$1,404:Xf}}},async a=>{let c=await o(a.params);return {data:await s.list(c)}}),e.post("/v1/projects/:projectId/tasks/:taskId/queue",{schema:{body:Lf,headers:X,params:Fe,response:{201:Mf,400:Xf}}},async(a,c)=>{let l=await o(a.params),u=await i(["queue-add",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>{let d=await s.add(l,a.body.input,a.body.clientUserMessageId);return await s.startNext(l).catch(m=>{a.log.error({err:m},"Failed to dispatch queued submission");}),d});return c.code(201).send({queue:{data:await s.list(l)},queuedSubmission:u})}),e.put("/v1/projects/:projectId/tasks/:taskId/queue/:queuedSubmissionId",{schema:{body:Nf,headers:X,params:ST,response:{200:Of,404:Xf,409:Xf}}},async a=>{let c=await o(a.params),l=await i(["queue-update",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],{...a.body,queuedSubmissionId:a.params.queuedSubmissionId},()=>s.update(c,a.params.queuedSubmissionId,a.body.input,a.body.status).catch(BW));return {queue:{data:await s.list(c)},queuedSubmission:l}}),e.delete("/v1/projects/:projectId/tasks/:taskId/queue/:queuedSubmissionId",{schema:{headers:X,params:ST,response:{200:Pf}}},async a=>{let c=await o(a.params);return {deleted:await i(["queue-delete",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],{queuedSubmissionId:a.params.queuedSubmissionId},()=>s.delete(c,a.params.queuedSubmissionId)),queue:{data:await s.list(c)}}}),e.put("/v1/projects/:projectId/tasks/:taskId/queue/reorder",{schema:{body:Qf,headers:X,params:Fe,response:{200:Rf}}},async a=>{let c=await o(a.params);return await i(["queue-reorder",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>(await s.reorder(c,a.body.queuedSubmissionIds),{status:"reordered"})),{queue:{data:await s.list(c)},status:"reordered"}}),e.post("/v1/projects/:projectId/tasks/:taskId/queue/start",{schema:{body:Sf,headers:X,params:Fe,response:{201:Tf}}},async(a,c)=>{let l=await o(a.params),u=await i(["queue-start",a.params.projectId,a.params.taskId],a.headers["idempotency-key"],a.body,async()=>{try{return await s.start(l,a.body.queuedSubmissionId)}catch(d){BW(d);}});return c.code(201).send({queue:{data:await s.list(l)},taskId:a.params.taskId,turn:u})}),r();};var GW=R.Object({owner:R.String({maxLength:100,minLength:1,pattern:"^[A-Za-z0-9_-]+$"}),slug:R.String({maxLength:100,minLength:1,pattern:"^[A-Za-z0-9_-]+$"})},{additionalProperties:false}),hNe=R.Object({path:R.String({maxLength:4096,minLength:1})},{additionalProperties:false}),pNe=R.Object({enabled:R.Boolean(),path:R.String({maxLength:4096,minLength:1})},{additionalProperties:false}),mNe=R.Object({enabled:R.Boolean()},{additionalProperties:false}),gNe=R.Object({projectId:R.Optional(R.String({minLength:1})),rootPath:R.Optional(R.String({minLength:1})),scope:Bc$1},{additionalProperties:false}),yNe=R.Object({cursor:R.Optional(R.String({maxLength:2048})),query:R.Optional(R.String({maxLength:120})),sort:R.Optional(R.Union([R.Literal("recommended"),R.Literal("downloads"),R.Literal("updated")]))},{additionalProperties:false}),Vk=R.Object({marketplaceName:R.String({maxLength:160,minLength:1}),pluginName:R.String({maxLength:240,minLength:1})},{additionalProperties:false}),wNe=R.Object({marketplacePath:R.Optional(R.String({maxLength:4096,minLength:1}))},{additionalProperties:false}),vNe=R.Object({forceRefetch:R.Optional(R.Boolean())},{additionalProperties:false}),_Ne=R.Object({installAttemptId:R.String({maxLength:200,minLength:1}),marketplacePath:R.Union([R.String({maxLength:4096,minLength:1}),R.Null()])},{additionalProperties:false}),SNe=R.Object({pluginId:R.String({maxLength:300,minLength:1})},{additionalProperties:false});function Xc(e){if(!(e instanceof Ue))throw e;let t={SKILL_MARKET_CONFLICT:409,SKILL_MARKET_FILESYSTEM:500,SKILL_MARKET_INCOMPATIBLE:409,SKILL_MARKET_INVALID_ARCHIVE:409,SKILL_MARKET_INVALID_RESPONSE:502,SKILL_MARKET_NETWORK:502,SKILL_MARKET_NOT_FOUND:404,SKILL_MARKET_RATE_LIMITED:429,SKILL_MARKET_UNSAFE:409};throw new L(e.code,e.message,t[e.code],e.code==="SKILL_MARKET_NETWORK"||e.code==="SKILL_MARKET_RATE_LIMITED")}var Vi={400:Xf,404:Xf,409:Xf,429:Xf,500:Xf,502:Xf},zW=(e,t,r)=>{let{runIdempotent:n,skillMarketService:i}=t;e.post("/v1/plugins/official/reconcile",{schema:{body:R.Object({},{additionalProperties:false}),headers:X,response:{200:sc,...Vi}}},s=>n(["reconcile-official-plugins"],s.headers["idempotency-key"],s.body,()=>i.reconcileOfficialPlugins())),e.get("/v1/skills/installed",{schema:{response:{200:uc$1}}},()=>i.listInstalledSkills(false)),e.get("/v1/plugins/official",{schema:{querystring:vNe,response:{200:Lc$1}}},s=>i.listOfficialPlugins(s.query.forceRefetch??false)),e.get("/v1/plugins/official/:marketplaceName/:pluginName",{schema:{params:Vk,querystring:wNe,response:{200:Oc$1,...Vi}}},s=>i.getOfficialPlugin(s.params.marketplaceName,s.query.marketplacePath??null,s.params.pluginName)),e.post("/v1/plugins/official/:marketplaceName/:pluginName/install",{schema:{body:_Ne,headers:X,params:Vk,response:{200:Qc$1,...Vi}}},s=>n(["install-official-plugin",s.params.marketplaceName,s.params.pluginName],s.headers["idempotency-key"],s.body,async()=>({...await i.installOfficialPlugin(s.params.marketplaceName,s.body.marketplacePath,s.params.pluginName,s.body.installAttemptId),plugins:await i.listOfficialPlugins(true)}))),e.post("/v1/plugins/official/:marketplaceName/:pluginName/uninstall",{schema:{body:SNe,headers:X,params:Vk,response:{200:Sc,...Vi}}},s=>n(["uninstall-official-plugin",s.params.marketplaceName,s.params.pluginName],s.headers["idempotency-key"],s.body,async()=>(await i.uninstallOfficialPlugin(s.body.pluginId),{plugins:await i.listOfficialPlugins(true)}))),e.get("/v1/skills/market",{schema:{querystring:yNe,response:{200:yc}}},s=>i.listSkills(s.query.query??"",s.query.cursor??null,s.query.sort??"recommended").catch(Xc)),e.get("/v1/skills/market/:owner/:slug",{schema:{params:GW,response:{200:Ac$1,...Vi}}},s=>i.getSkill(s.params.owner,s.params.slug).catch(Xc)),e.get("/v1/mcp-servers/configured",{schema:{response:{200:wc}}},()=>i.listConfiguredMcpServers()),e.post("/v1/skills/open",{schema:{body:hNe,headers:X,response:{200:Ic$1,...Vi}}},s=>n(["open-skill"],s.headers["idempotency-key"],s.body,()=>i.openSkillDirectory(s.body.path).catch(Xc))),e.put("/v1/skills/enabled",{schema:{body:pNe,headers:X,response:{200:Fc,...Vi}}},s=>n(["set-skill-enabled",s.body.path],s.headers["idempotency-key"],s.body,async()=>({...await i.setSkillEnabled(s.body.path,s.body.enabled).catch(Xc),installedSkills:await i.listInstalledSkills(true)}))),e.put("/v1/mcp-servers/configured/:name/enabled",{schema:{body:mNe,headers:X,response:{200:Hc$1,...Vi}}},s=>n(["set-mcp-enabled",s.params.name],s.headers["idempotency-key"],s.body,async()=>({...await i.setMcpServerEnabled(s.params.name,s.body.enabled).catch(Xc),servers:await i.listConfiguredMcpServers()}))),e.post("/v1/skills/market/:owner/:slug/install",{schema:{body:gNe,headers:X,params:GW,response:{200:Dc$1,...Vi}}},s=>n(["install-skill",s.params.owner,s.params.slug],s.headers["idempotency-key"],s.body,()=>i.installSkill(s.params.owner,s.params.slug,s.body).catch(Xc))),r();};var zs=class extends Error{constructor(r,n){super(r==="unknown"?"Launch outcome is unknown; inspect the task before creating another schedule":r==="cleanup_pending"?"Launch confirmed; cleanup will be retried":"Scheduled task could not be launched");this.status=r;this.taskId=n;}status;taskId};function VW(e){return e.status==="unknown"||e.status==="cleanup_pending"}var ENe=4,TNe=1e3,Wk=0,Zd=class extends Error{constructor(){super("Scheduled task recurrence workers are busy");}};function RNe(e){if(e.length>1024||/[\r\n]/u.test(e))throw new Error("Scheduled task RRULE is too complex");let t=e.trim().replace(/^RRULE:/u,"").split(";"),r=new Set,n=1;for(let i of t){let[s,o]=i.split("=");if(!s||!o||r.has(s))throw new Error("Scheduled task RRULE is invalid");if(r.add(s),s==="FREQ"&&o==="SECONDLY")throw new Error("Scheduled task recurrence must be at least one minute");if(s.startsWith("BY")&&(n*=o.split(",").length),n>1024)throw new Error("Scheduled task RRULE is too complex")}}async function ef(e,t,r=5){if(!Number.isInteger(r)||r<1)throw new Error("Scheduled task preview limit is invalid");if(e.type==="once")return e.atUnixMs>t?[e.atUnixMs]:[];if(RNe(e.rrule),Wk>=ENe)throw new Zd;Wk+=1;let n,i;try{n=new Worker(new URL("./scheduled-task-recurrence-worker.js",import.meta.url),{execArgv:["--experimental-strip-types"],workerData:{schedule:e,afterUnixMs:t,limit:Math.min(r,5)},resourceLimits:{maxOldGenerationSizeMb:32}});let s=n;return await new Promise((o,a)=>{i=setTimeout(()=>{a(new Error("Scheduled task RRULE computation timed out"));},TNe),s.once("message",c=>{c.error!==void 0?a(new Error(c.error)):o(c.dates);}),s.once("error",a),s.once("exit",()=>{a(new Error("Scheduled task recurrence worker exited"));});})}finally{i!==void 0&&clearTimeout(i);try{await n?.terminate();}finally{Wk-=1;}}}async function r0(e,t){if(e.type==="once"){if(e.atUnixMs<=t)throw new Error("Scheduled task time must be in the future");return e.atUnixMs}let r=(await ef(e,t,1))[0];if(r===void 0)throw new Error("Scheduled task RRULE has no future occurrence");return r}async function Kk(e,t,r){let n=t.name.trim();if(n==="")throw new Error("Scheduled task name must not be empty");return {...t,createdAtUnixMs:r,id:e,lastRunAtUnixMs:null,lastRunStatus:null,name:n,nextRunAtUnixMs:t.enabled?await r0(t.schedule,r):null,runs:[],updatedAtUnixMs:r}}function KW(e,t){return [...e.runs,t].slice(-20)}async function YW(e,t){if(e.schedule.type==="once")return {enabled:false,nextRunAtUnixMs:null};try{return {enabled:!0,nextRunAtUnixMs:await r0(e.schedule,t)}}catch(r){if(r instanceof Zd)throw r;return {enabled:false,nextRunAtUnixMs:null}}}async function Yk(e,t,r,n){let i=[],s=[];for(let a of e)s.push(await o(a));return {claims:i,tasks:s};async function o(a){if(!(n===void 0?a.enabled&&a.nextRunAtUnixMs!==null&&a.nextRunAtUnixMs<=r:a.id===n))return a;if(t.has(a.id)){if(n!==void 0)return a;let d={error:"previous scheduled launch is still running",finishedAtUnixMs:r,id:randomUUID(),startedAtUnixMs:r,status:"skipped",taskId:null};return {...a,...await YW(a,r),lastRunAtUnixMs:r,lastRunStatus:"skipped",runs:KW(a,d),updatedAtUnixMs:r}}let l=randomUUID(),u={...a,...n===void 0?await YW(a,r):{},lastRunAtUnixMs:r,lastRunStatus:"running",runs:KW(a,{error:null,finishedAtUnixMs:null,id:l,startedAtUnixMs:r,status:"running",taskId:null}),updatedAtUnixMs:r};return i.push({runId:l,task:u}),u}}function QW(e,t,r,n){return e.map(i=>{if(i.id!==t.task.id)return i;let s=n.status==="rejected"&&n.reason instanceof zs?n.reason:void 0,o=n.status==="fulfilled"?"started":s?.status??"failed";return {...i,...o==="unknown"?{enabled:false,nextRunAtUnixMs:null}:{},lastRunStatus:o,runs:i.runs.map(a=>a.id===t.runId?{...a,error:n.status==="rejected"?s?.message??"Scheduled task could not be launched":null,finishedAtUnixMs:r,status:o,taskId:n.status==="fulfilled"?n.value:s?.taskId??null}:a),updatedAtUnixMs:r}})}function JW(e,t){return e.map(r=>r.runs.some(n=>n.status==="running")?{...r,enabled:false,nextRunAtUnixMs:null,lastRunStatus:"unknown",runs:r.runs.map(n=>n.status==="running"?{...n,error:"server exited before launch was confirmed",finishedAtUnixMs:t,status:"unknown"}:n),updatedAtUnixMs:t}:r)}var gn=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ScheduledTaskServiceError";}code};function XW(){let e=[];return {listScheduledTasks:()=>Promise.resolve(e),replaceScheduledTasks:t=>(e=[...t],Promise.resolve(e))}}var n0=class{#e=new Set;#t=new Set;#n;#r;#i;#o=new Set;#f=new Set;#l=new Set;#s=new Map;#p;#h;#d=false;#c=Promise.resolve();#a=[];#m;constructor(t){this.#n=t.now??Date.now,this.#r=t.repository,this.#i=t.prepareTaskResources,this.#p=t.startTask,this.#h=t.recoverTask;}async start(){await this.#P(async()=>{let t=await this.#r.listScheduledTasks(),r=await this.#k(t);this.#a=r,r.some((n,i)=>n!==t[i])&&await this.#r.replaceScheduledTasks(r),this.#w();});}list(){return this.#P(()=>[...this.#a].sort((t,r)=>(t.nextRunAtUnixMs??Number.MAX_SAFE_INTEGER)-(r.nextRunAtUnixMs??Number.MAX_SAFE_INTEGER)||t.createdAtUnixMs-r.createdAtUnixMs))}subscribe(t){return this.#e.add(t),()=>{this.#e.delete(t);}}create(t){return this.#P(async()=>{let r;try{r=await Kk(randomUUID(),t,this.#n());}catch(n){throw new gn("invalid",String(n))}return await this.#u([...this.#a,r],r),r})}update(t,r){return this.#P(async()=>{let n=this.#y(t);this.#b(n);let i;try{i={...await Kk(t,r,this.#n()),createdAtUnixMs:n.createdAtUnixMs,lastRunAtUnixMs:n.lastRunAtUnixMs,lastRunStatus:n.lastRunStatus,runs:n.runs};}catch(s){throw new gn("invalid",String(s))}return await this.#u(this.#a.map(s=>s.id===t?i:s),i),i})}delete(t){return this.#P(async()=>{let r=this.#y(t);if(this.#o.has(t)||r.runs.some(n=>n.status==="running"||n.status==="cleanup_pending"))throw new gn("busy","Scheduled task is running");await this.#_(this.#a.filter(n=>n.id!==t));})}setEnabled(t,r){return this.#P(async()=>{let n=this.#y(t);r&&this.#b(n);let i=n.nextRunAtUnixMs;if(r)try{i=await r0(n.schedule,this.#n());}catch(o){throw new gn("invalid",String(o))}let s={...n,enabled:r,nextRunAtUnixMs:i,updatedAtUnixMs:this.#n()};return await this.#_(this.#a.map(o=>o.id===t?s:o)),s})}runNow(t){return this.#P(async()=>{this.#b(this.#y(t));let r=await Yk(this.#a,this.#o,this.#n(),t),n=r.claims[0];if(n===void 0)throw new gn("busy","Scheduled task is already running");return await this.#_(r.tasks),await this.#r.claimScheduledTaskRun?.(n.runId),this.#f.add(n.runId),this.#o.add(t),this.#T(n),n.task})}async close(){this.#d=true,this.#e.clear(),this.#m!==void 0&&clearTimeout(this.#m),await Promise.allSettled(this.#t),await this.#c,this.#f.size>0&&this.#r.withScheduledTaskLock!==void 0&&await this.#r.withScheduledTaskLock(async()=>{for(let t of this.#f)await this.#r.releaseScheduledTaskRun?.(t);this.#f.clear();});}#y(t){let r=this.#a.find(n=>n.id===t);if(r===void 0)throw new gn("not_found","Scheduled task not found");return r}#g(t){return t.runs.some(r=>this.#l.has(r.id))}async#k(t){let r=t.filter(o=>!this.#o.has(o.id)&&!this.#g(o)),n=this.#h,i=n===void 0?JW(r,this.#n()):await Promise.all(r.map(n)),s=new Map(i.map(o=>[o.id,o]));return t.map(o=>s.get(o.id)??o)}#b(t){if(this.#o.has(t.id)||t.runs.some(r=>r.status==="running"||VW(r)))throw new gn("busy","Previous launch requires reconciliation")}#T(t){let r=Promise.resolve().then(()=>this.#p(t.task)).then(n=>({status:"fulfilled",value:n})).catch(n=>({reason:n,status:"rejected"})).then(n=>this.#P(async()=>{this.#s.set(t.task.id,{claim:t,finishedAtUnixMs:this.#n(),result:n}),await this.#R();})).catch(()=>{this.#v();}).finally(()=>this.#t.delete(r));this.#t.add(r);}async#R(){for(let[t,r]of this.#s)await this.#_(QW(this.#a,r.claim,r.finishedAtUnixMs,r.result)),await this.#r.releaseScheduledTaskRun?.(r.claim.runId),this.#f.delete(r.claim.runId),this.#s.delete(t),this.#o.delete(t);}#v(){this.#m!==void 0&&clearTimeout(this.#m),!this.#d&&(this.#m=setTimeout(()=>{this.#E().catch(()=>{this.#v();});},1e3),this.#m.unref());}#w(){if(this.#m!==void 0&&clearTimeout(this.#m),this.#d)return;let t=this.#a.filter(o=>o.enabled).flatMap(o=>o.nextRunAtUnixMs===null?[]:[o.nextRunAtUnixMs]).reduce((o,a)=>o===void 0?a:Math.min(o,a),void 0),r=this.#a.some(o=>o.runs.some(a=>a.status==="cleanup_pending")),n=t===void 0?1440*60*1e3:Math.max(1,t-this.#n()),i=this.#r.withScheduledTaskLock===void 0?2147483647:5e3,s=r||this.#s.size>0?1e3:i;this.#m=setTimeout(()=>{this.#E().catch(()=>{this.#v();});},Math.min(n,s)),this.#m.unref();}async#E(){await this.#P(async()=>{if(this.#d)return;await this.#R();let t=this.#a.filter(i=>!this.#o.has(i.id)&&!this.#g(i)&&i.runs.some(s=>s.status==="running"));if(t.length>0){let i=new Map((await this.#k(t)).map(s=>[s.id,s]));await this.#_(this.#a.map(s=>i.get(s.id)??s));}for(let i of this.#a){let s=i.runs.find(o=>o.status==="cleanup_pending");s===void 0||this.#o.has(i.id)||this.#g(i)||(this.#o.add(i.id),await this.#r.claimScheduledTaskRun?.(s.id),this.#f.add(s.id),this.#T({task:i,runId:s.id}));}let r=new Set([...this.#o,...this.#a.filter(i=>this.#g(i)).map(i=>i.id)]),n=await Yk(this.#a,r,this.#n());await this.#_(n.tasks);for(let i of n.claims)await this.#r.claimScheduledTaskRun?.(i.runId),this.#f.add(i.runId);for(let i of n.claims)this.#o.add(i.task.id);for(let i of n.claims)this.#T(i);});}async#_(t,r){if(t.length===this.#a.length&&t.every((n,i)=>n===this.#a[i])){this.#w();return}this.#a=await this.#r.replaceScheduledTasks(t,r),this.#w();for(let n of this.#e)n();}async#u(t,r){let n;try{n=await this.#i?.(r);}catch(i){throw new gn("invalid",String(i))}await this.#_(t,n);}#P(t){let r=this.#c.then(()=>this.#r.withScheduledTaskLock===void 0?t():this.#r.withScheduledTaskLock(async()=>(this.#a=await this.#r.listScheduledTasks(),this.#l=new Set(await this.#r.listActiveScheduledTaskRunIds?.()),t())));return this.#c=r.then(()=>{},()=>{}),r}};function ZW(e,t){TT(e,t,"/v1/scheduled-tasks/events",{type:"scheduled-tasks.changed"},r=>t.scheduledTaskService.subscribe(()=>{r({type:"scheduled-tasks.changed"});}));}var i0=R.Object({taskId:R.String({minLength:1})},{additionalProperties:false});function xNe(e){throw e instanceof gn?e.code==="not_found"?new L("TASK_NOT_FOUND",e.message,404):new L("INVALID_REQUEST",e.message,e.code==="busy"?409:400):e}var e9=(e,t,r)=>{ZW(e,t);let n=(o,a,c,l)=>t.runIdempotent(o,a,c,async()=>{try{return await l()}catch(u){xNe(u);}}),i={400:Xf,404:Xf,409:Xf,502:Xf,503:Xf},s=async o=>({...o,tasks:{data:await t.scheduledTaskService.list()}});e.post("/v1/scheduled-tasks/preview",{schema:{body:Od,response:{200:Pd$1,400:Xf}}},async o=>{try{return {dates:await ef(o.body.schedule,Date.now())}}catch(a){throw new L("INVALID_REQUEST",a instanceof Error?a.message:String(a),400)}}),e.get("/v1/scheduled-tasks",{schema:{response:{200:Ud}}},async()=>({data:await t.scheduledTaskService.list()})),e.post("/v1/scheduled-tasks",{schema:{body:Sd$1,headers:X,response:{...i,201:Vd$1}}},async(o,a)=>{let c=await n(["create-scheduled-task"],o.headers["idempotency-key"],o.body,async()=>s({task:await t.scheduledTaskService.create(o.body)}));return a.code(201).send(c)}),e.put("/v1/scheduled-tasks/:taskId",{schema:{body:Sd$1,headers:X,params:i0,response:{...i,200:Vd$1}}},o=>n(["update-scheduled-task",o.params.taskId],o.headers["idempotency-key"],o.body,async()=>s({task:await t.scheduledTaskService.update(o.params.taskId,o.body)}))),e.delete("/v1/scheduled-tasks/:taskId",{schema:{params:i0,headers:X,response:{...i,200:Wd$1}}},o=>n(["delete-scheduled-task",o.params.taskId],o.headers["idempotency-key"],{},async()=>(await t.scheduledTaskService.delete(o.params.taskId),s({status:"deleted",taskId:o.params.taskId})))),e.patch("/v1/scheduled-tasks/:taskId/enabled",{schema:{body:Xd$1,headers:X,params:i0,response:{...i,200:Vd$1}}},o=>n(["set-scheduled-task-enabled",o.params.taskId],o.headers["idempotency-key"],o.body,async()=>s({task:await t.scheduledTaskService.setEnabled(o.params.taskId,o.body.enabled)}))),e.post("/v1/scheduled-tasks/:taskId/run",{schema:{params:i0,headers:X,response:{...i,200:Vd$1}}},o=>n(["run-scheduled-task",o.params.taskId],o.headers["idempotency-key"],{},async()=>s({task:await t.scheduledTaskService.runNow(o.params.taskId)}))),r();};function INe(e,t){return e.id===t.id&&e.kind===t.kind&&e.mediaType===t.mediaType&&e.name===t.name&&e.size===t.size}var s0=class{#e;#t;constructor(t,r){this.#e=t,this.#t=r;}async prepare(t){let r=new Set(t.prompt.attachments.map(o=>o.id)),n=new Map(t.messageAttachments.map(o=>[o.id,o]));if(r.size!==t.prompt.attachments.length||n.size!==r.size||[...r].some(o=>!n.has(o)))throw new Error("Scheduled task attachment metadata is incomplete");let i=new Map((await this.#t.listScheduledTaskAttachments(t.id)).map(o=>[o.attachment.id,o]));return {attachments:await Promise.all(t.messageAttachments.map(async o=>{let a;try{let c=await this.#e.read(t.projectId,o.id);a={attachment:c.attachment,content:c.content};}catch(c){if(!(c instanceof er))throw c;let l=i.get(o.id);if(l===void 0)throw c;a={attachment:l.attachment,content:l.content};}if(!INe(a.attachment,o))throw new Error("Scheduled task attachment metadata does not match stored content");return a})),projectId:t.projectId,taskId:t.id}}read(t,r){return this.#t.readScheduledTaskAttachment(t,r)}async restorePrompt(t){if(t.prompt.attachments.length===0)return {prompt:t.prompt,restoredIds:[]};let r=new Map((await this.#t.listScheduledTaskAttachments(t.id)).map(i=>[i.attachment.id,i])),n=[];try{let i=[];for(let s of t.prompt.attachments){let o=r.get(s.id);if(o===void 0)throw new Error("Scheduled task attachment was not found");let a=await this.#e.add(t.projectId,{content:Readable.from([o.content]),kind:o.attachment.kind,mediaType:o.attachment.mediaType,name:o.attachment.name});n.push(a.attachment.id),i.push({id:a.attachment.id});}return {prompt:{...t.prompt,attachments:i},restoredIds:n}}catch(i){throw await this.discard(n),i}}async discard(t){await Promise.all(t.map(r=>this.#e.discard(r)));}};function t9(e,t,r,n,i,s,o){let a=new Map,c=d=>`scheduled:${d.id}`;async function l(d){let m=d.runs.findLast(v=>v.status==="running"||v.status==="cleanup_pending");if(m===void 0)throw new Error("Scheduled run is unavailable");let p=c(m),h={type:"prompt",input:d.prompt,options:d.turnOptions},f=_c(h),g,y,_;try{let v=a.get(p);v!==void 0&&await e.writeSubmission(d.projectId,p,v),y=await e.readSubmission(d.projectId,p);let w=await i(d.projectId);if(w===void 0)throw new Error("Scheduled task project was not found");_=y?.task;let E,R=await d$1(e,d.projectId,p,f,h,{validate:async()=>{Km(await s(),d.turnOptions),g=n===void 0?{prompt:d.prompt,restoredIds:[]}:await n.restorePrompt(d);},createTask:async()=>(_=await w.provider.startTask(),_),prepare:async P=>{if(await t.writeTaskSettings(d.projectId,P,d.turnOptions),g===void 0)throw new Error("Scheduled attachments are unavailable");return E=await o(d.projectId,g.prompt,w.provider,P),E.attachmentIds},execute:async P=>{if(E===void 0)throw new Error("Scheduled input is unavailable");let b=w.eventStream.checkpoint,O=await w.provider.startTurn(P,E.providerInput,d.turnOptions),F={taskId:P,turn:O,checkpoint:b,..._===void 0?{}:{createdTask:_}};return a.set(p,{fingerprint:f,stage:"started",result:F,attachmentIds:E.attachmentIds,..._===void 0?{}:{task:_}}),F},complete:(P,b)=>r.consume(d.projectId,b,P.turn.status==="running"?P.turn.id:void 0)});return a.delete(p),R.taskId}catch{let v=a.get(p);try{v??=await e.readSubmission(d.projectId,p);}catch{throw new zs(v?.result===void 0?"unknown":"cleanup_pending",v?.result?.taskId??_?.id??y?.task?.id??m.taskId)}let w=v?.result!==void 0?"cleanup_pending":v?.stage==="creating"||v?.stage==="starting"?"unknown":"failed";throw w==="failed"&&await n?.discard(g?.restoredIds??[]).catch(()=>{}),new zs(w,v?.result?.taskId??_?.id??v?.task?.id??m.taskId)}}async function u(d){if(!d.runs.some(p=>["running","unknown","cleanup_pending"].includes(p.status)))return d;let m=await Promise.all(d.runs.map(async p=>{if(!["running","unknown","cleanup_pending"].includes(p.status))return p;let h=await e.readSubmission(d.projectId,c(p)),f=h?.result?.taskId??h?.task?.id??p.taskId,g=h?.stage==="completed"?"started":h?.result!==void 0?"cleanup_pending":h?.stage==="ready"?"failed":"unknown";return {...p,status:g,taskId:f,finishedAtUnixMs:p.finishedAtUnixMs??Date.now(),error:g==="started"?null:new zs(g,f).message}}));return {...d,runs:m,lastRunStatus:m.at(-1)?.status??d.lastRunStatus,...m.some(p=>p.status==="unknown")?{enabled:false,nextRunAtUnixMs:null}:{}}}return {recoverTask:u,startTask:l}}async function r9(e,t,r,n,i){let s=e.scheduledTaskAttachmentRepository===void 0?void 0:new s0(t,e.scheduledTaskAttachmentRepository),o=new n0({...s===void 0?{}:{prepareTaskResources:a=>s.prepare(a)},repository:e.scheduledTaskRepository??XW(),...t9(e.submissionRepository??Zy(1e3),e.settingsRepository,t,s,r,n,i)});return await o.start(),{scheduledTaskAttachmentManager:s,scheduledTaskService:o}}var FJ=e(p9(),1),$J=e(fK(),1),qJ=e(iQ(),1),UJ=e(jJ(),1);var iqe=5,DJ=6e4,sqe=1e3,oqe=1e3;function aqe(e,t){let r=createHash("sha256").update(e,"utf8").digest(),n=createHash("sha256").update(t,"utf8").digest();return timingSafeEqual(r,n)}var Gf=class{#e=new Map;#t;#n;#r;#i;#o;#f;#l=new Map;#s;constructor(t,r={}){if(t.sessionTtlMs!==void 0&&(!Number.isSafeInteger(t.sessionTtlMs)||t.sessionTtlMs<=0))throw new Error("sessionTtlMs must be a positive safe integer");this.#i=t.pairingCode,this.#f=t.sessionTtlMs,this.#t=r.maxFailureWindows??sqe,this.#n=r.maxSessions??oqe,this.#r=r.now??Date.now,this.#o=r.randomBytes??randomBytes,this.#s=setInterval(()=>{this.#h(this.#r());},DJ),this.#s.unref();}pair(t,r){let n=this.#r();this.#h(n);let i=this.#e.get(r);if(i!==void 0&&i.count>=iqe)return {status:"rate_limited"};if(!aqe(this.#i,t)){this.#p(this.#e,this.#t);let a=this.#e.get(r);return a===void 0?this.#e.set(r,{count:1,startedAt:n}):a.count+=1,{status:"failed"}}this.#p(this.#l,this.#n,a=>{this.logout(a);});let s=this.#o(32).toString("base64url"),o=this.#f===void 0?null:n+this.#f;return this.#l.set(s,{createdAt:n,expiresAt:o,invalidationListeners:new Set}),{expiresAt:o,sessionId:s,status:"paired"}}validate(t){return this.expiresAt(t)!==void 0}expiresAt(t){if(t===void 0)return;let r=this.#l.get(t);if(r!==void 0){if(r.expiresAt!==null&&r.expiresAt<=this.#r()){this.logout(t);return}return r.expiresAt}}logout(t){if(t!==void 0){let r=this.#l.get(t);this.#l.delete(t);for(let n of r?.invalidationListeners??[])n();r?.invalidationListeners.clear();}}onInvalidated(t,r){let n=t===void 0?void 0:this.#l.get(t);return !this.validate(t)||n===void 0?(r(),()=>{}):(n.invalidationListeners.add(r),()=>{n.invalidationListeners.delete(r);})}diagnostics(){return {failureWindows:this.#e.size,sessions:this.#l.size}}close(){clearInterval(this.#s),this.#e.clear();for(let t of this.#l.keys())this.logout(t);}#p(t,r,n=i=>{t.delete(i);}){for(;t.size>=r;){let i=t.keys().next().value;if(i===void 0)return;n(i);}}#h(t){for(let[r,n]of this.#e)n.startedAt+DJ<=t&&this.#e.delete(r);for(let[r,n]of this.#l)n.expiresAt!==null&&n.expiresAt<=t&&this.logout(r);}};function dqe(e){let t="/v1/projects/";if(!e.startsWith(t))return false;let r=e.slice(t.length).split("/",1)[0];try{return decodeURIComponent(r??"")===we}catch{return false}}function fqe(e){if(e!==void 0)try{let t=new URL(`http://${e}`);return t.username===""&&t.password===""&&t.pathname==="/"&&t.search===""&&t.hash===""?t:void 0}catch{return}}var hqe=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;function BJ(e){let t=domainToASCII(e).toLowerCase(),r=t.split(".");if(e===""||e!==e.trim()||t.length>253||isIP(t)!==0||r.some(n=>!hqe.test(n)))throw new Error("Invalid allowed Host; expected a domain name without scheme, port, or wildcard");return t}function pqe(e,t,r){let n=e.hostname.toLowerCase(),i=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n;return n==="localhost"||i==="127.0.0.1"||i==="::1"||r.has(i)?true:t&&isIP(i)!==0}async function HJ(e,t){await e.register(UJ.default,{options:{maxPayload:64*1024}}),await e.register(FJ.default);let r=new Set((t.allowedHosts??[]).map(BJ)),n=t.access===void 0?void 0:new Gf(t.access);e.addHook("onRequest",async(s,o)=>{let a=s.originalUrl.split("?",1)[0]??s.originalUrl;if(dqe(a))return o.code(404).send({code:"NOT_FOUND",message:"Route not found"});let c=s.headers.upgrade?.toLowerCase()==="websocket",l=s.cookies[cn],u=fqe(s.headers.host);if(u===void 0||!pqe(u,t.access!==void 0,r))return o.code(403).send({code:"ACCESS_DENIED",message:"Access denied",retryable:false});let d=t.access===void 0||n?.validate(l)===true;if(!(!a.startsWith("/v1/")||s.method==="GET"&&(a==="/v1/health"||a==="/v1/access")||s.method==="POST"&&a==="/v1/access/pair")&&!d)return o.code(401).send({code:"ACCESS_DENIED",message:"Access denied",retryable:false});let p=!["GET","HEAD","OPTIONS"].includes(s.method)&&(l!==void 0||s.headers.origin!==void 0);if(c||p){let h=s.headers.origin;try{let f=h===void 0?void 0:new URL(h);if(f===void 0||f.protocol!=="http:"&&f.protocol!=="https:"||f.host!==u.host)throw new Error("Origin mismatch")}catch{return o.code(403).send({code:"ACCESS_DENIED",message:"Access denied",retryable:false})}}}),e.addHook("onSend",async(s,o,a)=>{let c=o.getHeader("content-type")==="application/pdf";if(o.headers({"Content-Security-Policy":`default-src 'self'; base-uri 'none'; connect-src 'self'; frame-src 'self'; frame-ancestors ${c?"'self'":"'none'"}; img-src 'self' blob: data:; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'`,"Permissions-Policy":"camera=(), geolocation=(), microphone=()","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff","X-Frame-Options":c?"SAMEORIGIN":"DENY"}),s.url.startsWith("/v1/pets/assets/"))o.header("Cache-Control","private, no-cache");else if(s.url.startsWith("/v1/")){let l=o.getHeader("cache-control");(o.statusCode>=400||typeof l!="string"||!l.startsWith("private,"))&&o.header("Cache-Control","no-store");}return a}),await e.register($J.default,{limits:{fields:0,files:1,fileSize:Db,parts:1}}),e.setErrorHandler((s,o,a)=>{if(s instanceof L)return wT(o,s.code),a.code(s.statusCode).send({code:s.code,message:s.message,retryable:s.retryable});if(typeof s=="object"&&s!==null&&"validation"in s){let l=o.headers["idempotency-key"],d=!(o.routeOptions.url==="/v1/access/pair"||o.routeOptions.url==="/v1/access/logout")&&(o.method==="POST"||o.method==="PUT")&&(l===void 0||l==="");return a.code(400).send({code:d?"IDEMPOTENCY_KEY_REQUIRED":"INVALID_REQUEST",message:d?"Idempotency-Key header is required":"Request is invalid",retryable:false})}let c=typeof s=="object"&&s!==null&&"statusCode"in s&&typeof s.statusCode=="number"&&Number.isInteger(s.statusCode)&&s.statusCode>=400&&s.statusCode<=599?s.statusCode:500;return c<500?a.code(c).send({code:"INVALID_REQUEST",message:c===413?"Request is too large":"Request is invalid",retryable:false}):(wT(o,"INTERNAL_ERROR"),a.code(c).send({code:"INTERNAL_ERROR",message:"Internal server error",retryable:false}))}),e.addHook("onClose",async()=>{n?.close(),await t.releaseResources();});let{staticRoot:i}=t;return i!==void 0&&(await e.register(qJ.default,{cacheControl:false,preCompressed:true,root:i,setHeaders:(s,o)=>{let[a]=relative(i,o).split(sep);s.header("Cache-Control",a==="assets"?"public, max-age=31536000, immutable":"public, max-age=0");},wildcard:false}),e.setNotFoundHandler((s,o)=>s.method==="GET"&&!s.url.startsWith("/v1/")?o.type("text/html; charset=utf-8").sendFile("index.html"):o.code(404).send({code:"NOT_FOUND",message:"Route not found"}))),n}async function GJ(e,t,r){let n=e.get(t);if(n!==void 0)return n;let i=Promise.resolve().then(r);e.set(t,i);try{return await i}finally{e.get(t)===i&&e.delete(t);}}async function zJ(e,t){if(e===we)return {provider:t.provider.forTemporary(t.standaloneCwd),scope:{id:we,kind:"temporary",rootPath:t.standaloneCwd,runtimeWorkspaceRoots:[t.standaloneCwd]}};let r=await t.projectRepository.read(e);if(r===void 0)return;let n=r.roots[0];if(n!==void 0)return {provider:t.provider.forProject(r),scope:{id:r.id,kind:"project",rootPath:n.path,runtimeWorkspaceRoots:r.roots.map(i=>i.path)}}}function VJ(e){let t=e.indexOf("?"),r=t<0?e:e.slice(0,t),n=t<0?"":e.slice(t);if(!r.startsWith(xe))return e;let i=r.slice(xe.length),s=i==="/tasks"||i.startsWith("/tasks/"),o=i.startsWith("/attachments/");return !s&&!o&&!(i==="/files/pdf"||i==="/files/download"||i==="/files/image"||i==="/files/source")&&!(i==="/open"||i==="/open-capabilities")&&i!=="/submissions"&&i!=="/events"&&i!=="/skills"?e:`/v1/projects/${we}${i}${n}`}var WJ=(e,t,r)=>{let n=()=>{if(!t.provider.personalization)throw new L("PROVIDER_ERROR","Personalization is unavailable",503,true);return t.provider.personalization},i={409:Xf,502:Xf,503:Xf},s=(o,a,c,l)=>t.runIdempotent([o],a,c,async()=>{try{return await l()}catch(u){throw u instanceof L?u:u instanceof Error&&"code"in u&&u.code==="GLOBAL_INSTRUCTIONS_CHANGED"?new L("GLOBAL_INSTRUCTIONS_CHANGED",u.message,409):new L("PROVIDER_ERROR",u instanceof Error?u.message:"Personalization request failed",502,true)}});e.get("/v1/personalization/instructions",{schema:{response:{200:yg$1}}},()=>n().getGlobalInstructions()),e.get("/v1/personalization/memories",{schema:{response:{200:Ag$1}}},()=>n().getMemorySettings()),e.get("/v1/personalization/agent",{schema:{response:{200:Cg$1}}},()=>n().getAgentPreferences()),e.put("/v1/personalization/instructions",{schema:{body:zg,headers:X,response:{200:yg$1,...i}}},o=>s("save-global-instructions",o.headers["idempotency-key"],o.body,()=>n().saveGlobalInstructions(o.body))),e.put("/v1/personalization/memories",{schema:{body:Bg,headers:X,response:{200:Ag$1,...i}}},o=>s("update-memory-settings",o.headers["idempotency-key"],o.body,()=>n().updateMemorySettings(o.body))),e.put("/v1/personalization/agent",{schema:{body:Cg$1,headers:X,response:{200:Cg$1,...i}}},o=>s("update-agent-preferences",o.headers["idempotency-key"],o.body,()=>n().updateAgentPreferences(o.body))),e.post("/v1/personalization/memories/reset",{schema:{body:{type:"object",additionalProperties:false},headers:X,response:{200:Dg,...i}}},o=>s("reset-memories",o.headers["idempotency-key"],o.body,async()=>(await n().resetMemories(),{success:!0}))),r();};async function yqe(e){let t=e.handlerTimeoutMs??BH,r=e.loggerEnabled===false?false:{level:"info",redact:{censor:"[Redacted]",paths:["req.headers.authorization","req.headers.cookie",'req.headers["x-api-key"]','res.headers["set-cookie"]']},...e.logDestination===void 0?{}:{stream:e.logDestination}},n=(0, KJ.default)({handlerTimeout:0,logController:new nd,logger:r,rewriteUrl:A=>VJ(A.url??"/")});n.addHook("onRoute",A=>{t>0&&A.websocket!==true&&(A.handlerTimeout??=t);});let i=e.readProjectGitStatus??Y3,s=e.commitProjectChanges??bR,o=e.readProjectFileTree??Rz,a=e.readProjectFileDownload??xz,c=e.provider.fileSearch,l=e.searchProjectFiles??(A=>c===void 0?Promise.reject(new Error("Provider file search is unavailable")):c.search(A)),u=e.stopProjectFileSearch??((A,D)=>c===void 0?Promise.reject(new Error("Provider file search is unavailable")):c.stop(A,D)),d=e.readProjectImageFile??Uz,m=e.readProjectSourceFile??Gz,p=e.access===void 0?e.projectOpenService??r5():t5(),h=e.workspaceRoots===void 0?{}:{workspaceRoots:e.workspaceRoots},f=e.readProjectDirectory??((A,D)=>D6(A,{...D,...h})),g=e.resolveProjectDirectory??(A=>jk(A,h)),y=e.skillMarketService??I6({catalog:t6(),projectOpenService:p,projectRepository:e.projectRepository,provider:e.provider}),_=new Xm,v=new Ym,w=zz(_,(A,D)=>e.projectTodoRepository?.readProjectTodoAttachment(A,D)??Promise.resolve(void 0)),E=await e.provider.getCapabilities(),R=e.modelCatalogCacheMaxBytes??HH,P=e.modelCatalogCacheTtlMs??GH;if(!Number.isInteger(R)||R<=0)throw new RangeError("Model catalog cache capacity must be a positive integer");if(!Number.isFinite(P)||P<=0)throw new RangeError("Model catalog cache TTL must be a positive number");let b=new Wm($H(e.provider,e.providerConnectionRepository),{maxBytes:R,ttlMs:P});e.preloadModelCatalog===true&&await b.read().catch(()=>{});let O=new Map,F=new Map,j=new zy,N=async A=>{let D=O.get(A);return D!==void 0?(q.touch(A),D):GJ(F,A,()=>j.run(A,async()=>{let $=O.get(A);if($!==void 0)return q.touch(A),$;let V=await zJ(A,e);if(V===void 0)return;let S=O6({attachmentStore:_,...e.eventBufferSize===void 0?{}:{eventBufferSize:e.eventBufferSize},eventProvider:E.provider,...e.eventSessionId===void 0?{}:{eventSessionId:e.eventSessionId},onActivity:()=>{q.touch(A);},onAttachmentReleaseError:()=>{n.log.warn({errorCode:"ATTACHMENT_CLEANUP_FAILED"},"Failed to release turn attachments");},onTurnCompleted:k=>he.startNext(k),workbenchChanges:v,provider:V.provider,scope:V.scope});return O.set(A,S),q.touch(A),S}))},M=async(A,D=false)=>j.run(A,async()=>{q.forget(A);let $=O.get(A);$!==void 0&&($.unsubscribe(),$.eventStream.close(),O.delete(A)),await Promise.all([e.provider.releaseProject(A,$?.provider),D?_.releaseProjectRuntime(A):_.releaseProject(A)]);}),q=new Gy({cleanupIntervalMs:e.projectRuntimeCleanupIntervalMs??6e4,contexts:O,idleTtlMs:e.projectRuntimeIdleTtlMs??18e5,onReleaseError:(A,D)=>{n.log.warn({errorCode:"PROJECT_RELEASE_FAILED",projectId:D},"Failed to release idle Project runtime");},release:A=>M(A,true)}),z=async()=>(await b.read()).data,W=async A=>{let D=A??await z(),$=await e.settingsRepository.readGlobalSettings(),V=await e.provider.readDefaultSettings();return YH(D,$,V)},H=async(A,D,$)=>{let V=D??await z(),S=await e.settingsRepository.readProjectDefaults(A),k=$??await W(V),C=S??k;return {approvalPolicy:C.approvalPolicy,approvalsReviewer:C.approvalsReviewer,fastMode:C.fastMode,...Mi(V,C,k.sandboxMode)}},J=async(A,D)=>{let $=D??await z(),V=await W($),S=await H(A,$,V);return {approvalPolicy:S.approvalPolicy,approvalsReviewer:S.approvalsReviewer,model:S.model,reasoningEffort:S.reasoningEffort,sandboxMode:S.sandboxMode}},ce=async(A,D,$)=>{let V=$??await z(),S=await e.settingsRepository.readTaskSettings(A,D);if(S===void 0)return J(A,V);let k=Mi(V,S,S.sandboxMode);return {approvalPolicy:S.approvalPolicy,approvalsReviewer:S.approvalsReviewer,...k}},he=new Vy({attachmentStore:_,readTaskSettings:ce,repository:e.queueRepository??C6(),resolveProviderInput:w}),{scheduledTaskAttachmentManager:Te,scheduledTaskService:ue}=await r9(e,_,N,z,w),B=new Set,de=new Map,we=e.idempotencyCacheSize??qH,ie=e.idempotencyTtlMs??UH,U=bz(we,ie),Q=await HJ(n,{...e.access===void 0?{}:{access:e.access},...e.allowedHosts===void 0?{}:{allowedHosts:e.allowedHosts},releaseResources:async()=>{await ue.close(),await q.close(),await Promise.all([...O.keys()].map(A=>M(A))),await _.dispose(),B.clear(),U.clear(),b.clear(),de.clear();},...e.staticRoot===void 0?{}:{staticRoot:e.staticRoot}}),x={workbenchChanges:v,...e.asyncQuestionRepository===void 0?{}:{asyncQuestionRepository:e.asyncQuestionRepository},...e.projectTodoRepository===void 0?{}:{projectTodoRepository:e.projectTodoRepository},submissionRepository:e.submissionRepository??Zy(we),...Q===void 0?{}:{accessService:Q},activeGitMutations:B,assertCommitSelection:VH,assertValidProjectDefaults:Km,attachmentStore:_,buildCommitMessagePrompt:oz,capabilities:E,commitProjectChanges:s,pushProjectCommits:e.pushProjectCommits??ez,createProjectBranch:e.createProjectBranch??uz,createProjectWorktree:e.createProjectWorktree??fz,fingerprintPayload:_c,generateCommitMessageWithCodex:WH,getProjectContext:N,idempotencyCacheSize:we,installAppUpdate:e.installAppUpdate,listModels:z,maximumAttachmentBytes:MH,modelCatalogCache:b,multipartEnvelopeBytes:DH,projectContexts:O,projectOpenService:p,projectRepository:e.projectRepository,provider:e.provider,petProvider:e.petProvider,providerConnectionRepository:e.providerConnectionRepository,readAppInfo:e.readAppInfo,readAppUpdateProgress:e.readAppUpdateProgress,readEffectiveGlobalSettings:W,readEffectiveProjectDefaults:H,readEffectiveTaskSettings:ce,readFileTree:o,readFileDownload:a,deleteProjectFile:e.deleteProjectFile??Mz,renameProjectFile:e.renameProjectFile??Dz,searchProjectFiles:l,stopProjectFileSearch:u,readHostFileDirectory:e.readHostFileDirectory??_z,readProjectDirectory:f,readImageFile:d,readInheritedTaskSettings:J,readProjectGitHistory:e.readProjectGitHistory??pz,readProjectGitCommitFiles:e.readProjectGitCommitFiles??TR,readProjectGitCommitFileDiff:e.readProjectGitCommitFileDiff??RR,readProjectGitStatus:i,readProjectWorktrees:e.readProjectWorktrees??Cg,readSourceFile:m,releaseProjectContext:M,resolveProviderTurnInput:w,runIdempotent:U.run,resolveProjectDirectory:g,resolveHostAttachment:e.resolveHostAttachment??Sz,readScheduledTaskAttachment:async(A,D)=>Te===void 0?void 0:Te.read(A,D),settingsRepository:e.settingsRepository,scheduledTaskService:ue,skillMarketService:y,taskFromSnapshot:FH,taskQueue:he,taskStartRecoveries:de,switchProjectBranch:e.switchProjectBranch??lz,resolveProjectWorktree:e.resolveProjectWorktree??Ng,toGitCommitHttpError:KH,toPendingRequestHttpError:zH};return await n.register(sG,{...e.access===void 0?{}:{access:e.access},...Q===void 0?{}:{service:Q}}),await n.register(wW,x),await n.register(WJ,x),await n.register(iG,x),await n.register(dW,x),await n.register(fW,x),await n.register(cW,x),await n.register(zW,x),await n.register(e9,x),await n.register(OW,x),await n.register(CW,x),await n.register(NW,x),await n.register(LW,x),await n.register(FW,x),await n.register(UW,x),aG(n,x),await n.register(HW,x),await n.register(oG,x),await n.ready(),n}var QJ=1e3,JJ=1024*1024,XJ={name:"create_provider_connection",sql:`
|
|
566
566
|
CREATE TABLE provider_connection (
|
|
567
567
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
568
568
|
mode TEXT NOT NULL CHECK (mode IN ('official', 'custom')),
|