decocms 2.292.0 → 2.292.2
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/dist/client/assets/{AlertCircle-BJZjcLR8.js → AlertCircle-De2C9wZC.js} +1 -1
- package/dist/client/assets/{ArrowNarrowLeft-Yoaq7-cz.js → ArrowNarrowLeft-bSu4Kz2F.js} +1 -1
- package/dist/client/assets/{ArrowUpRight-DoZ1aCQb.js → ArrowUpRight-DT3QLsvt.js} +1 -1
- package/dist/client/assets/{CheckCircle-BbLUS0ek.js → CheckCircle-BIi7toDZ.js} +1 -1
- package/dist/client/assets/{ChevronDown-CGHjchOw.js → ChevronDown-DmIUGcFl.js} +1 -1
- package/dist/client/assets/{ChevronRight-Do3Je1ER.js → ChevronRight-CIh2nJ4L.js} +1 -1
- package/dist/client/assets/{ChevronUp-dSBPqUJ1.js → ChevronUp-BYOoc7wr.js} +1 -1
- package/dist/client/assets/{Container-CDgY_XYz.js → Container-BerLGLgK.js} +1 -1
- package/dist/client/assets/{DotsVertical-BxL7Owtq.js → DotsVertical-CDho1dav.js} +1 -1
- package/dist/client/assets/{LinkExternal01-DxLyrYeW.js → LinkExternal01-CcTNZj2P.js} +1 -1
- package/dist/client/assets/{Lock01-BI0K2L_g.js → Lock01-B-vCOiSg.js} +1 -1
- package/dist/client/assets/{Palette-CWiKw0AC.js → Palette-CqW3vcqn.js} +1 -1
- package/dist/client/assets/{Play-C7K9es-c.js → Play-CrdOw1Iv.js} +1 -1
- package/dist/client/assets/{Plus-BpCTKUfi.js → Plus-Zv0hv0Vg.js} +1 -1
- package/dist/client/assets/{RefreshCcw01-BEGaV3W5.js → RefreshCcw01-COL3SGLi.js} +1 -1
- package/dist/client/assets/{SearchMd-fRD_HHud.js → SearchMd-BjteSZXQ.js} +1 -1
- package/dist/client/assets/{Settings02-DtQ4_bLf.js → Settings02-w5kxVqcK.js} +1 -1
- package/dist/client/assets/{Shield01-Di_q_zxl.js → Shield01-DodcxEya.js} +1 -1
- package/dist/client/assets/{Star01-CIsSx9uE.js → Star01-BhFELsp4.js} +1 -1
- package/dist/client/assets/{Sun-CgyDUxcQ.js → Sun-DY_ADcda.js} +1 -1
- package/dist/client/assets/{Tool01-By8ElVEn.js → Tool01-B5mm7tYF.js} +1 -1
- package/dist/client/assets/{Trash01-BzOKZIoE.js → Trash01-DuRnWn1E.js} +1 -1
- package/dist/client/assets/{User01-B6EEMzxh.js → User01-CQoJwY3u.js} +1 -1
- package/dist/client/assets/{Users03-CKRT_0yR.js → Users03-DfcHW1oz.js} +1 -1
- package/dist/client/assets/{X-DXjTCsIF.js → X-Bgfd1eh0.js} +1 -1
- package/dist/client/assets/{XCircle-Ce7DOyui.js → XCircle-DUufUsoh.js} +1 -1
- package/dist/client/assets/{XClose-Bnw2tzQy.js → XClose-BQJEwJET.js} +1 -1
- package/dist/client/assets/{Zap-BEX7Xuxl.js → Zap-CDLB-lxK.js} +1 -1
- package/dist/client/assets/{ZapSquare-CsTKlylz.js → ZapSquare-BFGlmWLE.js} +1 -1
- package/dist/client/assets/{accordion-rxim1ZAp.js → accordion-zVtel299.js} +1 -1
- package/dist/client/assets/{agent-icon-DtvDglSH.js → agent-icon-DSfidSus.js} +1 -1
- package/dist/client/assets/{agents-list-Dn30Me50.js → agents-list-vffTTABq.js} +1 -1
- package/dist/client/assets/ai-providers-t0YXr9kj.js +1 -0
- package/dist/client/assets/{alert-dialog-DkRKYqdD.js → alert-dialog-rItivTOb.js} +1 -1
- package/dist/client/assets/{auth-catchall-BgWDU-In.js → auth-catchall-BGNYNNAk.js} +1 -1
- package/dist/client/assets/{automation-list-row-Dk3EbUOn.js → automation-list-row-lCQuQb2Q.js} +1 -1
- package/dist/client/assets/{automations-CbjDzR7F.js → automations-C7xJbJSO.js} +1 -1
- package/dist/client/assets/{avatar-CAgGCSe2.js → avatar-UVBUP_wG.js} +1 -1
- package/dist/client/assets/{badge-DBxFBhAO.js → badge-nX1O9Qf1.js} +1 -1
- package/dist/client/assets/{brand-context-C1u8HhCR.js → brand-context-7PuYXROc.js} +1 -1
- package/dist/client/assets/{card-DWuJsQ-l.js → card-B6kxnNb0.js} +1 -1
- package/dist/client/assets/{chat-context-w7qWGRrL.js → chat-context-KGI8H-cg.js} +1 -1
- package/dist/client/assets/{checkbox-CgUCf0vo.js → checkbox-CTi7T5x-.js} +1 -1
- package/dist/client/assets/{collection-detail-miARxdMD.js → collection-detail-D_GfRl2U.js} +1 -1
- package/dist/client/assets/{collection-display-button-IHUVDN00.js → collection-display-button-DtLA-_Qf.js} +1 -1
- package/dist/client/assets/{collection-search-9iq4cHBD.js → collection-search-BVB_BOr-.js} +1 -1
- package/dist/client/assets/{collection-search-Dz-DfctK.js → collection-search-DHiaU-oT.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-zolZkVPt.js → collection-table-wrapper-Cqd6KCzo.js} +1 -1
- package/dist/client/assets/{collection-tabs-DQLxqY5f.js → collection-tabs-CczYJtOJ.js} +1 -1
- package/dist/client/assets/{collections-U39XM2D0.js → collections-Czgjy6V_.js} +1 -1
- package/dist/client/assets/{command-YWTBTzZ-.js → command-C1riJax0.js} +1 -1
- package/dist/client/assets/{connection-card-CzIrL4EL.js → connection-card-MQF8JSkw.js} +1 -1
- package/dist/client/assets/{connection-detail-BAaKFeAe.js → connection-detail-Kmft9f88.js} +1 -1
- package/dist/client/assets/{connection-form-helpers-CkuYmS0Y.js → connection-form-helpers-DMZ5iUjm.js} +1 -1
- package/dist/client/assets/{connections-BhrD0IQp.js → connections-Qfmncrnr.js} +1 -1
- package/dist/client/assets/{constants-3nmHZB7k.js → constants-CMKJaZow.js} +1 -1
- package/dist/client/assets/{constants-C9aLxYHE.js → constants-puxzW8Tt.js} +1 -1
- package/dist/client/assets/{dialog-Dh1iMW0s.js → dialog-CAwNCLeY.js} +1 -1
- package/dist/client/assets/{domain-settings-AVM0VKvz.js → domain-settings-ZwlKCgS9.js} +1 -1
- package/dist/client/assets/{drawer-BVsQgzeD.js → drawer-Co7qhpAL.js} +1 -1
- package/dist/client/assets/{dropdown-menu-BFB_BhxE.js → dropdown-menu-CiJ99ly5.js} +1 -1
- package/dist/client/assets/{dynamic-plugin-layout-89eFL9j5.js → dynamic-plugin-layout-SGNBzqAT.js} +1 -1
- package/dist/client/assets/{empty-state-DaBJGn03.js → empty-state-Bio4MAFs.js} +1 -1
- package/dist/client/assets/{empty-state-Ccngpo14.js → empty-state-DIogXxVN.js} +1 -1
- package/dist/client/assets/{extract-connection-data-DTYSYxBG.js → extract-connection-data-BFIbyEiI.js} +1 -1
- package/dist/client/assets/{features-DyBQ3hAD.js → features-QRbg1n3B.js} +1 -1
- package/dist/client/assets/{form-D1t1amOF.js → form-FdRX5pG1.js} +1 -1
- package/dist/client/assets/{general-BSxOk1qz.js → general-Cc1ql58y.js} +1 -1
- package/dist/client/assets/{github-repo-picker-DSEipb9O.js → github-repo-picker-QAmOQiwy.js} +1 -1
- package/dist/client/assets/{index-aI7M0qEI.js → index-BhZeUpb1.js} +1 -1
- package/dist/client/assets/{index-CiGNH6-A.js → index-BiFex3ig.js} +1 -1
- package/dist/client/assets/{index-DKd6U8ZD.js → index-C4KOdiuW.js} +2 -2
- package/dist/client/assets/{index-DDmmZL9v.js → index-DFoLVe7P.js} +1 -1
- package/dist/client/assets/{index-D0Y3Q7N3.js → index-DcnXzgrr.js} +1 -1
- package/dist/client/assets/{index-BXJluhPl.js → index-DdEYcoGw.js} +1 -1
- package/dist/client/assets/{index-CfcY28zS.js → index-L8A_STvx.js} +1 -1
- package/dist/client/assets/{index-CxNPMl3z.js → index-SoZ9vkB3.js} +4 -4
- package/dist/client/assets/{index-DskwxDSD.js → index-mWgQ602E.js} +1 -1
- package/dist/client/assets/{index-Bgh3Fg-W.js → index-mcaIOSGF.js} +1 -1
- package/dist/client/assets/{infiniteQueryObserver-RFzqIOTQ.js → infiniteQueryObserver-DS8PEXT3.js} +1 -1
- package/dist/client/assets/{input-rXpcOW54.js → input-DrxCctpM.js} +1 -1
- package/dist/client/assets/{integration-icon-wh5nd5gB.js → integration-icon-B-ypwxt-.js} +1 -1
- package/dist/client/assets/{label-KG6f6ypV.js → label-qumw5kFa.js} +1 -1
- package/dist/client/assets/{layout-C1dBBrJO.js → layout-BHQW603q.js} +1 -1
- package/dist/client/assets/{login-aCzD1yj3.js → login-zoPe2LeA.js} +1 -1
- package/dist/client/assets/{members-CcYrdU9b.js → members-BrCn_crL.js} +1 -1
- package/dist/client/assets/{monaco-editor-CetiEdE3.js → monaco-editor-C80vYwBa.js} +1 -1
- package/dist/client/assets/{monitoring-stats-row-Bpsycv3a.js → monitoring-stats-row-DoiRCC4f.js} +1 -1
- package/dist/client/assets/{oauth-callback-Bgqii5KN.js → oauth-callback-CNmuoGWl.js} +1 -1
- package/dist/client/assets/{oauth-callback-ai-provider-BM8V8XSD.js → oauth-callback-ai-provider-CsQrJZmR.js} +1 -1
- package/dist/client/assets/{onboarding-BstJNU1_.js → onboarding-C7clLSW8.js} +1 -1
- package/dist/client/assets/{org-layout-Cbl-bpnq.js → org-layout-BmM2YD3_.js} +1 -1
- package/dist/client/assets/{org-plugin-layout-D5W8iJ__.js → org-plugin-layout-Csh0KNUp.js} +1 -1
- package/dist/client/assets/{plugin-empty-state-ClLmoORa.js → plugin-empty-state-DxSYI7WM.js} +1 -1
- package/dist/client/assets/{plugin-header-BfIRczN-.js → plugin-header-D0WCyAas.js} +1 -1
- package/dist/client/assets/{plugin-layout-CSlooCiQ.js → plugin-layout-BZBMQxU7.js} +1 -1
- package/dist/client/assets/{popover-oHy7A2NB.js → popover-BdnMz9At.js} +1 -1
- package/dist/client/assets/{profile--BcrwHZB.js → profile-BZlcE9Y0.js} +1 -1
- package/dist/client/assets/{project-app-view-7T_TcCNb.js → project-app-view-B8g2l52t.js} +1 -1
- package/dist/client/assets/{registry-layout-DSvJ6NrU.js → registry-layout-DF08kMn2.js} +1 -1
- package/dist/client/assets/registry-oDwGjrMT.js +2 -0
- package/dist/client/assets/{required-auth-layout-C9I2Cbbq.js → required-auth-layout-DAzAQKek.js} +1 -1
- package/dist/client/assets/{reset-password-CIaSK0Sp.js → reset-password-KFV68Ks-.js} +1 -1
- package/dist/client/assets/{roles-BquZRSxB.js → roles-CMvkTrhY.js} +1 -1
- package/dist/client/assets/{scroll-area-UNfVJI8t.js → scroll-area-BlUv7zcB.js} +1 -1
- package/dist/client/assets/{search-input-DfM3hp54.js → search-input-CbSuDoZL.js} +1 -1
- package/dist/client/assets/{select-CIfh_MBY.js → select-W23RccQR.js} +1 -1
- package/dist/client/assets/{select-model-BuijBTi2.js → select-model-BLp2y3cG.js} +1 -1
- package/dist/client/assets/{settings-layout-7GZHLZ6d.js → settings-layout-b1Br3189.js} +1 -1
- package/dist/client/assets/{settings-section-DU0g5n0Q.js → settings-section-CKsKmGWh.js} +1 -1
- package/dist/client/assets/{shell-layout-CcnEVz8S.js → shell-layout-BUuy9S_L.js} +1 -1
- package/dist/client/assets/{skeleton-DWxGcluE.js → skeleton-BKGbLlxs.js} +1 -1
- package/dist/client/assets/{sso-BwOkQ_ww.js → sso-aoLg93_m.js} +1 -1
- package/dist/client/assets/{store-R02TTTNN.js → store-DGgyYg8C.js} +1 -1
- package/dist/client/assets/store-registry-Dbm0_etm.js +2 -0
- package/dist/client/assets/{switch-CWaKO_3R.js → switch-DNv5M4ZB.js} +1 -1
- package/dist/client/assets/{table-UpR-J_t9.js → table-CaLu-Lo8.js} +1 -1
- package/dist/client/assets/{tabs-CgpYNCZH.js → tabs-Ds3m3VsK.js} +1 -1
- package/dist/client/assets/{task-status-CPd-pzw_.js → task-status-DhB__zcV.js} +1 -1
- package/dist/client/assets/{textarea-CVs7u-e-.js → textarea-D8dnqUDV.js} +1 -1
- package/dist/client/assets/{toggle-group-DIrVgcK0.js → toggle-group-DiaVR0jE.js} +1 -1
- package/dist/client/assets/{tools-list-C1Tdz1hL.js → tools-list-CVgYt-8F.js} +1 -1
- package/dist/client/assets/{types-DqiNUavs.js → types-Cj_XQKsH.js} +1 -1
- package/dist/client/assets/{use-ai-providers-D5Tufg2O.js → use-ai-providers-CiKg1J6I.js} +1 -1
- package/dist/client/assets/{use-collections-DpIHOTql.js → use-collections-BgcKlAB6.js} +1 -1
- package/dist/client/assets/{use-connection-1SSSHaHs.js → use-connection-D0OofLda.js} +1 -1
- package/dist/client/assets/{use-copy-CDfDyhwS.js → use-copy-DU9Tefqq.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-Bkn7rT3M.js → use-create-virtual-mcp-DAB2T3vN.js} +1 -1
- package/dist/client/assets/{use-decopilot-events-CN5jq2Ax.js → use-decopilot-events-ClmBUkq4.js} +1 -1
- package/dist/client/assets/{use-delete-connection-3pf7Gnxc.js → use-delete-connection-D8siAEqJ.js} +1 -1
- package/dist/client/assets/{use-infinite-scroll-DknIuIQ2.js → use-infinite-scroll-8BgvLQv0.js} +1 -1
- package/dist/client/assets/{use-list-state-8iqNUJS2.js → use-list-state-BEoAeszV.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-qxi4PxSc.js → use-mcp-tools-D1ScXFUK.js} +1 -1
- package/dist/client/assets/{use-members-Ck6hn7xk.js → use-members-BzwLO50s.js} +1 -1
- package/dist/client/assets/{use-mobile-DrlR5BbG.js → use-mobile-DvmdhkH5.js} +1 -1
- package/dist/client/assets/{use-navigate-to-agent-DlV84y97.js → use-navigate-to-agent-Dg24R1Fh.js} +1 -1
- package/dist/client/assets/{use-org-sso-CWrx0G98.js → use-org-sso-D0nq7yh3.js} +1 -1
- package/dist/client/assets/{use-organization-roles-DsSbdLcn.js → use-organization-roles-Dl9VoSUw.js} +1 -1
- package/dist/client/assets/{use-organization-settings-DoI0c_Gi.js → use-organization-settings-C1HGFbFZ.js} +1 -1
- package/dist/client/assets/{use-registry-connections-BZXVzsNL.js → use-registry-connections-DzXuLNdG.js} +1 -1
- package/dist/client/assets/{use-status-sounds-UAO5zXMo.js → use-status-sounds-BC_OJyRi.js} +1 -1
- package/dist/client/assets/{use-tasks-BGCdXCFh.js → use-tasks-BtGSWUvO.js} +1 -1
- package/dist/client/assets/{use-view-mode-Cobet5rP.js → use-view-mode-BnyE0_EO.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-G7jm3TGl.js → use-virtual-mcp-D1fXVRo5.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-H3t_tPfZ.js +1 -0
- package/dist/client/assets/useSuspenseInfiniteQuery-BAnABuH7.js +1 -0
- package/dist/client/assets/{user-BXlY7NuV.js → user-DAufXs4h.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-PXHnKZlc.js → view-mode-toggle-LshbVzEB.js} +1 -1
- package/dist/client/assets/{workflow-q8JEUlLD.js → workflow-Dt2CIq6i.js} +1 -1
- package/dist/client/assets/workflow-detail-BZ0JnpLY.js +1 -0
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +2 -2
- package/dist/server/node_modules/ansi-regex/index.d.ts +33 -0
- package/dist/server/node_modules/ansi-regex/index.js +14 -0
- package/dist/server/node_modules/ansi-regex/license +9 -0
- package/dist/server/node_modules/ansi-regex/package.json +61 -0
- package/dist/server/node_modules/ansi-regex/readme.md +66 -0
- package/dist/server/node_modules/ansi-styles/index.d.ts +236 -0
- package/dist/server/node_modules/ansi-styles/index.js +223 -0
- package/dist/server/node_modules/ansi-styles/license +9 -0
- package/dist/server/node_modules/ansi-styles/package.json +54 -0
- package/dist/server/node_modules/ansi-styles/readme.md +173 -0
- package/dist/server/node_modules/emoji-regex/LICENSE-MIT.txt +20 -0
- package/dist/server/node_modules/emoji-regex/README.md +107 -0
- package/dist/server/node_modules/emoji-regex/index.d.ts +3 -0
- package/dist/server/node_modules/emoji-regex/index.js +4 -0
- package/dist/server/node_modules/emoji-regex/index.mjs +4 -0
- package/dist/server/node_modules/emoji-regex/package.json +45 -0
- package/dist/server/node_modules/environment/index.d.ts +74 -0
- package/dist/server/node_modules/environment/index.js +47 -0
- package/dist/server/node_modules/environment/license +9 -0
- package/dist/server/node_modules/environment/package.json +74 -0
- package/dist/server/node_modules/environment/readme.md +94 -0
- package/dist/server/node_modules/is-fullwidth-code-point/index.d.ts +17 -0
- package/dist/server/node_modules/is-fullwidth-code-point/index.js +12 -0
- package/dist/server/node_modules/is-fullwidth-code-point/license +9 -0
- package/dist/server/node_modules/is-fullwidth-code-point/package.json +53 -0
- package/dist/server/node_modules/is-fullwidth-code-point/readme.md +31 -0
- package/dist/server/node_modules/is-unicode-supported/index.d.ts +12 -0
- package/dist/server/node_modules/is-unicode-supported/index.js +21 -0
- package/dist/server/node_modules/is-unicode-supported/license +9 -0
- package/dist/server/node_modules/is-unicode-supported/package.json +47 -0
- package/dist/server/node_modules/is-unicode-supported/readme.md +35 -0
- package/dist/server/node_modules/pg-int8/LICENSE +13 -0
- package/dist/server/node_modules/pg-int8/README.md +16 -0
- package/dist/server/node_modules/pg-int8/index.js +100 -0
- package/dist/server/node_modules/pg-int8/package.json +24 -0
- package/dist/server/node_modules/postgres-array/index.d.ts +4 -0
- package/dist/server/node_modules/postgres-array/index.js +97 -0
- package/dist/server/node_modules/postgres-array/license +21 -0
- package/dist/server/node_modules/postgres-array/package.json +35 -0
- package/dist/server/node_modules/postgres-array/readme.md +43 -0
- package/dist/server/node_modules/postgres-bytea/index.js +33 -0
- package/dist/server/node_modules/postgres-bytea/license +21 -0
- package/dist/server/node_modules/postgres-bytea/package.json +34 -0
- package/dist/server/node_modules/postgres-bytea/readme.md +34 -0
- package/dist/server/node_modules/postgres-date/index.js +116 -0
- package/dist/server/node_modules/postgres-date/license +21 -0
- package/dist/server/node_modules/postgres-date/package.json +33 -0
- package/dist/server/node_modules/postgres-date/readme.md +49 -0
- package/dist/server/node_modules/restore-cursor/index.d.ts +11 -0
- package/dist/server/node_modules/restore-cursor/index.js +11 -0
- package/dist/server/node_modules/restore-cursor/license +9 -0
- package/dist/server/node_modules/restore-cursor/package.json +55 -0
- package/dist/server/node_modules/restore-cursor/readme.md +31 -0
- package/dist/server/node_modules/split2/LICENSE +13 -0
- package/dist/server/node_modules/split2/README.md +85 -0
- package/dist/server/node_modules/split2/bench.js +27 -0
- package/dist/server/node_modules/split2/index.js +141 -0
- package/dist/server/node_modules/split2/package.json +39 -0
- package/dist/server/node_modules/split2/test.js +409 -0
- package/dist/server/node_modules/string-width/index.d.ts +39 -0
- package/dist/server/node_modules/string-width/index.js +82 -0
- package/dist/server/node_modules/string-width/license +9 -0
- package/dist/server/node_modules/string-width/package.json +64 -0
- package/dist/server/node_modules/string-width/readme.md +66 -0
- package/dist/server/node_modules/xtend/.jshintrc +30 -0
- package/dist/server/node_modules/{pg → xtend}/LICENSE +6 -7
- package/dist/server/node_modules/xtend/README.md +32 -0
- package/dist/server/node_modules/xtend/immutable.js +19 -0
- package/dist/server/node_modules/xtend/mutable.js +17 -0
- package/dist/server/node_modules/xtend/package.json +55 -0
- package/dist/server/node_modules/xtend/test.js +103 -0
- package/dist/server/server.js +1 -1
- package/package.json +1 -1
- package/dist/client/assets/ai-providers-CC7AZG4I.js +0 -1
- package/dist/client/assets/registry-CDfXAwnP.js +0 -2
- package/dist/client/assets/store-registry-DdbRGyFG.js +0 -2
- package/dist/client/assets/useInfiniteQuery-J4O9iX8k.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-BBJXEpEL.js +0 -1
- package/dist/client/assets/workflow-detail-FemzGjdG.js +0 -1
- package/dist/server/node_modules/pg/README.md +0 -95
- package/dist/server/node_modules/pg/esm/index.mjs +0 -20
- package/dist/server/node_modules/pg/lib/client.js +0 -743
- package/dist/server/node_modules/pg/lib/connection-parameters.js +0 -171
- package/dist/server/node_modules/pg/lib/connection.js +0 -221
- package/dist/server/node_modules/pg/lib/crypto/cert-signatures.js +0 -122
- package/dist/server/node_modules/pg/lib/crypto/sasl.js +0 -212
- package/dist/server/node_modules/pg/lib/crypto/utils-legacy.js +0 -43
- package/dist/server/node_modules/pg/lib/crypto/utils-webcrypto.js +0 -89
- package/dist/server/node_modules/pg/lib/crypto/utils.js +0 -9
- package/dist/server/node_modules/pg/lib/defaults.js +0 -91
- package/dist/server/node_modules/pg/lib/index.js +0 -73
- package/dist/server/node_modules/pg/lib/native/client.js +0 -323
- package/dist/server/node_modules/pg/lib/native/index.js +0 -2
- package/dist/server/node_modules/pg/lib/native/query.js +0 -165
- package/dist/server/node_modules/pg/lib/query.js +0 -252
- package/dist/server/node_modules/pg/lib/result.js +0 -109
- package/dist/server/node_modules/pg/lib/stream.js +0 -83
- package/dist/server/node_modules/pg/lib/type-overrides.js +0 -35
- package/dist/server/node_modules/pg/lib/utils.js +0 -217
- package/dist/server/node_modules/pg/package.json +0 -76
package/dist/server/cli.js
CHANGED
|
@@ -1636,7 +1636,7 @@ AS SELECT
|
|
|
1636
1636
|
FROM monitoring_metrics
|
|
1637
1637
|
GROUP BY organization_id, name, bucket, connection_id, tool_name, status
|
|
1638
1638
|
`}),console.log("[clickhouse-schema] monitoring_metrics_rollup_1m_mv view ready")}finally{await G.close()}}catch(Y){console.error("[clickhouse-schema] Failed to create rollup DDL (queries will fall back to raw table):",Y)}}async function AA1(X){let Y={...process.env},G=C$1(X,Y),Q=G.settings.encryptionKey;console.log(`[settings] ENCRYPTION_KEY = ${JSON.stringify(Q)} (${Q.length} chars)`);let{ensureServices:J}=await Promise.resolve().then(() => (z$1(),B$1)),{outputs:W,services:Z}=await J({home:G.settings.dataDir,externalDatabaseUrl:G.externalDatabaseUrl,externalNatsUrl:G.externalNatsUrl});if(!G.skipMigrations){let{migrateBetterAuth:K}=await Promise.resolve().then(() => ($30(),Ux6));await K(W.databaseUrl);let{createDatabase:H}=await Promise.resolve().then(() => (JU(),Fx6)),{migrateToLatest:U}=await Promise.resolve().then(() => (Dr6(),Or6)),N=H(W.databaseUrl);await U({keepOpen:!0,database:N,skipBetterAuth:!0})}if(G.settings.clickhouseUrl){let{ensureClickHouseRollup:K}=await Promise.resolve().then(() => ws6);await K(G.settings.clickhouseUrl)}let $={...G.settings,databaseUrl:W.databaseUrl,natsUrls:W.natsUrls};return Ul0($),{settings:$,services:Z.map((K)=>({name:K.name==="PostgreSQL"?"Postgres":K.name,port:K.port})),managedServiceNames:Z.filter((K)=>K.owner==="managed").map((K)=>K.name)}}var vN0=D(()=>{cn1();m9()});import{createServer as Ls6}from"net";function ki5(X){return new Promise((Y)=>{let G=Ls6();G.once("error",()=>Y(!1)),G.listen(X,"0.0.0.0",()=>{G.close(()=>Y(!0))})})}async function TA1(X){if(await ki5(X))return X;let Y=await new Promise((G,Q)=>{let J=Ls6();J.once("error",Q),J.listen(0,"0.0.0.0",()=>{let W=J.address(),Z=typeof W==="object"&&W?W.port:0;J.close(()=>G(Z))})});return console.warn(`Port ${X} is in use, using port ${Y} instead.`),Y}var _N0=()=>{};var fN0={};M0(fN0,{startDevServer:()=>_i5});import{join as vi5}from"path";function Es6(X){return X.replace(/\x1b\[[0-9;]*m/g,"")}function Ps6(X){let Y=X.getReader(),G=new TextDecoder,Q="";function J(){let W=Q.split(`
|
|
1639
|
-
`);Q=W.pop()??"";for(let Z of W){let $=Es6(Z).replace(/^\[\d+\]\s*/,"").trim();if(!$)continue;EK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:$})}}(async()=>{for(;;){let{done:W,value:Z}=await Y.read();if(W)break;Q+=G.decode(Z,{stream:!0}),J()}if(Q.trim()){let W=Es6(Q).replace(/^\[\d+\]\s*/,"").trim();if(W)EK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:W})}})()}async function _i5(X){let{vitePort:Y,baseUrl:G,noTui:Q}=X,J=await TA1(Number(X.port)),{settings:W,services:Z,managedServiceNames:$}=await AA1({port:String(J),home:X.home,baseUrl:X.baseUrl,localMode:X.localMode,skipMigrations:X.skipMigrations,noTui:X.noTui,vitePort:X.vitePort});for(let z of Z)Ld({name:z.name,status:"ready",port:z.port});Ve(W),Te();let K=vi5(import.meta.dir,"..","..","..","..",".."),H=Q===!0,U=Bun.spawn(["bun","run","--cwd=apps/mesh","dev:servers"],{cwd:K,env:{...process.env,PORT:String(W.port),VITE_PORT:String(Y),DATABASE_URL:W.databaseUrl,NATS_URL:W.natsUrls.join(","),NODE_ENV:W.nodeEnv,DECOCMS_LOCAL_MODE:String(W.localMode),DECOCMS_HOME:W.dataDir,DATA_DIR:W.dataDir,DECO_CLI:"1",...W.baseUrl?{BASE_URL:W.baseUrl}:{}},stdio:["inherit",H?"inherit":"pipe",H?"inherit":"pipe"]});if(!H)Ps6(U.stdout),Ps6(U.stderr);let N=G||`http://localhost:${W.port}`;Ie(N),Ld({name:"Vite",status:"ready",port:Number(Y)});let B=async(z)=>{if(U.kill(z),$.length>0){let{stopServices:O}=await Promise.resolve().then(() => (z$1(),B$1));await O(W.dataDir)}};return process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM")),{port:Number(W.port),process:U}}var bN0=D(()=>{vN0();GF();_N0()});import{Box as yN0,Text as xN0}from"ink";import{jsx as As6,jsxs as IA1}from"react/jsx-runtime";function qs6(X){if(!X)return"not set";try{let Y=new URL(X);if(Y.password)Y.password="***";if(Y.username&&Y.username.length>3)Y.username=Y.username.slice(0,3)+"***";return Y.pathname="/",Y.search="",Y.hash="",Y.toString()}catch{if(X.length<=10)return X;return X.slice(0,6)+"***"+X.slice(-4)}}function yi5(X,Y){if(fi5.has(X))return Y?{text:"\u25CF\u25CF\u25CF\u25CF\u25CF\u25CF",dimColor:!0}:{text:"not set",dimColor:!0};if(bi5.has(X)){if(Array.isArray(Y)){if(Y.length===0)return{text:"not set",dimColor:!0};return{text:Y.map((W)=>qs6(W)).join(", "),color:"cyan"}}let Q=qs6(Y);return Q==="not set"?{text:Q,dimColor:!0}:{text:Q,color:"cyan"}}if(Y===void 0||Y===null||Y==="")return{text:"not set",dimColor:!0};let G=String(Y);if(G==="true")return{text:G,color:"green"};if(G==="false")return{text:G,color:"yellow"};try{return new URL(G),{text:G,color:"cyan"}}catch{return{text:G}}}function xi5(X){return[{title:"Core",entries:[{key:"NODE_ENV",value:X.nodeEnv},{key:"PORT",value:X.port},{key:"BASE_URL",value:X.baseUrl??`http://localhost:${X.port}`},{key:"DATA_DIR",value:X.dataDir}]},{title:"Database",entries:[{key:"DATABASE_URL",value:X.databaseUrl},{key:"DATABASE_PG_SSL",value:X.databasePgSsl}]},{title:"Auth & Secrets",entries:[{key:"BETTER_AUTH_SECRET",value:X.betterAuthSecret},{key:"ENCRYPTION_KEY",value:X.encryptionKey},{key:"MESH_JWT_SECRET",value:X.meshJwtSecret},{key:"STUDIO_PROVISION_SECRET_KEY",value:X.studioProvisionSecretKey},{key:"DISABLE_RATE_LIMIT",value:X.disableRateLimit}]},{title:"Auth Providers",entries:[{key:"AUTH_EMAIL_PASSWORD_ENABLED",value:process.env.AUTH_EMAIL_PASSWORD_ENABLED??"true"},{key:"AUTH_GOOGLE_CLIENT_ID",value:!!process.env.AUTH_GOOGLE_CLIENT_ID},{key:"AUTH_GITHUB_CLIENT_ID",value:!!process.env.AUTH_GITHUB_CLIENT_ID},{key:"AUTH_RESEND_API_KEY",value:!!process.env.AUTH_RESEND_API_KEY},{key:"AUTH_SENDGRID_API_KEY",value:!!process.env.AUTH_SENDGRID_API_KEY},{key:"AUTH_SSO_MS_CLIENT_ID",value:!!process.env.AUTH_SSO_MS_CLIENT_ID},{key:"AUTH_MAGIC_LINK_ENABLED",value:process.env.AUTH_MAGIC_LINK_ENABLED==="true"},{key:"AUTH_EMAIL_OTP_ENABLED",value:process.env.AUTH_EMAIL_OTP_ENABLED==="true"}]},{title:"Observability",entries:[{key:"CLICKHOUSE_URL",value:X.clickhouseUrl},{key:"OTEL_SERVICE_NAME",value:X.otelServiceName}]},{title:"Event Bus & Networking",entries:[{key:"NATS_URL",value:X.natsUrls}]},{title:"Config Files",entries:[{key:"CONFIG_PATH",value:X.configPath}]},{title:"Transport",entries:[{key:"UNSAFE_ALLOW_STDIO_TRANSPORT",value:X.unsafeAllowStdioTransport}]},{title:"AI Gateway",entries:[{key:"DECO_AI_GATEWAY_ENABLED",value:X.aiGatewayEnabled},{key:"DECO_AI_GATEWAY_URL",value:X.aiGatewayUrl}]}]}function Ts6({env:X}){let Y=xi5(X);return As6(yN0,{flexDirection:"column",children:Y.map((G)=>IA1(yN0,{flexDirection:"column",marginTop:1,children:[IA1(xN0,{dimColor:!0,children:[" ","\u2500\u2500 ",G.title," ","\u2500".repeat(Math.max(0,38-G.title.length))]}),G.entries.map(({key:Q,value:J})=>{let W=yi5(Q,J);return IA1(yN0,{children:[IA1(xN0,{dimColor:!0,children:[" ",Q.padEnd(36)]}),As6(xN0,{color:W.color,dimColor:W.dimColor,children:W.text})]},Q)})]},G.title))})}var fi5,bi5;var Is6=D(()=>{fi5=new Set(["BETTER_AUTH_SECRET","ENCRYPTION_KEY","MESH_JWT_SECRET","STUDIO_PROVISION_SECRET_KEY"]),bi5=new Set(["DATABASE_URL","CLICKHOUSE_URL","NATS_URL"])});var hN0;var Vs6=D(()=>{hN0={name:"decocms",version:"2.292.0",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/mesh"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:'bun run migrate && concurrently "bun run dev:client" "bun run dev:server"',"dev:servers":'concurrently "bun run dev:client" "bun run dev:server"',"dev:client":"bun --bun vite dev","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts","build:client":"bun --bun vite build","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","db:migrate":"bun run ./dist/server/migrate.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts",test:"bun test","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run build:client && bun run build:server"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1","@freestyle-sh/with-bun":"^0.2.12","@freestyle-sh/with-deno":"^0.0.4","@freestyle-sh/with-nodejs":"^0.2.9","freestyle-sandboxes":"^0.1.46"},dependencies:{"@ai-sdk/anthropic":"^3.0.58","@ai-sdk/google":"^3.0.60","@ai-sdk/openai":"^3.0.50","@anthropic-ai/sdk":"^0.79.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dnd-kit/core":"^6.3.1","@dnd-kit/sortable":"^10.0.0","@dnd-kit/utilities":"^3.2.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/ext-apps":"^1.2.2","@openrouter/ai-sdk-provider":"^2.2.5","@opentelemetry/core":"^2.6.0","@tanstack/react-virtual":"^3.13.21","@xterm/addon-fit":"^0.11.0","@xterm/xterm":"^6.0.0","ai-sdk-provider-claude-code":"^3.4.4","ai-sdk-provider-codex-cli":"^1.1.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12",nats:"^2.29.3","posthog-js":"^1.371.1","posthog-node":"^5.0.0",react:"^19.2.0","react-dom":"^19.2.0"},devDependencies:{"@ai-sdk/provider":"^3.0.8","@ai-sdk/react":"^3.0.118","@anthropic-ai/claude-agent-sdk":"^0.2.80","@better-auth/sso":"1.4.1","@daveyplate/better-auth-ui":"^3.2.7","@deco/ui":"workspace:*","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/mesh-sdk":"workspace:*","@decocms/runtime":"workspace:*","@decocms/vite-plugin":"workspace:*","@electric-sql/pglite":"^0.3.15","@floating-ui/react":"^0.27.16","@hookform/resolvers":"^5.2.2","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.27.1","@monaco-editor/react":"^4.7.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@playwright/test":"^1.58.2","@radix-ui/react-avatar":"^1.1.10","@radix-ui/react-checkbox":"^1.3.3","@radix-ui/react-dialog":"^1.1.15","@radix-ui/react-dropdown-menu":"^2.1.16","@radix-ui/react-label":"^2.1.7","@radix-ui/react-select":"^2.2.6","@radix-ui/react-separator":"^1.1.7","@radix-ui/react-slot":"^1.2.3","@radix-ui/react-tabs":"^1.1.13","@rjsf/core":"^6.1.2","@rjsf/shadcn":"^6.1.2","@rjsf/utils":"^6.1.2","@rjsf/validator-ajv8":"^6.1.2","@tailwindcss/vite":"^4.1.17","@tanstack/react-query":"5.90.11","@tanstack/react-router":"^1.139.7","@tiptap/core":"3.20.2","@tiptap/extension-mention":"3.20.2","@tiptap/extension-placeholder":"3.20.2","@tiptap/pm":"3.20.2","@tiptap/react":"3.20.2","@tiptap/starter-kit":"3.20.2","@tiptap/suggestion":"3.20.2","@types/bun":"^1.3.1","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@untitledui/icons":"^0.0.19","@vercel/nft":"^1.1.1","@vitejs/plugin-react":"^5.1.0",ai:"^6.0.116","babel-plugin-react-compiler":"^1.0.0","better-auth":"1.4.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",concurrently:"^9.2.1",croner:"^9.1.0","date-fns":"^4.1.0",degit:"^2.8.4",hono:"^4.10.7","input-otp":"^1.4.2",jose:"^6.0.11","kysely-pglite":"^0.6.1","lucide-react":"^0.468.0",marked:"^15.0.6","@decocms/sandbox":"workspace:*","mesh-plugin-workflows":"workspace:*",nanoid:"^5.1.6",pg:"^8.16.3",prettier:"^3.4.2","react-hook-form":"^7.66.0","react-markdown":"^10.1.0","react-resizable-panels":"^2.1.7","react-syntax-highlighter":"^15.6.1",recharts:"^3.6.0","rehype-raw":"^7.0.0","remark-gfm":"^4.0.0","sass-embedded":"^1.97.2",sonner:"^2.0.7","tailwind-merge":"^3.3.1",tailwindcss:"^4.1.17",typescript:"^5.9.3",vite:"^7.2.1","vite-tsconfig-paths":"^5.1.4",zod:"^4.0.0",zustand:"^5.0.9"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","mesh","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as AU,Text as MX}from"ink";import{Spinner as gi5}from"@inkjs/ui";import{useSyncExternalStore as js6}from"react";import{jsx as qY,jsxs as rQ}from"react/jsx-runtime";function ci5(X,Y){if(!X||!di5.has(X))return X;let G=gN0[Y]??gN0[gN0.length-1];return X==="#875f00"?G[0]:G[1]}function Ms6({status:X}){if(X==="pending")return qY(gi5,{label:""});return qY(MX,{color:"green",children:"\u2713"})}function Rs6({services:X,migrationsStatus:Y,home:G,serverUrl:Q,vibe:J}){let W=js6(fu0,_u0),Z=js6(uu0,gu0);return rQ(AU,{flexDirection:"column",paddingBottom:1,children:[J?rQ(AU,{flexDirection:"column",children:[W.map(($,K)=>{let H=Z[K],U=$.reduce((B,z)=>B+z.text.length,0),N=Math.max(0,mi5-U);return rQ(AU,{flexDirection:"row",children:[$.map((B,z)=>{let O=ci5(B.color,K);return O?qY(MX,{color:O,children:B.text},z):qY(MX,{children:B.text},z)}),qY(MX,{children:" ".repeat(N+2)}),H?.map((B,z)=>B.color?qY(MX,{color:B.color,children:B.char},z):qY(MX,{children:B.char},z))]},K)}),rQ(MX,{dimColor:!0,children:[" v",hN0.version]})]}):rQ(AU,{flexDirection:"column",marginTop:1,children:[ui5.map(($,K)=>qY(MX,{color:li5[K],children:$},K)),rQ(MX,{dimColor:!0,children:[" v",hN0.version]})]}),qY(AU,{marginBottom:1,children:qY(MX,{dimColor:!0,children:"\u2500".repeat(80)})}),qY(AU,{children:rQ(MX,{dimColor:!0,children:["Home: ",G]})}),rQ(AU,{gap:2,children:[X.map(($)=>rQ(AU,{gap:1,children:[rQ(MX,{children:[$.name," :",$.port||"...."]}),qY(Ms6,{status:$.status})]},$.name)),rQ(AU,{gap:1,children:[qY(MX,{children:"Migrations"}),qY(Ms6,{status:Y})]})]}),qY(AU,{children:Q?rQ(MX,{children:["Open in browser: ",qY(MX,{color:"cyan",children:Q})]}):qY(MX,{dimColor:!0,children:"Starting..."})}),rQ(AU,{gap:2,children:[rQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"K"})," ","toggle config"]}),rQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"L"})," ","toggle log flow"]}),rQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"V"})," ","toggle vibe ",J?"\u266A Nihilore \xB7 CC BY 4.0":""]}),J&&rQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"N"})," ","skip song"]})]})]})}var ui5,li5,gN0,mi5=30,di5;var Ss6=D(()=>{Vs6();Pn1();jn1();ui5=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 ","\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588 \u2591 \u2588\u2588\u2588 \u2591\u2591\u2591 \u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591 \u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588 "," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591 ","\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591 "],li5=["#00ff64","#00ee5e","#00dc56","#00c84e","#00b444","#00a03c","#008832","#006e28"],gN0=[["#00ff64","#00cc50"],["#00f060","#00c04c"],["#00e05c","#00b448"],["#00d058","#00a844"],["#00c054","#009c40"],["#00b050","#00903c"],["#00a04c","#008438"],["#009048","#007834"],["#008044","#006c30"],["#007040","#00602c"],["#00603c","#005428"]],di5=new Set(["#875f00","#5f3800"])});import{useSyncExternalStore as ii5}from"react";function pi5(){let X=process.stdout.rows||24,Y=process.stdout.columns||80;if(X!==VA1.rows||Y!==VA1.columns)VA1={rows:X,columns:Y};return VA1}function ni5(X){return process.stdout.on("resize",X),()=>{process.stdout.off("resize",X)}}function Cs6(){return ii5(ni5,pi5)}var VA1;var ks6=D(()=>{VA1={rows:process.stdout.rows||24,columns:process.stdout.columns||80}});import{Box as ai5,Text as AX1}from"ink";import{useSyncExternalStore as ti5}from"react";import{jsx as uN0,jsxs as lN0}from"react/jsx-runtime";function ri5(X){if(X>=500)return"red";if(X>=400)return"yellow";if(X>=300)return"cyan";return"green"}function vs6({logs:X,headerHeight:Y}){let{rows:G}=Cs6(),{logFlow:Q}=ti5(Ae,qe),J=Math.max(1,G-Y-1),W=Q?X:X.slice(-J);return uN0(ai5,{flexDirection:"column",children:W.map((Z,$)=>{if(Z.rawLine)return uN0(AX1,{dimColor:!0,children:Z.rawLine},$);let K=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return lN0(AX1,{children:[lN0(AX1,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),uN0(AX1,{color:ri5(Z.status),children:Z.status}),lN0(AX1,{dimColor:!0,children:[" ",K.padStart(8)]})]},$)})})}var _s6=D(()=>{GF();ks6()});var mN0={};M0(mN0,{App:()=>Qp5});import{Box as oi5,Text as si5,useInput as ei5}from"ink";import{useSyncExternalStore as Xp5}from"react";import{jsx as jA1,jsxs as Jp5}from"react/jsx-runtime";function Qp5({home:X}){let Y=Xp5(Ae,qe);return ei5((G)=>{if(G==="k"||G==="K")vn1();if(G==="l"||G==="L")_n1();if((G==="v"||G==="V")&&Y.dataDir)Cn1(Y.dataDir),fn1();if((G==="n"||G==="N")&&Y.vibe)Sn1()}),Jp5(oi5,{flexDirection:"column",children:[jA1(Rs6,{services:Y.services,migrationsStatus:Y.migrationsStatus,home:X,serverUrl:Y.serverUrl,vibe:Y.vibe}),Y.viewMode==="config"?Y.env?jA1(Ts6,{env:Y.env}):jA1(si5,{dimColor:!0,children:"Loading configuration..."}):jA1(vs6,{logs:Y.logs,headerHeight:Y.vibe?Gp5:Yp5})]})}var Yp5=15,Gp5=19;var dN0=D(()=>{Is6();Ss6();_s6();GF();wd()});function fs6(X,Y={}){return{PORT:String(X.port),NODE_ENV:X.nodeEnv,BASE_URL:X.baseUrl,DATA_DIR:X.dataDir,DECOCMS_HOME:X.dataDir,DATABASE_URL:X.databaseUrl,DATABASE_PG_SSL:String(X.databasePgSsl),DATABASE_POOL_MAX:String(X.databasePoolMax),NATS_URL:X.natsUrls.join(","),BETTER_AUTH_SECRET:X.betterAuthSecret,ENCRYPTION_KEY:X.encryptionKey,MESH_JWT_SECRET:X.meshJwtSecret,DECOCMS_LOCAL_MODE:String(X.localMode),DECOCMS_ALLOW_LOCAL_PROD:String(X.allowLocalProd),DISABLE_RATE_LIMIT:String(X.disableRateLimit),STUDIO_PROVISION_SECRET_KEY:X.studioProvisionSecretKey,CONFIG_PATH:X.configPath,...Object.fromEntries(Object.entries(process.env).filter(([G])=>G.startsWith("AUTH_"))),UNSAFE_ALLOW_STDIO_TRANSPORT:String(X.unsafeAllowStdioTransport),DECO_AI_GATEWAY_ENABLED:String(X.aiGatewayEnabled),DECO_AI_GATEWAY_URL:X.aiGatewayUrl,ENABLE_DECO_IMPORT:String(X.enableDecoImport),S3_ENDPOINT:X.s3Endpoint,S3_BUCKET:X.s3Bucket,S3_REGION:X.s3Region,S3_ACCESS_KEY_ID:X.s3AccessKeyId,S3_SECRET_ACCESS_KEY:X.s3SecretAccessKey,S3_FORCE_PATH_STYLE:String(X.s3ForcePathStyle),OTEL_SERVICE_NAME:X.otelServiceName,CLICKHOUSE_URL:X.clickhouseUrl,DECO_SUPABASE_URL:X.decoSupabaseUrl,DECO_SUPABASE_SERVICE_KEY:X.decoSupabaseServiceKey,FIRECRAWL_API_KEY:X.firecrawlApiKey,STUDIO_SANDBOX_RUNNER:process.env.STUDIO_SANDBOX_RUNNER,STUDIO_SANDBOX_TEMPLATE_NAME:process.env.STUDIO_SANDBOX_TEMPLATE_NAME,FREESTYLE_API_KEY:process.env.FREESTYLE_API_KEY,BROWSERLESS_TOKEN:process.env.BROWSERLESS_TOKEN,NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS,DECO_CLI:"1",DECO_NO_TUI:"true",...Y}}function ys6(X){if(!X)return!1;try{return new URL(X).host==="api.decocms.com"&&X!=="https://studio.decocms.com/org/deco/registry/mcp"}catch{return!1}}var bs6="https://studio.decocms.com/org/deco/registry/mcp";var cN0=(X,Y,G)=>{return(Q,J)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,U;if(X[$])U=X[$][0][0],Q.req.routeIndex=$;else U=$===X.length&&J||void 0;if(U)try{K=await U(Q,()=>Z($+1))}catch(N){if(N instanceof Error&&Y)Q.error=N,K=await Y(N,Q),H=!0;else throw N}else if(Q.finalized===!1&&G)K=await G(Q);if(K&&(Q.finalized===!1||H))Q.res=K;return Q}}};var xs6=()=>{};var M9;var Lq=D(()=>{M9=class extends Error{res;status;constructor(X=500,Y){super(Y?.message,{cause:Y?.cause});this.res=Y?.res,this.status=X}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var hs6;var gs6=D(()=>{hs6=Symbol()});async function Zp5(X,Y){let G=await X.formData();if(G)return Wp5(G,Y);return{}}function Wp5(X,Y){let G=Object.create(null);if(X.forEach((Q,J)=>{if(!(Y.all||J.endsWith("[]")))G[J]=Q;else $p5(G,J,Q)}),Y.dot)Object.entries(G).forEach(([Q,J])=>{if(Q.includes("."))Kp5(G,Q,J),delete G[Q]});return G}var us6=async(X,Y=Object.create(null))=>{let{all:G=!1,dot:Q=!1}=Y,W=(X instanceof MA1?X.raw.headers:X.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return Zp5(X,{all:G,dot:Q});return{}},$p5=(X,Y,G)=>{if(X[Y]!==void 0)if(Array.isArray(X[Y]))X[Y].push(G);else X[Y]=[X[Y],G];else if(!Y.endsWith("[]"))X[Y]=G;else X[Y]=[G]},Kp5=(X,Y,G)=>{if(/(?:^|\.)__proto__\./.test(Y))return;let Q=X,J=Y.split(".");J.forEach((W,Z)=>{if(Z===J.length-1)Q[W]=G;else{if(!Q[W]||typeof Q[W]!=="object"||Array.isArray(Q[W])||Q[W]instanceof File)Q[W]=Object.create(null);Q=Q[W]}})};var ls6=D(()=>{iN0()});var nN0=(X)=>{let Y=X.split("/");if(Y[0]==="")Y.shift();return Y},ms6=(X)=>{let{groups:Y,path:G}=Hp5(X),Q=nN0(G);return Fp5(Q,Y)},Hp5=(X)=>{let Y=[];return X=X.replace(/\{[^}]+\}/g,(G,Q)=>{let J=`@${Q}`;return Y.push([J,G]),J}),{groups:Y,path:X}},Fp5=(X,Y)=>{for(let G=Y.length-1;G>=0;G--){let[Q]=Y[G];for(let J=X.length-1;J>=0;J--)if(X[J].includes(Q)){X[J]=X[J].replace(Q,Y[G][1]);break}}return X},RA1,ds6=(X,Y)=>{if(X==="*")return"*";let G=X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(G){let Q=`${X}#${Y}`;if(!RA1[Q])if(G[2])RA1[Q]=Y&&Y[0]!==":"&&Y[0]!=="*"?[Q,G[1],new RegExp(`^${G[2]}(?=/${Y})`)]:[X,G[1],new RegExp(`^${G[2]}$`)];else RA1[Q]=[X,G[1],!0];return RA1[Q]}return null},ia=(X,Y)=>{try{return Y(X)}catch{return X.replace(/(?:%[0-9A-Fa-f]{2})+/g,(G)=>{try{return Y(G)}catch{return G}})}},cs6=(X)=>ia(X,decodeURI),aN0=(X)=>{let Y=X.url,G=Y.indexOf("/",Y.indexOf(":")+4),Q=G;for(;Q<Y.length;Q++){let J=Y.charCodeAt(Q);if(J===37){let W=Y.indexOf("?",Q),Z=Y.indexOf("#",Q),$=W===-1?Z===-1?void 0:Z:Z===-1?W:Math.min(W,Z),K=Y.slice(G,$);return cs6(K.includes("%25")?K.replace(/%25/g,"%2525"):K)}else if(J===63||J===35)break}return Y.slice(G,Q)},is6=(X)=>{let Y=aN0(X);return Y.length>1&&Y.at(-1)==="/"?Y.slice(0,-1):Y},Tj=(X,Y,...G)=>{if(G.length)Y=Tj(Y,...G);return`${X?.[0]==="/"?"":"/"}${X}${Y==="/"?"":`${X?.at(-1)==="/"?"":"/"}${Y?.[0]==="/"?Y.slice(1):Y}`}`},SA1=(X)=>{if(X.charCodeAt(X.length-1)!==63||!X.includes(":"))return null;let Y=X.split("/"),G=[],Q="";return Y.forEach((J)=>{if(J!==""&&!/\:/.test(J))Q+="/"+J;else if(/\:/.test(J))if(/\?/.test(J)){if(G.length===0&&Q==="")G.push("/");else G.push(Q);let W=J.replace("?","");Q+="/"+W,G.push(Q)}else Q+="/"+J}),G.filter((J,W,Z)=>Z.indexOf(J)===W)},pN0=(X)=>{if(!/[%+]/.test(X))return X;if(X.indexOf("+")!==-1)X=X.replace(/\+/g," ");return X.indexOf("%")!==-1?ia(X,TX1):X},ps6=(X,Y,G)=>{let Q;if(!G&&Y&&!/[%+]/.test(Y)){let Z=X.indexOf("?",8);if(Z===-1)return;if(!X.startsWith(Y,Z+1))Z=X.indexOf(`&${Y}`,Z+1);while(Z!==-1){let $=X.charCodeAt(Z+Y.length+1);if($===61){let K=Z+Y.length+2,H=X.indexOf("&",K);return pN0(X.slice(K,H===-1?void 0:H))}else if($==38||isNaN($))return"";Z=X.indexOf(`&${Y}`,Z+1)}if(Q=/[%+]/.test(X),!Q)return}let J={};Q??=/[%+]/.test(X);let W=X.indexOf("?",8);while(W!==-1){let Z=X.indexOf("&",W+1),$=X.indexOf("=",W);if($>Z&&Z!==-1)$=-1;let K=X.slice(W+1,$===-1?Z===-1?void 0:Z:$);if(Q)K=pN0(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=X.slice($+1,Z===-1?void 0:Z),Q)H=pN0(H);if(G){if(!(J[K]&&Array.isArray(J[K])))J[K]=[];J[K].push(H)}else J[K]??=H}return Y?J[Y]:J},ns6,as6=(X,Y)=>{return ps6(X,Y,!0)},TX1;var Eq=D(()=>{RA1={},ns6=ps6,TX1=decodeURIComponent});var ts6=(X)=>ia(X,TX1),MA1;var iN0=D(()=>{Lq();gs6();ls6();Eq();MA1=class{raw;#X;#Y;routeIndex=0;path;bodyCache={};constructor(X,Y="/",G=[[]]){this.raw=X,this.path=Y,this.#Y=G,this.#X={}}param(X){return X?this.#G(X):this.#Q()}#G(X){let Y=this.#Y[0][this.routeIndex][1][X],G=this.#J(Y);return G&&/\%/.test(G)?ts6(G):G}#Q(){let X={},Y=Object.keys(this.#Y[0][this.routeIndex][1]);for(let G of Y){let Q=this.#J(this.#Y[0][this.routeIndex][1][G]);if(Q!==void 0)X[G]=/\%/.test(Q)?ts6(Q):Q}return X}#J(X){return this.#Y[1]?this.#Y[1][X]:X}query(X){return ns6(this.url,X)}queries(X){return as6(this.url,X)}header(X){if(X)return this.raw.headers.get(X)??void 0;let Y={};return this.raw.headers.forEach((G,Q)=>{Y[Q]=G}),Y}async parseBody(X){return us6(this,X)}#Z=(X)=>{let{bodyCache:Y,raw:G}=this,Q=Y[X];if(Q)return Q;let J=Object.keys(Y)[0];if(J)return Y[J].then((W)=>{if(J==="json")W=JSON.stringify(W);return new Response(W)[X]()});return Y[X]=G[X]()};json(){return this.#Z("text").then((X)=>JSON.parse(X))}text(){return this.#Z("text")}arrayBuffer(){return this.#Z("arrayBuffer")}blob(){return this.#Z("blob")}formData(){return this.#Z("formData")}addValidatedData(X,Y){this.#X[X]=Y}valid(X){return this.#X[X]}get url(){return this.raw.url}get method(){return this.raw.method}get[hs6](){return this.#Y}get matchedRoutes(){return this.#Y[0].map(([[,X]])=>X)}get routePath(){return this.#Y[0].map(([[,X]])=>X)[this.routeIndex].path}}});var CA1,rs6=(X,Y)=>{let G=new String(X);return G.isEscaped=!0,G.callbacks=Y,G},IX1=async(X,Y,G,Q,J)=>{if(typeof X==="object"&&!(X instanceof String)){if(!(X instanceof Promise))X=X.toString();if(X instanceof Promise)X=await X}let W=X.callbacks;if(!W?.length)return Promise.resolve(X);if(J)J[0]+=X;else J=[X];let Z=Promise.all(W.map(($)=>$({phase:Y,buffer:J,context:Q}))).then(($)=>Promise.all($.filter(Boolean).map((K)=>IX1(K,Y,!1,Q,J))).then(()=>J[0]));if(G)return rs6(await Z,W);else return Z};var kA1=D(()=>{CA1={Stringify:1,BeforeStream:2,Stream:3}});var os6="text/plain; charset=UTF-8",tN0=(X,Y)=>{return{"Content-Type":X,...Y}},VX1=(X,Y)=>new Response(X,Y),ss6=class{#X;#Y;env={};#G;finalized=!1;error;#Q;#J;#Z;#$;#W;#K;#H;#U;#N;constructor(X,Y){if(this.#X=X,Y)this.#J=Y.executionCtx,this.env=Y.env,this.#K=Y.notFoundHandler,this.#N=Y.path,this.#U=Y.matchResult}get req(){return this.#Y??=new MA1(this.#X,this.#N,this.#U),this.#Y}get event(){if(this.#J&&"respondWith"in this.#J)return this.#J;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#J)return this.#J;else throw Error("This context has no ExecutionContext")}get res(){return this.#Z||=VX1(null,{headers:this.#H??=new Headers})}set res(X){if(this.#Z&&X){X=VX1(X.body,X);for(let[Y,G]of this.#Z.headers.entries()){if(Y==="content-type")continue;if(Y==="set-cookie"){let Q=this.#Z.headers.getSetCookie();X.headers.delete("set-cookie");for(let J of Q)X.headers.append("set-cookie",J)}else X.headers.set(Y,G)}}this.#Z=X,this.finalized=!0}render=(...X)=>{return this.#W??=(Y)=>this.html(Y),this.#W(...X)};setLayout=(X)=>this.#$=X;getLayout=()=>this.#$;setRenderer=(X)=>{this.#W=X};header=(X,Y,G)=>{if(this.finalized)this.#Z=VX1(this.#Z.body,this.#Z);let Q=this.#Z?this.#Z.headers:this.#H??=new Headers;if(Y===void 0)Q.delete(X);else if(G?.append)Q.append(X,Y);else Q.set(X,Y)};status=(X)=>{this.#Q=X};set=(X,Y)=>{this.#G??=new Map,this.#G.set(X,Y)};get=(X)=>{return this.#G?this.#G.get(X):void 0};get var(){if(!this.#G)return{};return Object.fromEntries(this.#G)}#F(X,Y,G){let Q=this.#Z?new Headers(this.#Z.headers):this.#H??new Headers;if(typeof Y==="object"&&"headers"in Y){let W=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);for(let[Z,$]of W)if(Z.toLowerCase()==="set-cookie")Q.append(Z,$);else Q.set(Z,$)}if(G)for(let[W,Z]of Object.entries(G))if(typeof Z==="string")Q.set(W,Z);else{Q.delete(W);for(let $ of Z)Q.append(W,$)}let J=typeof Y==="number"?Y:Y?.status??this.#Q;return VX1(X,{status:J,headers:Q})}newResponse=(...X)=>this.#F(...X);body=(X,Y,G)=>this.#F(X,Y,G);text=(X,Y,G)=>{return!this.#H&&!this.#Q&&!Y&&!G&&!this.finalized?new Response(X):this.#F(X,Y,tN0(os6,G))};json=(X,Y,G)=>{return this.#F(JSON.stringify(X),Y,tN0("application/json",G))};html=(X,Y,G)=>{let Q=(J)=>this.#F(J,Y,tN0("text/html; charset=UTF-8",G));return typeof X==="object"?IX1(X,CA1.Stringify,!1,{}).then(Q):Q(X)};redirect=(X,Y)=>{let G=String(X);return this.header("Location",!/[^\x00-\xFF]/.test(G)?G:encodeURI(G)),this.newResponse(null,Y??302)};notFound=()=>{return this.#K??=()=>VX1(),this.#K(this)}};var vA1=D(()=>{iN0();kA1()});var T7="ALL",es6="all",Xe6,_A1="Can not add a route since the matcher is already built.",fA1;var Pq=D(()=>{Xe6=["get","post","put","delete","options","patch"],fA1=class extends Error{}});var rN0="__COMPOSED_HANDLER";var oN0=()=>{};var Up5=(X)=>{return X.text("404 Not Found",404)},Ye6=(X,Y)=>{if("getResponse"in X){let G=X.getResponse();return Y.newResponse(G.body,G)}return console.error(X),Y.text("Internal Server Error",500)},Ge6=class X{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#X="/";routes=[];constructor(Y={}){[...Xe6,es6].forEach((W)=>{this[W]=(Z,...$)=>{if(typeof Z==="string")this.#X=Z;else this.#Q(W,this.#X,Z);return $.forEach((K)=>{this.#Q(W,this.#X,K)}),this}}),this.on=(W,Z,...$)=>{for(let K of[Z].flat()){this.#X=K;for(let H of[W].flat())$.map((U)=>{this.#Q(H.toUpperCase(),this.#X,U)})}return this},this.use=(W,...Z)=>{if(typeof W==="string")this.#X=W;else this.#X="*",Z.unshift(W);return Z.forEach(($)=>{this.#Q(T7,this.#X,$)}),this};let{strict:Q,...J}=Y;Object.assign(this,J),this.getPath=Q??!0?Y.getPath??aN0:is6}#Y(){let Y=new X({router:this.router,getPath:this.getPath});return Y.errorHandler=this.errorHandler,Y.#G=this.#G,Y.routes=this.routes,Y}#G=Up5;errorHandler=Ye6;route(Y,G){let Q=this.basePath(Y);return G.routes.map((J)=>{let W;if(G.errorHandler===Ye6)W=J.handler;else W=async(Z,$)=>(await cN0([],G.errorHandler)(Z,()=>J.handler(Z,$))).res,W[rN0]=J.handler;Q.#Q(J.method,J.path,W)}),this}basePath(Y){let G=this.#Y();return G._basePath=Tj(this._basePath,Y),G}onError=(Y)=>{return this.errorHandler=Y,this};notFound=(Y)=>{return this.#G=Y,this};mount(Y,G,Q){let J,W;if(Q)if(typeof Q==="function")W=Q;else if(W=Q.optionHandler,Q.replaceRequest===!1)J=(K)=>K;else J=Q.replaceRequest;let Z=W?(K)=>{let H=W(K);return Array.isArray(H)?H:[H]}:(K)=>{let H=void 0;try{H=K.executionCtx}catch{}return[K.env,H]};J||=(()=>{let K=Tj(this._basePath,Y),H=K==="/"?0:K.length;return(U)=>{let N=new URL(U.url);return N.pathname=N.pathname.slice(H)||"/",new Request(N,U)}})();let $=async(K,H)=>{let U=await G(J(K.req.raw),...Z(K));if(U)return U;await H()};return this.#Q(T7,Tj(Y,"*"),$),this}#Q(Y,G,Q){Y=Y.toUpperCase(),G=Tj(this._basePath,G);let J={basePath:this._basePath,path:G,method:Y,handler:Q};this.router.add(Y,G,[Q,J]),this.routes.push(J)}#J(Y,G){if(Y instanceof Error)return this.errorHandler(Y,G);throw Y}#Z(Y,G,Q,J){if(J==="HEAD")return(async()=>new Response(null,await this.#Z(Y,G,Q,"GET")))();let W=this.getPath(Y,{env:Q}),Z=this.router.match(J,W),$=new ss6(Y,{path:W,matchResult:Z,env:Q,executionCtx:G,notFoundHandler:this.#G});if(Z[0].length===1){let H;try{H=Z[0][0][0][0]($,async()=>{$.res=await this.#G($)})}catch(U){return this.#J(U,$)}return H instanceof Promise?H.then((U)=>U||($.finalized?$.res:this.#G($))).catch((U)=>this.#J(U,$)):H??this.#G($)}let K=cN0(Z[0],this.errorHandler,this.#G);return(async()=>{try{let H=await K($);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#J(H,$)}})()}fetch=(Y,...G)=>{return this.#Z(Y,G[1],G[0],Y.method)};request=(Y,G,Q,J)=>{if(Y instanceof Request)return this.fetch(G?new Request(Y,G):Y,Q,J);return Y=Y.toString(),this.fetch(new Request(/^https?:\/\//.test(Y)?Y:`http://localhost${Tj("/",Y)}`,G),Q,J)};fire=()=>{addEventListener("fetch",(Y)=>{Y.respondWith(this.#Z(Y.request,Y,void 0,Y.request.method))})}};var Qe6=D(()=>{xs6();vA1();Pq();oN0();Eq()});function bA1(X,Y){let G=this.buildAllMatchers(),Q=(J,W)=>{let Z=G[J]||G[T7],$=Z[2][W];if($)return $;let K=W.match(Z[0]);if(!K)return[[],jX1];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=Q,Q(X,Y)}var jX1;var sN0=D(()=>{Pq();jX1=[]});function Bp5(X,Y){if(X.length===1)return Y.length===1?X<Y?-1:1:-1;if(Y.length===1)return 1;if(X===MX1||X===RX1)return 1;else if(Y===MX1||Y===RX1)return-1;if(X===yA1)return 1;else if(Y===yA1)return-1;return X.length===Y.length?X<Y?-1:1:Y.length-X.length}var yA1="[^/]+",MX1=".*",RX1="(?:|/.*)",Ij,Np5,Je6=class X{#X;#Y;#G=Object.create(null);insert(Y,G,Q,J,W){if(Y.length===0){if(this.#X!==void 0)throw Ij;if(W)return;this.#X=G;return}let[Z,...$]=Y,K=Z==="*"?$.length===0?["","",MX1]:["","",yA1]:Z==="/*"?["","",RX1]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let U=K[1],N=K[2]||yA1;if(U&&K[2]){if(N===".*")throw Ij;if(N=N.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(N))throw Ij}if(H=this.#G[N],!H){if(Object.keys(this.#G).some((B)=>B!==MX1&&B!==RX1))throw Ij;if(W)return;if(H=this.#G[N]=new X,U!=="")H.#Y=J.varIndex++}if(!W&&U!=="")Q.push([U,H.#Y])}else if(H=this.#G[Z],!H){if(Object.keys(this.#G).some((U)=>U.length>1&&U!==MX1&&U!==RX1))throw Ij;if(W)return;H=this.#G[Z]=new X}H.insert($,G,Q,J,W)}buildRegExpStr(){let G=Object.keys(this.#G).sort(Bp5).map((Q)=>{let J=this.#G[Q];return(typeof J.#Y==="number"?`(${Q})@${J.#Y}`:Np5.has(Q)?`\\${Q}`:Q)+J.buildRegExpStr()});if(typeof this.#X==="number")G.unshift(`#${this.#X}`);if(G.length===0)return"";if(G.length===1)return G[0];return"(?:"+G.join("|")+")"}};var eN0=D(()=>{Ij=Symbol(),Np5=new Set(".\\+*[^]$()")});var Ze6=class{#X={varIndex:0};#Y=new Je6;insert(X,Y,G){let Q=[],J=[];for(let Z=0;;){let $=!1;if(X=X.replace(/\{[^}]+\}/g,(K)=>{let H=`@\\${Z}`;return J[Z]=[H,K],Z++,$=!0,H}),!$)break}let W=X.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Z=J.length-1;Z>=0;Z--){let[$]=J[Z];for(let K=W.length-1;K>=0;K--)if(W[K].indexOf($)!==-1){W[K]=W[K].replace($,J[Z][1]);break}}return this.#Y.insert(W,Y,Q,this.#X,G),Q}buildRegExp(){let X=this.#Y.buildRegExpStr();if(X==="")return[/^$/,[],[]];let Y=0,G=[],Q=[];return X=X.replace(/#(\d+)|@(\d+)|\.\*\$/g,(J,W,Z)=>{if(W!==void 0)return G[++Y]=Number(W),"$()";if(Z!==void 0)return Q[Number(Z)]=++Y,"";return""}),[new RegExp(`^${X}`),G,Q]}};var We6=D(()=>{eN0()});function Ke6(X){return $e6[X]??=new RegExp(X==="*"?"":`^${X.replace(/\/\*$|([.\\+*[^\]$()])/g,(Y,G)=>G?`\\${G}`:"(?:|/.*)")}$`)}function Op5(){$e6=Object.create(null)}function Dp5(X){let Y=new Ze6,G=[];if(X.length===0)return zp5;let Q=X.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,U],[N,B])=>H?1:N?-1:U.length-B.length),J=Object.create(null);for(let H=0,U=-1,N=Q.length;H<N;H++){let[B,z,O]=Q[H];if(B)J[z]=[O.map(([E])=>[E,Object.create(null)]),jX1];else U++;let w;try{w=Y.insert(z,U,B)}catch(E){throw E===Ij?new fA1(z):E}if(B)continue;G[U]=O.map(([E,P])=>{let q=Object.create(null);P-=1;for(;P>=0;P--){let[j,M]=w[P];q[j]=M}return[E,q]})}let[W,Z,$]=Y.buildRegExp();for(let H=0,U=G.length;H<U;H++)for(let N=0,B=G[H].length;N<B;N++){let z=G[H][N]?.[1];if(!z)continue;let O=Object.keys(z);for(let w=0,E=O.length;w<E;w++)z[O[w]]=$[z[O[w]]]}let K=[];for(let H in Z)K[H]=G[Z[H]];return[W,K,J]}function pa(X,Y){if(!X)return;for(let G of Object.keys(X).sort((Q,J)=>J.length-Q.length))if(Ke6(G).test(Y))return[...X[G]];return}var zp5,$e6,xA1=class{name="RegExpRouter";#X;#Y;constructor(){this.#X={[T7]:Object.create(null)},this.#Y={[T7]:Object.create(null)}}add(X,Y,G){let Q=this.#X,J=this.#Y;if(!Q||!J)throw Error(_A1);if(!Q[X])[Q,J].forEach(($)=>{$[X]=Object.create(null),Object.keys($[T7]).forEach((K)=>{$[X][K]=[...$[T7][K]]})});if(Y==="/*")Y="*";let W=(Y.match(/\/:/g)||[]).length;if(/\*$/.test(Y)){let $=Ke6(Y);if(X===T7)Object.keys(Q).forEach((K)=>{Q[K][Y]||=pa(Q[K],Y)||pa(Q[T7],Y)||[]});else Q[X][Y]||=pa(Q[X],Y)||pa(Q[T7],Y)||[];Object.keys(Q).forEach((K)=>{if(X===T7||X===K)Object.keys(Q[K]).forEach((H)=>{$.test(H)&&Q[K][H].push([G,W])})}),Object.keys(J).forEach((K)=>{if(X===T7||X===K)Object.keys(J[K]).forEach((H)=>$.test(H)&&J[K][H].push([G,W]))});return}let Z=SA1(Y)||[Y];for(let $=0,K=Z.length;$<K;$++){let H=Z[$];Object.keys(J).forEach((U)=>{if(X===T7||X===U)J[U][H]||=[...pa(Q[U],H)||pa(Q[T7],H)||[]],J[U][H].push([G,W-K+$+1])})}}match=bA1;buildAllMatchers(){let X=Object.create(null);return Object.keys(this.#Y).concat(Object.keys(this.#X)).forEach((Y)=>{X[Y]||=this.#G(Y)}),this.#X=this.#Y=void 0,Op5(),X}#G(X){let Y=[],G=X===T7;if([this.#X,this.#Y].forEach((Q)=>{let J=Q[X]?Object.keys(Q[X]).map((W)=>[W,Q[X][W]]):[];if(J.length!==0)G||=!0,Y.push(...J);else if(X!==T7)Y.push(...Object.keys(Q[T7]).map((W)=>[W,Q[T7][W]]))}),!G)return null;else return Dp5(Y)}};var XB0=D(()=>{Pq();Eq();sN0();eN0();We6();zp5=[/^$/,[],Object.create(null)],$e6=Object.create(null)});var wp5=class{name="PreparedRegExpRouter";#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}#G(X,Y){let G=this.#X[X];G[1].forEach((Q)=>Q&&Q.push(Y)),Object.values(G[2]).forEach((Q)=>Q[0].push(Y))}#Q(X,Y,G,Q,J){let W=this.#X[X];if(!J)W[2][Y][0].push([G,{}]);else Q.forEach((Z)=>{if(typeof Z==="number")W[1][Z].push([G,J]);else W[2][Z||Y][0].push([G,J])})}add(X,Y,G){if(!this.#X[X]){let J=this.#X[T7],W={};for(let Z in J[2])W[Z]=[J[2][Z][0].slice(),jX1];this.#X[X]=[J[0],J[1].map((Z)=>Array.isArray(Z)?Z.slice():0),W]}if(Y==="/*"||Y==="*"){let J=[G,{}];if(X===T7)for(let W in this.#X)this.#G(W,J);else this.#G(X,J);return}let Q=this.#Y[Y];if(!Q)throw Error(`Path ${Y} is not registered`);for(let[J,W]of Q)if(X===T7)for(let Z in this.#X)this.#Q(Z,Y,G,J,W);else this.#Q(X,Y,G,J,W)}buildAllMatchers(){return this.#X}match=bA1};var He6=D(()=>{Pq();sN0();XB0()});var Fe6=D(()=>{XB0();He6()});var YB0=class{name="SmartRouter";#X=[];#Y=[];constructor(X){this.#X=X.routers}add(X,Y,G){if(!this.#Y)throw Error(_A1);this.#Y.push([X,Y,G])}match(X,Y){if(!this.#Y)throw Error("Fatal error");let G=this.#X,Q=this.#Y,J=G.length,W=0,Z;for(;W<J;W++){let $=G[W];try{for(let K=0,H=Q.length;K<H;K++)$.add(...Q[K]);Z=$.match(X,Y)}catch(K){if(K instanceof fA1)continue;throw K}this.match=$.match.bind($),this.#X=[$],this.#Y=void 0;break}if(W===J)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Z}get activeRouter(){if(this.#Y||this.#X.length!==1)throw Error("No active router has been determined yet.");return this.#X[0]}};var Ue6=D(()=>{Pq()});var Ne6=D(()=>{Ue6()});var SX1,Lp5=(X)=>{for(let Y in X)return!0;return!1},Be6=class X{#X;#Y;#G;#Q=0;#J=SX1;constructor(Y,G,Q){if(this.#Y=Q||Object.create(null),this.#X=[],Y&&G){let J=Object.create(null);J[Y]={handler:G,possibleKeys:[],score:0},this.#X=[J]}this.#G=[]}insert(Y,G,Q){this.#Q=++this.#Q;let J=this,W=ms6(G),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],U=W[$+1],N=ds6(H,U),B=Array.isArray(N)?N[0]:H;if(B in J.#Y){if(J=J.#Y[B],N)Z.push(N[1]);continue}if(J.#Y[B]=new X,N)J.#G.push(N),Z.push(N[1]);J=J.#Y[B]}return J.#X.push({[Y]:{handler:Q,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#Q}}),J}#Z(Y,G,Q,J,W){for(let Z=0,$=G.#X.length;Z<$;Z++){let K=G.#X[Z],H=K[Q]||K[T7],U={};if(H!==void 0){if(H.params=Object.create(null),Y.push(H),J!==SX1||W&&W!==SX1)for(let N=0,B=H.possibleKeys.length;N<B;N++){let z=H.possibleKeys[N],O=U[H.score];H.params[z]=W?.[z]&&!O?W[z]:J[z]??W?.[z],U[H.score]=!0}}}}search(Y,G){let Q=[];this.#J=SX1;let W=[this],Z=nN0(G),$=[],K=Z.length,H=null;for(let U=0;U<K;U++){let N=Z[U],B=U===K-1,z=[];for(let w=0,E=W.length;w<E;w++){let P=W[w],q=P.#Y[N];if(q)if(q.#J=P.#J,B){if(q.#Y["*"])this.#Z(Q,q.#Y["*"],Y,P.#J);this.#Z(Q,q,Y,P.#J)}else z.push(q);for(let j=0,M=P.#G.length;j<M;j++){let V=P.#G[j],R=P.#J===SX1?{}:{...P.#J};if(V==="*"){let h=P.#Y["*"];if(h)this.#Z(Q,h,Y,P.#J),h.#J=R,z.push(h);continue}let[k,_,v]=V;if(!N&&!(v instanceof RegExp))continue;let y=P.#Y[k];if(v instanceof RegExp){if(H===null){H=Array(K);let p=G[0]==="/"?1:0;for(let f=0;f<K;f++)H[f]=p,p+=Z[f].length+1}let h=G.substring(H[U]),i=v.exec(h);if(i){if(R[_]=i[0],this.#Z(Q,y,Y,P.#J,R),Lp5(y.#Y)){y.#J=R;let p=i[0].match(/\//)?.length??0;($[p]||=[]).push(y)}continue}}if(v===!0||v.test(N))if(R[_]=N,B){if(this.#Z(Q,y,Y,R,P.#J),y.#Y["*"])this.#Z(Q,y.#Y["*"],Y,R,P.#J)}else y.#J=R,z.push(y)}}let O=$.shift();W=O?z.concat(O):z}if(Q.length>1)Q.sort((U,N)=>{return U.score-N.score});return[Q.map(({handler:U,params:N})=>[U,N])]}};var ze6=D(()=>{Pq();Eq();SX1=Object.create(null)});var GB0=class{name="TrieRouter";#X;constructor(){this.#X=new Be6}add(X,Y,G){let Q=SA1(Y);if(Q){for(let J=0,W=Q.length;J<W;J++)this.#X.insert(X,Q[J],G);return}this.#X.insert(X,Y,G)}match(X,Y){return this.#X.search(X,Y)}};var Oe6=D(()=>{Eq();ze6()});var De6=D(()=>{Oe6()});var R5;var we6=D(()=>{Qe6();Fe6();Ne6();De6();R5=class extends Ge6{constructor(X={}){super(X);this.router=X.router??new YB0({routers:[new xA1,new GB0]})}}});var ZQ=D(()=>{we6()});var Ee6,Ep5,Le6=(X)=>{let Y=0,G=X.length;while(Y<G){let Q=X.charCodeAt(Y);if(Q!==32&&Q!==9)break;Y++}while(G>Y){let Q=X.charCodeAt(G-1);if(Q!==32&&Q!==9)break;G--}return Y===0&&G===X.length?X:X.slice(Y,G)},QB0=(X,Y)=>{if(Y&&X.indexOf(Y)===-1)return{};let G=X.split(";"),Q={};for(let J of G){let W=J.indexOf("=");if(W===-1)continue;let Z=Le6(J.substring(0,W));if(Y&&Y!==Z||!Ee6.test(Z))continue;let $=Le6(J.substring(W+1));if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(Ep5.test($)){if(Q[Z]=$.indexOf("%")!==-1?ia($,TX1):$,Y)break}}return Q},Pp5=(X,Y,G={})=>{if(!Ee6.test(X))throw Error("Invalid cookie name");let Q=`${X}=${Y}`;if(X.startsWith("__Secure-")&&!G.secure)throw Error("__Secure- Cookie must have Secure attributes");if(X.startsWith("__Host-")){if(!G.secure)throw Error("__Host- Cookie must have Secure attributes");if(G.path!=="/")throw Error('__Host- Cookie must have Path attributes with "/"');if(G.domain)throw Error("__Host- Cookie must not have Domain attributes")}for(let J of["domain","path"])if(G[J]&&/[;\r\n]/.test(G[J]))throw Error(`${J} must not contain ";", "\\r", or "\\n"`);if(G&&typeof G.maxAge==="number"&&G.maxAge>=0){if(G.maxAge>34560000)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");Q+=`; Max-Age=${G.maxAge|0}`}if(G.domain&&G.prefix!=="host")Q+=`; Domain=${G.domain}`;if(G.path)Q+=`; Path=${G.path}`;if(G.expires){if(G.expires.getTime()-Date.now()>34560000000)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");Q+=`; Expires=${G.expires.toUTCString()}`}if(G.httpOnly)Q+="; HttpOnly";if(G.secure)Q+="; Secure";if(G.sameSite)Q+=`; SameSite=${G.sameSite.charAt(0).toUpperCase()+G.sameSite.slice(1)}`;if(G.priority)Q+=`; Priority=${G.priority.charAt(0).toUpperCase()+G.priority.slice(1)}`;if(G.partitioned){if(!G.secure)throw Error("Partitioned Cookie must have Secure attributes");Q+="; Partitioned"}return Q},hA1=(X,Y,G)=>{return Y=encodeURIComponent(Y),Pp5(X,Y,G)};var Pe6=D(()=>{Eq();Ee6=/^[\w!#$%&'*.^`|~+-]+$/,Ep5=/^[ !#-:<-[\]-~]*$/});var gA1=(X,Y,G)=>{let Q=X.req.raw.headers.get("Cookie");if(typeof Y==="string"){if(!Q)return;let W=Y;if(G==="secure")W="__Secure-"+Y;else if(G==="host")W="__Host-"+Y;return QB0(Q,W)[W]}if(!Q)return{};return QB0(Q)},qp5=(X,Y,G)=>{let Q;if(G?.prefix==="secure")Q=hA1("__Secure-"+X,Y,{path:"/",...G,secure:!0});else if(G?.prefix==="host")Q=hA1("__Host-"+X,Y,{...G,path:"/",secure:!0,domain:void 0});else Q=hA1(X,Y,{path:"/",...G});return Q},JB0=(X,Y,G,Q)=>{let J=qp5(Y,G,Q);X.header("Set-Cookie",J,{append:!0})};var ZB0=D(()=>{Pe6()});var qe6=(X)=>{let G={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...X},Q=((W)=>{if(typeof W==="string")if(W==="*"){if(G.credentials)return(Z)=>Z||null;return()=>W}else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(G.origin),J=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(G.allowMethods);return async function(Z,$){function K(U,N){Z.res.headers.set(U,N)}let H=await Q(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(G.credentials)K("Access-Control-Allow-Credentials","true");if(G.exposeHeaders?.length)K("Access-Control-Expose-Headers",G.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(G.origin!=="*"||G.credentials)K("Vary","Origin");if(G.maxAge!=null)K("Access-Control-Max-Age",G.maxAge.toString());let U=await J(Z.req.header("origin")||"",Z);if(U.length)K("Access-Control-Allow-Methods",U.join(","));let N=G.allowHeaders;if(!N?.length){let B=Z.req.header("Access-Control-Request-Headers");if(B)N=B.split(/\s*,\s*/)}if(N?.length)K("Access-Control-Allow-Headers",N.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),G.origin!=="*"||G.credentials)Z.header("Vary","Origin",{append:!0})}};var Ae6=()=>{};var Te6=()=>{try{return performance.now()}catch{}return Date.now()},WB0=(X)=>{let Y={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...X};return async function(Q,J){let W=[],Z=new Map;if(Q.get("metric"))return await J();if(Q.set("metric",{headers:W,timers:Z}),Y.total)OH(Q,"total",Y.totalDescription);if(await J(),Y.total)g$(Q,"total");if(Y.autoEnd)Z.forEach((K,H)=>g$(Q,H));if(typeof Y.enabled==="function"?Y.enabled(Q):Y.enabled){Q.res.headers.append("Server-Timing",W.join(","));let K=typeof Y.crossOrigin==="function"?Y.crossOrigin(Q):Y.crossOrigin;if(K)Q.res.headers.append("Timing-Allow-Origin",typeof K==="string"?K:"*")}}},Ie6=(X,Y,G,Q,J)=>{let W=X.get("metric");if(!W){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof G==="number"){let Z=G.toFixed(J||1),$=Q?`${Y};dur=${Z};desc="${Q}"`:`${Y};dur=${Z}`;W.headers.push($)}else{let Z=G?`${Y};desc="${G}"`:`${Y}`;W.headers.push(Z)}},OH=(X,Y,G)=>{let Q=X.get("metric");if(!Q){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}Q.timers.set(Y,{description:G,start:Te6()})},g$=(X,Y,G)=>{let Q=X.get("metric");if(!Q){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let J=Q.timers.get(Y);if(!J){console.warn(`Timer "${Y}" does not exist!`);return}let{description:W,start:Z}=J,$=Te6()-Z;Ie6(X,Y,$,W,G),Q.timers.delete(Y)};var Ve6=D(()=>{vA1()});var $B0=D(()=>{Ve6()});function CX1(){let X={Organizations:[],Connections:[],"Virtual MCPs":[],Threads:[],Monitoring:[],Users:[],"API Keys":[],"Event Bus":[],Tags:[],"AI Providers":[],Automations:[],"Object Storage":[],Registry:[],GitHub:[],VM:[]};for(let Y of KB0)X[Y.category]?.push(Y);return X}var KB0;var HB0=D(()=>{KB0=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"BRAND_CONTEXT_LIST",description:"List brand contexts",category:"Organizations"},{name:"BRAND_CONTEXT_GET",description:"View brand context",category:"Organizations"},{name:"BRAND_CONTEXT_CREATE",description:"Create brand context",category:"Organizations"},{name:"BRAND_CONTEXT_UPDATE",description:"Update brand context",category:"Organizations"},{name:"BRAND_CONTEXT_DELETE",description:"Delete brand context",category:"Organizations",dangerous:!0},{name:"BRAND_CONTEXT_EXTRACT",description:"Extract brand context from website",category:"Organizations"},{name:"BRAND_GET",description:"Get brand (binding)",category:"Organizations"},{name:"BRAND_LIST",description:"List brands (binding)",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_GET",description:"Get organization domain claim",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_SET",description:"Set organization domain claim",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_UPDATE",description:"Update organization domain settings",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_CLEAR",description:"Clear organization domain claim",category:"Organizations"},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_GET",description:"View virtual MCP details",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete virtual MCPs",category:"Virtual MCPs",dangerous:!0},{name:"MONITORING_LOG_GET",description:"View monitoring log details",category:"Monitoring"},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"EVENT_PUBLISH",description:"Publish events",category:"Event Bus"},{name:"EVENT_SUBSCRIBE",description:"Subscribe to events",category:"Event Bus"},{name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events",category:"Event Bus"},{name:"EVENT_CANCEL",description:"Cancel recurring events",category:"Event Bus"},{name:"EVENT_ACK",description:"Acknowledge event delivery",category:"Event Bus"},{name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions",category:"Event Bus"},{name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state",category:"Event Bus"},{name:"USER_GET",description:"Get a user by id",category:"Users"},{name:"COLLECTION_THREADS_CREATE",description:"Create threads",category:"Threads"},{name:"COLLECTION_THREADS_LIST",description:"List threads",category:"Threads"},{name:"COLLECTION_THREADS_GET",description:"View thread details",category:"Threads"},{name:"COLLECTION_THREADS_UPDATE",description:"Update threads",category:"Threads"},{name:"COLLECTION_THREADS_DELETE",description:"Delete threads",category:"Threads",dangerous:!0},{name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List thread messages",category:"Threads"},{name:"TAGS_LIST",description:"List organization tags",category:"Tags"},{name:"TAGS_CREATE",description:"Create organization tag",category:"Tags"},{name:"TAGS_DELETE",description:"Delete organization tag",category:"Tags",dangerous:!0},{name:"MEMBER_TAGS_GET",description:"Get member tags",category:"Tags"},{name:"MEMBER_TAGS_SET",description:"Set member tags",category:"Tags"},{name:"AUTOMATION_CREATE",description:"Create automation",category:"Automations"},{name:"AUTOMATION_GET",description:"View automation details",category:"Automations"},{name:"AUTOMATION_LIST",description:"List automations",category:"Automations"},{name:"AUTOMATION_UPDATE",description:"Update automation",category:"Automations"},{name:"AUTOMATION_DELETE",description:"Delete automation",category:"Automations",dangerous:!0},{name:"AUTOMATION_TRIGGER_ADD",description:"Add trigger to automation",category:"Automations"},{name:"AUTOMATION_TRIGGER_REMOVE",description:"Remove trigger from automation",category:"Automations"},{name:"AUTOMATION_RUN",description:"Manually trigger an automation run",category:"Automations"},{name:"VIRTUAL_MCP_PLUGIN_CONFIG_GET",description:"View virtual MCP plugin configuration",category:"Virtual MCPs"},{name:"VIRTUAL_MCP_PLUGIN_CONFIG_UPDATE",description:"Update virtual MCP plugin configuration",category:"Virtual MCPs"},{name:"VIRTUAL_MCP_PINNED_VIEWS_UPDATE",description:"Update virtual MCP pinned sidebar views",category:"Virtual MCPs"},{name:"AI_PROVIDERS_LIST",description:"List available AI providers",category:"AI Providers"},{name:"AI_PROVIDERS_LIST_MODELS",description:"List AI provider models",category:"AI Providers"},{name:"AI_PROVIDERS_ACTIVE",description:"List active AI providers",category:"AI Providers"},{name:"AI_PROVIDER_KEY_CREATE",description:"Store AI provider API key",category:"AI Providers"},{name:"AI_PROVIDER_KEY_LIST",description:"List AI provider API keys",category:"AI Providers"},{name:"AI_PROVIDER_KEY_DELETE",description:"Delete AI provider API key",category:"AI Providers",dangerous:!0},{name:"AI_PROVIDER_OAUTH_URL",description:"Get OAuth URL for provider",category:"AI Providers"},{name:"AI_PROVIDER_OAUTH_EXCHANGE",description:"Exchange OAuth code for API key",category:"AI Providers"},{name:"AI_PROVIDER_PROVISION_KEY",description:"Auto-provision API key for a provider",category:"AI Providers"},{name:"AI_PROVIDER_TOPUP_URL",description:"Get checkout URL to top up provider credits",category:"AI Providers"},{name:"AI_PROVIDER_CREDITS",description:"Get current credit balance for a provider",category:"AI Providers"},{name:"AI_PROVIDER_CLI_ACTIVATE",description:"Activate Claude Code via local CLI",category:"AI Providers"},{name:"LIST_OBJECTS",description:"List objects in storage",category:"Object Storage"},{name:"GET_OBJECT_METADATA",description:"Get object metadata",category:"Object Storage"},{name:"GET_PRESIGNED_URL",description:"Generate download URL",category:"Object Storage"},{name:"PUT_PRESIGNED_URL",description:"Generate upload URL",category:"Object Storage"},{name:"DELETE_OBJECT",description:"Delete object",category:"Object Storage",dangerous:!0},{name:"DELETE_OBJECTS",description:"Delete multiple objects",category:"Object Storage",dangerous:!0},{name:"COLLECTION_REGISTRY_APP_LIST",description:"List registry apps",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_GET",description:"Get registry app details",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_VERSIONS",description:"List registry app versions",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_FILTERS",description:"Get registry app filters",category:"Registry"},{name:"REGISTRY_ITEM_LIST",description:"List private registry items",category:"Registry"},{name:"REGISTRY_ITEM_SEARCH",description:"Search registry items",category:"Registry"},{name:"REGISTRY_ITEM_GET",description:"Get registry item details",category:"Registry"},{name:"REGISTRY_ITEM_VERSIONS",description:"List registry item versions",category:"Registry"},{name:"REGISTRY_ITEM_CREATE",description:"Create registry item",category:"Registry"},{name:"REGISTRY_ITEM_BULK_CREATE",description:"Bulk create registry items",category:"Registry"},{name:"REGISTRY_ITEM_UPDATE",description:"Update registry item",category:"Registry"},{name:"REGISTRY_ITEM_DELETE",description:"Delete registry item",category:"Registry",dangerous:!0},{name:"REGISTRY_ITEM_FILTERS",description:"Get registry item filters",category:"Registry"},{name:"REGISTRY_DISCOVER_TOOLS",description:"Discover tools from MCP server",category:"Registry"},{name:"REGISTRY_AI_GENERATE",description:"AI-generate registry content",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_LIST",description:"List publish requests",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_REVIEW",description:"Review publish request",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_COUNT",description:"Count pending publish requests",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_DELETE",description:"Delete publish request",category:"Registry",dangerous:!0},{name:"REGISTRY_PUBLISH_API_KEY_GENERATE",description:"Generate publish API key",category:"Registry"},{name:"REGISTRY_PUBLISH_API_KEY_LIST",description:"List publish API keys",category:"Registry"},{name:"REGISTRY_PUBLISH_API_KEY_REVOKE",description:"Revoke publish API key",category:"Registry",dangerous:!0},{name:"REGISTRY_MONITOR_RUN_START",description:"Start monitor run",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_LIST",description:"List monitor runs",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_GET",description:"Get monitor run details",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_CANCEL",description:"Cancel monitor run",category:"Registry"},{name:"REGISTRY_MONITOR_RESULT_LIST",description:"List monitor results",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_LIST",description:"List monitor connections",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_SYNC",description:"Sync monitor connections",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_UPDATE_AUTH",description:"Update monitor connection auth",category:"Registry"},{name:"REGISTRY_MONITOR_SCHEDULE_SET",description:"Set monitor schedule",category:"Registry"},{name:"REGISTRY_MONITOR_SCHEDULE_CANCEL",description:"Cancel monitor schedule",category:"Registry"},{name:"VM_START",description:"Start a Freestyle VM with dev server preview",category:"VM"},{name:"VM_DELETE",description:"Stop and delete a Freestyle VM",category:"VM"},{name:"GITHUB_LIST_USER_ORGS",description:"List GitHub user's personal account and organizations",category:"GitHub"}]});var je6=D(()=>{oi();tz1()});function Me6(){return Tp5.parse(process.env)}var FB0=(X)=>F.enum(["true","false","1","0"]).optional().transform((Y)=>Y===void 0?X:Y==="true"||Y==="1"),Ap5=(X)=>F.string().optional().transform((Y)=>Y?Y.split(",").map((G)=>G.trim()):X),Tp5;var Re6=D(()=>{H0();Tp5=F.object({AUTH_EMAIL_PASSWORD_ENABLED:FB0(!0),AUTH_GOOGLE_CLIENT_ID:F.string().optional(),AUTH_GOOGLE_CLIENT_SECRET:F.string().optional(),AUTH_GITHUB_CLIENT_ID:F.string().optional(),AUTH_GITHUB_CLIENT_SECRET:F.string().optional(),AUTH_RESEND_API_KEY:F.string().optional(),AUTH_RESEND_FROM_EMAIL:F.string().optional(),AUTH_SENDGRID_API_KEY:F.string().optional(),AUTH_SENDGRID_FROM_EMAIL:F.string().optional(),AUTH_INVITE_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_RESET_PASSWORD_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_MAGIC_LINK_ENABLED:FB0(!1),AUTH_MAGIC_LINK_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_ENABLED:FB0(!1),AUTH_EMAIL_OTP_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_LENGTH:F.coerce.number().optional(),AUTH_EMAIL_OTP_EXPIRES_IN:F.coerce.number().optional(),AUTH_SSO_DOMAIN:F.string().optional(),AUTH_SSO_MS_TENANT_ID:F.string().optional(),AUTH_SSO_MS_CLIENT_ID:F.string().optional(),AUTH_SSO_MS_CLIENT_SECRET:F.string().optional(),AUTH_SSO_SCOPES:Ap5(["openid","email","profile"])}).transform((X)=>{let Y={};if(X.AUTH_GOOGLE_CLIENT_ID)Y.google={clientId:X.AUTH_GOOGLE_CLIENT_ID,clientSecret:X.AUTH_GOOGLE_CLIENT_SECRET??""};if(X.AUTH_GITHUB_CLIENT_ID)Y.github={clientId:X.AUTH_GITHUB_CLIENT_ID,clientSecret:X.AUTH_GITHUB_CLIENT_SECRET??""};let G=[];if(X.AUTH_RESEND_API_KEY)G.push({id:"resend",provider:"resend",config:{apiKey:X.AUTH_RESEND_API_KEY,fromEmail:X.AUTH_RESEND_FROM_EMAIL??"noreply@example.com"}});if(X.AUTH_SENDGRID_API_KEY)G.push({id:"sendgrid",provider:"sendgrid",config:{apiKey:X.AUTH_SENDGRID_API_KEY,fromEmail:X.AUTH_SENDGRID_FROM_EMAIL??"noreply@example.com"}});let Q=G[0]?.id,J;if(X.AUTH_SSO_MS_CLIENT_ID&&X.AUTH_SSO_DOMAIN)J={providerId:"microsoft",domain:X.AUTH_SSO_DOMAIN,MS_TENANT_ID:X.AUTH_SSO_MS_TENANT_ID??"",MS_CLIENT_ID:X.AUTH_SSO_MS_CLIENT_ID,MS_CLIENT_SECRET:X.AUTH_SSO_MS_CLIENT_SECRET??"",scopes:X.AUTH_SSO_SCOPES};let W;if(X.AUTH_MAGIC_LINK_ENABLED)W={enabled:!0,emailProviderId:X.AUTH_MAGIC_LINK_EMAIL_PROVIDER??Q??""};let Z;if(X.AUTH_EMAIL_OTP_ENABLED)Z={enabled:!0,emailProviderId:X.AUTH_EMAIL_OTP_EMAIL_PROVIDER??Q??"",...X.AUTH_EMAIL_OTP_LENGTH!==void 0&&{otpLength:X.AUTH_EMAIL_OTP_LENGTH},...X.AUTH_EMAIL_OTP_EXPIRES_IN!==void 0&&{expiresIn:X.AUTH_EMAIL_OTP_EXPIRES_IN}};return{emailAndPassword:{enabled:X.AUTH_EMAIL_PASSWORD_ENABLED},socialProviders:Object.keys(Y).length>0?Y:void 0,emailProviders:G.length>0?G:void 0,inviteEmailProviderId:X.AUTH_INVITE_EMAIL_PROVIDER,resetPasswordEmailProviderId:X.AUTH_RESET_PASSWORD_EMAIL_PROVIDER,ssoConfig:J,magicLinkConfig:W,emailOtpConfig:Z}})});var uA1;var Se6=D(()=>{uA1={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"}});import{existsSync as Ip5,readFileSync as Vp5}from"fs";function jp5(){let X=Me6(),Y=v6().configPath;if(!Ip5(Y))return{auth:X,monitoring:uA1};try{let G=JSON.parse(Vp5(Y,"utf-8"));if(G.auth)console.warn("[config] DEPRECATION: 'auth' key found in config.json. Auth is now configured via AUTH_* environment variables. The 'auth' key will be ignored.");return{auth:X,monitoring:G.monitoring??uA1,theme:G.theme,logo:G.logo,autoCreateOrganizationOnSignup:G.autoCreateOrganizationOnSignup}}catch{return{auth:X,monitoring:uA1}}}function Vj(){if(!UB0)UB0=jp5();return UB0}function Ce6(){return Vj().theme}var UB0=null;var NB0=D(()=>{Re6();Se6();m9()});import{dirname as Mp5,posix as Rp5,sep as Sp5}from"path";function ve6(){let X=Cp5();return async(Y)=>{for(let G of Y)G.module=X(G.filename);return Y}}function Cp5(X=process.argv[1]?Mp5(process.argv[1]):process.cwd(),Y=Sp5==="\\"){let G=Y?ke6(X):X;return(Q)=>{if(!Q)return;let J=Y?ke6(Q):Q,{dir:W,base:Z,ext:$}=Rp5.parse(J);if($===".js"||$===".mjs"||$===".cjs")Z=Z.slice(0,-1*$.length);let K=decodeURIComponent(Z);if(!W)W=".";let H=W.lastIndexOf("/node_modules");if(H>-1)return`${W.slice(H+14).replace(/\//g,".")}:${K}`;if(W.startsWith(G)){let U=W.slice(G.length+1).replace(/\//g,".");return U?`${U}:${K}`:K}return K}}function ke6(X){return X.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var _e6=()=>{};function kp5(X,Y,G){return{key:X,enabled:typeof Y=="string"?!0:Y,variant:typeof Y=="string"?Y:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:G?JSON.stringify(G):void 0,description:void 0}}}var BB0=(X)=>{if("flags"in X){let Y=fe6(X.flags),G=be6(X.flags);return{...X,featureFlags:Y,featureFlagPayloads:G}}{let Y=X.featureFlags??{},G=Object.fromEntries(Object.entries(X.featureFlagPayloads||{}).map(([J,W])=>[J,zB0(W)])),Q=Object.fromEntries(Object.entries(Y).map(([J,W])=>[J,kp5(J,W,G[J])]));return{...X,featureFlags:Y,featureFlagPayloads:G,flags:Q}}},fe6=(X)=>Object.fromEntries(Object.entries(X??{}).map(([Y,G])=>[Y,kX1(G)]).filter(([,Y])=>Y!==void 0)),be6=(X)=>{let Y=X??{};return Object.fromEntries(Object.keys(Y).filter((G)=>{let Q=Y[G];return Q.enabled&&Q.metadata&&Q.metadata.payload!==void 0}).map((G)=>{let Q=Y[G].metadata?.payload;return[G,Q?zB0(Q):void 0]}))},kX1=(X)=>X===void 0?void 0:X.variant??X.enabled,zB0=(X)=>{if(typeof X!="string")return X;try{return JSON.parse(X)}catch{return X}};var lA1=()=>{};function ye6(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}async function mA1(X,Y=!0,G){try{let Q=new CompressionStream("gzip"),J=Q.writable.getWriter(),W=J.write(new TextEncoder().encode(X)).then(()=>J.close()).catch(async(K)=>{try{await J.abort(K)}catch{}throw K}),Z=new Response(Q.readable).blob(),[$]=await Promise.all([Z,W]);return $}catch(Q){if(G?.rethrow)throw Q;if(Y)console.error("Failed to gzip compress data",Q);return null}}var OB0=()=>{};var vp5,xe6=function(X,Y=[]){if(!X)return!1;let G=X.toLowerCase();return vp5.concat(Y).some((Q)=>{let J=Q.toLowerCase();return G.indexOf(J)!==-1})};var he6=D(()=>{vp5=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"]});var nJ;var jj=D(()=>{nJ=function(X){return X.AnonymousId="anonymous_id",X.DistinctId="distinct_id",X.Props="props",X.EnablePersonProcessing="enable_person_processing",X.PersonMode="person_mode",X.FeatureFlagDetails="feature_flag_details",X.FeatureFlags="feature_flags",X.FeatureFlagPayloads="feature_flag_payloads",X.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",X.BootstrapFeatureFlags="bootstrap_feature_flags",X.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",X.OverrideFeatureFlags="override_feature_flags",X.Queue="queue",X.LogsQueue="logs_queue",X.OptedOut="opted_out",X.SessionId="session_id",X.SessionStartTimestamp="session_start_timestamp",X.SessionLastTimestamp="session_timestamp",X.PersonProperties="person_properties",X.GroupProperties="group_properties",X.InstalledAppBuild="installed_app_build",X.InstalledAppVersion="installed_app_version",X.SessionReplay="session_replay",X.SurveyLastSeenDate="survey_last_seen_date",X.SurveysSeen="surveys_seen",X.Surveys="surveys",X.RemoteConfig="remote_config",X.FlagsEndpointWasHit="flags_endpoint_was_hit",X.DeviceId="device_id",X}({})});var dA1=()=>{};function iA1(X){return X===null||typeof X!="object"}function Mj(X,Y){return Object.prototype.toString.call(X)===`[object ${Y}]`}function le6(X){return Mj(X,"ErrorEvent")}function aa(X){return typeof Event<"u"&&bp5(X,Event)}function me6(X){return Mj(X,"Object")}function bp5(X,Y){try{return X instanceof Y}catch{return!1}}var fp5,ge6,llX,DB0,cA1,vX1=(X)=>X===Object(X)&&!cA1(X),na=(X)=>X===void 0,qq=(X)=>DB0.call(X)=="[object String]",ue6=(X)=>qq(X)&&X.trim().length===0,_X1=(X)=>DB0.call(X)=="[object Number]"&&X===X,wB0=(X)=>X instanceof Error;var fX1=D(()=>{jj();dA1();fp5=Array.isArray,ge6=Object.prototype,llX=ge6.hasOwnProperty,DB0=ge6.toString,cA1=fp5||function(X){return DB0.call(X)==="[object Array]"}});function bX1(X,Y,G,Q,J){if(Y>G)Q.warn("min cannot be greater than max."),Y=G;if(_X1(X))if(X>G)return Q.warn(" cannot be greater than max: "+G+". Using max value instead."),G;else{if(!(X<Y))return X;return Q.warn(" cannot be less than min: "+Y+". Using min value instead."),Y}return Q.warn(" must be a number. using max or fallback. max: "+G+", fallback: "+J),bX1(J||G,Y,G,Q)}var LB0=D(()=>{fX1()});class EB0{constructor(X){this._buckets={},this._onBucketRateLimited=X._onBucketRateLimited,this._bucketSize=bX1(X.bucketSize,0,100,X._logger),this._refillRate=bX1(X.refillRate,0,this._bucketSize,X._logger),this._refillInterval=bX1(X.refillInterval,0,yp5,X._logger)}_applyRefill(X,Y){let G=Y-X.lastAccess,Q=Math.floor(G/this._refillInterval);if(Q>0){let J=Q*this._refillRate;X.tokens=Math.min(X.tokens+J,this._bucketSize),X.lastAccess=X.lastAccess+Q*this._refillInterval}}consumeRateLimit(X){let Y=Date.now(),G=String(X),Q=this._buckets[G];if(Q)this._applyRefill(Q,Y);else Q={tokens:this._bucketSize,lastAccess:Y},this._buckets[G]=Q;if(Q.tokens===0)return!0;if(Q.tokens--,Q.tokens===0)this._onBucketRateLimited?.(X);return Q.tokens===0}stop(){this._buckets={}}}var yp5=86400000;var de6=D(()=>{LB0()});class Rj{constructor(X){this.bytes=X}static ofInner(X){if(X.length===16)return new Rj(X);throw TypeError("not 128-bit length")}static fromFieldsV7(X,Y,G,Q){if(!Number.isInteger(X)||!Number.isInteger(Y)||!Number.isInteger(G)||!Number.isInteger(Q)||X<0||Y<0||G<0||Q<0||X>281474976710655||Y>4095||G>1073741823||Q>4294967295)throw RangeError("invalid field value");let J=new Uint8Array(16);return J[0]=X/1099511627776,J[1]=X/4294967296,J[2]=X/16777216,J[3]=X/65536,J[4]=X/256,J[5]=X,J[6]=112|Y>>>8,J[7]=Y,J[8]=128|G>>>24,J[9]=G>>>16,J[10]=G>>>8,J[11]=G,J[12]=Q>>>24,J[13]=Q>>>16,J[14]=Q>>>8,J[15]=Q,new Rj(J)}static parse(X){let Y;switch(X.length){case 32:Y=/^[0-9a-f]{32}$/i.exec(X)?.[0];break;case 36:Y=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(X)?.slice(1,6).join("");break;case 38:Y=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(X)?.slice(1,6).join("");break;case 45:Y=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(X)?.slice(1,6).join("");break;default:break}if(Y){let G=new Uint8Array(16);for(let Q=0;Q<16;Q+=4){let J=parseInt(Y.substring(2*Q,2*Q+8),16);G[Q+0]=J>>>24,G[Q+1]=J>>>16,G[Q+2]=J>>>8,G[Q+3]=J}return new Rj(G)}throw SyntaxError("could not parse UUID string")}toString(){let X="";for(let Y=0;Y<this.bytes.length;Y++)if(X+="0123456789abcdef".charAt(this.bytes[Y]>>>4),X+="0123456789abcdef".charAt(15&this.bytes[Y]),Y===3||Y===5||Y===7||Y===9)X+="-";return X}toHex(){let X="";for(let Y=0;Y<this.bytes.length;Y++)X+="0123456789abcdef".charAt(this.bytes[Y]>>>4),X+="0123456789abcdef".charAt(15&this.bytes[Y]);return X}toJSON(){return this.toString()}getVariant(){let X=this.bytes[8]>>>4;if(X<0)throw Error("unreachable");if(X<=7)return this.bytes.every((Y)=>Y===0)?"NIL":"VAR_0";if(X<=11)return"VAR_10";if(X<=13)return"VAR_110";if(X<=15)return this.bytes.every((Y)=>Y===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new Rj(this.bytes.slice(0))}equals(X){return this.compareTo(X)===0}compareTo(X){for(let Y=0;Y<16;Y++){let G=this.bytes[Y]-X.bytes[Y];if(G!==0)return Math.sign(G)}return 0}}class ie6{constructor(X){this.timestamp=0,this.counter=0,this.random=X??xp5()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(X,Y){let G=this.generateOrAbortCore(X,Y);if(G===void 0)this.timestamp=0,G=this.generateOrAbortCore(X,Y);return G}generateOrAbortCore(X,Y){if(!Number.isInteger(X)||X<1||X>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(Y<0||Y>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(X>this.timestamp)this.timestamp=X,this.resetCounter();else{if(!(X+Y>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return Rj.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let X=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return X[6]=64|X[6]>>>4,X[8]=128|X[8]>>>2,Rj.ofInner(X)}}var xp5=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),ce6,Aq=()=>hp5().toString(),hp5=()=>(ce6||(ce6=new ie6)).generate();var yX1=D(()=>{/*! For license information please see uuidv7.mjs.LICENSE.txt */});class PB0{add(X){let Y=Aq();return this.promiseByIds[Y]=X,X.catch(()=>{}).finally(()=>{delete this.promiseByIds[Y]}),X}async join(){let X=Object.values(this.promiseByIds),Y=X.length;while(Y>0)await Promise.all(X),X=Object.values(this.promiseByIds),Y=X.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}}var pe6=D(()=>{yX1()});function gp5(X=console){return{log:X.log.bind(X),warn:X.warn.bind(X),error:X.error.bind(X),debug:X.debug.bind(X)}}function ae6(X,Y=up5){return ne6(X,Y,gp5())}var ne6=(X,Y,G)=>{function Q(W,...Z){Y(()=>{let $=G[W];$(X,...Z)})}return{info:(...W)=>{Q("log",...W)},warn:(...W)=>{Q("warn",...W)},error:(...W)=>{Q("error",...W)},critical:(...W)=>{G.error(X,...W)},createLogger:(W)=>ne6(`${X} ${W}`,Y,G)}},up5=(X)=>X();var te6=()=>{};var ra="Mobile",nA1="iOS",ta="Android",re6="Tablet",elX,mp5="Apple",XmX,oe6="Safari",aA1="BlackBerry",se6="Samsung",dp5,cp5,tA1="Chrome",ip5,pp5,ee6="Internet Explorer",np5,AB0="Opera",YmX,X14="Edge",ap5,TB0="Firefox",tp5,IB0="Nintendo",VB0="PlayStation",pA1="Xbox",rp5,op5,xX1="Windows",sp5,Y14="Generic",GmX,QmX,ep5="Konqueror",H3="(\\d+(\\.\\d+)?)",qB0,JmX,ZmX,WmX,Xn5,Yn5,$mX,KmX;var G14=D(()=>{dA1();fX1();elX=ta+" "+re6,XmX=mp5+" Watch",dp5=se6+"Browser",cp5=se6+" Internet",ip5=tA1+" OS",pp5=tA1+" "+nA1,np5=ee6+" "+ra,YmX=AB0+" Mini",ap5="Microsoft "+X14,tp5=TB0+" "+nA1,rp5=ta+" "+ra,op5=ra+" "+oe6,sp5=xX1+" Phone",GmX=Y14+" "+ra.toLowerCase(),QmX=Y14+" "+re6.toLowerCase(),qB0=new RegExp("Version/"+H3),JmX=new RegExp(pA1,"i"),ZmX=new RegExp(VB0+" \\w+","i"),WmX=new RegExp(IB0+" \\w+","i"),Xn5=new RegExp(aA1+"|PlayBook|BB10","i"),Yn5={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"},$mX={[np5]:[new RegExp("rv:"+H3)],[ap5]:[new RegExp(X14+"?\\/"+H3)],[tA1]:[new RegExp("("+tA1+"|CrMo)\\/"+H3)],[pp5]:[new RegExp("CriOS\\/"+H3)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+H3)],[oe6]:[qB0],[op5]:[qB0],[AB0]:[new RegExp("("+AB0+"|OPR)\\/"+H3)],[TB0]:[new RegExp(TB0+"\\/"+H3)],[tp5]:[new RegExp("FxiOS\\/"+H3)],[ep5]:[new RegExp("Konqueror[:/]?"+H3,"i")],[aA1]:[new RegExp(aA1+" "+H3),qB0],[rp5]:[new RegExp("android\\s"+H3,"i")],[cp5]:[new RegExp(dp5+"\\/"+H3)],[ee6]:[new RegExp("(rv:|MSIE )"+H3)],Mozilla:[new RegExp("rv:"+H3)]},KmX=[[new RegExp(pA1+"; "+pA1+" (.*?)[);]","i"),(X)=>[pA1,X&&X[1]||""]],[new RegExp(IB0,"i"),[IB0,""]],[new RegExp(VB0,"i"),[VB0,""]],[Xn5,[aA1,""]],[new RegExp(xX1,"i"),(X,Y)=>{if(/Phone/.test(Y)||/WPDesktop/.test(Y))return[sp5,""];if(new RegExp(ra).test(Y)&&!/IEMobile\b/.test(Y))return[xX1+" "+ra,""];let G=/Windows NT ([0-9.]+)/i.exec(Y);if(G&&G[1]){let Q=G[1],J=Yn5[Q]||"";if(/arm/i.test(Y))J="RT";return[xX1,J]}return[xX1,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(X)=>{if(X&&X[3]){let Y=[X[3],X[4],X[5]||"0"];return[nA1,Y.join(".")]}return[nA1,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(X)=>{let Y="";if(X&&X.length>=3)Y=na(X[2])?X[3]:X[2];return["watchOS",Y]}],[new RegExp("("+ta+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+ta+")","i"),(X)=>{if(X&&X[2]){let Y=[X[2],X[3],X[4]||"0"];return[ta,Y.join(".")]}return[ta,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(X)=>{let Y=["Mac OS X",""];if(X&&X[1]){let G=[X[1],X[2],X[3]||"0"];Y[1]=G.join(".")}return Y}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[ip5,""]],[/Linux|debian/i,["Linux",""]]]});function J14(X){return X?.replace(/\/+$/,"")}async function Z14(X,Y){let G=null;for(let Q=0;Q<Y.retryCount+1;Q++){if(Q>0)await new Promise((J)=>setTimeout(J,Y.retryDelay));try{return await X()}catch(J){if(G=J,!Y.retryCheck(J))throw J}}throw G}function rA1(){return new Date().toISOString()}function Hw(X,Y){let G=setTimeout(X,Y);return G?.unref&&G?.unref(),G}function jB0(X){return Promise.all(X.map((Y)=>(Y??Promise.resolve()).then((G)=>({status:"fulfilled",value:G}),(G)=>({status:"rejected",reason:G}))))}var Q14="utf8",W14=(X)=>X instanceof Error;var F3=D(()=>{he6();de6();LB0();dA1();fX1();pe6();te6();G14()});var Gn5,AmX;var MB0=D(()=>{F3();Gn5={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},AmX=Gn5.info});var $14=D(()=>{MB0();jj()});var K14=D(()=>{jj()});class RB0{constructor(){this.events={},this.events={}}on(X,Y){if(!this.events[X])this.events[X]=[];return this.events[X].push(Y),()=>{this.events[X]=this.events[X].filter((G)=>G!==Y)}}emit(X,Y){for(let G of this.events[X]||[])G(Y);for(let G of this.events["*"]||[])G(X,Y)}}var H14=()=>{};async function F14(X){if(X instanceof oa){let Y="";try{Y=await X.text}catch{}console.error(`Error while flushing PostHog: message=${X.message}, response body=${Y}`,X)}else console.error("Error while flushing PostHog",X);return Promise.resolve()}function SB0(X){return typeof X=="object"&&(X instanceof oa||X instanceof hX1)}function U14(X){return typeof X=="object"&&X instanceof oa&&X.status===413}class oA1{constructor(X,Y={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new PB0,this._events=new RB0,this._isInitialized=!1;let G=typeof X=="string"?X.trim():"",Q=typeof Y.host=="string"?Y.host.trim():"",J=!G;if(this._logger=ae6("[PostHog]",this.logMsgIfDebug.bind(this)),J)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=G,this.host=J14(Q||"https://us.i.posthog.com"),this.flushAt=Y.flushAt?Math.max(Y.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,Y.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,Y.maxQueueSize??1000),this.flushInterval=Y.flushInterval??1e4,this.preloadFeatureFlags=Y.preloadFeatureFlags??!0,this.defaultOptIn=Y.defaultOptIn??!0,this.disableSurveys=Y.disableSurveys??!1,this._retryOptions={retryCount:Y.fetchRetryCount??3,retryDelay:Y.fetchRetryDelay??3000,retryCheck:SB0},this.requestTimeout=Y.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=Y.featureFlagsRequestTimeoutMs??3000,this.remoteConfigRequestTimeoutMs=Y.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=Y.disableGeoip??!0,this.disabled=(Y.disabled??!1)||J,this.historicalMigration=Y?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=Y?.evaluationContexts??Y?.evaluationEnvironments,Y?.evaluationEnvironments&&!Y?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!ye6()||(Y?.disableCompression??!1)}logMsgIfDebug(X){if(this.isDebug)X()}wrap(X){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return X();this._initPromise.then(()=>X())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(nJ.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(nJ.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(nJ.OptedOut,!0)})}on(X,Y){return this._events.on(X,Y)}debug(X=!0){if(this.removeDebugCallback?.(),X){let Y=this.on("*",(G,Q)=>this._logger.info(G,Q));this.removeDebugCallback=()=>{Y(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(X){return{distinct_id:X.distinct_id,event:X.event,properties:{...X.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(X){return this.promiseQueue.add(X)}identifyStateless(X,Y,G){this.wrap(()=>{let Q={...this.buildPayload({distinct_id:X,event:"$identify",properties:Y})};this.enqueue("identify",Q,G)})}async identifyStatelessImmediate(X,Y,G){let Q={...this.buildPayload({distinct_id:X,event:"$identify",properties:Y})};await this.sendImmediate("identify",Q,G)}captureStateless(X,Y,G,Q){this.wrap(()=>{let J=this.buildPayload({distinct_id:X,event:Y,properties:G});this.enqueue("capture",J,Q)})}async captureStatelessImmediate(X,Y,G,Q){let J=this.buildPayload({distinct_id:X,event:Y,properties:G});await this.sendImmediate("capture",J,Q)}aliasStateless(X,Y,G,Q){this.wrap(()=>{let J=this.buildPayload({event:"$create_alias",distinct_id:Y,properties:{...G||{},distinct_id:Y,alias:X}});this.enqueue("alias",J,Q)})}async aliasStatelessImmediate(X,Y,G,Q){let J=this.buildPayload({event:"$create_alias",distinct_id:Y,properties:{...G||{},distinct_id:Y,alias:X}});await this.sendImmediate("alias",J,Q)}groupIdentifyStateless(X,Y,G,Q,J,W){this.wrap(()=>{let Z=this.buildPayload({distinct_id:J||`$${X}_${Y}`,event:"$groupidentify",properties:{$group_type:X,$group_key:Y,$group_set:G||{},...W||{}}});this.enqueue("capture",Z,Q)})}async getRemoteConfig(){await this._initPromise;let X=this.host;if(X==="https://us.i.posthog.com")X="https://us-assets.i.posthog.com";else if(X==="https://eu.i.posthog.com")X="https://eu-assets.i.posthog.com";let Y=`${X}/array/${this.apiKey}/config`,G={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(Y,G,{retryCount:0},this.remoteConfigRequestTimeoutMs).then((Q)=>Q.json()).catch((Q)=>{this._logger.error("Remote config could not be loaded",Q),this._events.emit("error",Q)})}async getFlags(X,Y={},G={},Q={},J={},W=!1){await this._initPromise;let Z=W?"&config=true":"",$=`${this.host}/flags/?v=2${Z}`,K={token:this.apiKey,distinct_id:X,groups:Y,person_properties:G,group_properties:Q,...J};if(G.$device_id)K.$device_id=G.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)K.evaluation_contexts=this.evaluationContexts;let H={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(K)};return this._logger.info("Flags URL",$),this.fetchWithRetry($,H,{retryCount:0},this.featureFlagsRequestTimeoutMs).then((U)=>U.json()).then((U)=>({success:!0,response:BB0(U)})).catch((U)=>{return this._events.emit("error",U),{success:!1,error:this.categorizeRequestError(U)}})}categorizeRequestError(X){if(X instanceof oa)return{type:"api_error",statusCode:X.status};if(X instanceof hX1){let Y=X.error;if(Y instanceof Error&&(Y.name==="AbortError"||Y.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagDetailStateless(X,Y,G,Q,J,W);if(Z===void 0)return{response:void 0,requestId:void 0};let $=kX1(Z.response);if($===void 0)$=!1;return{response:$,requestId:Z.requestId}}async getFeatureFlagDetailStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagDetailsStateless(Y,G,Q,J,W,[X]);if(Z===void 0)return;return{response:Z.flags[X],requestId:Z.requestId,evaluatedAt:Z.evaluatedAt}}async getFeatureFlagPayloadStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagPayloadsStateless(Y,G,Q,J,W,[X]);if(!Z)return;let $=Z[X];if($===void 0)return null;return $}async getFeatureFlagPayloadsStateless(X,Y={},G={},Q={},J,W){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(X,Y,G,Q,J,W)).payloads}async getFeatureFlagsStateless(X,Y={},G={},Q={},J,W){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(X,Y,G,Q,J,W)}async getFeatureFlagsAndPayloadsStateless(X,Y={},G={},Q={},J,W){await this._initPromise;let Z=await this.getFeatureFlagDetailsStateless(X,Y,G,Q,J,W);if(!Z)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:Z.featureFlags,payloads:Z.featureFlagPayloads,requestId:Z.requestId}}async getFeatureFlagDetailsStateless(X,Y={},G={},Q={},J,W){await this._initPromise;let Z={};if(J??this.disableGeoip)Z.geoip_disable=!0;if(W)Z.flag_keys_to_evaluate=W;let $=await this.getFlags(X,Y,G,Q,Z);if(!$.success)return;let K=$.response;if(K.errorsWhileComputingFlags)console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");if(K.quotaLimited?.includes("feature_flags"))return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:K?.requestId,quotaLimited:K.quotaLimited};return K}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let X=`${this.host}/api/surveys/?token=${this.apiKey}`,Y={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},Q=(await this.fetchWithRetry(X,Y).then((J)=>{if(J.status!==200||!J.json){let W=`Surveys API could not be loaded: ${J.status}`,Z=Error(W);this._logger.error(Z),this._events.emit("error",Error(W));return}return J.json()}).catch((J)=>{this._logger.error("Surveys API could not be loaded",J),this._events.emit("error",J)}))?.surveys;if(Q)this._logger.info("Surveys fetched from API: ",JSON.stringify(Q));return Q??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(nJ.Props);return this._props||{}}set props(X){this._props=X}async register(X){this.wrap(()=>{this.props={...this.props,...X},this.setPersistedProperty(nJ.Props,this.props)})}async unregister(X){this.wrap(()=>{delete this.props[X],this.setPersistedProperty(nJ.Props,this.props)})}processBeforeEnqueue(X){return X}async flushStorage(){}enqueue(X,Y,G){this.wrap(()=>{if(this.optedOut)return void this._events.emit(X,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let Q=this.prepareMessage(X,Y,G);if(Q=this.processBeforeEnqueue(Q),Q===null)return;let J=this.getPersistedProperty(nJ.Queue)||[];if(J.length>=this.maxQueueSize)J.shift(),this._logger.info("Queue is full, the oldest event is dropped.");if(J.push({message:Q}),this.setPersistedProperty(nJ.Queue,J),this._events.emit(X,Q),J.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=Hw(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(X,Y,G){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(X,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let Q=this.prepareMessage(X,Y,G);if(Q=this.processBeforeEnqueue(Q),Q===null)return;let J={api_key:this.apiKey,batch:[Q],sent_at:rA1()};if(this.historicalMigration)J.historical_migration=!0;let W=JSON.stringify(J),Z=`${this.host}/batch/`,$=this.disableCompression?null:await mA1(W,this.isDebug),K={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...$!==null&&{"Content-Encoding":"gzip"}},body:$||W};try{await this.fetchWithRetry(Z,K)}catch(H){this._events.emit("error",H)}}prepareMessage(X,Y,G){let Q={...Y,type:X,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:G?.timestamp?G?.timestamp:rA1(),uuid:G?.uuid?G.uuid:Aq()};if(G?.disableGeoip??this.disableGeoip){if(!Q.properties)Q.properties={};Q.properties.$geoip_disable=!0}if(Q.distinctId)Q.distinct_id=Q.distinctId,delete Q.distinctId;return Q}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){this.flush().catch(async(X)=>{await F14(X)})}async flush(){let X=jB0([this.flushPromise]).then(()=>this._flush());return this.flushPromise=X,this.addPendingPromise(X),jB0([X]).then(()=>{if(this.flushPromise===X)this.flushPromise=null}),X}getCustomHeaders(){let X=this.getCustomUserAgent(),Y={};if(X&&X!=="")Y["User-Agent"]=X;return Y}async _flush(){this.clearFlushTimer(),await this._initPromise;let X=this.getPersistedProperty(nJ.Queue)||[];if(!X.length)return;let Y=[],G=X.length;while(X.length>0&&Y.length<G){let Q=X.slice(0,this.maxBatchSize),J=Q.map((B)=>B.message),W=async()=>{let z=(this.getPersistedProperty(nJ.Queue)||[]).slice(Q.length);this.setPersistedProperty(nJ.Queue,z),X=z,await this.flushStorage()},Z={api_key:this.apiKey,batch:J,sent_at:rA1()};if(this.historicalMigration)Z.historical_migration=!0;let $=JSON.stringify(Z),K=`${this.host}/batch/`,H=this.disableCompression?null:await mA1($,this.isDebug),U={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...H!==null&&{"Content-Encoding":"gzip"}},body:H||$},N={retryCheck:(B)=>{if(U14(B))return!1;return SB0(B)}};try{await this.fetchWithRetry(K,U,N)}catch(B){if(U14(B)&&J.length>1){this.maxBatchSize=Math.max(1,Math.floor(J.length/2)),this._logger.warn(`Received 413 when sending batch of size ${J.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(B instanceof hX1))await W();throw this._events.emit("error",B),B}await W(),Y.push(...J)}this._events.emit("flush",Y)}async fetchWithRetry(X,Y,G,Q){let J=Y.body?Y.body:"",W=-1;try{W=J instanceof Blob?J.size:Buffer.byteLength(J,Q14)}catch{if(J instanceof Blob)W=J.size;else W=new TextEncoder().encode(J).length}return await Z14(async()=>{let Z=new AbortController,$=Q??this.requestTimeout,K=Hw(()=>Z.abort(),$),H=null;try{H=await this.fetch(X,{signal:Z.signal,...Y})}catch(N){throw new hX1(N)}finally{clearTimeout(K)}if(Y.mode!=="no-cors"&&(H.status<200||H.status>=400))throw new oa(H,W);return H},{...this._retryOptions,...G})}async _shutdown(X=30000){await this._initPromise;let Y=!1;this.clearFlushTimer();let G=async()=>{try{await this.promiseQueue.join();while(!0){if((this.getPersistedProperty(nJ.Queue)||[]).length===0)break;if(await this.flush(),Y)break}}catch(J){if(!SB0(J))throw J;await F14(J)}},Q;try{return await Promise.race([new Promise((J,W)=>{Q=Hw(()=>{this._logger.error("Timed out while shutting down PostHog"),Y=!0,W("Timeout while shutting down PostHog. Some events may not have been sent.")},X)}),G()])}finally{clearTimeout(Q)}}async shutdown(X=30000){if(this.shutdownPromise)this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");else this.shutdownPromise=this._shutdown(X).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var oa,hX1;var CB0=D(()=>{H14();lA1();OB0();jj();F3();yX1();oa=class oa extends Error{constructor(X,Y){super("HTTP error while fetching PostHog: status="+X.status+", reqByteLength="+Y),this.response=X,this.reqByteLength=Y,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}};hX1=class hX1 extends Error{constructor(X){super("Network error while fetching PostHog",X instanceof Error?{cause:X}:{}),this.error=X,this.name="PostHogFetchNetworkError"}}});var N14=D(()=>{lA1();jj();CB0();yX1();F3()});var B14=D(()=>{fX1()});function O14(X){let Y=globalThis._posthogChunkIds;if(!Y)return;let G=Object.keys(Y);if(eA1&&G.length===z14)return eA1;return z14=G.length,eA1=G.reduce((Q,J)=>{if(!sA1)sA1={};let W=sA1[J];if(W)Q[W[0]]=W[1];else{let Z=X(J);for(let $=Z.length-1;$>=0;$--){let H=Z[$]?.filename,U=Y[J];if(H&&U){Q[H]=U,sA1[J]=[H,U];break}}}return Q},{}),eA1}var sA1,z14,eA1;var D14=()=>{};class w14{constructor(X,Y,G=[]){this.coercers=X,this.stackParser=Y,this.modifiers=G}buildFromUnknown(X,Y={}){let Q=Y&&Y.mechanism||{handled:!0,type:"generic"},W=this.buildCoercingContext(Q,Y,0).apply(X),Z=this.buildParsingContext(Y),$=this.parseStacktrace(W,Z);return{$exception_list:this.convertToExceptionList($,Q),$exception_level:"error"}}async modifyFrames(X){for(let Y of X)if(Y.stacktrace&&Y.stacktrace.frames&&cA1(Y.stacktrace.frames))Y.stacktrace.frames=await this.applyModifiers(Y.stacktrace.frames);return X}coerceFallback(X){return{type:"Error",value:"Unknown error",stack:X.syntheticException?.stack,synthetic:!0}}parseStacktrace(X,Y){let G;if(X.cause!=null)G=this.parseStacktrace(X.cause,Y);let Q;if(X.stack!=""&&X.stack!=null)Q=this.applyChunkIds(this.stackParser(X.stack,X.synthetic?Y.skipFirstLines:0),Y.chunkIdMap);return{...X,cause:G,stack:Q}}applyChunkIds(X,Y){return X.map((G)=>{if(G.filename&&Y)G.chunk_id=Y[G.filename];return G})}applyCoercers(X,Y){for(let G of this.coercers)if(G.match(X))return G.coerce(X,Y);return this.coerceFallback(Y)}async applyModifiers(X){let Y=X;for(let G of this.modifiers)Y=await G(Y);return Y}convertToExceptionList(X,Y){let G={type:X.type,value:X.value,mechanism:{type:Y.type??"generic",handled:Y.handled??!0,synthetic:X.synthetic??!1}};if(X.stack)G.stacktrace={type:"raw",frames:X.stack};let Q=[G];if(X.cause!=null)Q.push(...this.convertToExceptionList(X.cause,{...Y,handled:!0}));return Q}buildParsingContext(X){return{chunkIdMap:O14(this.stackParser),skipFirstLines:X.skipFirstLines??1}}buildCoercingContext(X,Y,G=0){let Q=(W,Z)=>{if(!(Z<=Zn5))return;{let $=this.buildCoercingContext(X,Y,Z);return this.applyCoercers(W,$)}};return{...Y,syntheticException:G==0?Y.syntheticException:void 0,mechanism:X,apply:(W)=>Q(W,G),next:(W)=>Q(W,G+1)}}}var Zn5=4;var L14=D(()=>{F3();D14()});function Gz(X,Y,G,Q,J){let W={platform:X,filename:Y,function:G==="<anonymous>"?oQ:G,in_app:!0};if(!na(Q))W.lineno=Q;if(!na(J))W.colno=J;return W}var oQ="?";var Tq=D(()=>{F3()});var XT1=(X,Y)=>{let G=X.indexOf("safari-extension")!==-1,Q=X.indexOf("safari-web-extension")!==-1;return G||Q?[X.indexOf("@")!==-1?X.split("@")[0]:oQ,G?`safari-extension:${Y}`:`safari-web-extension:${Y}`]:[X,Y]};var kB0=D(()=>{Tq()});var Wn5,$n5,Kn5,vB0=(X,Y)=>{let G=Wn5.exec(X);if(G){let[,J,W,Z]=G;return Gz(Y,J,oQ,+W,+Z)}let Q=$n5.exec(X);if(Q){if(Q[2]&&Q[2].indexOf("eval")===0){let $=Kn5.exec(Q[2]);if($)Q[2]=$[1],Q[3]=$[2],Q[4]=$[3]}let[W,Z]=XT1(Q[1]||oQ,Q[2]);return Gz(Y,Z,W,Q[3]?+Q[3]:void 0,Q[4]?+Q[4]:void 0)}};var E14=D(()=>{Tq();kB0();Wn5=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,$n5=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Kn5=/\((\S*)(?::(\d+))(?::(\d+))\)/});var Hn5,Fn5,_B0=(X,Y)=>{let G=Hn5.exec(X);if(G){if(G[3]&&G[3].indexOf(" > eval")>-1){let Z=Fn5.exec(G[3]);if(Z)G[1]=G[1]||"eval",G[3]=Z[1],G[4]=Z[2],G[5]=""}let J=G[3],W=G[1]||oQ;return[W,J]=XT1(W,J),Gz(Y,J,W,G[4]?+G[4]:void 0,G[5]?+G[5]:void 0)}};var P14=D(()=>{Tq();kB0();Hn5=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Fn5=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i});var Un5,q14=(X,Y)=>{let G=Un5.exec(X);return G?Gz(Y,G[2],G[1]||oQ,+G[3],G[4]?+G[4]:void 0):void 0};var A14=D(()=>{Tq();Un5=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i});var Nn5,T14=(X,Y)=>{let G=Nn5.exec(X);return G?Gz(Y,G[2],G[3]||oQ,+G[1]):void 0},Bn5,I14=(X,Y)=>{let G=Bn5.exec(X);return G?Gz(Y,G[5],G[3]||G[4]||oQ,+G[1],+G[2]):void 0};var V14=D(()=>{Tq();Nn5=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Bn5=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i});function Dn5(X,Y=!1){return!(Y||X&&!X.startsWith("/")&&!X.match(/^[A-Z]:/)&&!X.startsWith(".")&&!X.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&X!==void 0&&!X.includes("node_modules/")}function j14(X){return parseInt(X||"",10)||void 0}var zn5,On5,M14=(X,Y)=>{let G=X.match(On5);if(G){let Q,J,W,Z,$;if(G[1]){W=G[1];let U=W.lastIndexOf(".");if(W[U-1]===".")U--;if(U>0){Q=W.slice(0,U),J=W.slice(U+1);let N=Q.indexOf(".Module");if(N>0)W=W.slice(N+1),Q=Q.slice(0,N)}Z=void 0}if(J)Z=Q,$=J;if(J==="<anonymous>")$=void 0,W=void 0;if(W===void 0)$=$||oQ,W=Z?`${Z}.${$}`:$;let K=G[2]?.startsWith("file://")?G[2].slice(7):G[2],H=G[5]==="native";if(K?.match(/\/[A-Z]:/))K=K.slice(1);if(!K&&G[5]&&!H)K=G[5];return{filename:K?decodeURI(K):void 0,module:void 0,function:W,lineno:j14(G[3]),colno:j14(G[4]),in_app:Dn5(K||"",H),platform:Y}}if(X.match(zn5))return{filename:X,platform:Y}};var R14=D(()=>{Tq();zn5=/^\s*[-]{4,}$/,On5=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/});function k14(X){if(!X.length)return[];let Y=Array.from(X);return Y.reverse(),Y.slice(0,C14).map((G)=>({...G,filename:G.filename||wn5(Y).filename,function:G.function||oQ}))}function wn5(X){return X[X.length-1]||{}}function Ln5(){return v14("web:javascript",vB0,_B0)}function v14(X,...Y){return(G,Q=0)=>{let J=[],W=G.split(`
|
|
1639
|
+
`);Q=W.pop()??"";for(let Z of W){let $=Es6(Z).replace(/^\[\d+\]\s*/,"").trim();if(!$)continue;EK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:$})}}(async()=>{for(;;){let{done:W,value:Z}=await Y.read();if(W)break;Q+=G.decode(Z,{stream:!0}),J()}if(Q.trim()){let W=Es6(Q).replace(/^\[\d+\]\s*/,"").trim();if(W)EK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:W})}})()}async function _i5(X){let{vitePort:Y,baseUrl:G,noTui:Q}=X,J=await TA1(Number(X.port)),{settings:W,services:Z,managedServiceNames:$}=await AA1({port:String(J),home:X.home,baseUrl:X.baseUrl,localMode:X.localMode,skipMigrations:X.skipMigrations,noTui:X.noTui,vitePort:X.vitePort});for(let z of Z)Ld({name:z.name,status:"ready",port:z.port});Ve(W),Te();let K=vi5(import.meta.dir,"..","..","..","..",".."),H=Q===!0,U=Bun.spawn(["bun","run","--cwd=apps/mesh","dev:servers"],{cwd:K,env:{...process.env,PORT:String(W.port),VITE_PORT:String(Y),DATABASE_URL:W.databaseUrl,NATS_URL:W.natsUrls.join(","),NODE_ENV:W.nodeEnv,DECOCMS_LOCAL_MODE:String(W.localMode),DECOCMS_HOME:W.dataDir,DATA_DIR:W.dataDir,DECO_CLI:"1",...W.baseUrl?{BASE_URL:W.baseUrl}:{}},stdio:["inherit",H?"inherit":"pipe",H?"inherit":"pipe"]});if(!H)Ps6(U.stdout),Ps6(U.stderr);let N=G||`http://localhost:${W.port}`;Ie(N),Ld({name:"Vite",status:"ready",port:Number(Y)});let B=async(z)=>{if(U.kill(z),$.length>0){let{stopServices:O}=await Promise.resolve().then(() => (z$1(),B$1));await O(W.dataDir)}};return process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM")),{port:Number(W.port),process:U}}var bN0=D(()=>{vN0();GF();_N0()});import{Box as yN0,Text as xN0}from"ink";import{jsx as As6,jsxs as IA1}from"react/jsx-runtime";function qs6(X){if(!X)return"not set";try{let Y=new URL(X);if(Y.password)Y.password="***";if(Y.username&&Y.username.length>3)Y.username=Y.username.slice(0,3)+"***";return Y.pathname="/",Y.search="",Y.hash="",Y.toString()}catch{if(X.length<=10)return X;return X.slice(0,6)+"***"+X.slice(-4)}}function yi5(X,Y){if(fi5.has(X))return Y?{text:"\u25CF\u25CF\u25CF\u25CF\u25CF\u25CF",dimColor:!0}:{text:"not set",dimColor:!0};if(bi5.has(X)){if(Array.isArray(Y)){if(Y.length===0)return{text:"not set",dimColor:!0};return{text:Y.map((W)=>qs6(W)).join(", "),color:"cyan"}}let Q=qs6(Y);return Q==="not set"?{text:Q,dimColor:!0}:{text:Q,color:"cyan"}}if(Y===void 0||Y===null||Y==="")return{text:"not set",dimColor:!0};let G=String(Y);if(G==="true")return{text:G,color:"green"};if(G==="false")return{text:G,color:"yellow"};try{return new URL(G),{text:G,color:"cyan"}}catch{return{text:G}}}function xi5(X){return[{title:"Core",entries:[{key:"NODE_ENV",value:X.nodeEnv},{key:"PORT",value:X.port},{key:"BASE_URL",value:X.baseUrl??`http://localhost:${X.port}`},{key:"DATA_DIR",value:X.dataDir}]},{title:"Database",entries:[{key:"DATABASE_URL",value:X.databaseUrl},{key:"DATABASE_PG_SSL",value:X.databasePgSsl}]},{title:"Auth & Secrets",entries:[{key:"BETTER_AUTH_SECRET",value:X.betterAuthSecret},{key:"ENCRYPTION_KEY",value:X.encryptionKey},{key:"MESH_JWT_SECRET",value:X.meshJwtSecret},{key:"STUDIO_PROVISION_SECRET_KEY",value:X.studioProvisionSecretKey},{key:"DISABLE_RATE_LIMIT",value:X.disableRateLimit}]},{title:"Auth Providers",entries:[{key:"AUTH_EMAIL_PASSWORD_ENABLED",value:process.env.AUTH_EMAIL_PASSWORD_ENABLED??"true"},{key:"AUTH_GOOGLE_CLIENT_ID",value:!!process.env.AUTH_GOOGLE_CLIENT_ID},{key:"AUTH_GITHUB_CLIENT_ID",value:!!process.env.AUTH_GITHUB_CLIENT_ID},{key:"AUTH_RESEND_API_KEY",value:!!process.env.AUTH_RESEND_API_KEY},{key:"AUTH_SENDGRID_API_KEY",value:!!process.env.AUTH_SENDGRID_API_KEY},{key:"AUTH_SSO_MS_CLIENT_ID",value:!!process.env.AUTH_SSO_MS_CLIENT_ID},{key:"AUTH_MAGIC_LINK_ENABLED",value:process.env.AUTH_MAGIC_LINK_ENABLED==="true"},{key:"AUTH_EMAIL_OTP_ENABLED",value:process.env.AUTH_EMAIL_OTP_ENABLED==="true"}]},{title:"Observability",entries:[{key:"CLICKHOUSE_URL",value:X.clickhouseUrl},{key:"OTEL_SERVICE_NAME",value:X.otelServiceName}]},{title:"Event Bus & Networking",entries:[{key:"NATS_URL",value:X.natsUrls}]},{title:"Config Files",entries:[{key:"CONFIG_PATH",value:X.configPath}]},{title:"Transport",entries:[{key:"UNSAFE_ALLOW_STDIO_TRANSPORT",value:X.unsafeAllowStdioTransport}]},{title:"AI Gateway",entries:[{key:"DECO_AI_GATEWAY_ENABLED",value:X.aiGatewayEnabled},{key:"DECO_AI_GATEWAY_URL",value:X.aiGatewayUrl}]}]}function Ts6({env:X}){let Y=xi5(X);return As6(yN0,{flexDirection:"column",children:Y.map((G)=>IA1(yN0,{flexDirection:"column",marginTop:1,children:[IA1(xN0,{dimColor:!0,children:[" ","\u2500\u2500 ",G.title," ","\u2500".repeat(Math.max(0,38-G.title.length))]}),G.entries.map(({key:Q,value:J})=>{let W=yi5(Q,J);return IA1(yN0,{children:[IA1(xN0,{dimColor:!0,children:[" ",Q.padEnd(36)]}),As6(xN0,{color:W.color,dimColor:W.dimColor,children:W.text})]},Q)})]},G.title))})}var fi5,bi5;var Is6=D(()=>{fi5=new Set(["BETTER_AUTH_SECRET","ENCRYPTION_KEY","MESH_JWT_SECRET","STUDIO_PROVISION_SECRET_KEY"]),bi5=new Set(["DATABASE_URL","CLICKHOUSE_URL","NATS_URL"])});var hN0;var Vs6=D(()=>{hN0={name:"decocms",version:"2.292.2",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/mesh"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:'bun run migrate && concurrently "bun run dev:client" "bun run dev:server"',"dev:servers":'concurrently "bun run dev:client" "bun run dev:server"',"dev:client":"bun --bun vite dev","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts","build:client":"bun --bun vite build","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","db:migrate":"bun run ./dist/server/migrate.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts",test:"bun test","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run build:client && bun run build:server"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1","@freestyle-sh/with-bun":"^0.2.12","@freestyle-sh/with-deno":"^0.0.4","@freestyle-sh/with-nodejs":"^0.2.9","freestyle-sandboxes":"^0.1.46"},dependencies:{"@ai-sdk/anthropic":"^3.0.58","@ai-sdk/google":"^3.0.60","@ai-sdk/openai":"^3.0.50","@anthropic-ai/sdk":"^0.79.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dnd-kit/core":"^6.3.1","@dnd-kit/sortable":"^10.0.0","@dnd-kit/utilities":"^3.2.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/ext-apps":"^1.2.2","@openrouter/ai-sdk-provider":"^2.2.5","@opentelemetry/core":"^2.6.0","@tanstack/react-virtual":"^3.13.21","@xterm/addon-fit":"^0.11.0","@xterm/xterm":"^6.0.0","ai-sdk-provider-claude-code":"^3.4.4","ai-sdk-provider-codex-cli":"^1.1.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12",nats:"^2.29.3","posthog-js":"^1.371.1","posthog-node":"^5.0.0",react:"^19.2.0","react-dom":"^19.2.0"},devDependencies:{"@ai-sdk/provider":"^3.0.8","@ai-sdk/react":"^3.0.118","@anthropic-ai/claude-agent-sdk":"^0.2.80","@better-auth/sso":"1.4.1","@daveyplate/better-auth-ui":"^3.2.7","@deco/ui":"workspace:*","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/mesh-sdk":"workspace:*","@decocms/runtime":"workspace:*","@decocms/vite-plugin":"workspace:*","@electric-sql/pglite":"^0.3.15","@floating-ui/react":"^0.27.16","@hookform/resolvers":"^5.2.2","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.27.1","@monaco-editor/react":"^4.7.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@playwright/test":"^1.58.2","@radix-ui/react-avatar":"^1.1.10","@radix-ui/react-checkbox":"^1.3.3","@radix-ui/react-dialog":"^1.1.15","@radix-ui/react-dropdown-menu":"^2.1.16","@radix-ui/react-label":"^2.1.7","@radix-ui/react-select":"^2.2.6","@radix-ui/react-separator":"^1.1.7","@radix-ui/react-slot":"^1.2.3","@radix-ui/react-tabs":"^1.1.13","@rjsf/core":"^6.1.2","@rjsf/shadcn":"^6.1.2","@rjsf/utils":"^6.1.2","@rjsf/validator-ajv8":"^6.1.2","@tailwindcss/vite":"^4.1.17","@tanstack/react-query":"5.90.11","@tanstack/react-router":"^1.139.7","@tiptap/core":"3.20.2","@tiptap/extension-mention":"3.20.2","@tiptap/extension-placeholder":"3.20.2","@tiptap/pm":"3.20.2","@tiptap/react":"3.20.2","@tiptap/starter-kit":"3.20.2","@tiptap/suggestion":"3.20.2","@types/bun":"^1.3.1","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@untitledui/icons":"^0.0.19","@vercel/nft":"^1.1.1","@vitejs/plugin-react":"^5.1.0",ai:"^6.0.116","babel-plugin-react-compiler":"^1.0.0","better-auth":"1.4.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",concurrently:"^9.2.1",croner:"^9.1.0","date-fns":"^4.1.0",degit:"^2.8.4",hono:"^4.10.7","input-otp":"^1.4.2",jose:"^6.0.11","kysely-pglite":"^0.6.1","lucide-react":"^0.468.0",marked:"^15.0.6","@decocms/sandbox":"workspace:*","mesh-plugin-workflows":"workspace:*",nanoid:"^5.1.6",pg:"^8.16.3",prettier:"^3.4.2","react-hook-form":"^7.66.0","react-markdown":"^10.1.0","react-resizable-panels":"^2.1.7","react-syntax-highlighter":"^15.6.1",recharts:"^3.6.0","rehype-raw":"^7.0.0","remark-gfm":"^4.0.0","sass-embedded":"^1.97.2",sonner:"^2.0.7","tailwind-merge":"^3.3.1",tailwindcss:"^4.1.17",typescript:"^5.9.3",vite:"^7.2.1","vite-tsconfig-paths":"^5.1.4",zod:"^4.0.0",zustand:"^5.0.9"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","mesh","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as AU,Text as MX}from"ink";import{Spinner as gi5}from"@inkjs/ui";import{useSyncExternalStore as js6}from"react";import{jsx as qY,jsxs as rQ}from"react/jsx-runtime";function ci5(X,Y){if(!X||!di5.has(X))return X;let G=gN0[Y]??gN0[gN0.length-1];return X==="#875f00"?G[0]:G[1]}function Ms6({status:X}){if(X==="pending")return qY(gi5,{label:""});return qY(MX,{color:"green",children:"\u2713"})}function Rs6({services:X,migrationsStatus:Y,home:G,serverUrl:Q,vibe:J}){let W=js6(fu0,_u0),Z=js6(uu0,gu0);return rQ(AU,{flexDirection:"column",paddingBottom:1,children:[J?rQ(AU,{flexDirection:"column",children:[W.map(($,K)=>{let H=Z[K],U=$.reduce((B,z)=>B+z.text.length,0),N=Math.max(0,mi5-U);return rQ(AU,{flexDirection:"row",children:[$.map((B,z)=>{let O=ci5(B.color,K);return O?qY(MX,{color:O,children:B.text},z):qY(MX,{children:B.text},z)}),qY(MX,{children:" ".repeat(N+2)}),H?.map((B,z)=>B.color?qY(MX,{color:B.color,children:B.char},z):qY(MX,{children:B.char},z))]},K)}),rQ(MX,{dimColor:!0,children:[" v",hN0.version]})]}):rQ(AU,{flexDirection:"column",marginTop:1,children:[ui5.map(($,K)=>qY(MX,{color:li5[K],children:$},K)),rQ(MX,{dimColor:!0,children:[" v",hN0.version]})]}),qY(AU,{marginBottom:1,children:qY(MX,{dimColor:!0,children:"\u2500".repeat(80)})}),qY(AU,{children:rQ(MX,{dimColor:!0,children:["Home: ",G]})}),rQ(AU,{gap:2,children:[X.map(($)=>rQ(AU,{gap:1,children:[rQ(MX,{children:[$.name," :",$.port||"...."]}),qY(Ms6,{status:$.status})]},$.name)),rQ(AU,{gap:1,children:[qY(MX,{children:"Migrations"}),qY(Ms6,{status:Y})]})]}),qY(AU,{children:Q?rQ(MX,{children:["Open in browser: ",qY(MX,{color:"cyan",children:Q})]}):qY(MX,{dimColor:!0,children:"Starting..."})}),rQ(AU,{gap:2,children:[rQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"K"})," ","toggle config"]}),rQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"L"})," ","toggle log flow"]}),rQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"V"})," ","toggle vibe ",J?"\u266A Nihilore \xB7 CC BY 4.0":""]}),J&&rQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"N"})," ","skip song"]})]})]})}var ui5,li5,gN0,mi5=30,di5;var Ss6=D(()=>{Vs6();Pn1();jn1();ui5=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 ","\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588 \u2591 \u2588\u2588\u2588 \u2591\u2591\u2591 \u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591 \u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588 "," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591 ","\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591 "],li5=["#00ff64","#00ee5e","#00dc56","#00c84e","#00b444","#00a03c","#008832","#006e28"],gN0=[["#00ff64","#00cc50"],["#00f060","#00c04c"],["#00e05c","#00b448"],["#00d058","#00a844"],["#00c054","#009c40"],["#00b050","#00903c"],["#00a04c","#008438"],["#009048","#007834"],["#008044","#006c30"],["#007040","#00602c"],["#00603c","#005428"]],di5=new Set(["#875f00","#5f3800"])});import{useSyncExternalStore as ii5}from"react";function pi5(){let X=process.stdout.rows||24,Y=process.stdout.columns||80;if(X!==VA1.rows||Y!==VA1.columns)VA1={rows:X,columns:Y};return VA1}function ni5(X){return process.stdout.on("resize",X),()=>{process.stdout.off("resize",X)}}function Cs6(){return ii5(ni5,pi5)}var VA1;var ks6=D(()=>{VA1={rows:process.stdout.rows||24,columns:process.stdout.columns||80}});import{Box as ai5,Text as AX1}from"ink";import{useSyncExternalStore as ti5}from"react";import{jsx as uN0,jsxs as lN0}from"react/jsx-runtime";function ri5(X){if(X>=500)return"red";if(X>=400)return"yellow";if(X>=300)return"cyan";return"green"}function vs6({logs:X,headerHeight:Y}){let{rows:G}=Cs6(),{logFlow:Q}=ti5(Ae,qe),J=Math.max(1,G-Y-1),W=Q?X:X.slice(-J);return uN0(ai5,{flexDirection:"column",children:W.map((Z,$)=>{if(Z.rawLine)return uN0(AX1,{dimColor:!0,children:Z.rawLine},$);let K=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return lN0(AX1,{children:[lN0(AX1,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),uN0(AX1,{color:ri5(Z.status),children:Z.status}),lN0(AX1,{dimColor:!0,children:[" ",K.padStart(8)]})]},$)})})}var _s6=D(()=>{GF();ks6()});var mN0={};M0(mN0,{App:()=>Qp5});import{Box as oi5,Text as si5,useInput as ei5}from"ink";import{useSyncExternalStore as Xp5}from"react";import{jsx as jA1,jsxs as Jp5}from"react/jsx-runtime";function Qp5({home:X}){let Y=Xp5(Ae,qe);return ei5((G)=>{if(G==="k"||G==="K")vn1();if(G==="l"||G==="L")_n1();if((G==="v"||G==="V")&&Y.dataDir)Cn1(Y.dataDir),fn1();if((G==="n"||G==="N")&&Y.vibe)Sn1()}),Jp5(oi5,{flexDirection:"column",children:[jA1(Rs6,{services:Y.services,migrationsStatus:Y.migrationsStatus,home:X,serverUrl:Y.serverUrl,vibe:Y.vibe}),Y.viewMode==="config"?Y.env?jA1(Ts6,{env:Y.env}):jA1(si5,{dimColor:!0,children:"Loading configuration..."}):jA1(vs6,{logs:Y.logs,headerHeight:Y.vibe?Gp5:Yp5})]})}var Yp5=15,Gp5=19;var dN0=D(()=>{Is6();Ss6();_s6();GF();wd()});function fs6(X,Y={}){return{PORT:String(X.port),NODE_ENV:X.nodeEnv,BASE_URL:X.baseUrl,DATA_DIR:X.dataDir,DECOCMS_HOME:X.dataDir,DATABASE_URL:X.databaseUrl,DATABASE_PG_SSL:String(X.databasePgSsl),DATABASE_POOL_MAX:String(X.databasePoolMax),NATS_URL:X.natsUrls.join(","),BETTER_AUTH_SECRET:X.betterAuthSecret,ENCRYPTION_KEY:X.encryptionKey,MESH_JWT_SECRET:X.meshJwtSecret,DECOCMS_LOCAL_MODE:String(X.localMode),DECOCMS_ALLOW_LOCAL_PROD:String(X.allowLocalProd),DISABLE_RATE_LIMIT:String(X.disableRateLimit),STUDIO_PROVISION_SECRET_KEY:X.studioProvisionSecretKey,CONFIG_PATH:X.configPath,...Object.fromEntries(Object.entries(process.env).filter(([G])=>G.startsWith("AUTH_"))),UNSAFE_ALLOW_STDIO_TRANSPORT:String(X.unsafeAllowStdioTransport),DECO_AI_GATEWAY_ENABLED:String(X.aiGatewayEnabled),DECO_AI_GATEWAY_URL:X.aiGatewayUrl,ENABLE_DECO_IMPORT:String(X.enableDecoImport),S3_ENDPOINT:X.s3Endpoint,S3_BUCKET:X.s3Bucket,S3_REGION:X.s3Region,S3_ACCESS_KEY_ID:X.s3AccessKeyId,S3_SECRET_ACCESS_KEY:X.s3SecretAccessKey,S3_FORCE_PATH_STYLE:String(X.s3ForcePathStyle),OTEL_SERVICE_NAME:X.otelServiceName,CLICKHOUSE_URL:X.clickhouseUrl,DECO_SUPABASE_URL:X.decoSupabaseUrl,DECO_SUPABASE_SERVICE_KEY:X.decoSupabaseServiceKey,FIRECRAWL_API_KEY:X.firecrawlApiKey,STUDIO_SANDBOX_RUNNER:process.env.STUDIO_SANDBOX_RUNNER,STUDIO_SANDBOX_TEMPLATE_NAME:process.env.STUDIO_SANDBOX_TEMPLATE_NAME,STUDIO_SANDBOX_PREVIEW_URL_PATTERN:process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN,STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME:process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME,STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE:process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE,KUBERNETES_SERVICE_HOST:process.env.KUBERNETES_SERVICE_HOST,KUBERNETES_SERVICE_PORT:process.env.KUBERNETES_SERVICE_PORT,FREESTYLE_API_KEY:process.env.FREESTYLE_API_KEY,BROWSERLESS_TOKEN:process.env.BROWSERLESS_TOKEN,NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS,DECO_CLI:"1",DECO_NO_TUI:"true",...Y}}function ys6(X){if(!X)return!1;try{return new URL(X).host==="api.decocms.com"&&X!=="https://studio.decocms.com/org/deco/registry/mcp"}catch{return!1}}var bs6="https://studio.decocms.com/org/deco/registry/mcp";var cN0=(X,Y,G)=>{return(Q,J)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,U;if(X[$])U=X[$][0][0],Q.req.routeIndex=$;else U=$===X.length&&J||void 0;if(U)try{K=await U(Q,()=>Z($+1))}catch(N){if(N instanceof Error&&Y)Q.error=N,K=await Y(N,Q),H=!0;else throw N}else if(Q.finalized===!1&&G)K=await G(Q);if(K&&(Q.finalized===!1||H))Q.res=K;return Q}}};var xs6=()=>{};var M9;var Lq=D(()=>{M9=class extends Error{res;status;constructor(X=500,Y){super(Y?.message,{cause:Y?.cause});this.res=Y?.res,this.status=X}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var hs6;var gs6=D(()=>{hs6=Symbol()});async function Zp5(X,Y){let G=await X.formData();if(G)return Wp5(G,Y);return{}}function Wp5(X,Y){let G=Object.create(null);if(X.forEach((Q,J)=>{if(!(Y.all||J.endsWith("[]")))G[J]=Q;else $p5(G,J,Q)}),Y.dot)Object.entries(G).forEach(([Q,J])=>{if(Q.includes("."))Kp5(G,Q,J),delete G[Q]});return G}var us6=async(X,Y=Object.create(null))=>{let{all:G=!1,dot:Q=!1}=Y,W=(X instanceof MA1?X.raw.headers:X.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return Zp5(X,{all:G,dot:Q});return{}},$p5=(X,Y,G)=>{if(X[Y]!==void 0)if(Array.isArray(X[Y]))X[Y].push(G);else X[Y]=[X[Y],G];else if(!Y.endsWith("[]"))X[Y]=G;else X[Y]=[G]},Kp5=(X,Y,G)=>{if(/(?:^|\.)__proto__\./.test(Y))return;let Q=X,J=Y.split(".");J.forEach((W,Z)=>{if(Z===J.length-1)Q[W]=G;else{if(!Q[W]||typeof Q[W]!=="object"||Array.isArray(Q[W])||Q[W]instanceof File)Q[W]=Object.create(null);Q=Q[W]}})};var ls6=D(()=>{iN0()});var nN0=(X)=>{let Y=X.split("/");if(Y[0]==="")Y.shift();return Y},ms6=(X)=>{let{groups:Y,path:G}=Hp5(X),Q=nN0(G);return Fp5(Q,Y)},Hp5=(X)=>{let Y=[];return X=X.replace(/\{[^}]+\}/g,(G,Q)=>{let J=`@${Q}`;return Y.push([J,G]),J}),{groups:Y,path:X}},Fp5=(X,Y)=>{for(let G=Y.length-1;G>=0;G--){let[Q]=Y[G];for(let J=X.length-1;J>=0;J--)if(X[J].includes(Q)){X[J]=X[J].replace(Q,Y[G][1]);break}}return X},RA1,ds6=(X,Y)=>{if(X==="*")return"*";let G=X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(G){let Q=`${X}#${Y}`;if(!RA1[Q])if(G[2])RA1[Q]=Y&&Y[0]!==":"&&Y[0]!=="*"?[Q,G[1],new RegExp(`^${G[2]}(?=/${Y})`)]:[X,G[1],new RegExp(`^${G[2]}$`)];else RA1[Q]=[X,G[1],!0];return RA1[Q]}return null},ia=(X,Y)=>{try{return Y(X)}catch{return X.replace(/(?:%[0-9A-Fa-f]{2})+/g,(G)=>{try{return Y(G)}catch{return G}})}},cs6=(X)=>ia(X,decodeURI),aN0=(X)=>{let Y=X.url,G=Y.indexOf("/",Y.indexOf(":")+4),Q=G;for(;Q<Y.length;Q++){let J=Y.charCodeAt(Q);if(J===37){let W=Y.indexOf("?",Q),Z=Y.indexOf("#",Q),$=W===-1?Z===-1?void 0:Z:Z===-1?W:Math.min(W,Z),K=Y.slice(G,$);return cs6(K.includes("%25")?K.replace(/%25/g,"%2525"):K)}else if(J===63||J===35)break}return Y.slice(G,Q)},is6=(X)=>{let Y=aN0(X);return Y.length>1&&Y.at(-1)==="/"?Y.slice(0,-1):Y},Tj=(X,Y,...G)=>{if(G.length)Y=Tj(Y,...G);return`${X?.[0]==="/"?"":"/"}${X}${Y==="/"?"":`${X?.at(-1)==="/"?"":"/"}${Y?.[0]==="/"?Y.slice(1):Y}`}`},SA1=(X)=>{if(X.charCodeAt(X.length-1)!==63||!X.includes(":"))return null;let Y=X.split("/"),G=[],Q="";return Y.forEach((J)=>{if(J!==""&&!/\:/.test(J))Q+="/"+J;else if(/\:/.test(J))if(/\?/.test(J)){if(G.length===0&&Q==="")G.push("/");else G.push(Q);let W=J.replace("?","");Q+="/"+W,G.push(Q)}else Q+="/"+J}),G.filter((J,W,Z)=>Z.indexOf(J)===W)},pN0=(X)=>{if(!/[%+]/.test(X))return X;if(X.indexOf("+")!==-1)X=X.replace(/\+/g," ");return X.indexOf("%")!==-1?ia(X,TX1):X},ps6=(X,Y,G)=>{let Q;if(!G&&Y&&!/[%+]/.test(Y)){let Z=X.indexOf("?",8);if(Z===-1)return;if(!X.startsWith(Y,Z+1))Z=X.indexOf(`&${Y}`,Z+1);while(Z!==-1){let $=X.charCodeAt(Z+Y.length+1);if($===61){let K=Z+Y.length+2,H=X.indexOf("&",K);return pN0(X.slice(K,H===-1?void 0:H))}else if($==38||isNaN($))return"";Z=X.indexOf(`&${Y}`,Z+1)}if(Q=/[%+]/.test(X),!Q)return}let J={};Q??=/[%+]/.test(X);let W=X.indexOf("?",8);while(W!==-1){let Z=X.indexOf("&",W+1),$=X.indexOf("=",W);if($>Z&&Z!==-1)$=-1;let K=X.slice(W+1,$===-1?Z===-1?void 0:Z:$);if(Q)K=pN0(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=X.slice($+1,Z===-1?void 0:Z),Q)H=pN0(H);if(G){if(!(J[K]&&Array.isArray(J[K])))J[K]=[];J[K].push(H)}else J[K]??=H}return Y?J[Y]:J},ns6,as6=(X,Y)=>{return ps6(X,Y,!0)},TX1;var Eq=D(()=>{RA1={},ns6=ps6,TX1=decodeURIComponent});var ts6=(X)=>ia(X,TX1),MA1;var iN0=D(()=>{Lq();gs6();ls6();Eq();MA1=class{raw;#X;#Y;routeIndex=0;path;bodyCache={};constructor(X,Y="/",G=[[]]){this.raw=X,this.path=Y,this.#Y=G,this.#X={}}param(X){return X?this.#G(X):this.#Q()}#G(X){let Y=this.#Y[0][this.routeIndex][1][X],G=this.#J(Y);return G&&/\%/.test(G)?ts6(G):G}#Q(){let X={},Y=Object.keys(this.#Y[0][this.routeIndex][1]);for(let G of Y){let Q=this.#J(this.#Y[0][this.routeIndex][1][G]);if(Q!==void 0)X[G]=/\%/.test(Q)?ts6(Q):Q}return X}#J(X){return this.#Y[1]?this.#Y[1][X]:X}query(X){return ns6(this.url,X)}queries(X){return as6(this.url,X)}header(X){if(X)return this.raw.headers.get(X)??void 0;let Y={};return this.raw.headers.forEach((G,Q)=>{Y[Q]=G}),Y}async parseBody(X){return us6(this,X)}#Z=(X)=>{let{bodyCache:Y,raw:G}=this,Q=Y[X];if(Q)return Q;let J=Object.keys(Y)[0];if(J)return Y[J].then((W)=>{if(J==="json")W=JSON.stringify(W);return new Response(W)[X]()});return Y[X]=G[X]()};json(){return this.#Z("text").then((X)=>JSON.parse(X))}text(){return this.#Z("text")}arrayBuffer(){return this.#Z("arrayBuffer")}blob(){return this.#Z("blob")}formData(){return this.#Z("formData")}addValidatedData(X,Y){this.#X[X]=Y}valid(X){return this.#X[X]}get url(){return this.raw.url}get method(){return this.raw.method}get[hs6](){return this.#Y}get matchedRoutes(){return this.#Y[0].map(([[,X]])=>X)}get routePath(){return this.#Y[0].map(([[,X]])=>X)[this.routeIndex].path}}});var CA1,rs6=(X,Y)=>{let G=new String(X);return G.isEscaped=!0,G.callbacks=Y,G},IX1=async(X,Y,G,Q,J)=>{if(typeof X==="object"&&!(X instanceof String)){if(!(X instanceof Promise))X=X.toString();if(X instanceof Promise)X=await X}let W=X.callbacks;if(!W?.length)return Promise.resolve(X);if(J)J[0]+=X;else J=[X];let Z=Promise.all(W.map(($)=>$({phase:Y,buffer:J,context:Q}))).then(($)=>Promise.all($.filter(Boolean).map((K)=>IX1(K,Y,!1,Q,J))).then(()=>J[0]));if(G)return rs6(await Z,W);else return Z};var kA1=D(()=>{CA1={Stringify:1,BeforeStream:2,Stream:3}});var os6="text/plain; charset=UTF-8",tN0=(X,Y)=>{return{"Content-Type":X,...Y}},VX1=(X,Y)=>new Response(X,Y),ss6=class{#X;#Y;env={};#G;finalized=!1;error;#Q;#J;#Z;#$;#W;#K;#H;#U;#N;constructor(X,Y){if(this.#X=X,Y)this.#J=Y.executionCtx,this.env=Y.env,this.#K=Y.notFoundHandler,this.#N=Y.path,this.#U=Y.matchResult}get req(){return this.#Y??=new MA1(this.#X,this.#N,this.#U),this.#Y}get event(){if(this.#J&&"respondWith"in this.#J)return this.#J;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#J)return this.#J;else throw Error("This context has no ExecutionContext")}get res(){return this.#Z||=VX1(null,{headers:this.#H??=new Headers})}set res(X){if(this.#Z&&X){X=VX1(X.body,X);for(let[Y,G]of this.#Z.headers.entries()){if(Y==="content-type")continue;if(Y==="set-cookie"){let Q=this.#Z.headers.getSetCookie();X.headers.delete("set-cookie");for(let J of Q)X.headers.append("set-cookie",J)}else X.headers.set(Y,G)}}this.#Z=X,this.finalized=!0}render=(...X)=>{return this.#W??=(Y)=>this.html(Y),this.#W(...X)};setLayout=(X)=>this.#$=X;getLayout=()=>this.#$;setRenderer=(X)=>{this.#W=X};header=(X,Y,G)=>{if(this.finalized)this.#Z=VX1(this.#Z.body,this.#Z);let Q=this.#Z?this.#Z.headers:this.#H??=new Headers;if(Y===void 0)Q.delete(X);else if(G?.append)Q.append(X,Y);else Q.set(X,Y)};status=(X)=>{this.#Q=X};set=(X,Y)=>{this.#G??=new Map,this.#G.set(X,Y)};get=(X)=>{return this.#G?this.#G.get(X):void 0};get var(){if(!this.#G)return{};return Object.fromEntries(this.#G)}#F(X,Y,G){let Q=this.#Z?new Headers(this.#Z.headers):this.#H??new Headers;if(typeof Y==="object"&&"headers"in Y){let W=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);for(let[Z,$]of W)if(Z.toLowerCase()==="set-cookie")Q.append(Z,$);else Q.set(Z,$)}if(G)for(let[W,Z]of Object.entries(G))if(typeof Z==="string")Q.set(W,Z);else{Q.delete(W);for(let $ of Z)Q.append(W,$)}let J=typeof Y==="number"?Y:Y?.status??this.#Q;return VX1(X,{status:J,headers:Q})}newResponse=(...X)=>this.#F(...X);body=(X,Y,G)=>this.#F(X,Y,G);text=(X,Y,G)=>{return!this.#H&&!this.#Q&&!Y&&!G&&!this.finalized?new Response(X):this.#F(X,Y,tN0(os6,G))};json=(X,Y,G)=>{return this.#F(JSON.stringify(X),Y,tN0("application/json",G))};html=(X,Y,G)=>{let Q=(J)=>this.#F(J,Y,tN0("text/html; charset=UTF-8",G));return typeof X==="object"?IX1(X,CA1.Stringify,!1,{}).then(Q):Q(X)};redirect=(X,Y)=>{let G=String(X);return this.header("Location",!/[^\x00-\xFF]/.test(G)?G:encodeURI(G)),this.newResponse(null,Y??302)};notFound=()=>{return this.#K??=()=>VX1(),this.#K(this)}};var vA1=D(()=>{iN0();kA1()});var T7="ALL",es6="all",Xe6,_A1="Can not add a route since the matcher is already built.",fA1;var Pq=D(()=>{Xe6=["get","post","put","delete","options","patch"],fA1=class extends Error{}});var rN0="__COMPOSED_HANDLER";var oN0=()=>{};var Up5=(X)=>{return X.text("404 Not Found",404)},Ye6=(X,Y)=>{if("getResponse"in X){let G=X.getResponse();return Y.newResponse(G.body,G)}return console.error(X),Y.text("Internal Server Error",500)},Ge6=class X{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#X="/";routes=[];constructor(Y={}){[...Xe6,es6].forEach((W)=>{this[W]=(Z,...$)=>{if(typeof Z==="string")this.#X=Z;else this.#Q(W,this.#X,Z);return $.forEach((K)=>{this.#Q(W,this.#X,K)}),this}}),this.on=(W,Z,...$)=>{for(let K of[Z].flat()){this.#X=K;for(let H of[W].flat())$.map((U)=>{this.#Q(H.toUpperCase(),this.#X,U)})}return this},this.use=(W,...Z)=>{if(typeof W==="string")this.#X=W;else this.#X="*",Z.unshift(W);return Z.forEach(($)=>{this.#Q(T7,this.#X,$)}),this};let{strict:Q,...J}=Y;Object.assign(this,J),this.getPath=Q??!0?Y.getPath??aN0:is6}#Y(){let Y=new X({router:this.router,getPath:this.getPath});return Y.errorHandler=this.errorHandler,Y.#G=this.#G,Y.routes=this.routes,Y}#G=Up5;errorHandler=Ye6;route(Y,G){let Q=this.basePath(Y);return G.routes.map((J)=>{let W;if(G.errorHandler===Ye6)W=J.handler;else W=async(Z,$)=>(await cN0([],G.errorHandler)(Z,()=>J.handler(Z,$))).res,W[rN0]=J.handler;Q.#Q(J.method,J.path,W)}),this}basePath(Y){let G=this.#Y();return G._basePath=Tj(this._basePath,Y),G}onError=(Y)=>{return this.errorHandler=Y,this};notFound=(Y)=>{return this.#G=Y,this};mount(Y,G,Q){let J,W;if(Q)if(typeof Q==="function")W=Q;else if(W=Q.optionHandler,Q.replaceRequest===!1)J=(K)=>K;else J=Q.replaceRequest;let Z=W?(K)=>{let H=W(K);return Array.isArray(H)?H:[H]}:(K)=>{let H=void 0;try{H=K.executionCtx}catch{}return[K.env,H]};J||=(()=>{let K=Tj(this._basePath,Y),H=K==="/"?0:K.length;return(U)=>{let N=new URL(U.url);return N.pathname=N.pathname.slice(H)||"/",new Request(N,U)}})();let $=async(K,H)=>{let U=await G(J(K.req.raw),...Z(K));if(U)return U;await H()};return this.#Q(T7,Tj(Y,"*"),$),this}#Q(Y,G,Q){Y=Y.toUpperCase(),G=Tj(this._basePath,G);let J={basePath:this._basePath,path:G,method:Y,handler:Q};this.router.add(Y,G,[Q,J]),this.routes.push(J)}#J(Y,G){if(Y instanceof Error)return this.errorHandler(Y,G);throw Y}#Z(Y,G,Q,J){if(J==="HEAD")return(async()=>new Response(null,await this.#Z(Y,G,Q,"GET")))();let W=this.getPath(Y,{env:Q}),Z=this.router.match(J,W),$=new ss6(Y,{path:W,matchResult:Z,env:Q,executionCtx:G,notFoundHandler:this.#G});if(Z[0].length===1){let H;try{H=Z[0][0][0][0]($,async()=>{$.res=await this.#G($)})}catch(U){return this.#J(U,$)}return H instanceof Promise?H.then((U)=>U||($.finalized?$.res:this.#G($))).catch((U)=>this.#J(U,$)):H??this.#G($)}let K=cN0(Z[0],this.errorHandler,this.#G);return(async()=>{try{let H=await K($);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#J(H,$)}})()}fetch=(Y,...G)=>{return this.#Z(Y,G[1],G[0],Y.method)};request=(Y,G,Q,J)=>{if(Y instanceof Request)return this.fetch(G?new Request(Y,G):Y,Q,J);return Y=Y.toString(),this.fetch(new Request(/^https?:\/\//.test(Y)?Y:`http://localhost${Tj("/",Y)}`,G),Q,J)};fire=()=>{addEventListener("fetch",(Y)=>{Y.respondWith(this.#Z(Y.request,Y,void 0,Y.request.method))})}};var Qe6=D(()=>{xs6();vA1();Pq();oN0();Eq()});function bA1(X,Y){let G=this.buildAllMatchers(),Q=(J,W)=>{let Z=G[J]||G[T7],$=Z[2][W];if($)return $;let K=W.match(Z[0]);if(!K)return[[],jX1];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=Q,Q(X,Y)}var jX1;var sN0=D(()=>{Pq();jX1=[]});function Bp5(X,Y){if(X.length===1)return Y.length===1?X<Y?-1:1:-1;if(Y.length===1)return 1;if(X===MX1||X===RX1)return 1;else if(Y===MX1||Y===RX1)return-1;if(X===yA1)return 1;else if(Y===yA1)return-1;return X.length===Y.length?X<Y?-1:1:Y.length-X.length}var yA1="[^/]+",MX1=".*",RX1="(?:|/.*)",Ij,Np5,Je6=class X{#X;#Y;#G=Object.create(null);insert(Y,G,Q,J,W){if(Y.length===0){if(this.#X!==void 0)throw Ij;if(W)return;this.#X=G;return}let[Z,...$]=Y,K=Z==="*"?$.length===0?["","",MX1]:["","",yA1]:Z==="/*"?["","",RX1]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let U=K[1],N=K[2]||yA1;if(U&&K[2]){if(N===".*")throw Ij;if(N=N.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(N))throw Ij}if(H=this.#G[N],!H){if(Object.keys(this.#G).some((B)=>B!==MX1&&B!==RX1))throw Ij;if(W)return;if(H=this.#G[N]=new X,U!=="")H.#Y=J.varIndex++}if(!W&&U!=="")Q.push([U,H.#Y])}else if(H=this.#G[Z],!H){if(Object.keys(this.#G).some((U)=>U.length>1&&U!==MX1&&U!==RX1))throw Ij;if(W)return;H=this.#G[Z]=new X}H.insert($,G,Q,J,W)}buildRegExpStr(){let G=Object.keys(this.#G).sort(Bp5).map((Q)=>{let J=this.#G[Q];return(typeof J.#Y==="number"?`(${Q})@${J.#Y}`:Np5.has(Q)?`\\${Q}`:Q)+J.buildRegExpStr()});if(typeof this.#X==="number")G.unshift(`#${this.#X}`);if(G.length===0)return"";if(G.length===1)return G[0];return"(?:"+G.join("|")+")"}};var eN0=D(()=>{Ij=Symbol(),Np5=new Set(".\\+*[^]$()")});var Ze6=class{#X={varIndex:0};#Y=new Je6;insert(X,Y,G){let Q=[],J=[];for(let Z=0;;){let $=!1;if(X=X.replace(/\{[^}]+\}/g,(K)=>{let H=`@\\${Z}`;return J[Z]=[H,K],Z++,$=!0,H}),!$)break}let W=X.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Z=J.length-1;Z>=0;Z--){let[$]=J[Z];for(let K=W.length-1;K>=0;K--)if(W[K].indexOf($)!==-1){W[K]=W[K].replace($,J[Z][1]);break}}return this.#Y.insert(W,Y,Q,this.#X,G),Q}buildRegExp(){let X=this.#Y.buildRegExpStr();if(X==="")return[/^$/,[],[]];let Y=0,G=[],Q=[];return X=X.replace(/#(\d+)|@(\d+)|\.\*\$/g,(J,W,Z)=>{if(W!==void 0)return G[++Y]=Number(W),"$()";if(Z!==void 0)return Q[Number(Z)]=++Y,"";return""}),[new RegExp(`^${X}`),G,Q]}};var We6=D(()=>{eN0()});function Ke6(X){return $e6[X]??=new RegExp(X==="*"?"":`^${X.replace(/\/\*$|([.\\+*[^\]$()])/g,(Y,G)=>G?`\\${G}`:"(?:|/.*)")}$`)}function Op5(){$e6=Object.create(null)}function Dp5(X){let Y=new Ze6,G=[];if(X.length===0)return zp5;let Q=X.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,U],[N,B])=>H?1:N?-1:U.length-B.length),J=Object.create(null);for(let H=0,U=-1,N=Q.length;H<N;H++){let[B,z,O]=Q[H];if(B)J[z]=[O.map(([E])=>[E,Object.create(null)]),jX1];else U++;let w;try{w=Y.insert(z,U,B)}catch(E){throw E===Ij?new fA1(z):E}if(B)continue;G[U]=O.map(([E,P])=>{let q=Object.create(null);P-=1;for(;P>=0;P--){let[j,M]=w[P];q[j]=M}return[E,q]})}let[W,Z,$]=Y.buildRegExp();for(let H=0,U=G.length;H<U;H++)for(let N=0,B=G[H].length;N<B;N++){let z=G[H][N]?.[1];if(!z)continue;let O=Object.keys(z);for(let w=0,E=O.length;w<E;w++)z[O[w]]=$[z[O[w]]]}let K=[];for(let H in Z)K[H]=G[Z[H]];return[W,K,J]}function pa(X,Y){if(!X)return;for(let G of Object.keys(X).sort((Q,J)=>J.length-Q.length))if(Ke6(G).test(Y))return[...X[G]];return}var zp5,$e6,xA1=class{name="RegExpRouter";#X;#Y;constructor(){this.#X={[T7]:Object.create(null)},this.#Y={[T7]:Object.create(null)}}add(X,Y,G){let Q=this.#X,J=this.#Y;if(!Q||!J)throw Error(_A1);if(!Q[X])[Q,J].forEach(($)=>{$[X]=Object.create(null),Object.keys($[T7]).forEach((K)=>{$[X][K]=[...$[T7][K]]})});if(Y==="/*")Y="*";let W=(Y.match(/\/:/g)||[]).length;if(/\*$/.test(Y)){let $=Ke6(Y);if(X===T7)Object.keys(Q).forEach((K)=>{Q[K][Y]||=pa(Q[K],Y)||pa(Q[T7],Y)||[]});else Q[X][Y]||=pa(Q[X],Y)||pa(Q[T7],Y)||[];Object.keys(Q).forEach((K)=>{if(X===T7||X===K)Object.keys(Q[K]).forEach((H)=>{$.test(H)&&Q[K][H].push([G,W])})}),Object.keys(J).forEach((K)=>{if(X===T7||X===K)Object.keys(J[K]).forEach((H)=>$.test(H)&&J[K][H].push([G,W]))});return}let Z=SA1(Y)||[Y];for(let $=0,K=Z.length;$<K;$++){let H=Z[$];Object.keys(J).forEach((U)=>{if(X===T7||X===U)J[U][H]||=[...pa(Q[U],H)||pa(Q[T7],H)||[]],J[U][H].push([G,W-K+$+1])})}}match=bA1;buildAllMatchers(){let X=Object.create(null);return Object.keys(this.#Y).concat(Object.keys(this.#X)).forEach((Y)=>{X[Y]||=this.#G(Y)}),this.#X=this.#Y=void 0,Op5(),X}#G(X){let Y=[],G=X===T7;if([this.#X,this.#Y].forEach((Q)=>{let J=Q[X]?Object.keys(Q[X]).map((W)=>[W,Q[X][W]]):[];if(J.length!==0)G||=!0,Y.push(...J);else if(X!==T7)Y.push(...Object.keys(Q[T7]).map((W)=>[W,Q[T7][W]]))}),!G)return null;else return Dp5(Y)}};var XB0=D(()=>{Pq();Eq();sN0();eN0();We6();zp5=[/^$/,[],Object.create(null)],$e6=Object.create(null)});var wp5=class{name="PreparedRegExpRouter";#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}#G(X,Y){let G=this.#X[X];G[1].forEach((Q)=>Q&&Q.push(Y)),Object.values(G[2]).forEach((Q)=>Q[0].push(Y))}#Q(X,Y,G,Q,J){let W=this.#X[X];if(!J)W[2][Y][0].push([G,{}]);else Q.forEach((Z)=>{if(typeof Z==="number")W[1][Z].push([G,J]);else W[2][Z||Y][0].push([G,J])})}add(X,Y,G){if(!this.#X[X]){let J=this.#X[T7],W={};for(let Z in J[2])W[Z]=[J[2][Z][0].slice(),jX1];this.#X[X]=[J[0],J[1].map((Z)=>Array.isArray(Z)?Z.slice():0),W]}if(Y==="/*"||Y==="*"){let J=[G,{}];if(X===T7)for(let W in this.#X)this.#G(W,J);else this.#G(X,J);return}let Q=this.#Y[Y];if(!Q)throw Error(`Path ${Y} is not registered`);for(let[J,W]of Q)if(X===T7)for(let Z in this.#X)this.#Q(Z,Y,G,J,W);else this.#Q(X,Y,G,J,W)}buildAllMatchers(){return this.#X}match=bA1};var He6=D(()=>{Pq();sN0();XB0()});var Fe6=D(()=>{XB0();He6()});var YB0=class{name="SmartRouter";#X=[];#Y=[];constructor(X){this.#X=X.routers}add(X,Y,G){if(!this.#Y)throw Error(_A1);this.#Y.push([X,Y,G])}match(X,Y){if(!this.#Y)throw Error("Fatal error");let G=this.#X,Q=this.#Y,J=G.length,W=0,Z;for(;W<J;W++){let $=G[W];try{for(let K=0,H=Q.length;K<H;K++)$.add(...Q[K]);Z=$.match(X,Y)}catch(K){if(K instanceof fA1)continue;throw K}this.match=$.match.bind($),this.#X=[$],this.#Y=void 0;break}if(W===J)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Z}get activeRouter(){if(this.#Y||this.#X.length!==1)throw Error("No active router has been determined yet.");return this.#X[0]}};var Ue6=D(()=>{Pq()});var Ne6=D(()=>{Ue6()});var SX1,Lp5=(X)=>{for(let Y in X)return!0;return!1},Be6=class X{#X;#Y;#G;#Q=0;#J=SX1;constructor(Y,G,Q){if(this.#Y=Q||Object.create(null),this.#X=[],Y&&G){let J=Object.create(null);J[Y]={handler:G,possibleKeys:[],score:0},this.#X=[J]}this.#G=[]}insert(Y,G,Q){this.#Q=++this.#Q;let J=this,W=ms6(G),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],U=W[$+1],N=ds6(H,U),B=Array.isArray(N)?N[0]:H;if(B in J.#Y){if(J=J.#Y[B],N)Z.push(N[1]);continue}if(J.#Y[B]=new X,N)J.#G.push(N),Z.push(N[1]);J=J.#Y[B]}return J.#X.push({[Y]:{handler:Q,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#Q}}),J}#Z(Y,G,Q,J,W){for(let Z=0,$=G.#X.length;Z<$;Z++){let K=G.#X[Z],H=K[Q]||K[T7],U={};if(H!==void 0){if(H.params=Object.create(null),Y.push(H),J!==SX1||W&&W!==SX1)for(let N=0,B=H.possibleKeys.length;N<B;N++){let z=H.possibleKeys[N],O=U[H.score];H.params[z]=W?.[z]&&!O?W[z]:J[z]??W?.[z],U[H.score]=!0}}}}search(Y,G){let Q=[];this.#J=SX1;let W=[this],Z=nN0(G),$=[],K=Z.length,H=null;for(let U=0;U<K;U++){let N=Z[U],B=U===K-1,z=[];for(let w=0,E=W.length;w<E;w++){let P=W[w],q=P.#Y[N];if(q)if(q.#J=P.#J,B){if(q.#Y["*"])this.#Z(Q,q.#Y["*"],Y,P.#J);this.#Z(Q,q,Y,P.#J)}else z.push(q);for(let j=0,M=P.#G.length;j<M;j++){let V=P.#G[j],R=P.#J===SX1?{}:{...P.#J};if(V==="*"){let h=P.#Y["*"];if(h)this.#Z(Q,h,Y,P.#J),h.#J=R,z.push(h);continue}let[k,_,v]=V;if(!N&&!(v instanceof RegExp))continue;let y=P.#Y[k];if(v instanceof RegExp){if(H===null){H=Array(K);let p=G[0]==="/"?1:0;for(let f=0;f<K;f++)H[f]=p,p+=Z[f].length+1}let h=G.substring(H[U]),i=v.exec(h);if(i){if(R[_]=i[0],this.#Z(Q,y,Y,P.#J,R),Lp5(y.#Y)){y.#J=R;let p=i[0].match(/\//)?.length??0;($[p]||=[]).push(y)}continue}}if(v===!0||v.test(N))if(R[_]=N,B){if(this.#Z(Q,y,Y,R,P.#J),y.#Y["*"])this.#Z(Q,y.#Y["*"],Y,R,P.#J)}else y.#J=R,z.push(y)}}let O=$.shift();W=O?z.concat(O):z}if(Q.length>1)Q.sort((U,N)=>{return U.score-N.score});return[Q.map(({handler:U,params:N})=>[U,N])]}};var ze6=D(()=>{Pq();Eq();SX1=Object.create(null)});var GB0=class{name="TrieRouter";#X;constructor(){this.#X=new Be6}add(X,Y,G){let Q=SA1(Y);if(Q){for(let J=0,W=Q.length;J<W;J++)this.#X.insert(X,Q[J],G);return}this.#X.insert(X,Y,G)}match(X,Y){return this.#X.search(X,Y)}};var Oe6=D(()=>{Eq();ze6()});var De6=D(()=>{Oe6()});var R5;var we6=D(()=>{Qe6();Fe6();Ne6();De6();R5=class extends Ge6{constructor(X={}){super(X);this.router=X.router??new YB0({routers:[new xA1,new GB0]})}}});var ZQ=D(()=>{we6()});var Ee6,Ep5,Le6=(X)=>{let Y=0,G=X.length;while(Y<G){let Q=X.charCodeAt(Y);if(Q!==32&&Q!==9)break;Y++}while(G>Y){let Q=X.charCodeAt(G-1);if(Q!==32&&Q!==9)break;G--}return Y===0&&G===X.length?X:X.slice(Y,G)},QB0=(X,Y)=>{if(Y&&X.indexOf(Y)===-1)return{};let G=X.split(";"),Q={};for(let J of G){let W=J.indexOf("=");if(W===-1)continue;let Z=Le6(J.substring(0,W));if(Y&&Y!==Z||!Ee6.test(Z))continue;let $=Le6(J.substring(W+1));if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(Ep5.test($)){if(Q[Z]=$.indexOf("%")!==-1?ia($,TX1):$,Y)break}}return Q},Pp5=(X,Y,G={})=>{if(!Ee6.test(X))throw Error("Invalid cookie name");let Q=`${X}=${Y}`;if(X.startsWith("__Secure-")&&!G.secure)throw Error("__Secure- Cookie must have Secure attributes");if(X.startsWith("__Host-")){if(!G.secure)throw Error("__Host- Cookie must have Secure attributes");if(G.path!=="/")throw Error('__Host- Cookie must have Path attributes with "/"');if(G.domain)throw Error("__Host- Cookie must not have Domain attributes")}for(let J of["domain","path"])if(G[J]&&/[;\r\n]/.test(G[J]))throw Error(`${J} must not contain ";", "\\r", or "\\n"`);if(G&&typeof G.maxAge==="number"&&G.maxAge>=0){if(G.maxAge>34560000)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");Q+=`; Max-Age=${G.maxAge|0}`}if(G.domain&&G.prefix!=="host")Q+=`; Domain=${G.domain}`;if(G.path)Q+=`; Path=${G.path}`;if(G.expires){if(G.expires.getTime()-Date.now()>34560000000)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");Q+=`; Expires=${G.expires.toUTCString()}`}if(G.httpOnly)Q+="; HttpOnly";if(G.secure)Q+="; Secure";if(G.sameSite)Q+=`; SameSite=${G.sameSite.charAt(0).toUpperCase()+G.sameSite.slice(1)}`;if(G.priority)Q+=`; Priority=${G.priority.charAt(0).toUpperCase()+G.priority.slice(1)}`;if(G.partitioned){if(!G.secure)throw Error("Partitioned Cookie must have Secure attributes");Q+="; Partitioned"}return Q},hA1=(X,Y,G)=>{return Y=encodeURIComponent(Y),Pp5(X,Y,G)};var Pe6=D(()=>{Eq();Ee6=/^[\w!#$%&'*.^`|~+-]+$/,Ep5=/^[ !#-:<-[\]-~]*$/});var gA1=(X,Y,G)=>{let Q=X.req.raw.headers.get("Cookie");if(typeof Y==="string"){if(!Q)return;let W=Y;if(G==="secure")W="__Secure-"+Y;else if(G==="host")W="__Host-"+Y;return QB0(Q,W)[W]}if(!Q)return{};return QB0(Q)},qp5=(X,Y,G)=>{let Q;if(G?.prefix==="secure")Q=hA1("__Secure-"+X,Y,{path:"/",...G,secure:!0});else if(G?.prefix==="host")Q=hA1("__Host-"+X,Y,{...G,path:"/",secure:!0,domain:void 0});else Q=hA1(X,Y,{path:"/",...G});return Q},JB0=(X,Y,G,Q)=>{let J=qp5(Y,G,Q);X.header("Set-Cookie",J,{append:!0})};var ZB0=D(()=>{Pe6()});var qe6=(X)=>{let G={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...X},Q=((W)=>{if(typeof W==="string")if(W==="*"){if(G.credentials)return(Z)=>Z||null;return()=>W}else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(G.origin),J=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(G.allowMethods);return async function(Z,$){function K(U,N){Z.res.headers.set(U,N)}let H=await Q(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(G.credentials)K("Access-Control-Allow-Credentials","true");if(G.exposeHeaders?.length)K("Access-Control-Expose-Headers",G.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(G.origin!=="*"||G.credentials)K("Vary","Origin");if(G.maxAge!=null)K("Access-Control-Max-Age",G.maxAge.toString());let U=await J(Z.req.header("origin")||"",Z);if(U.length)K("Access-Control-Allow-Methods",U.join(","));let N=G.allowHeaders;if(!N?.length){let B=Z.req.header("Access-Control-Request-Headers");if(B)N=B.split(/\s*,\s*/)}if(N?.length)K("Access-Control-Allow-Headers",N.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),G.origin!=="*"||G.credentials)Z.header("Vary","Origin",{append:!0})}};var Ae6=()=>{};var Te6=()=>{try{return performance.now()}catch{}return Date.now()},WB0=(X)=>{let Y={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...X};return async function(Q,J){let W=[],Z=new Map;if(Q.get("metric"))return await J();if(Q.set("metric",{headers:W,timers:Z}),Y.total)OH(Q,"total",Y.totalDescription);if(await J(),Y.total)g$(Q,"total");if(Y.autoEnd)Z.forEach((K,H)=>g$(Q,H));if(typeof Y.enabled==="function"?Y.enabled(Q):Y.enabled){Q.res.headers.append("Server-Timing",W.join(","));let K=typeof Y.crossOrigin==="function"?Y.crossOrigin(Q):Y.crossOrigin;if(K)Q.res.headers.append("Timing-Allow-Origin",typeof K==="string"?K:"*")}}},Ie6=(X,Y,G,Q,J)=>{let W=X.get("metric");if(!W){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof G==="number"){let Z=G.toFixed(J||1),$=Q?`${Y};dur=${Z};desc="${Q}"`:`${Y};dur=${Z}`;W.headers.push($)}else{let Z=G?`${Y};desc="${G}"`:`${Y}`;W.headers.push(Z)}},OH=(X,Y,G)=>{let Q=X.get("metric");if(!Q){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}Q.timers.set(Y,{description:G,start:Te6()})},g$=(X,Y,G)=>{let Q=X.get("metric");if(!Q){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let J=Q.timers.get(Y);if(!J){console.warn(`Timer "${Y}" does not exist!`);return}let{description:W,start:Z}=J,$=Te6()-Z;Ie6(X,Y,$,W,G),Q.timers.delete(Y)};var Ve6=D(()=>{vA1()});var $B0=D(()=>{Ve6()});function CX1(){let X={Organizations:[],Connections:[],"Virtual MCPs":[],Threads:[],Monitoring:[],Users:[],"API Keys":[],"Event Bus":[],Tags:[],"AI Providers":[],Automations:[],"Object Storage":[],Registry:[],GitHub:[],VM:[]};for(let Y of KB0)X[Y.category]?.push(Y);return X}var KB0;var HB0=D(()=>{KB0=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"BRAND_CONTEXT_LIST",description:"List brand contexts",category:"Organizations"},{name:"BRAND_CONTEXT_GET",description:"View brand context",category:"Organizations"},{name:"BRAND_CONTEXT_CREATE",description:"Create brand context",category:"Organizations"},{name:"BRAND_CONTEXT_UPDATE",description:"Update brand context",category:"Organizations"},{name:"BRAND_CONTEXT_DELETE",description:"Delete brand context",category:"Organizations",dangerous:!0},{name:"BRAND_CONTEXT_EXTRACT",description:"Extract brand context from website",category:"Organizations"},{name:"BRAND_GET",description:"Get brand (binding)",category:"Organizations"},{name:"BRAND_LIST",description:"List brands (binding)",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_GET",description:"Get organization domain claim",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_SET",description:"Set organization domain claim",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_UPDATE",description:"Update organization domain settings",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_CLEAR",description:"Clear organization domain claim",category:"Organizations"},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_GET",description:"View virtual MCP details",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete virtual MCPs",category:"Virtual MCPs",dangerous:!0},{name:"MONITORING_LOG_GET",description:"View monitoring log details",category:"Monitoring"},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"EVENT_PUBLISH",description:"Publish events",category:"Event Bus"},{name:"EVENT_SUBSCRIBE",description:"Subscribe to events",category:"Event Bus"},{name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events",category:"Event Bus"},{name:"EVENT_CANCEL",description:"Cancel recurring events",category:"Event Bus"},{name:"EVENT_ACK",description:"Acknowledge event delivery",category:"Event Bus"},{name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions",category:"Event Bus"},{name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state",category:"Event Bus"},{name:"USER_GET",description:"Get a user by id",category:"Users"},{name:"COLLECTION_THREADS_CREATE",description:"Create threads",category:"Threads"},{name:"COLLECTION_THREADS_LIST",description:"List threads",category:"Threads"},{name:"COLLECTION_THREADS_GET",description:"View thread details",category:"Threads"},{name:"COLLECTION_THREADS_UPDATE",description:"Update threads",category:"Threads"},{name:"COLLECTION_THREADS_DELETE",description:"Delete threads",category:"Threads",dangerous:!0},{name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List thread messages",category:"Threads"},{name:"TAGS_LIST",description:"List organization tags",category:"Tags"},{name:"TAGS_CREATE",description:"Create organization tag",category:"Tags"},{name:"TAGS_DELETE",description:"Delete organization tag",category:"Tags",dangerous:!0},{name:"MEMBER_TAGS_GET",description:"Get member tags",category:"Tags"},{name:"MEMBER_TAGS_SET",description:"Set member tags",category:"Tags"},{name:"AUTOMATION_CREATE",description:"Create automation",category:"Automations"},{name:"AUTOMATION_GET",description:"View automation details",category:"Automations"},{name:"AUTOMATION_LIST",description:"List automations",category:"Automations"},{name:"AUTOMATION_UPDATE",description:"Update automation",category:"Automations"},{name:"AUTOMATION_DELETE",description:"Delete automation",category:"Automations",dangerous:!0},{name:"AUTOMATION_TRIGGER_ADD",description:"Add trigger to automation",category:"Automations"},{name:"AUTOMATION_TRIGGER_REMOVE",description:"Remove trigger from automation",category:"Automations"},{name:"AUTOMATION_RUN",description:"Manually trigger an automation run",category:"Automations"},{name:"VIRTUAL_MCP_PLUGIN_CONFIG_GET",description:"View virtual MCP plugin configuration",category:"Virtual MCPs"},{name:"VIRTUAL_MCP_PLUGIN_CONFIG_UPDATE",description:"Update virtual MCP plugin configuration",category:"Virtual MCPs"},{name:"VIRTUAL_MCP_PINNED_VIEWS_UPDATE",description:"Update virtual MCP pinned sidebar views",category:"Virtual MCPs"},{name:"AI_PROVIDERS_LIST",description:"List available AI providers",category:"AI Providers"},{name:"AI_PROVIDERS_LIST_MODELS",description:"List AI provider models",category:"AI Providers"},{name:"AI_PROVIDERS_ACTIVE",description:"List active AI providers",category:"AI Providers"},{name:"AI_PROVIDER_KEY_CREATE",description:"Store AI provider API key",category:"AI Providers"},{name:"AI_PROVIDER_KEY_LIST",description:"List AI provider API keys",category:"AI Providers"},{name:"AI_PROVIDER_KEY_DELETE",description:"Delete AI provider API key",category:"AI Providers",dangerous:!0},{name:"AI_PROVIDER_OAUTH_URL",description:"Get OAuth URL for provider",category:"AI Providers"},{name:"AI_PROVIDER_OAUTH_EXCHANGE",description:"Exchange OAuth code for API key",category:"AI Providers"},{name:"AI_PROVIDER_PROVISION_KEY",description:"Auto-provision API key for a provider",category:"AI Providers"},{name:"AI_PROVIDER_TOPUP_URL",description:"Get checkout URL to top up provider credits",category:"AI Providers"},{name:"AI_PROVIDER_CREDITS",description:"Get current credit balance for a provider",category:"AI Providers"},{name:"AI_PROVIDER_CLI_ACTIVATE",description:"Activate Claude Code via local CLI",category:"AI Providers"},{name:"LIST_OBJECTS",description:"List objects in storage",category:"Object Storage"},{name:"GET_OBJECT_METADATA",description:"Get object metadata",category:"Object Storage"},{name:"GET_PRESIGNED_URL",description:"Generate download URL",category:"Object Storage"},{name:"PUT_PRESIGNED_URL",description:"Generate upload URL",category:"Object Storage"},{name:"DELETE_OBJECT",description:"Delete object",category:"Object Storage",dangerous:!0},{name:"DELETE_OBJECTS",description:"Delete multiple objects",category:"Object Storage",dangerous:!0},{name:"COLLECTION_REGISTRY_APP_LIST",description:"List registry apps",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_GET",description:"Get registry app details",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_VERSIONS",description:"List registry app versions",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_FILTERS",description:"Get registry app filters",category:"Registry"},{name:"REGISTRY_ITEM_LIST",description:"List private registry items",category:"Registry"},{name:"REGISTRY_ITEM_SEARCH",description:"Search registry items",category:"Registry"},{name:"REGISTRY_ITEM_GET",description:"Get registry item details",category:"Registry"},{name:"REGISTRY_ITEM_VERSIONS",description:"List registry item versions",category:"Registry"},{name:"REGISTRY_ITEM_CREATE",description:"Create registry item",category:"Registry"},{name:"REGISTRY_ITEM_BULK_CREATE",description:"Bulk create registry items",category:"Registry"},{name:"REGISTRY_ITEM_UPDATE",description:"Update registry item",category:"Registry"},{name:"REGISTRY_ITEM_DELETE",description:"Delete registry item",category:"Registry",dangerous:!0},{name:"REGISTRY_ITEM_FILTERS",description:"Get registry item filters",category:"Registry"},{name:"REGISTRY_DISCOVER_TOOLS",description:"Discover tools from MCP server",category:"Registry"},{name:"REGISTRY_AI_GENERATE",description:"AI-generate registry content",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_LIST",description:"List publish requests",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_REVIEW",description:"Review publish request",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_COUNT",description:"Count pending publish requests",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_DELETE",description:"Delete publish request",category:"Registry",dangerous:!0},{name:"REGISTRY_PUBLISH_API_KEY_GENERATE",description:"Generate publish API key",category:"Registry"},{name:"REGISTRY_PUBLISH_API_KEY_LIST",description:"List publish API keys",category:"Registry"},{name:"REGISTRY_PUBLISH_API_KEY_REVOKE",description:"Revoke publish API key",category:"Registry",dangerous:!0},{name:"REGISTRY_MONITOR_RUN_START",description:"Start monitor run",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_LIST",description:"List monitor runs",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_GET",description:"Get monitor run details",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_CANCEL",description:"Cancel monitor run",category:"Registry"},{name:"REGISTRY_MONITOR_RESULT_LIST",description:"List monitor results",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_LIST",description:"List monitor connections",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_SYNC",description:"Sync monitor connections",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_UPDATE_AUTH",description:"Update monitor connection auth",category:"Registry"},{name:"REGISTRY_MONITOR_SCHEDULE_SET",description:"Set monitor schedule",category:"Registry"},{name:"REGISTRY_MONITOR_SCHEDULE_CANCEL",description:"Cancel monitor schedule",category:"Registry"},{name:"VM_START",description:"Start a Freestyle VM with dev server preview",category:"VM"},{name:"VM_DELETE",description:"Stop and delete a Freestyle VM",category:"VM"},{name:"GITHUB_LIST_USER_ORGS",description:"List GitHub user's personal account and organizations",category:"GitHub"}]});var je6=D(()=>{oi();tz1()});function Me6(){return Tp5.parse(process.env)}var FB0=(X)=>F.enum(["true","false","1","0"]).optional().transform((Y)=>Y===void 0?X:Y==="true"||Y==="1"),Ap5=(X)=>F.string().optional().transform((Y)=>Y?Y.split(",").map((G)=>G.trim()):X),Tp5;var Re6=D(()=>{H0();Tp5=F.object({AUTH_EMAIL_PASSWORD_ENABLED:FB0(!0),AUTH_GOOGLE_CLIENT_ID:F.string().optional(),AUTH_GOOGLE_CLIENT_SECRET:F.string().optional(),AUTH_GITHUB_CLIENT_ID:F.string().optional(),AUTH_GITHUB_CLIENT_SECRET:F.string().optional(),AUTH_RESEND_API_KEY:F.string().optional(),AUTH_RESEND_FROM_EMAIL:F.string().optional(),AUTH_SENDGRID_API_KEY:F.string().optional(),AUTH_SENDGRID_FROM_EMAIL:F.string().optional(),AUTH_INVITE_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_RESET_PASSWORD_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_MAGIC_LINK_ENABLED:FB0(!1),AUTH_MAGIC_LINK_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_ENABLED:FB0(!1),AUTH_EMAIL_OTP_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_LENGTH:F.coerce.number().optional(),AUTH_EMAIL_OTP_EXPIRES_IN:F.coerce.number().optional(),AUTH_SSO_DOMAIN:F.string().optional(),AUTH_SSO_MS_TENANT_ID:F.string().optional(),AUTH_SSO_MS_CLIENT_ID:F.string().optional(),AUTH_SSO_MS_CLIENT_SECRET:F.string().optional(),AUTH_SSO_SCOPES:Ap5(["openid","email","profile"])}).transform((X)=>{let Y={};if(X.AUTH_GOOGLE_CLIENT_ID)Y.google={clientId:X.AUTH_GOOGLE_CLIENT_ID,clientSecret:X.AUTH_GOOGLE_CLIENT_SECRET??""};if(X.AUTH_GITHUB_CLIENT_ID)Y.github={clientId:X.AUTH_GITHUB_CLIENT_ID,clientSecret:X.AUTH_GITHUB_CLIENT_SECRET??""};let G=[];if(X.AUTH_RESEND_API_KEY)G.push({id:"resend",provider:"resend",config:{apiKey:X.AUTH_RESEND_API_KEY,fromEmail:X.AUTH_RESEND_FROM_EMAIL??"noreply@example.com"}});if(X.AUTH_SENDGRID_API_KEY)G.push({id:"sendgrid",provider:"sendgrid",config:{apiKey:X.AUTH_SENDGRID_API_KEY,fromEmail:X.AUTH_SENDGRID_FROM_EMAIL??"noreply@example.com"}});let Q=G[0]?.id,J;if(X.AUTH_SSO_MS_CLIENT_ID&&X.AUTH_SSO_DOMAIN)J={providerId:"microsoft",domain:X.AUTH_SSO_DOMAIN,MS_TENANT_ID:X.AUTH_SSO_MS_TENANT_ID??"",MS_CLIENT_ID:X.AUTH_SSO_MS_CLIENT_ID,MS_CLIENT_SECRET:X.AUTH_SSO_MS_CLIENT_SECRET??"",scopes:X.AUTH_SSO_SCOPES};let W;if(X.AUTH_MAGIC_LINK_ENABLED)W={enabled:!0,emailProviderId:X.AUTH_MAGIC_LINK_EMAIL_PROVIDER??Q??""};let Z;if(X.AUTH_EMAIL_OTP_ENABLED)Z={enabled:!0,emailProviderId:X.AUTH_EMAIL_OTP_EMAIL_PROVIDER??Q??"",...X.AUTH_EMAIL_OTP_LENGTH!==void 0&&{otpLength:X.AUTH_EMAIL_OTP_LENGTH},...X.AUTH_EMAIL_OTP_EXPIRES_IN!==void 0&&{expiresIn:X.AUTH_EMAIL_OTP_EXPIRES_IN}};return{emailAndPassword:{enabled:X.AUTH_EMAIL_PASSWORD_ENABLED},socialProviders:Object.keys(Y).length>0?Y:void 0,emailProviders:G.length>0?G:void 0,inviteEmailProviderId:X.AUTH_INVITE_EMAIL_PROVIDER,resetPasswordEmailProviderId:X.AUTH_RESET_PASSWORD_EMAIL_PROVIDER,ssoConfig:J,magicLinkConfig:W,emailOtpConfig:Z}})});var uA1;var Se6=D(()=>{uA1={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"}});import{existsSync as Ip5,readFileSync as Vp5}from"fs";function jp5(){let X=Me6(),Y=v6().configPath;if(!Ip5(Y))return{auth:X,monitoring:uA1};try{let G=JSON.parse(Vp5(Y,"utf-8"));if(G.auth)console.warn("[config] DEPRECATION: 'auth' key found in config.json. Auth is now configured via AUTH_* environment variables. The 'auth' key will be ignored.");return{auth:X,monitoring:G.monitoring??uA1,theme:G.theme,logo:G.logo,autoCreateOrganizationOnSignup:G.autoCreateOrganizationOnSignup}}catch{return{auth:X,monitoring:uA1}}}function Vj(){if(!UB0)UB0=jp5();return UB0}function Ce6(){return Vj().theme}var UB0=null;var NB0=D(()=>{Re6();Se6();m9()});import{dirname as Mp5,posix as Rp5,sep as Sp5}from"path";function ve6(){let X=Cp5();return async(Y)=>{for(let G of Y)G.module=X(G.filename);return Y}}function Cp5(X=process.argv[1]?Mp5(process.argv[1]):process.cwd(),Y=Sp5==="\\"){let G=Y?ke6(X):X;return(Q)=>{if(!Q)return;let J=Y?ke6(Q):Q,{dir:W,base:Z,ext:$}=Rp5.parse(J);if($===".js"||$===".mjs"||$===".cjs")Z=Z.slice(0,-1*$.length);let K=decodeURIComponent(Z);if(!W)W=".";let H=W.lastIndexOf("/node_modules");if(H>-1)return`${W.slice(H+14).replace(/\//g,".")}:${K}`;if(W.startsWith(G)){let U=W.slice(G.length+1).replace(/\//g,".");return U?`${U}:${K}`:K}return K}}function ke6(X){return X.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var _e6=()=>{};function kp5(X,Y,G){return{key:X,enabled:typeof Y=="string"?!0:Y,variant:typeof Y=="string"?Y:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:G?JSON.stringify(G):void 0,description:void 0}}}var BB0=(X)=>{if("flags"in X){let Y=fe6(X.flags),G=be6(X.flags);return{...X,featureFlags:Y,featureFlagPayloads:G}}{let Y=X.featureFlags??{},G=Object.fromEntries(Object.entries(X.featureFlagPayloads||{}).map(([J,W])=>[J,zB0(W)])),Q=Object.fromEntries(Object.entries(Y).map(([J,W])=>[J,kp5(J,W,G[J])]));return{...X,featureFlags:Y,featureFlagPayloads:G,flags:Q}}},fe6=(X)=>Object.fromEntries(Object.entries(X??{}).map(([Y,G])=>[Y,kX1(G)]).filter(([,Y])=>Y!==void 0)),be6=(X)=>{let Y=X??{};return Object.fromEntries(Object.keys(Y).filter((G)=>{let Q=Y[G];return Q.enabled&&Q.metadata&&Q.metadata.payload!==void 0}).map((G)=>{let Q=Y[G].metadata?.payload;return[G,Q?zB0(Q):void 0]}))},kX1=(X)=>X===void 0?void 0:X.variant??X.enabled,zB0=(X)=>{if(typeof X!="string")return X;try{return JSON.parse(X)}catch{return X}};var lA1=()=>{};function ye6(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}async function mA1(X,Y=!0,G){try{let Q=new CompressionStream("gzip"),J=Q.writable.getWriter(),W=J.write(new TextEncoder().encode(X)).then(()=>J.close()).catch(async(K)=>{try{await J.abort(K)}catch{}throw K}),Z=new Response(Q.readable).blob(),[$]=await Promise.all([Z,W]);return $}catch(Q){if(G?.rethrow)throw Q;if(Y)console.error("Failed to gzip compress data",Q);return null}}var OB0=()=>{};var vp5,xe6=function(X,Y=[]){if(!X)return!1;let G=X.toLowerCase();return vp5.concat(Y).some((Q)=>{let J=Q.toLowerCase();return G.indexOf(J)!==-1})};var he6=D(()=>{vp5=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"]});var nJ;var jj=D(()=>{nJ=function(X){return X.AnonymousId="anonymous_id",X.DistinctId="distinct_id",X.Props="props",X.EnablePersonProcessing="enable_person_processing",X.PersonMode="person_mode",X.FeatureFlagDetails="feature_flag_details",X.FeatureFlags="feature_flags",X.FeatureFlagPayloads="feature_flag_payloads",X.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",X.BootstrapFeatureFlags="bootstrap_feature_flags",X.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",X.OverrideFeatureFlags="override_feature_flags",X.Queue="queue",X.LogsQueue="logs_queue",X.OptedOut="opted_out",X.SessionId="session_id",X.SessionStartTimestamp="session_start_timestamp",X.SessionLastTimestamp="session_timestamp",X.PersonProperties="person_properties",X.GroupProperties="group_properties",X.InstalledAppBuild="installed_app_build",X.InstalledAppVersion="installed_app_version",X.SessionReplay="session_replay",X.SurveyLastSeenDate="survey_last_seen_date",X.SurveysSeen="surveys_seen",X.Surveys="surveys",X.RemoteConfig="remote_config",X.FlagsEndpointWasHit="flags_endpoint_was_hit",X.DeviceId="device_id",X}({})});var dA1=()=>{};function iA1(X){return X===null||typeof X!="object"}function Mj(X,Y){return Object.prototype.toString.call(X)===`[object ${Y}]`}function le6(X){return Mj(X,"ErrorEvent")}function aa(X){return typeof Event<"u"&&bp5(X,Event)}function me6(X){return Mj(X,"Object")}function bp5(X,Y){try{return X instanceof Y}catch{return!1}}var fp5,ge6,llX,DB0,cA1,vX1=(X)=>X===Object(X)&&!cA1(X),na=(X)=>X===void 0,qq=(X)=>DB0.call(X)=="[object String]",ue6=(X)=>qq(X)&&X.trim().length===0,_X1=(X)=>DB0.call(X)=="[object Number]"&&X===X,wB0=(X)=>X instanceof Error;var fX1=D(()=>{jj();dA1();fp5=Array.isArray,ge6=Object.prototype,llX=ge6.hasOwnProperty,DB0=ge6.toString,cA1=fp5||function(X){return DB0.call(X)==="[object Array]"}});function bX1(X,Y,G,Q,J){if(Y>G)Q.warn("min cannot be greater than max."),Y=G;if(_X1(X))if(X>G)return Q.warn(" cannot be greater than max: "+G+". Using max value instead."),G;else{if(!(X<Y))return X;return Q.warn(" cannot be less than min: "+Y+". Using min value instead."),Y}return Q.warn(" must be a number. using max or fallback. max: "+G+", fallback: "+J),bX1(J||G,Y,G,Q)}var LB0=D(()=>{fX1()});class EB0{constructor(X){this._buckets={},this._onBucketRateLimited=X._onBucketRateLimited,this._bucketSize=bX1(X.bucketSize,0,100,X._logger),this._refillRate=bX1(X.refillRate,0,this._bucketSize,X._logger),this._refillInterval=bX1(X.refillInterval,0,yp5,X._logger)}_applyRefill(X,Y){let G=Y-X.lastAccess,Q=Math.floor(G/this._refillInterval);if(Q>0){let J=Q*this._refillRate;X.tokens=Math.min(X.tokens+J,this._bucketSize),X.lastAccess=X.lastAccess+Q*this._refillInterval}}consumeRateLimit(X){let Y=Date.now(),G=String(X),Q=this._buckets[G];if(Q)this._applyRefill(Q,Y);else Q={tokens:this._bucketSize,lastAccess:Y},this._buckets[G]=Q;if(Q.tokens===0)return!0;if(Q.tokens--,Q.tokens===0)this._onBucketRateLimited?.(X);return Q.tokens===0}stop(){this._buckets={}}}var yp5=86400000;var de6=D(()=>{LB0()});class Rj{constructor(X){this.bytes=X}static ofInner(X){if(X.length===16)return new Rj(X);throw TypeError("not 128-bit length")}static fromFieldsV7(X,Y,G,Q){if(!Number.isInteger(X)||!Number.isInteger(Y)||!Number.isInteger(G)||!Number.isInteger(Q)||X<0||Y<0||G<0||Q<0||X>281474976710655||Y>4095||G>1073741823||Q>4294967295)throw RangeError("invalid field value");let J=new Uint8Array(16);return J[0]=X/1099511627776,J[1]=X/4294967296,J[2]=X/16777216,J[3]=X/65536,J[4]=X/256,J[5]=X,J[6]=112|Y>>>8,J[7]=Y,J[8]=128|G>>>24,J[9]=G>>>16,J[10]=G>>>8,J[11]=G,J[12]=Q>>>24,J[13]=Q>>>16,J[14]=Q>>>8,J[15]=Q,new Rj(J)}static parse(X){let Y;switch(X.length){case 32:Y=/^[0-9a-f]{32}$/i.exec(X)?.[0];break;case 36:Y=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(X)?.slice(1,6).join("");break;case 38:Y=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(X)?.slice(1,6).join("");break;case 45:Y=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(X)?.slice(1,6).join("");break;default:break}if(Y){let G=new Uint8Array(16);for(let Q=0;Q<16;Q+=4){let J=parseInt(Y.substring(2*Q,2*Q+8),16);G[Q+0]=J>>>24,G[Q+1]=J>>>16,G[Q+2]=J>>>8,G[Q+3]=J}return new Rj(G)}throw SyntaxError("could not parse UUID string")}toString(){let X="";for(let Y=0;Y<this.bytes.length;Y++)if(X+="0123456789abcdef".charAt(this.bytes[Y]>>>4),X+="0123456789abcdef".charAt(15&this.bytes[Y]),Y===3||Y===5||Y===7||Y===9)X+="-";return X}toHex(){let X="";for(let Y=0;Y<this.bytes.length;Y++)X+="0123456789abcdef".charAt(this.bytes[Y]>>>4),X+="0123456789abcdef".charAt(15&this.bytes[Y]);return X}toJSON(){return this.toString()}getVariant(){let X=this.bytes[8]>>>4;if(X<0)throw Error("unreachable");if(X<=7)return this.bytes.every((Y)=>Y===0)?"NIL":"VAR_0";if(X<=11)return"VAR_10";if(X<=13)return"VAR_110";if(X<=15)return this.bytes.every((Y)=>Y===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new Rj(this.bytes.slice(0))}equals(X){return this.compareTo(X)===0}compareTo(X){for(let Y=0;Y<16;Y++){let G=this.bytes[Y]-X.bytes[Y];if(G!==0)return Math.sign(G)}return 0}}class ie6{constructor(X){this.timestamp=0,this.counter=0,this.random=X??xp5()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(X,Y){let G=this.generateOrAbortCore(X,Y);if(G===void 0)this.timestamp=0,G=this.generateOrAbortCore(X,Y);return G}generateOrAbortCore(X,Y){if(!Number.isInteger(X)||X<1||X>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(Y<0||Y>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(X>this.timestamp)this.timestamp=X,this.resetCounter();else{if(!(X+Y>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return Rj.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let X=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return X[6]=64|X[6]>>>4,X[8]=128|X[8]>>>2,Rj.ofInner(X)}}var xp5=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),ce6,Aq=()=>hp5().toString(),hp5=()=>(ce6||(ce6=new ie6)).generate();var yX1=D(()=>{/*! For license information please see uuidv7.mjs.LICENSE.txt */});class PB0{add(X){let Y=Aq();return this.promiseByIds[Y]=X,X.catch(()=>{}).finally(()=>{delete this.promiseByIds[Y]}),X}async join(){let X=Object.values(this.promiseByIds),Y=X.length;while(Y>0)await Promise.all(X),X=Object.values(this.promiseByIds),Y=X.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}}var pe6=D(()=>{yX1()});function gp5(X=console){return{log:X.log.bind(X),warn:X.warn.bind(X),error:X.error.bind(X),debug:X.debug.bind(X)}}function ae6(X,Y=up5){return ne6(X,Y,gp5())}var ne6=(X,Y,G)=>{function Q(W,...Z){Y(()=>{let $=G[W];$(X,...Z)})}return{info:(...W)=>{Q("log",...W)},warn:(...W)=>{Q("warn",...W)},error:(...W)=>{Q("error",...W)},critical:(...W)=>{G.error(X,...W)},createLogger:(W)=>ne6(`${X} ${W}`,Y,G)}},up5=(X)=>X();var te6=()=>{};var ra="Mobile",nA1="iOS",ta="Android",re6="Tablet",elX,mp5="Apple",XmX,oe6="Safari",aA1="BlackBerry",se6="Samsung",dp5,cp5,tA1="Chrome",ip5,pp5,ee6="Internet Explorer",np5,AB0="Opera",YmX,X14="Edge",ap5,TB0="Firefox",tp5,IB0="Nintendo",VB0="PlayStation",pA1="Xbox",rp5,op5,xX1="Windows",sp5,Y14="Generic",GmX,QmX,ep5="Konqueror",H3="(\\d+(\\.\\d+)?)",qB0,JmX,ZmX,WmX,Xn5,Yn5,$mX,KmX;var G14=D(()=>{dA1();fX1();elX=ta+" "+re6,XmX=mp5+" Watch",dp5=se6+"Browser",cp5=se6+" Internet",ip5=tA1+" OS",pp5=tA1+" "+nA1,np5=ee6+" "+ra,YmX=AB0+" Mini",ap5="Microsoft "+X14,tp5=TB0+" "+nA1,rp5=ta+" "+ra,op5=ra+" "+oe6,sp5=xX1+" Phone",GmX=Y14+" "+ra.toLowerCase(),QmX=Y14+" "+re6.toLowerCase(),qB0=new RegExp("Version/"+H3),JmX=new RegExp(pA1,"i"),ZmX=new RegExp(VB0+" \\w+","i"),WmX=new RegExp(IB0+" \\w+","i"),Xn5=new RegExp(aA1+"|PlayBook|BB10","i"),Yn5={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"},$mX={[np5]:[new RegExp("rv:"+H3)],[ap5]:[new RegExp(X14+"?\\/"+H3)],[tA1]:[new RegExp("("+tA1+"|CrMo)\\/"+H3)],[pp5]:[new RegExp("CriOS\\/"+H3)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+H3)],[oe6]:[qB0],[op5]:[qB0],[AB0]:[new RegExp("("+AB0+"|OPR)\\/"+H3)],[TB0]:[new RegExp(TB0+"\\/"+H3)],[tp5]:[new RegExp("FxiOS\\/"+H3)],[ep5]:[new RegExp("Konqueror[:/]?"+H3,"i")],[aA1]:[new RegExp(aA1+" "+H3),qB0],[rp5]:[new RegExp("android\\s"+H3,"i")],[cp5]:[new RegExp(dp5+"\\/"+H3)],[ee6]:[new RegExp("(rv:|MSIE )"+H3)],Mozilla:[new RegExp("rv:"+H3)]},KmX=[[new RegExp(pA1+"; "+pA1+" (.*?)[);]","i"),(X)=>[pA1,X&&X[1]||""]],[new RegExp(IB0,"i"),[IB0,""]],[new RegExp(VB0,"i"),[VB0,""]],[Xn5,[aA1,""]],[new RegExp(xX1,"i"),(X,Y)=>{if(/Phone/.test(Y)||/WPDesktop/.test(Y))return[sp5,""];if(new RegExp(ra).test(Y)&&!/IEMobile\b/.test(Y))return[xX1+" "+ra,""];let G=/Windows NT ([0-9.]+)/i.exec(Y);if(G&&G[1]){let Q=G[1],J=Yn5[Q]||"";if(/arm/i.test(Y))J="RT";return[xX1,J]}return[xX1,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(X)=>{if(X&&X[3]){let Y=[X[3],X[4],X[5]||"0"];return[nA1,Y.join(".")]}return[nA1,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(X)=>{let Y="";if(X&&X.length>=3)Y=na(X[2])?X[3]:X[2];return["watchOS",Y]}],[new RegExp("("+ta+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+ta+")","i"),(X)=>{if(X&&X[2]){let Y=[X[2],X[3],X[4]||"0"];return[ta,Y.join(".")]}return[ta,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(X)=>{let Y=["Mac OS X",""];if(X&&X[1]){let G=[X[1],X[2],X[3]||"0"];Y[1]=G.join(".")}return Y}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[ip5,""]],[/Linux|debian/i,["Linux",""]]]});function J14(X){return X?.replace(/\/+$/,"")}async function Z14(X,Y){let G=null;for(let Q=0;Q<Y.retryCount+1;Q++){if(Q>0)await new Promise((J)=>setTimeout(J,Y.retryDelay));try{return await X()}catch(J){if(G=J,!Y.retryCheck(J))throw J}}throw G}function rA1(){return new Date().toISOString()}function Hw(X,Y){let G=setTimeout(X,Y);return G?.unref&&G?.unref(),G}function jB0(X){return Promise.all(X.map((Y)=>(Y??Promise.resolve()).then((G)=>({status:"fulfilled",value:G}),(G)=>({status:"rejected",reason:G}))))}var Q14="utf8",W14=(X)=>X instanceof Error;var F3=D(()=>{he6();de6();LB0();dA1();fX1();pe6();te6();G14()});var Gn5,AmX;var MB0=D(()=>{F3();Gn5={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},AmX=Gn5.info});var $14=D(()=>{MB0();jj()});var K14=D(()=>{jj()});class RB0{constructor(){this.events={},this.events={}}on(X,Y){if(!this.events[X])this.events[X]=[];return this.events[X].push(Y),()=>{this.events[X]=this.events[X].filter((G)=>G!==Y)}}emit(X,Y){for(let G of this.events[X]||[])G(Y);for(let G of this.events["*"]||[])G(X,Y)}}var H14=()=>{};async function F14(X){if(X instanceof oa){let Y="";try{Y=await X.text}catch{}console.error(`Error while flushing PostHog: message=${X.message}, response body=${Y}`,X)}else console.error("Error while flushing PostHog",X);return Promise.resolve()}function SB0(X){return typeof X=="object"&&(X instanceof oa||X instanceof hX1)}function U14(X){return typeof X=="object"&&X instanceof oa&&X.status===413}class oA1{constructor(X,Y={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new PB0,this._events=new RB0,this._isInitialized=!1;let G=typeof X=="string"?X.trim():"",Q=typeof Y.host=="string"?Y.host.trim():"",J=!G;if(this._logger=ae6("[PostHog]",this.logMsgIfDebug.bind(this)),J)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=G,this.host=J14(Q||"https://us.i.posthog.com"),this.flushAt=Y.flushAt?Math.max(Y.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,Y.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,Y.maxQueueSize??1000),this.flushInterval=Y.flushInterval??1e4,this.preloadFeatureFlags=Y.preloadFeatureFlags??!0,this.defaultOptIn=Y.defaultOptIn??!0,this.disableSurveys=Y.disableSurveys??!1,this._retryOptions={retryCount:Y.fetchRetryCount??3,retryDelay:Y.fetchRetryDelay??3000,retryCheck:SB0},this.requestTimeout=Y.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=Y.featureFlagsRequestTimeoutMs??3000,this.remoteConfigRequestTimeoutMs=Y.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=Y.disableGeoip??!0,this.disabled=(Y.disabled??!1)||J,this.historicalMigration=Y?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=Y?.evaluationContexts??Y?.evaluationEnvironments,Y?.evaluationEnvironments&&!Y?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!ye6()||(Y?.disableCompression??!1)}logMsgIfDebug(X){if(this.isDebug)X()}wrap(X){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return X();this._initPromise.then(()=>X())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(nJ.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(nJ.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(nJ.OptedOut,!0)})}on(X,Y){return this._events.on(X,Y)}debug(X=!0){if(this.removeDebugCallback?.(),X){let Y=this.on("*",(G,Q)=>this._logger.info(G,Q));this.removeDebugCallback=()=>{Y(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(X){return{distinct_id:X.distinct_id,event:X.event,properties:{...X.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(X){return this.promiseQueue.add(X)}identifyStateless(X,Y,G){this.wrap(()=>{let Q={...this.buildPayload({distinct_id:X,event:"$identify",properties:Y})};this.enqueue("identify",Q,G)})}async identifyStatelessImmediate(X,Y,G){let Q={...this.buildPayload({distinct_id:X,event:"$identify",properties:Y})};await this.sendImmediate("identify",Q,G)}captureStateless(X,Y,G,Q){this.wrap(()=>{let J=this.buildPayload({distinct_id:X,event:Y,properties:G});this.enqueue("capture",J,Q)})}async captureStatelessImmediate(X,Y,G,Q){let J=this.buildPayload({distinct_id:X,event:Y,properties:G});await this.sendImmediate("capture",J,Q)}aliasStateless(X,Y,G,Q){this.wrap(()=>{let J=this.buildPayload({event:"$create_alias",distinct_id:Y,properties:{...G||{},distinct_id:Y,alias:X}});this.enqueue("alias",J,Q)})}async aliasStatelessImmediate(X,Y,G,Q){let J=this.buildPayload({event:"$create_alias",distinct_id:Y,properties:{...G||{},distinct_id:Y,alias:X}});await this.sendImmediate("alias",J,Q)}groupIdentifyStateless(X,Y,G,Q,J,W){this.wrap(()=>{let Z=this.buildPayload({distinct_id:J||`$${X}_${Y}`,event:"$groupidentify",properties:{$group_type:X,$group_key:Y,$group_set:G||{},...W||{}}});this.enqueue("capture",Z,Q)})}async getRemoteConfig(){await this._initPromise;let X=this.host;if(X==="https://us.i.posthog.com")X="https://us-assets.i.posthog.com";else if(X==="https://eu.i.posthog.com")X="https://eu-assets.i.posthog.com";let Y=`${X}/array/${this.apiKey}/config`,G={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(Y,G,{retryCount:0},this.remoteConfigRequestTimeoutMs).then((Q)=>Q.json()).catch((Q)=>{this._logger.error("Remote config could not be loaded",Q),this._events.emit("error",Q)})}async getFlags(X,Y={},G={},Q={},J={},W=!1){await this._initPromise;let Z=W?"&config=true":"",$=`${this.host}/flags/?v=2${Z}`,K={token:this.apiKey,distinct_id:X,groups:Y,person_properties:G,group_properties:Q,...J};if(G.$device_id)K.$device_id=G.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)K.evaluation_contexts=this.evaluationContexts;let H={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(K)};return this._logger.info("Flags URL",$),this.fetchWithRetry($,H,{retryCount:0},this.featureFlagsRequestTimeoutMs).then((U)=>U.json()).then((U)=>({success:!0,response:BB0(U)})).catch((U)=>{return this._events.emit("error",U),{success:!1,error:this.categorizeRequestError(U)}})}categorizeRequestError(X){if(X instanceof oa)return{type:"api_error",statusCode:X.status};if(X instanceof hX1){let Y=X.error;if(Y instanceof Error&&(Y.name==="AbortError"||Y.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagDetailStateless(X,Y,G,Q,J,W);if(Z===void 0)return{response:void 0,requestId:void 0};let $=kX1(Z.response);if($===void 0)$=!1;return{response:$,requestId:Z.requestId}}async getFeatureFlagDetailStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagDetailsStateless(Y,G,Q,J,W,[X]);if(Z===void 0)return;return{response:Z.flags[X],requestId:Z.requestId,evaluatedAt:Z.evaluatedAt}}async getFeatureFlagPayloadStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagPayloadsStateless(Y,G,Q,J,W,[X]);if(!Z)return;let $=Z[X];if($===void 0)return null;return $}async getFeatureFlagPayloadsStateless(X,Y={},G={},Q={},J,W){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(X,Y,G,Q,J,W)).payloads}async getFeatureFlagsStateless(X,Y={},G={},Q={},J,W){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(X,Y,G,Q,J,W)}async getFeatureFlagsAndPayloadsStateless(X,Y={},G={},Q={},J,W){await this._initPromise;let Z=await this.getFeatureFlagDetailsStateless(X,Y,G,Q,J,W);if(!Z)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:Z.featureFlags,payloads:Z.featureFlagPayloads,requestId:Z.requestId}}async getFeatureFlagDetailsStateless(X,Y={},G={},Q={},J,W){await this._initPromise;let Z={};if(J??this.disableGeoip)Z.geoip_disable=!0;if(W)Z.flag_keys_to_evaluate=W;let $=await this.getFlags(X,Y,G,Q,Z);if(!$.success)return;let K=$.response;if(K.errorsWhileComputingFlags)console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");if(K.quotaLimited?.includes("feature_flags"))return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:K?.requestId,quotaLimited:K.quotaLimited};return K}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let X=`${this.host}/api/surveys/?token=${this.apiKey}`,Y={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},Q=(await this.fetchWithRetry(X,Y).then((J)=>{if(J.status!==200||!J.json){let W=`Surveys API could not be loaded: ${J.status}`,Z=Error(W);this._logger.error(Z),this._events.emit("error",Error(W));return}return J.json()}).catch((J)=>{this._logger.error("Surveys API could not be loaded",J),this._events.emit("error",J)}))?.surveys;if(Q)this._logger.info("Surveys fetched from API: ",JSON.stringify(Q));return Q??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(nJ.Props);return this._props||{}}set props(X){this._props=X}async register(X){this.wrap(()=>{this.props={...this.props,...X},this.setPersistedProperty(nJ.Props,this.props)})}async unregister(X){this.wrap(()=>{delete this.props[X],this.setPersistedProperty(nJ.Props,this.props)})}processBeforeEnqueue(X){return X}async flushStorage(){}enqueue(X,Y,G){this.wrap(()=>{if(this.optedOut)return void this._events.emit(X,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let Q=this.prepareMessage(X,Y,G);if(Q=this.processBeforeEnqueue(Q),Q===null)return;let J=this.getPersistedProperty(nJ.Queue)||[];if(J.length>=this.maxQueueSize)J.shift(),this._logger.info("Queue is full, the oldest event is dropped.");if(J.push({message:Q}),this.setPersistedProperty(nJ.Queue,J),this._events.emit(X,Q),J.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=Hw(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(X,Y,G){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(X,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let Q=this.prepareMessage(X,Y,G);if(Q=this.processBeforeEnqueue(Q),Q===null)return;let J={api_key:this.apiKey,batch:[Q],sent_at:rA1()};if(this.historicalMigration)J.historical_migration=!0;let W=JSON.stringify(J),Z=`${this.host}/batch/`,$=this.disableCompression?null:await mA1(W,this.isDebug),K={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...$!==null&&{"Content-Encoding":"gzip"}},body:$||W};try{await this.fetchWithRetry(Z,K)}catch(H){this._events.emit("error",H)}}prepareMessage(X,Y,G){let Q={...Y,type:X,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:G?.timestamp?G?.timestamp:rA1(),uuid:G?.uuid?G.uuid:Aq()};if(G?.disableGeoip??this.disableGeoip){if(!Q.properties)Q.properties={};Q.properties.$geoip_disable=!0}if(Q.distinctId)Q.distinct_id=Q.distinctId,delete Q.distinctId;return Q}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){this.flush().catch(async(X)=>{await F14(X)})}async flush(){let X=jB0([this.flushPromise]).then(()=>this._flush());return this.flushPromise=X,this.addPendingPromise(X),jB0([X]).then(()=>{if(this.flushPromise===X)this.flushPromise=null}),X}getCustomHeaders(){let X=this.getCustomUserAgent(),Y={};if(X&&X!=="")Y["User-Agent"]=X;return Y}async _flush(){this.clearFlushTimer(),await this._initPromise;let X=this.getPersistedProperty(nJ.Queue)||[];if(!X.length)return;let Y=[],G=X.length;while(X.length>0&&Y.length<G){let Q=X.slice(0,this.maxBatchSize),J=Q.map((B)=>B.message),W=async()=>{let z=(this.getPersistedProperty(nJ.Queue)||[]).slice(Q.length);this.setPersistedProperty(nJ.Queue,z),X=z,await this.flushStorage()},Z={api_key:this.apiKey,batch:J,sent_at:rA1()};if(this.historicalMigration)Z.historical_migration=!0;let $=JSON.stringify(Z),K=`${this.host}/batch/`,H=this.disableCompression?null:await mA1($,this.isDebug),U={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...H!==null&&{"Content-Encoding":"gzip"}},body:H||$},N={retryCheck:(B)=>{if(U14(B))return!1;return SB0(B)}};try{await this.fetchWithRetry(K,U,N)}catch(B){if(U14(B)&&J.length>1){this.maxBatchSize=Math.max(1,Math.floor(J.length/2)),this._logger.warn(`Received 413 when sending batch of size ${J.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(B instanceof hX1))await W();throw this._events.emit("error",B),B}await W(),Y.push(...J)}this._events.emit("flush",Y)}async fetchWithRetry(X,Y,G,Q){let J=Y.body?Y.body:"",W=-1;try{W=J instanceof Blob?J.size:Buffer.byteLength(J,Q14)}catch{if(J instanceof Blob)W=J.size;else W=new TextEncoder().encode(J).length}return await Z14(async()=>{let Z=new AbortController,$=Q??this.requestTimeout,K=Hw(()=>Z.abort(),$),H=null;try{H=await this.fetch(X,{signal:Z.signal,...Y})}catch(N){throw new hX1(N)}finally{clearTimeout(K)}if(Y.mode!=="no-cors"&&(H.status<200||H.status>=400))throw new oa(H,W);return H},{...this._retryOptions,...G})}async _shutdown(X=30000){await this._initPromise;let Y=!1;this.clearFlushTimer();let G=async()=>{try{await this.promiseQueue.join();while(!0){if((this.getPersistedProperty(nJ.Queue)||[]).length===0)break;if(await this.flush(),Y)break}}catch(J){if(!SB0(J))throw J;await F14(J)}},Q;try{return await Promise.race([new Promise((J,W)=>{Q=Hw(()=>{this._logger.error("Timed out while shutting down PostHog"),Y=!0,W("Timeout while shutting down PostHog. Some events may not have been sent.")},X)}),G()])}finally{clearTimeout(Q)}}async shutdown(X=30000){if(this.shutdownPromise)this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");else this.shutdownPromise=this._shutdown(X).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var oa,hX1;var CB0=D(()=>{H14();lA1();OB0();jj();F3();yX1();oa=class oa extends Error{constructor(X,Y){super("HTTP error while fetching PostHog: status="+X.status+", reqByteLength="+Y),this.response=X,this.reqByteLength=Y,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}};hX1=class hX1 extends Error{constructor(X){super("Network error while fetching PostHog",X instanceof Error?{cause:X}:{}),this.error=X,this.name="PostHogFetchNetworkError"}}});var N14=D(()=>{lA1();jj();CB0();yX1();F3()});var B14=D(()=>{fX1()});function O14(X){let Y=globalThis._posthogChunkIds;if(!Y)return;let G=Object.keys(Y);if(eA1&&G.length===z14)return eA1;return z14=G.length,eA1=G.reduce((Q,J)=>{if(!sA1)sA1={};let W=sA1[J];if(W)Q[W[0]]=W[1];else{let Z=X(J);for(let $=Z.length-1;$>=0;$--){let H=Z[$]?.filename,U=Y[J];if(H&&U){Q[H]=U,sA1[J]=[H,U];break}}}return Q},{}),eA1}var sA1,z14,eA1;var D14=()=>{};class w14{constructor(X,Y,G=[]){this.coercers=X,this.stackParser=Y,this.modifiers=G}buildFromUnknown(X,Y={}){let Q=Y&&Y.mechanism||{handled:!0,type:"generic"},W=this.buildCoercingContext(Q,Y,0).apply(X),Z=this.buildParsingContext(Y),$=this.parseStacktrace(W,Z);return{$exception_list:this.convertToExceptionList($,Q),$exception_level:"error"}}async modifyFrames(X){for(let Y of X)if(Y.stacktrace&&Y.stacktrace.frames&&cA1(Y.stacktrace.frames))Y.stacktrace.frames=await this.applyModifiers(Y.stacktrace.frames);return X}coerceFallback(X){return{type:"Error",value:"Unknown error",stack:X.syntheticException?.stack,synthetic:!0}}parseStacktrace(X,Y){let G;if(X.cause!=null)G=this.parseStacktrace(X.cause,Y);let Q;if(X.stack!=""&&X.stack!=null)Q=this.applyChunkIds(this.stackParser(X.stack,X.synthetic?Y.skipFirstLines:0),Y.chunkIdMap);return{...X,cause:G,stack:Q}}applyChunkIds(X,Y){return X.map((G)=>{if(G.filename&&Y)G.chunk_id=Y[G.filename];return G})}applyCoercers(X,Y){for(let G of this.coercers)if(G.match(X))return G.coerce(X,Y);return this.coerceFallback(Y)}async applyModifiers(X){let Y=X;for(let G of this.modifiers)Y=await G(Y);return Y}convertToExceptionList(X,Y){let G={type:X.type,value:X.value,mechanism:{type:Y.type??"generic",handled:Y.handled??!0,synthetic:X.synthetic??!1}};if(X.stack)G.stacktrace={type:"raw",frames:X.stack};let Q=[G];if(X.cause!=null)Q.push(...this.convertToExceptionList(X.cause,{...Y,handled:!0}));return Q}buildParsingContext(X){return{chunkIdMap:O14(this.stackParser),skipFirstLines:X.skipFirstLines??1}}buildCoercingContext(X,Y,G=0){let Q=(W,Z)=>{if(!(Z<=Zn5))return;{let $=this.buildCoercingContext(X,Y,Z);return this.applyCoercers(W,$)}};return{...Y,syntheticException:G==0?Y.syntheticException:void 0,mechanism:X,apply:(W)=>Q(W,G),next:(W)=>Q(W,G+1)}}}var Zn5=4;var L14=D(()=>{F3();D14()});function Gz(X,Y,G,Q,J){let W={platform:X,filename:Y,function:G==="<anonymous>"?oQ:G,in_app:!0};if(!na(Q))W.lineno=Q;if(!na(J))W.colno=J;return W}var oQ="?";var Tq=D(()=>{F3()});var XT1=(X,Y)=>{let G=X.indexOf("safari-extension")!==-1,Q=X.indexOf("safari-web-extension")!==-1;return G||Q?[X.indexOf("@")!==-1?X.split("@")[0]:oQ,G?`safari-extension:${Y}`:`safari-web-extension:${Y}`]:[X,Y]};var kB0=D(()=>{Tq()});var Wn5,$n5,Kn5,vB0=(X,Y)=>{let G=Wn5.exec(X);if(G){let[,J,W,Z]=G;return Gz(Y,J,oQ,+W,+Z)}let Q=$n5.exec(X);if(Q){if(Q[2]&&Q[2].indexOf("eval")===0){let $=Kn5.exec(Q[2]);if($)Q[2]=$[1],Q[3]=$[2],Q[4]=$[3]}let[W,Z]=XT1(Q[1]||oQ,Q[2]);return Gz(Y,Z,W,Q[3]?+Q[3]:void 0,Q[4]?+Q[4]:void 0)}};var E14=D(()=>{Tq();kB0();Wn5=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,$n5=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Kn5=/\((\S*)(?::(\d+))(?::(\d+))\)/});var Hn5,Fn5,_B0=(X,Y)=>{let G=Hn5.exec(X);if(G){if(G[3]&&G[3].indexOf(" > eval")>-1){let Z=Fn5.exec(G[3]);if(Z)G[1]=G[1]||"eval",G[3]=Z[1],G[4]=Z[2],G[5]=""}let J=G[3],W=G[1]||oQ;return[W,J]=XT1(W,J),Gz(Y,J,W,G[4]?+G[4]:void 0,G[5]?+G[5]:void 0)}};var P14=D(()=>{Tq();kB0();Hn5=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Fn5=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i});var Un5,q14=(X,Y)=>{let G=Un5.exec(X);return G?Gz(Y,G[2],G[1]||oQ,+G[3],G[4]?+G[4]:void 0):void 0};var A14=D(()=>{Tq();Un5=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i});var Nn5,T14=(X,Y)=>{let G=Nn5.exec(X);return G?Gz(Y,G[2],G[3]||oQ,+G[1]):void 0},Bn5,I14=(X,Y)=>{let G=Bn5.exec(X);return G?Gz(Y,G[5],G[3]||G[4]||oQ,+G[1],+G[2]):void 0};var V14=D(()=>{Tq();Nn5=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Bn5=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i});function Dn5(X,Y=!1){return!(Y||X&&!X.startsWith("/")&&!X.match(/^[A-Z]:/)&&!X.startsWith(".")&&!X.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&X!==void 0&&!X.includes("node_modules/")}function j14(X){return parseInt(X||"",10)||void 0}var zn5,On5,M14=(X,Y)=>{let G=X.match(On5);if(G){let Q,J,W,Z,$;if(G[1]){W=G[1];let U=W.lastIndexOf(".");if(W[U-1]===".")U--;if(U>0){Q=W.slice(0,U),J=W.slice(U+1);let N=Q.indexOf(".Module");if(N>0)W=W.slice(N+1),Q=Q.slice(0,N)}Z=void 0}if(J)Z=Q,$=J;if(J==="<anonymous>")$=void 0,W=void 0;if(W===void 0)$=$||oQ,W=Z?`${Z}.${$}`:$;let K=G[2]?.startsWith("file://")?G[2].slice(7):G[2],H=G[5]==="native";if(K?.match(/\/[A-Z]:/))K=K.slice(1);if(!K&&G[5]&&!H)K=G[5];return{filename:K?decodeURI(K):void 0,module:void 0,function:W,lineno:j14(G[3]),colno:j14(G[4]),in_app:Dn5(K||"",H),platform:Y}}if(X.match(zn5))return{filename:X,platform:Y}};var R14=D(()=>{Tq();zn5=/^\s*[-]{4,}$/,On5=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/});function k14(X){if(!X.length)return[];let Y=Array.from(X);return Y.reverse(),Y.slice(0,C14).map((G)=>({...G,filename:G.filename||wn5(Y).filename,function:G.function||oQ}))}function wn5(X){return X[X.length-1]||{}}function Ln5(){return v14("web:javascript",vB0,_B0)}function v14(X,...Y){return(G,Q=0)=>{let J=[],W=G.split(`
|
|
1640
1640
|
`);for(let Z=Q;Z<W.length;Z++){let $=W[Z];if($.length>1024)continue;let K=S14.test($)?$.replace(S14,"$1"):$;if(!K.match(/\S*Error: /)){for(let H of Y){let U=H(K,X);if(U){J.push(U);break}}if(J.length>=C14)break}}return k14(J)}}var S14,C14=50;var _14=D(()=>{Tq();E14();P14();A14();V14();R14();S14=/\(error: (.*)\)/});class f14{match(X){return this.isDOMException(X)||this.isDOMError(X)}coerce(X,Y){let G=qq(X.stack);return{type:this.getType(X),value:this.getValue(X),stack:G?X.stack:void 0,cause:X.cause?Y.next(X.cause):void 0,synthetic:!1}}getType(X){return this.isDOMError(X)?"DOMError":"DOMException"}getValue(X){let Y=X.name||(this.isDOMError(X)?"DOMError":"DOMException");return X.message?`${Y}: ${X.message}`:Y}isDOMException(X){return Mj(X,"DOMException")}isDOMError(X){return Mj(X,"DOMError")}}var b14=D(()=>{F3()});class y14{match(X){return wB0(X)}coerce(X,Y){return{type:this.getType(X),value:this.getMessage(X,Y),stack:this.getStack(X),cause:X.cause?Y.next(X.cause):void 0,synthetic:!1}}getType(X){return X.name||X.constructor.name}getMessage(X,Y){let G=X.message;if(G.error&&typeof G.error.message=="string")return String(G.error.message);return String(G)}getStack(X){return X.stacktrace||X.stack||void 0}}var x14=D(()=>{F3()});class h14{constructor(){}match(X){return le6(X)&&X.error!=null}coerce(X,Y){let G=Y.apply(X.error);if(!G)return{type:"ErrorEvent",value:X.message,stack:Y.syntheticException?.stack,synthetic:!0};return G}}var g14=D(()=>{F3()});class u14{match(X){return typeof X=="string"}coerce(X,Y){let[G,Q]=this.getInfos(X);return{type:G??"Error",value:Q??X,stack:Y.syntheticException?.stack,synthetic:!0}}getInfos(X){let Y="Error",G=X,Q=X.match(En5);if(Q)Y=Q[1],G=Q[2];return[Y,G]}}var En5;var l14=D(()=>{En5=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i});var m14;var d14=D(()=>{m14=["fatal","error","warning","log","info","debug"]});function YT1(X,Y=40){let G=Object.keys(X);if(G.sort(),!G.length)return"[object has no keys]";for(let Q=G.length;Q>0;Q--){let J=G.slice(0,Q).join(", ");if(!(J.length>Y)){if(Q===G.length)return J;return J.length<=Y?J:`${J.slice(0,Y)}...`}}return""}var fB0=()=>{};class c14{match(X){return typeof X=="object"&&X!==null}coerce(X,Y){let G=this.getErrorPropertyFromObject(X);if(G)return Y.apply(G);return{type:this.getType(X),value:this.getValue(X),stack:Y.syntheticException?.stack,level:this.isSeverityLevel(X.level)?X.level:"error",synthetic:!0}}getType(X){return aa(X)?X.constructor.name:"Error"}getValue(X){if("name"in X&&typeof X.name=="string"){let Q=`'${X.name}' captured as exception`;if("message"in X&&typeof X.message=="string")Q+=` with message: '${X.message}'`;return Q}if("message"in X&&typeof X.message=="string")return X.message;let Y=this.getObjectClassName(X),G=YT1(X);return`${Y&&Y!=="Object"?`'${Y}'`:"Object"} captured as exception with keys: ${G}`}isSeverityLevel(X){return qq(X)&&!ue6(X)&&m14.indexOf(X)>=0}getErrorPropertyFromObject(X){for(let Y in X)if(Object.prototype.hasOwnProperty.call(X,Y)){let G=X[Y];if(W14(G))return G}}getObjectClassName(X){try{let Y=Object.getPrototypeOf(X);return Y?Y.constructor.name:void 0}catch(Y){return}}}var i14=D(()=>{F3();d14();fB0()});class p14{match(X){return aa(X)}coerce(X,Y){let G=X.constructor.name;return{type:G,value:`${G} captured as exception with keys: ${YT1(X)}`,stack:Y.syntheticException?.stack,synthetic:!0}}}var n14=D(()=>{F3();fB0()});class a14{match(X){return iA1(X)}coerce(X,Y){return{type:"Error",value:`Primitive value captured as exception: ${String(X)}`,stack:Y.syntheticException?.stack,synthetic:!0}}}var t14=D(()=>{F3()});class r14{match(X){return Mj(X,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(X)}isCustomEventWrappingRejection(X){if(!aa(X))return!1;try{let Y=X.detail;return Y!=null&&typeof Y=="object"&&"reason"in Y}catch{return!1}}coerce(X,Y){let G=this.getUnhandledRejectionReason(X);if(iA1(G))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(G)}`,stack:Y.syntheticException?.stack,synthetic:!0};return Y.apply(G)}getUnhandledRejectionReason(X){try{if("reason"in X)return X.reason;if("detail"in X&&X.detail!=null&&typeof X.detail=="object"&&"reason"in X.detail)return X.detail.reason}catch{}return X}}var o14=D(()=>{F3()});var s14=D(()=>{b14();x14();g14();l14();i14();n14();t14();o14()});class e14{constructor(X){this._maxSize=X,this._cache=new Map}get(X){let Y=this._cache.get(X);if(Y===void 0)return;return this._cache.delete(X),this._cache.set(X,Y),Y}set(X,Y){this._cache.set(X,Y)}reduce(){while(this._cache.size>=this._maxSize){let X=this._cache.keys().next().value;if(X)this._cache.delete(X)}}}var X04=()=>{};function bB0(X){if(!X)return{...GT1};return{enabled:X.enabled??GT1.enabled,max_bytes:An5(X.max_bytes,GT1.max_bytes)}}function qn5(X){if(!X)return{sanitizedProperties:{},droppedKeys:[]};let Y=[];return{sanitizedProperties:Object.keys(X).reduce((Q,J)=>{if(Pn5.has(J))return Y.push(J),Q;return Q[J]=X[J],Q},{}),droppedKeys:Y}}class Y04{constructor(X){this._entries=[],this._totalBytes=0,this._config=bB0(X)}setConfig(X){this._config=bB0(X),this._trimToMaxBytes()}add(X){let Y=Tn5(X);if(!Y)return;let G=G04(Y.json);if(G>this._config.max_bytes)return;this._entries.push({step:Y.step,bytes:G}),this._totalBytes+=G,this._trimToMaxBytes()}getAttachable(){return this._entries.map((X)=>X.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){while(this._totalBytes>this._config.max_bytes&&this._entries.length>0){let X=this._entries.shift();if(X)this._totalBytes-=X.bytes}}}function An5(X,Y){if(!_X1(X)||X===1/0||X===-1/0)return Y;let G=Math.floor(X);if(G<0)return Y;return G}function Tn5(X){let Y=In5(X);if(!Y)return;try{let G=JSON.parse(Y);if(!vX1(G))return;let Q=G,J=Q[gX1.MESSAGE],W=Q[gX1.TIMESTAMP];if(!qq(J)||J.trim().length===0)return;if(!qq(W)&&!_X1(W))return;return{step:Q,json:Y}}catch{return}}function In5(X){let Y=new WeakSet;try{return JSON.stringify(X,(G,Q)=>{if(typeof Q=="bigint")return Q.toString();if(typeof Q=="function"||typeof Q=="symbol")return;if(Q instanceof Date)return Q.toISOString();if(Q instanceof Error)return{name:Q.name,message:Q.message,stack:Q.stack};if(Q&&typeof Q=="object"){if(Y.has(Q))return"[Circular]";Y.add(Q)}return Q})}catch{return}}function G04(X){if(typeof TextEncoder<"u")return new TextEncoder().encode(X).length;let Y=encodeURIComponent(X),G=0;for(let Q=0;Q<Y.length;Q++)if(Y[Q]==="%")G+=1,Q+=2;else G+=1;return G}var gX1,Pn5,GT1;var Q04=D(()=>{F3();gX1={MESSAGE:"$message",TIMESTAMP:"$timestamp"},Pn5=new Set([gX1.MESSAGE,gX1.TIMESTAMP]),GT1={enabled:!0,max_bytes:32768}});var qW={};M0(qW,{winjsStackLineParser:()=>q14,stripReservedExceptionStepFields:()=>qn5,reverseAndStripFrames:()=>k14,resolveExceptionStepsConfig:()=>bB0,opera11StackLineParser:()=>I14,opera10StackLineParser:()=>T14,nodeStackLineParser:()=>M14,getUtf8ByteLength:()=>G04,geckoStackLineParser:()=>_B0,createStackParser:()=>v14,createDefaultStackParser:()=>Ln5,chromeStackLineParser:()=>vB0,StringCoercer:()=>u14,ReduceableCache:()=>e14,PromiseRejectionEventCoercer:()=>r14,PrimitiveCoercer:()=>a14,ObjectCoercer:()=>c14,ExceptionStepsBuffer:()=>Y04,EventCoercer:()=>p14,ErrorPropertiesBuilder:()=>w14,ErrorEventCoercer:()=>h14,ErrorCoercer:()=>y14,EXCEPTION_STEP_INTERNAL_FIELDS:()=>gX1,DOMExceptionCoercer:()=>f14,DEFAULT_EXCEPTION_STEPS_CONFIG:()=>GT1});var J04=D(()=>{L14();_14();s14();X04();Q04()});var Sj=D(()=>{lA1();OB0();MB0();$14();yX1();K14();J04();F3();N14();CB0();B14();jj()});import{createReadStream as Vn5}from"fs";import{createInterface as jn5}from"readline";async function K04(X){let Y={};for(let J=X.length-1;J>=0;J--){let W=X[J],Z=W?.filename;if(!W||typeof Z!="string"||typeof W.lineno!="number"||vn5(Z)||_n5(W))continue;if(!Y[Z])Y[Z]=[];Y[Z].push(W.lineno)}let G=Object.keys(Y);if(G.length==0)return X;let Q=[];for(let J of G){if($04.get(J))continue;let W=Y[J];if(!W)continue;W.sort((K,H)=>K-H);let Z=bn5(W);if(Z.every((K)=>fn5(J,K)))continue;let $=yn5(QT1,J,{});Q.push(Sn5(J,Z,$))}if(await Promise.all(Q).catch(()=>{}),X&&X.length>0)Cn5(X,QT1);return QT1.reduce(),X}function Sn5(X,Y,G){return new Promise((Q)=>{let J=Vn5(X),W=jn5({input:J});function Z(){J.destroy(),Q()}let $=0,K=0,H=Y[K];if(H===void 0)return void Z();let U=H[0],N=H[1];function B(){$04.set(X,1),W.close(),W.removeAllListeners(),Z()}J.on("error",B),W.on("error",B),W.on("close",Z),W.on("line",(z)=>{if($++,$<U)return;if(G[$]=xn5(z,0),$>=N){if(K===Y.length-1){W.close(),W.removeAllListeners();return}K++;let O=Y[K];if(O===void 0){W.close(),W.removeAllListeners();return}U=O[0],N=O[1]}})})}function Cn5(X,Y){for(let G of X)if(G.filename&&G.context_line===void 0&&typeof G.lineno=="number"){let Q=Y.get(G.filename);if(Q===void 0)continue;kn5(G.lineno,G,Q)}}function kn5(X,Y,G){if(Y.lineno===void 0||G===void 0)return;Y.pre_context=[];for(let J=H04(X);J<X;J++){let W=G[J];if(W===void 0)return void Z04(Y);Y.pre_context.push(W)}if(G[X]===void 0)return void Z04(Y);Y.context_line=G[X];let Q=F04(X);Y.post_context=[];for(let J=X+1;J<=Q;J++){let W=G[J];if(W===void 0)break;Y.post_context.push(W)}}function Z04(X){delete X.pre_context,delete X.context_line,delete X.post_context}function vn5(X){return X.startsWith("node:")||X.endsWith(".min.js")||X.endsWith(".min.cjs")||X.endsWith(".min.mjs")||X.startsWith("data:")}function _n5(X){if(X.lineno!==void 0&&X.lineno>Rn5)return!0;if(X.colno!==void 0&&X.colno>Mn5)return!0;return!1}function fn5(X,Y){let G=QT1.get(X);if(G===void 0)return!1;for(let Q=Y[0];Q<=Y[1];Q++)if(G[Q]===void 0)return!1;return!0}function bn5(X){if(!X.length)return[];let Y=0,G=X[0];if(typeof G!="number")return[];let Q=W04(G),J=[];while(!0){if(Y===X.length-1){J.push(Q);break}let W=X[Y+1];if(typeof W!="number")break;if(W<=Q[1])Q[1]=W+yB0;else J.push(Q),Q=W04(W);Y++}return J}function W04(X){return[H04(X),F04(X)]}function H04(X){return Math.max(1,X-yB0)}function F04(X){return X+yB0}function yn5(X,Y,G){let Q=X.get(Y);if(Q===void 0)return X.set(Y,G),G;return Q}function xn5(X,Y){let G=X,Q=G.length;if(Q<=150)return G;if(Y>Q)Y=Q;let J=Math.max(Y-60,0);if(J<5)J=0;let W=Math.min(J+140,Q);if(W>Q-5)W=Q;if(W===Q)J=Math.max(W-140,0);if(G=G.slice(J,W),J>0)G=`...${G}`;if(W<Q)G+="...";return G}var QT1,$04,yB0=7,Mn5=1000,Rn5=1e4;var U04=D(()=>{Sj();QT1=new qW.ReduceableCache(25),$04=new qW.ReduceableCache(20)});import{isAbsolute as hn5,relative as gn5,sep as un5}from"path";function N04(X=process.cwd()){let Y=un5==="\\",G=(J)=>Y?J.replace(/\\/g,"/"):J,Q=G(X);return async(J)=>{for(let W of J)if(!(!W.filename||W.filename.startsWith("node:")||W.filename.startsWith("data:"))){if(hn5(W.filename))W.filename=G(gn5(Q,G(W.filename)))}return J}}var B04=()=>{};function ln5(X,Y){let G=!1;return Object.assign((Q)=>{let W=global.process.listeners("uncaughtException").filter((Z)=>Z.name!=="domainUncaughtExceptionClear"&&Z._posthogErrorHandler!==!0).length===0;if(X(Q,{mechanism:{type:"onuncaughtexception",handled:!1}}),!G&&W)G=!0,Y(Q)},{_posthogErrorHandler:!0})}function z04(X,Y){globalThis.process?.on("uncaughtException",ln5(X,Y))}function O04(X){globalThis.process?.on("unhandledRejection",(Y)=>X(Y,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var D04=()=>{};class DH{constructor(X,Y,G){this.client=X,this._exceptionAutocaptureEnabled=Y.enableExceptionAutocapture||!1,this._logger=G,this._rateLimiter=new EB0({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(X){return vX1(X)&&"__posthog_previously_captured_error"in X&&X.__posthog_previously_captured_error===!0}static async buildEventMessage(X,Y,G,Q){let J={...Q},W=this.errorPropertiesBuilder.buildFromUnknown(X,Y);return W.$exception_list=await this.errorPropertiesBuilder.modifyFrames(W.$exception_list),{event:"$exception",distinctId:G,properties:{...W,...J},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())z04(this.onException.bind(this),this.onFatalError.bind(this)),O04(this.onException.bind(this))}onException(X,Y){this.client.addPendingPromise((async()=>{if(!DH.isPreviouslyCapturedError(X)){let G=await DH.buildEventMessage(X,Y),J=G.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(J))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:J});return this.client.capture(G)}})())}async onFatalError(X){console.error(X),await this.client.shutdown(mn5),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}var mn5=2000;var JT1=D(()=>{D04();Sj()});var w04="5.30.6";var L04=()=>{};var uX1;var xB0=D(()=>{uX1={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"}});async function E04(X){let Y=globalThis.crypto?.subtle;if(!Y)throw Error("SubtleCrypto API not available");let G=await Y.digest("SHA-1",new TextEncoder().encode(X));return Array.from(new Uint8Array(G)).map((J)=>J.toString(16).padStart(2,"0")).join("")}var P04=()=>{};class hB0{constructor({pollingInterval:X,personalApiKey:Y,projectApiKey:G,timeout:Q,host:J,customHeaders:W,...Z}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=X,this.personalApiKey=Y,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=Q,this.projectApiKey=G,this.host=J,this.poller=void 0,this.fetch=Z.fetch||fetch,this.onError=Z.onError,this.customHeaders=W,this.onLoad=Z.onLoad,this.cacheProvider=Z.cacheProvider,this.strictLocalEvaluation=Z.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(X=!0){this.debugMode=X}logMsgIfDebug(X){if(this.debugMode)X()}createEvaluationContext(X,Y={},G={},Q={},J={}){return{distinctId:X,groups:Y,personProperties:G,groupProperties:Q,evaluationCache:J}}async getFeatureFlag(X,Y,G={},Q={},J={}){await this.loadFeatureFlags();let W,Z;if(!this.loadedSuccessfullyOnce)return W;if(Z=this.featureFlagsByKey[X],Z!==void 0){let $=this.createEvaluationContext(Y,G,Q,J);try{W=(await this.computeFlagAndPayloadLocally(Z,$)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${X} -> ${W}`))}catch(K){if(K instanceof Qz||K instanceof d5)this.logMsgIfDebug(()=>console.debug(`${K.name} when computing flag locally: ${X}: ${K.message}`));else if(K instanceof Error)this.onError?.(Error(`Error computing flag locally: ${X}: ${K}`))}}return W}async getAllFlagsAndPayloads(X,Y){await this.loadFeatureFlags();let G={},Q={},J=this.featureFlags.length==0,W=Y?Y.map(($)=>this.featureFlagsByKey[$]).filter(Boolean):this.featureFlags,Z={...X,evaluationCache:X.evaluationCache??{}};return await Promise.all(W.map(async($)=>{try{let{value:K,payload:H}=await this.computeFlagAndPayloadLocally($,Z);if(G[$.key]=K,H)Q[$.key]=H}catch(K){if(K instanceof Qz||K instanceof d5)this.logMsgIfDebug(()=>console.debug(`${K.name} when computing flag locally: ${$.key}: ${K.message}`));else if(K instanceof Error)this.onError?.(Error(`Error computing flag locally: ${$.key}: ${K}`));J=!0}})),{response:G,payloads:Q,fallbackToFlags:J}}async computeFlagAndPayloadLocally(X,Y,G={}){let{matchValue:Q,skipLoadCheck:J=!1}=G;if(!J)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let W;W=Q!==void 0?Q:await this.computeFlagValueLocally(X,Y);let Z=this.getFeatureFlagPayload(X.key,W);return{value:W,payload:Z}}async computeFlagValueLocally(X,Y){let{distinctId:G,groups:Q,personProperties:J,groupProperties:W}=Y;if(X.ensure_experience_continuity)throw new d5("Flag has experience continuity enabled");if(!X.active)return!1;let $=(X.filters||{}).aggregation_group_type_index;if($!=null){let K=this.groupTypeMapping[String($)];if(!K)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${$} for feature flag ${X.key}`)),new d5("Flag has unknown group type index");if(!(K in Q))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${X.key} without group names passed in`)),!1;if(X.bucketing_identifier==="device_id"&&(J?.$device_id===void 0||J?.$device_id===null||J?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${X.key}`));let H=W[K];return await this.matchFeatureFlagProperties(X,Q[K],H,Y)}{let K=this.getBucketingValueForFlag(X,G,J);if(K===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${X.key} without $device_id, falling back to server evaluation`)),new d5(`Can't compute feature flag: ${X.key} without $device_id`);return await this.matchFeatureFlagProperties(X,K,J,Y)}}getBucketingValueForFlag(X,Y,G){if(X.filters?.aggregation_group_type_index!=null)return Y;if(X.bucketing_identifier==="device_id"){let Q=G?.$device_id;if(Q==null||Q==="")return;return Q}return Y}getFeatureFlagPayload(X,Y){let G=null;if(Y!==!1&&Y!=null){if(typeof Y=="boolean")G=this.featureFlagsByKey?.[X]?.filters?.payloads?.[Y.toString()]||null;else if(typeof Y=="string")G=this.featureFlagsByKey?.[X]?.filters?.payloads?.[Y]||null;if(G!=null){if(typeof G=="object")return G;if(typeof G=="string")try{return JSON.parse(G)}catch{}return G}}return null}async evaluateFlagDependency(X,Y,G){let{evaluationCache:Q}=G,J=X.key;if(!this.featureFlagsByKey)throw new d5("Feature flags not available for dependency evaluation");if(!("dependency_chain"in X))throw new d5(`Flag dependency property for '${J}' is missing required 'dependency_chain' field`);let W=X.dependency_chain;if(!Array.isArray(W))throw new d5(`Flag dependency property for '${J}' has an invalid 'dependency_chain' (expected array, got ${typeof W})`);if(W.length===0)throw new d5(`Circular dependency detected for flag '${J}' (empty dependency chain)`);for(let $ of W){if(!($ in Q)){let H=this.featureFlagsByKey[$];if(H)if(H.active)try{let U=await this.computeFlagValueLocally(H,G);Q[$]=U}catch(U){throw new d5(`Error evaluating flag dependency '${$}' for flag '${J}': ${U}`)}else Q[$]=!1;else throw new d5(`Missing flag dependency '${$}' for flag '${J}'`)}if(Q[$]==null)throw new d5(`Dependency '${$}' could not be evaluated`)}let Z=Q[J];return this.flagEvaluatesToExpectedValue(X.value,Z)}flagEvaluatesToExpectedValue(X,Y){if(typeof X=="boolean")return X===Y||typeof Y=="string"&&Y!==""&&X===!0;if(typeof X=="string")return Y===X;return!1}async matchFeatureFlagProperties(X,Y,G,Q){let J=X.filters||{},W=J.groups||[],Z=!1,$;for(let K of W)try{if(await this.isConditionMatch(X,Y,K,G,Q)){let H=K.variant,U=J.multivariate?.variants||[];$=H&&U.some((N)=>N.key===H)?H:await this.getMatchingVariant(X,Y)||!0;break}}catch(H){if(H instanceof Qz)throw H;if(H instanceof d5)Z=!0;else throw H}if($!==void 0)return $;if(Z)throw new d5("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(X,Y,G,Q,J){let W=G.rollout_percentage,Z=($)=>{this.logMsgIfDebug(()=>console.warn($))};if((G.properties||[]).length>0){for(let $ of G.properties){let K=$.type,H=!1;if(H=K==="cohort"?V04($,Q,this.cohorts,this.debugMode):K==="flag"?await this.evaluateFlagDependency($,Q,J):I04($,Q,Z),!H)return!1}if(W==null)return!0}if(W!=null&&await q04(X.key,Y)>W/100)return!1;return!0}async getMatchingVariant(X,Y){let G=await q04(X.key,Y,"variant"),Q=this.variantLookupTable(X).find((J)=>G>=J.valueMin&&G<J.valueMax);if(Q)return Q.key}variantLookupTable(X){let Y=[],G=0,Q=0;return((X.filters||{}).multivariate?.variants||[]).forEach((Z)=>{Q=G+Z.rollout_percentage/100,Y.push({valueMin:G,valueMax:Q,key:Z.key}),G=Q}),Y}updateFlagState(X){this.featureFlags=X.flags,this.featureFlagsByKey=X.flags.reduce((Y,G)=>(Y[G.key]=G,Y),{}),this.groupTypeMapping=X.groupTypeMapping,this.cohorts=X.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(X){if(this.strictLocalEvaluation)return;let Y=X.filter((G)=>G.ensure_experience_continuity);if(Y.length>0)console.warn(`[PostHog] You are using local evaluation but ${Y.length} flag(s) have experience continuity enabled: ${Y.map((G)=>G.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(X){if(!this.cacheProvider)return!1;try{let Y=await this.cacheProvider.getFlagDefinitions();if(Y)return this.updateFlagState(Y),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${X} (${Y.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(Y.flags),!0;return!1}catch(Y){return this.onError?.(Error(`Failed to load from cache: ${Y}`)),!1}}async loadFeatureFlags(X=!1){if(this.loadedSuccessfullyOnce&&!X)return;if(!X&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt)return void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period"));if(!this.loadingPromise)this.loadingPromise=this._loadFeatureFlags().catch((Y)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${Y}`))).finally(()=>{this.loadingPromise=void 0});return this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){if(!this.shouldBeginExponentialBackoff)return this.pollingInterval;return Math.min(dn5,this.pollingInterval*2**this.backOffCount)}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){if(this.poller)clearTimeout(this.poller),this.poller=void 0;this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let X=!0;if(this.cacheProvider)try{X=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(G){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${G}`))}if(!X){if(await this.loadFromCache("Loaded flags from cache (skipped fetch)"))return;if(this.loadedSuccessfullyOnce)return}let Y=await this._requestFeatureFlagDefinitions();if(!Y)return;switch(Y.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=Y.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new sa(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new sa(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new sa(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let G=await Y.json()??{};if(!("flags"in G))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(G)}`));this.flagsEtag=Y.headers?.get("ETag")??void 0;let Q={flags:G.flags??[],groupTypeMapping:G.group_type_mapping||{},cohorts:G.cohorts||{}};if(this.updateFlagState(Q),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&X)try{await this.cacheProvider.onFlagDefinitionsReceived(Q)}catch(J){this.onError?.(Error(`Failed to store in cache: ${J}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(Q.flags);break}default:return}}catch(X){if(X instanceof sa)this.onError?.(X)}}getPersonalApiKeyRequestOptions(X="GET",Y){let G={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(Y)G["If-None-Match"]=Y;return{method:X,headers:G}}_requestFeatureFlagDefinitions(){let X=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,Y=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),G=null;if(this.timeout&&typeof this.timeout=="number"){let Q=new AbortController;G=Hw(()=>{Q.abort()},this.timeout),Y.signal=Q.signal}try{let Q=this.fetch;return Q(X,Y)}finally{clearTimeout(G)}}async stopPoller(X=30000){if(clearTimeout(this.poller),this.cacheProvider)try{let Y=this.cacheProvider.shutdown();if(Y instanceof Promise)await Promise.race([Y,new Promise((G,Q)=>setTimeout(()=>Q(Error(`Cache shutdown timeout after ${X}ms`)),X))])}catch(Y){this.onError?.(Error(`Error during cache shutdown: ${Y}`))}}}async function q04(X,Y,G=""){let Q=await E04(`${X}.${Y}${G}`);return parseInt(Q.slice(0,15),16)/cn5}function I04(X,Y,G){let{key:Q,value:J}=X,W=X.operator||"exact";if(Q in Y){if(W==="is_not_set")throw new d5("Operator is_not_set is not supported")}else throw new d5(`Property ${Q} not found in propertyValues`);let Z=Y[Q];if(Z==null&&!in5.includes(W)){if(G)G(`Property ${Q} cannot have a value of null/undefined with the ${W} operator`);return!1}function $(H,U){if(Array.isArray(H))return H.map((N)=>String(N).toLowerCase()).includes(String(U).toLowerCase());return String(H).toLowerCase()===String(U).toLowerCase()}function K(H,U,N){if(N==="gt")return H>U;if(N==="gte")return H>=U;if(N==="lt")return H<U;if(N==="lte")return H<=U;throw Error(`Invalid operator: ${N}`)}switch(W){case"exact":return $(J,Z);case"is_not":return!$(J,Z);case"is_set":return Q in Y;case"icontains":return String(Z).toLowerCase().includes(String(J).toLowerCase());case"not_icontains":return!String(Z).toLowerCase().includes(String(J).toLowerCase());case"regex":return A04(String(J))&&String(Z).match(String(J))!==null;case"not_regex":return A04(String(J))&&String(Z).match(String(J))===null;case"gt":case"gte":case"lt":case"lte":{let H=typeof J=="number"?J:null;if(typeof J=="string")try{H=parseFloat(J)}catch(U){}if(H==null||Z==null)return K(String(Z),String(J),W);if(typeof Z=="string")return K(Z,String(J),W);return K(Z,H,W)}case"is_date_after":case"is_date_before":{if(typeof J=="boolean")throw new d5("Date operations cannot be performed on boolean values");let H=rn5(String(J));if(H==null)H=T04(J);if(H==null)throw new d5(`Invalid date: ${J}`);let U=T04(Z);if(["is_date_before"].includes(W))return U<H;return U>H}case"semver_eq":return wH(sQ(String(Z)),sQ(String(J)))===0;case"semver_neq":return wH(sQ(String(Z)),sQ(String(J)))!==0;case"semver_gt":return wH(sQ(String(Z)),sQ(String(J)))>0;case"semver_gte":return wH(sQ(String(Z)),sQ(String(J)))>=0;case"semver_lt":return wH(sQ(String(Z)),sQ(String(J)))<0;case"semver_lte":return wH(sQ(String(Z)),sQ(String(J)))<=0;case"semver_tilde":{let H=sQ(String(Z)),{lower:U,upper:N}=nn5(String(J));return wH(H,U)>=0&&wH(H,N)<0}case"semver_caret":{let H=sQ(String(Z)),{lower:U,upper:N}=an5(String(J));return wH(H,U)>=0&&wH(H,N)<0}case"semver_wildcard":{let H=sQ(String(Z)),{lower:U,upper:N}=tn5(String(J));return wH(H,U)>=0&&wH(H,N)<0}default:throw new d5(`Unknown operator: ${W}`)}}function pn5(X,Y){if(!(X in Y))throw new Qz(`cohort ${X} not found in local cohorts - likely a static cohort that requires server evaluation`)}function V04(X,Y,G,Q=!1){let J=String(X.value);pn5(J,G);let W=G[J];return j04(W,Y,G,Q)}function j04(X,Y,G,Q=!1){if(!X)return!0;let{type:J,values:W}=X;if(!W||W.length===0)return!0;let Z=!1;if("values"in W[0]){for(let $ of W)try{let K=j04($,Y,G,Q);if(J==="AND"){if(!K)return!1}else if(K)return!0}catch(K){if(K instanceof Qz)throw K;if(K instanceof d5){if(Q)console.debug(`Failed to compute property ${$} locally: ${K}`);Z=!0}else throw K}if(Z)throw new d5("Can't match cohort without a given cohort property value");return J==="AND"}for(let $ of W)try{let K;if($.type==="cohort")K=V04($,Y,G,Q);else if($.type==="flag"){if(Q)console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${$.key||"unknown"}'`);continue}else K=I04($,Y);let H=$.negation||!1;if(J==="AND"){if(!K&&!H)return!1;if(K&&H)return!1}else{if(K&&!H)return!0;if(!K&&H)return!0}}catch(K){if(K instanceof Qz)throw K;if(K instanceof d5){if(Q)console.debug(`Failed to compute property ${$} locally: ${K}`);Z=!0}else throw K}if(Z)throw new d5("can't match cohort without a given cohort property value");return J==="AND"}function A04(X){try{return new RegExp(X),!0}catch(Y){return!1}}function sQ(X){let G=String(X).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!G||G.startsWith("."))throw new d5(`Invalid semver: ${X}`);let Q=G.split("."),J=(K)=>{if(K===void 0||K==="")return 0;if(!/^\d+$/.test(K))throw new d5(`Invalid semver: ${X}`);return parseInt(K,10)},W=J(Q[0]),Z=J(Q[1]),$=J(Q[2]);return[W,Z,$]}function wH(X,Y){for(let G=0;G<3;G++){if(X[G]<Y[G])return-1;if(X[G]>Y[G])return 1}return 0}function nn5(X){let Y=sQ(X),G=[Y[0],Y[1],Y[2]],Q=[Y[0],Y[1]+1,0];return{lower:G,upper:Q}}function an5(X){let Y=sQ(X),[G,Q,J]=Y,W=[G,Q,J],Z;return Z=G>0?[G+1,0,0]:Q>0?[0,Q+1,0]:[0,0,J+1],{lower:W,upper:Z}}function tn5(X){let G=String(X).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!G)throw new d5(`Invalid wildcard semver: ${X}`);let Q=G.split("."),J=parseInt(Q[0],10);if(isNaN(J))throw new d5(`Invalid wildcard semver: ${X}`);let W,Z;if(Q.length===1)W=[J,0,0],Z=[J+1,0,0];else{let $=parseInt(Q[1],10);if(isNaN($))throw new d5(`Invalid wildcard semver: ${X}`);W=[J,$,0],Z=[J,$+1,0]}return{lower:W,upper:Z}}function T04(X){if(X instanceof Date)return X;if(typeof X=="string"||typeof X=="number"){let Y=new Date(X);if(!isNaN(Y.valueOf()))return Y;throw new d5(`${X} is in an invalid date format`)}throw new d5(`The date provided ${X} must be a string, number, or date object`)}function rn5(X){let Y=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,G=X.match(Y),Q=new Date(new Date().toISOString());if(!G)return null;{if(!G.groups)return null;let J=parseInt(G.groups.number);if(J>=1e4)return null;let W=G.groups.interval;if(W=="h")Q.setUTCHours(Q.getUTCHours()-J);else if(W=="d")Q.setUTCDate(Q.getUTCDate()-J);else if(W=="w")Q.setUTCDate(Q.getUTCDate()-7*J);else if(W=="m")Q.setUTCMonth(Q.getUTCMonth()-J);else{if(W!="y")return null;Q.setUTCFullYear(Q.getUTCFullYear()-J)}return Q}}var dn5=60000,cn5=1152921504606847000,in5,sa,d5,Qz;var M04=D(()=>{Sj();P04();in5=["is_not"];sa=class sa extends Error{constructor(X){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=X,Object.setPrototypeOf(this,sa.prototype)}};d5=class d5 extends Error{constructor(X){super(X);this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,d5.prototype)}};Qz=class Qz extends Error{constructor(X){super(X);this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,Qz.prototype)}}});class gB0{getProperty(X){return this._memoryStorage[X]}setProperty(X,Y){this._memoryStorage[X]=Y!==null?Y:void 0}constructor(){this._memoryStorage={}}}var R04=()=>{};function Ga5(X){return typeof X=="string"?X.trim():""}function Qa5(X){return(typeof X=="string"?X.trim():"")||void 0}function Ja5(X){return(typeof X=="string"?X.trim():"")||Ya5}var on5=100,S04=30000,sn5=50000,en5=50,Xa5=500,Ya5="https://us.i.posthog.com",uB0;var C04=D(()=>{L04();Sj();xB0();M04();JT1();R04();uB0=class uB0 extends oA1{constructor(X,Y={}){let G=Ga5(X),Q={...Y,host:Ja5(Y.host),personalApiKey:Qa5(Y.personalApiKey)};if(super(G,Q),this._memoryStorage=new gB0,this.options=Q,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof Q.featureFlagsPollingInterval=="number"?Math.max(Q.featureFlagsPollingInterval,on5):S04,typeof Q.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(Q.waitUntilDebounceMs,0);if(typeof Q.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(Q.waitUntilMaxWaitMs,0);if(Q.personalApiKey){if(Q.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');if(Q.enableLocalEvaluation!==!1)this.featureFlagsPoller=new hB0({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:Q.personalApiKey,projectApiKey:G,timeout:Q.requestTimeout??1e4,host:this.host,fetch:Q.fetch,onError:(W)=>{this._events.emit("error",W)},onLoad:(W)=>{this._events.emit("localEvaluationFlagsLoaded",W)},customHeaders:this.getCustomHeaders(),cacheProvider:Q.flagDefinitionCacheProvider,strictLocalEvaluation:Q.strictLocalEvaluation})}this.errorTracking=new DH(this,Q,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=Q.maxCacheSize||sn5}enqueue(X,Y,G){super.enqueue(X,Y,G),this.scheduleDebouncedFlush()}async flush(){let X=super.flush(),Y=this.options.waitUntil;if(Y&&!this._waitUntilCycle)try{Y(X.catch(()=>{}))}catch{}return X}scheduleDebouncedFlush(){let X=this.options.waitUntil;if(!X)return;if(this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let W,Z=new Promise(($)=>{W=$});try{X(Z)}catch{return}this._waitUntilCycle={resolve:W,startedAt:Date.now(),timer:void 0}}let Y=Date.now()-this._waitUntilCycle.startedAt,G=this.options.waitUntilMaxWaitMs??Xa5,Q=Y>=G;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(Q)return void this.resolveWaitUntilFlush();let J=this.options.waitUntilDebounceMs??en5;this._waitUntilCycle.timer=Hw(()=>{this.resolveWaitUntilFlush()},J)}_consumeWaitUntilCycle(){let X=this._waitUntilCycle;if(X)clearTimeout(X.timer),this._waitUntilCycle=void 0;return X?.resolve}async resolveWaitUntilFlush(){let X=this._consumeWaitUntilCycle();try{await super.flush()}catch{}finally{X?.()}}getPersistedProperty(X){return this._memoryStorage.getProperty(X)}setPersistedProperty(X,Y){return this._memoryStorage.setProperty(X,Y)}fetch(X,Y){return this.options.fetch?this.options.fetch(X,Y):fetch(X,Y)}getLibraryVersion(){return w04}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(X=!0){super.debug(X),this.featureFlagsPoller?.debug(X)}capture(X){if(typeof X=="string")this._logger.warn("Called capture() with a string as the first argument when an object was expected.");if(X.event==="$exception"&&!X._originatedFromCaptureException)this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically.");this.addPendingPromise(this.prepareEventMessage(X).then(({distinctId:Y,event:G,properties:Q,options:J})=>super.captureStateless(Y,G,Q,{timestamp:J.timestamp,disableGeoip:J.disableGeoip,uuid:J.uuid})).catch((Y)=>{if(Y)console.error(Y)}))}async captureImmediate(X){if(typeof X=="string")this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected.");if(X.event==="$exception"&&!X._originatedFromCaptureException)this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default.");return this.addPendingPromise(this.prepareEventMessage(X).then(({distinctId:Y,event:G,properties:Q,options:J})=>super.captureStatelessImmediate(Y,G,Q,{timestamp:J.timestamp,disableGeoip:J.disableGeoip,uuid:J.uuid})).catch((Y)=>{if(Y)console.error(Y)}))}identify({distinctId:X,properties:Y={},disableGeoip:G}){let{$set:Q,$set_once:J,$anon_distinct_id:W,...Z}=Y,H={$set:Q||Z,$set_once:J||{},$anon_distinct_id:W??void 0};super.identifyStateless(X,H,{disableGeoip:G})}async identifyImmediate({distinctId:X,properties:Y={},disableGeoip:G}){let{$set:Q,$set_once:J,$anon_distinct_id:W,...Z}=Y,H={$set:Q||Z,$set_once:J||{},$anon_distinct_id:W??void 0};super.identifyStatelessImmediate(X,H,{disableGeoip:G})}alias(X){super.aliasStateless(X.alias,X.distinctId,void 0,{disableGeoip:X.disableGeoip})}async aliasImmediate(X){await super.aliasStatelessImmediate(X.alias,X.distinctId,void 0,{disableGeoip:X.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(X=S04){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((Y)=>{let G=setTimeout(()=>{Q(),Y(!1)},X),Q=this._events.on("localEvaluationFlagsLoaded",(J)=>{clearTimeout(G),Q(),Y(J>0)})})}_resolveDistinctId(X,Y){if(typeof X=="string")return{distinctId:X,options:Y};return{distinctId:this.context?.get()?.distinctId,options:X}}async _getFeatureFlagResult(X,Y,G={},Q){let J=G.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&X in this._flagOverrides){let V=this._flagOverrides[X];if(V===void 0)return;let R=this._payloadOverrides?.[X];return{key:X,enabled:V!==!1,variant:typeof V=="string"?V:void 0,payload:R}}let{groups:W,disableGeoip:Z}=G,{onlyEvaluateLocally:$,personProperties:K,groupProperties:H}=G,U=this.addLocalPersonAndGroupProperties(Y,W,K,H);K=U.allPersonProperties,H=U.allGroupProperties;let N=this.createFeatureFlagEvaluationContext(Y,W,K,H);if($==null)$=this.options.strictLocalEvaluation??!1;let B,z=!1,O,w,E,P,q,j;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let V=this.featureFlagsPoller?.featureFlagsByKey[X];if(V)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(V,N,{matchValue:Q});if(R){z=!0;let k=R.value;P=V.id,j="Evaluated locally",B={key:X,enabled:k!==!1,variant:typeof k=="string"?k:void 0,payload:R.payload??void 0}}}catch(R){if(R instanceof Qz||R instanceof d5)this._logger?.info(`${R.name} when computing flag locally: ${X}: ${R.message}`);else throw R}}if(!z&&!$){let V=await super.getFeatureFlagDetailsStateless(N.distinctId,N.groups,N.personProperties,N.groupProperties,Z,[X]);if(V===void 0)E=uX1.UNKNOWN_ERROR;else{O=V.requestId,w=V.evaluatedAt;let R=[];if(V.errorsWhileComputingFlags)R.push(uX1.ERRORS_WHILE_COMPUTING);if(V.quotaLimited?.includes("feature_flags"))R.push(uX1.QUOTA_LIMITED);let k=V.flags[X];if(k===void 0)R.push(uX1.FLAG_MISSING);else{P=k.metadata?.id,q=k.metadata?.version,j=k.reason?.description??k.reason?.code;let _;if(k.metadata?.payload!==void 0)try{_=JSON.parse(k.metadata.payload)}catch{_=k.metadata.payload}B={key:X,enabled:k.enabled,variant:k.variant,payload:_}}if(R.length>0)E=R.join(",")}}if(J){let V=B===void 0?void 0:B.enabled===!1?!1:B.variant??!0,R=`${X}_${V}`;if(!(Y in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[Y].includes(R)){if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(Array.isArray(this.distinctIdHasSentFlagCalls[Y]))this.distinctIdHasSentFlagCalls[Y].push(R);else this.distinctIdHasSentFlagCalls[Y]=[R];let k={$feature_flag:X,$feature_flag_response:V,$feature_flag_id:P,$feature_flag_version:q,$feature_flag_reason:j,locally_evaluated:z,[`$feature/${X}`]:V,$feature_flag_request_id:O,$feature_flag_evaluated_at:z?Date.now():w};if(z&&this.featureFlagsPoller){let _=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(_!==void 0)k.$feature_flag_definitions_loaded_at=_}if(E)k.$feature_flag_error=E;this.capture({distinctId:Y,event:"$feature_flag_called",properties:k,groups:W,disableGeoip:Z})}}if(B!==void 0&&this._payloadOverrides!==void 0&&X in this._payloadOverrides)B={...B,payload:this._payloadOverrides[X]};return B}async getFeatureFlag(X,Y,G){let Q=await this._getFeatureFlagResult(X,Y,{...G,sendFeatureFlagEvents:G?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(Q===void 0)return;if(Q.enabled===!1)return!1;return Q.variant??!0}async getFeatureFlagPayload(X,Y,G,Q){if(this._payloadOverrides!==void 0&&X in this._payloadOverrides)return this._payloadOverrides[X];let J=await this._getFeatureFlagResult(X,Y,{...Q,sendFeatureFlagEvents:!1},G);if(J===void 0)return;return J.payload??null}async getFeatureFlagResult(X,Y,G){let{distinctId:Q,options:J}=this._resolveDistinctId(Y,G);if(!Q)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(X,Q,{...J,sendFeatureFlagEvents:J?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(X){if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let Y=await this._requestRemoteConfigPayload(X);if(!Y)return;let G=await Y.json();if(typeof G=="string")try{return JSON.parse(G)}catch(Q){}return G}async isFeatureEnabled(X,Y,G){let Q=await this.getFeatureFlag(X,Y,G);if(Q===void 0)return;return!!Q||!1}async getAllFlags(X,Y){let{distinctId:G,options:Q}=this._resolveDistinctId(X,Y);if(!G)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(G,Q)).featureFlags||{}}async getAllFlagsAndPayloads(X,Y){let{distinctId:G,options:Q}=this._resolveDistinctId(X,Y);if(!G)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};let{groups:J,disableGeoip:W,flagKeys:Z}=Q||{},{onlyEvaluateLocally:$,personProperties:K,groupProperties:H}=Q||{},U=this.addLocalPersonAndGroupProperties(G,J,K,H);K=U.allPersonProperties,H=U.allGroupProperties;let N=this.createFeatureFlagEvaluationContext(G,J,K,H);if($==null)$=this.options.strictLocalEvaluation??!1;let B=await this.featureFlagsPoller?.getAllFlagsAndPayloads(N,Z),z={},O={},w=!0;if(B)z=B.response,O=B.payloads,w=B.fallbackToFlags;if(w&&!$){let E=await super.getFeatureFlagsAndPayloadsStateless(N.distinctId,N.groups,N.personProperties,N.groupProperties,W,Z);z={...z,...E.flags||{}},O={...O,...E.payloads||{}}}if(this._flagOverrides!==void 0)z={...z,...this._flagOverrides};if(this._payloadOverrides!==void 0)O={...O,...this._payloadOverrides};return{featureFlags:z,featureFlagPayloads:O}}groupIdentify({groupType:X,groupKey:Y,properties:G,distinctId:Q,disableGeoip:J}){super.groupIdentifyStateless(X,Y,G,{disableGeoip:J},Q)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(X){let Y=(G)=>Object.fromEntries(G.map((Q)=>[Q,!0]));if(X===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(X)){this._flagOverrides=Y(X);return}if(this._isFeatureFlagOverrideOptions(X)){if("flags"in X){if(X.flags===!1)this._flagOverrides=void 0;else if(Array.isArray(X.flags))this._flagOverrides=Y(X.flags);else if(X.flags!==void 0)this._flagOverrides={...X.flags}}if("payloads"in X){if(X.payloads===!1)this._payloadOverrides=void 0;else if(X.payloads!==void 0)this._payloadOverrides={...X.payloads}}return}this._flagOverrides={...X}}_isFeatureFlagOverrideOptions(X){if(typeof X!="object"||X===null||Array.isArray(X))return!1;let Y=X;if("flags"in Y){let G=Y.flags;if(G===!1||Array.isArray(G)||typeof G=="object"&&G!==null)return!0}if("payloads"in Y){let G=Y.payloads;if(G===!1||typeof G=="object"&&G!==null)return!0}return!1}withContext(X,Y,G){if(!this.context)return Y();return this.context.run(X,Y,G)}getContext(){return this.context?.get()}enterContext(X,Y){this.context?.enter(X,Y)}async _shutdown(X){let Y=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(X),this.errorTracking.shutdown();try{return await super._shutdown(X)}finally{Y?.()}}async _requestRemoteConfigPayload(X){if(!this.options.personalApiKey)return;let Y=`${this.host}/api/projects/@current/feature_flags/${X}/remote_config?token=${encodeURIComponent(this.apiKey)}`,G={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},Q=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let J=new AbortController;Q=Hw(()=>{J.abort()},this.options.requestTimeout),G.signal=J.signal}try{return await this.fetch(Y,G)}catch(J){this._events.emit("error",J);return}finally{if(Q)clearTimeout(Q)}}extractPropertiesFromEvent(X,Y){if(!X)return{personProperties:{},groupProperties:{}};let G={},Q={};for(let[J,W]of Object.entries(X))if(me6(W)&&Y&&J in Y){let Z={};for(let[$,K]of Object.entries(W))Z[String($)]=String(K);Q[String(J)]=Z}else G[String(J)]=String(W);return{personProperties:G,groupProperties:Q}}async getFeatureFlagsForEvent(X,Y,G,Q){let J=Q?.personProperties||{},W=Q?.groupProperties||{},Z=Q?.flagKeys;if(Q?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let K={};for(let[H,U]of Object.entries(Y||{}))K[H]=String(U);return await this.getAllFlags(X,{groups:K,personProperties:J,groupProperties:W,disableGeoip:G,onlyEvaluateLocally:!0,flagKeys:Z})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let K={};for(let[H,U]of Object.entries(Y||{}))K[H]=String(U);return await this.getAllFlags(X,{groups:K,personProperties:J,groupProperties:W,disableGeoip:G,onlyEvaluateLocally:!0,flagKeys:Z})}return(await super.getFeatureFlagsStateless(X,Y,J,W,G)).flags}addLocalPersonAndGroupProperties(X,Y,G,Q){let J={distinct_id:X,...G||{}},W={};if(Y)for(let Z of Object.keys(Y))W[Z]={$group_key:Y[Z],...Q?.[Z]||{}};return{allPersonProperties:J,allGroupProperties:W}}createFeatureFlagEvaluationContext(X,Y,G,Q){return{distinctId:X,groups:Y||{},personProperties:G||{},groupProperties:Q||{},evaluationCache:{}}}captureException(X,Y,G,Q){if(!DH.isPreviouslyCapturedError(X)){let J=Error("PostHog syntheticException");this.addPendingPromise(DH.buildEventMessage(X,{syntheticException:J},Y,G).then((W)=>this.capture({...W,uuid:Q})))}}async captureExceptionImmediate(X,Y,G){if(!DH.isPreviouslyCapturedError(X)){let Q=Error("PostHog syntheticException");return this.addPendingPromise(DH.buildEventMessage(X,{syntheticException:Q},Y,G).then((J)=>this.captureImmediate(J)))}}async prepareEventMessage(X){let{distinctId:Y,event:G,properties:Q,groups:J,sendFeatureFlags:W,timestamp:Z,disableGeoip:$,uuid:K}=X,H=this.context?.get(),U=Y||H?.distinctId,N={...this.props,...H?.properties||{},...Q||{}};if(!U)U=Aq(),N.$process_person_profile=!1;if(H?.sessionId&&!N.$session_id)N.$session_id=H.sessionId;let B=this._runBeforeSend({distinctId:U,event:G,properties:N,groups:J,sendFeatureFlags:W,timestamp:Z,disableGeoip:$,uuid:K});if(!B)return Promise.reject(null);let z=await Promise.resolve().then(async()=>{if(W){let O=typeof W=="object"?W:void 0;return await this.getFeatureFlagsForEvent(B.distinctId,J,$,O)}return B.event,{}}).then((O)=>{let w={};if(O)for(let[P,q]of Object.entries(O))w[`$feature/${P}`]=q;let E=Object.keys(O||{}).filter((P)=>O?.[P]!==!1).sort();if(E.length>0)w.$active_feature_flags=E;return w}).catch(()=>({})).then((O)=>{return{...O,...B.properties||{},$groups:B.groups||J}});if(B.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof z.$raw_user_agent=="string"){if(xe6(z.$raw_user_agent,this.options.custom_blocked_useragents||[]))B.event="$bot_pageview",z.$browser_type="bot"}return{distinctId:B.distinctId,event:B.event,properties:z,options:{timestamp:B.timestamp,disableGeoip:B.disableGeoip,uuid:B.uuid}}}_runBeforeSend(X){let Y=this.options.before_send;if(!Y)return X;let G=Array.isArray(Y)?Y:[Y],Q=X;for(let J of G){if(Q=J(Q),!Q)return this._logger.info(`Event '${X.event}' was rejected in beforeSend function`),null;if(!Q.properties||Object.keys(Q.properties).length===0){let W=`Event '${Q.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(W)}}return Q}}});import{AsyncLocalStorage as Za5}from"async_hooks";class lB0{constructor(){this.storage=new Za5}get(){return this.storage.getStore()}run(X,Y,G){return this.storage.run(this.resolve(X,G),Y)}enter(X,Y){this.storage.enterWith(this.resolve(X,Y))}resolve(X,Y){if(Y?.fresh===!0)return X;let G=this.get()||{};return{distinctId:X.distinctId??G.distinctId,sessionId:X.sessionId??G.sessionId,properties:{...G.properties||{},...X.properties||{}}}}}var k04=()=>{};function Wa5(X,{organization:Y,projectId:G,prefix:Q,severityAllowList:J=["error"],sendExceptionsToPostHog:W=!0}={}){return(Z)=>{if(!(J==="*"||J.includes(Z.level)))return Z;if(!Z.tags)Z.tags={};let K=Z.tags[v04.POSTHOG_ID_TAG];if(K===void 0)return Z;let H=X.options.host??"https://us.i.posthog.com",U=new URL(`/project/${X.apiKey}/person/${K}`,H).toString();Z.tags["PostHog Person URL"]=U;let N=Z.exception?.values||[],B=N.map((O)=>({...O,stacktrace:O.stacktrace?{...O.stacktrace,type:"raw",frames:(O.stacktrace.frames||[]).map((w)=>({...w,platform:"node:javascript"}))}:void 0})),z={$exception_message:N[0]?.value||Z.message,$exception_type:N[0]?.type,$exception_level:Z.level,$exception_list:B,$sentry_event_id:Z.event_id,$sentry_exception:Z.exception,$sentry_exception_message:N[0]?.value||Z.message,$sentry_exception_type:N[0]?.type,$sentry_tags:Z.tags};if(Y&&G)z.$sentry_url=(Q||"https://sentry.io/organizations/")+Y+"/issues/?project="+G+"&query="+Z.event_id;if(W)X.capture({event:"$exception",distinctId:K,properties:z});return Z}}var v04;var _04=D(()=>{v04=class v04{static#X=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(X,Y,G,Q,J){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(W,Z){let $=Z()?.getClient()?.getDsn()?.projectId;W(Wa5(X,{organization:Y,projectId:$,prefix:G,severityAllowList:Q,sendExceptionsToPostHog:J??!0}))}}}});var f04=D(()=>{JT1()});var b04=D(()=>{Sj();_04();f04();xB0()});var mB0;var y04=D(()=>{_e6();U04();B04();JT1();C04();Sj();k04();b04();DH.errorPropertiesBuilder=new qW.ErrorPropertiesBuilder([new qW.EventCoercer,new qW.ErrorCoercer,new qW.ObjectCoercer,new qW.StringCoercer,new qW.PrimitiveCoercer],qW.createStackParser("node:javascript",qW.nodeStackLineParser),[ve6(),K04,N04()]);mB0=class mB0 extends uB0{getLibraryId(){return"posthog-node"}initializeContext(){return new lB0}}});function $a5(){return{capture:()=>{},identify:()=>{},captureException:()=>{},groupIdentify:()=>{},shutdown:async()=>{}}}var dB0,x04,j4;var RX=D(()=>{y04();dB0=process.env.POSTHOG_KEY,x04=process.env.POSTHOG_HOST;j4=dB0?new mB0(dB0,{...x04?{host:x04}:{},enableExceptionAutocapture:!0,flushAt:1,flushInterval:0}):$a5();if(dB0){let X=()=>{j4.shutdown().catch(()=>{})};process.on("SIGTERM",X),process.on("SIGINT",X)}});function u$(){let X=v6();if(X.baseUrl)return X.baseUrl;return`http://localhost:${X.port??3000}`}function lX1(){return`http://localhost:${v6().port??3000}`}var Fw=D(()=>{m9()});var h04=D(()=>{kV()});function g04(X){return{organizationId:X.organization_id,domain:X.domain,autoJoinEnabled:X.auto_join_enabled,createdAt:X.created_at,updatedAt:X.updated_at}}class Uw{db;constructor(X){this.db=X}async getByDomain(X){let Y=await this.db.selectFrom("organization_domains").selectAll().where("domain","=",X.toLowerCase()).executeTakeFirst();return Y?g04(Y):null}async getByOrganizationId(X){let Y=await this.db.selectFrom("organization_domains").selectAll().where("organization_id","=",X).executeTakeFirst();return Y?g04(Y):null}async setDomain(X,Y,G=!1){let Q=new Date().toISOString(),J=Y.toLowerCase();try{await this.db.insertInto("organization_domains").values({organization_id:X,domain:J,auto_join_enabled:G,created_at:Q,updated_at:Q}).onConflict((Z)=>Z.column("organization_id").doUpdateSet({domain:J,auto_join_enabled:G,updated_at:Q})).execute()}catch(Z){if(Z.code==="23505")throw Error(`Domain "${J}" is already claimed by another organization.`);throw Z}let W=await this.getByOrganizationId(X);if(!W)throw Error("Failed to set domain");return W}async updateAutoJoin(X,Y){let G=new Date().toISOString();await this.db.updateTable("organization_domains").set({auto_join_enabled:Y,updated_at:G}).where("organization_id","=",X).execute();let Q=await this.getByOrganizationId(X);if(!Q)throw Error("No domain found for organization");return Q}async clearDomain(X){await this.db.deleteFrom("organization_domains").where("organization_id","=",X).execute()}}class cB0{apiKey;constructor(X){this.apiKey=X}async sendEmail({to:X,from:Y,subject:G,html:Q}){let J=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:X,from:Y,subject:G,html:Q})});if(!J.ok)throw Error(`Failed to send email: ${J.statusText}`)}}class iB0{apiKey;constructor(X){this.apiKey=X}async sendEmail({to:X,from:Y,subject:G,html:Q}){let J=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:X}]}],from:{email:Y},subject:G,content:[{type:"text/html",value:Q}]})});if(!J.ok){let W=await J.text();throw Error(`Failed to send email via SendGrid: ${J.statusText} - ${W}`)}}}function Cj(X){let Y=Fa5[X.provider];if(!Y)throw Error(`Unknown email provider: ${X.provider}`);return Y(X)}function kj(X,Y){return X.find((G)=>G.id===Y)}var Ka5=(X)=>{let Y=new cB0(X.config.apiKey);return async({to:G,subject:Q,html:J})=>{await Y.sendEmail({to:G,from:X.config.fromEmail,subject:Q,html:J})}},Ha5=(X)=>{let Y=new iB0(X.config.apiKey);return async({to:G,subject:Q,html:J})=>{await Y.sendEmail({to:G,from:X.config.fromEmail,subject:Q,html:J})}},Fa5;var ZT1=D(()=>{Fa5={resend:Ka5,sendgrid:Ha5}});function vj({preheader:X="",heading:Y,subheading:G,body:Q,footnote:J}){return`<!DOCTYPE html>
|
|
1641
1641
|
<html lang="en">
|
|
1642
1642
|
<head>
|
|
@@ -5026,7 +5026,7 @@ mkdir -p /app && chown deco:deco /app
|
|
|
5026
5026
|
`);if(Y.linkname)G+=Cb0(" linkpath="+Y.linkname+`
|
|
5027
5027
|
`);let Q=Y.pax;if(Q)for(let J in Q)G+=Cb0(" "+J+"="+Q[J]+`
|
|
5028
5028
|
`);return n5.from(G)};bY7.decodePax=function(Y){let G={};while(Y.length){let Q=0;while(Q<Y.length&&Y[Q]!==32)Q++;let J=parseInt(n5.toString(Y.subarray(0,Q)),10);if(!J)return G;let W=n5.toString(Y.subarray(Q+1,J-1)),Z=W.indexOf("=");if(Z===-1)return G;G[W.slice(0,Z)]=W.slice(Z+1),Y=Y.subarray(J)}return G};bY7.encode=function(Y){let G=n5.alloc(512),Q=Y.name,J="";if(Y.typeflag===5&&Q[Q.length-1]!=="/")Q+="/";if(n5.byteLength(Q)!==Q.length)return null;while(n5.byteLength(Q)>100){let W=Q.indexOf("/");if(W===-1)return null;J+=J?"/"+Q.slice(0,W):Q.slice(0,W),Q=Q.slice(W+1)}if(n5.byteLength(Q)>100||n5.byteLength(J)>155)return null;if(Y.linkname&&n5.byteLength(Y.linkname)>100)return null;if(n5.write(G,Q),n5.write(G,qT(Y.mode&4095,6),100),n5.write(G,qT(Y.uid,6),108),n5.write(G,qT(Y.gid,6),116),_Y7(Y.size,G,124),n5.write(G,qT(Y.mtime.getTime()/1000|0,11),136),G[156]=48+kY7(Y.type),Y.linkname)n5.write(G,Y.linkname,157);if(n5.copy(GQ8,G,257),n5.copy(IY7,G,263),Y.uname)n5.write(G,Y.uname,265);if(Y.gname)n5.write(G,Y.gname,297);if(n5.write(G,qT(Y.devmajor||0,6),329),n5.write(G,qT(Y.devminor||0,6),337),J)n5.write(G,J,345);return n5.write(G,qT(JQ8(G),6),148),G};bY7.decode=function(Y,G,Q){let J=Y[156]===0?0:Y[156]-48,W=Cs(Y,0,100,G),Z=PT(Y,100,8),$=PT(Y,108,8),K=PT(Y,116,8),H=PT(Y,124,12),U=PT(Y,136,12),N=CY7(J),B=Y[157]===0?null:Cs(Y,157,100,G),z=Cs(Y,265,32),O=Cs(Y,297,32),w=PT(Y,329,8),E=PT(Y,337,8),P=JQ8(Y);if(P===256)return null;if(P!==PT(Y,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(MY7(Y)){if(Y[345])W=Cs(Y,345,155,G)+"/"+W}else if(RY7(Y));else if(!Q)throw Error("Invalid tar header: unknown format.");if(J===0&&W&&W[W.length-1]==="/")J=5;return{name:W,mode:Z,uid:$,gid:K,size:H,mtime:new Date(1000*U),type:N,linkname:B,uname:z,gname:O,devmajor:w,devminor:E,pax:null}};function MY7(X){return n5.equals(GQ8,X.subarray(257,263))}function RY7(X){return n5.equals(VY7,X.subarray(257,263))&&n5.equals(jY7,X.subarray(263,265))}function SY7(X,Y,G){if(typeof X!=="number")return G;if(X=~~X,X>=Y)return Y;if(X>=0)return X;if(X+=Y,X>=0)return X;return 0}function CY7(X){switch(X){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function kY7(X){switch(X){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function QQ8(X,Y,G,Q){for(;G<Q;G++)if(X[G]===Y)return G;return Q}function JQ8(X){let Y=256;for(let G=0;G<148;G++)Y+=X[G];for(let G=156;G<512;G++)Y+=X[G];return Y}function qT(X,Y){if(X=X.toString(8),X.length>Y)return"7777777777777777777".slice(0,Y)+" ";return"0000000000000000000".slice(0,Y-X.length)+X+" "}function vY7(X,Y,G){Y[G]=128;for(let Q=11;Q>0;Q--)Y[G+Q]=X&255,X=Math.floor(X/256)}function _Y7(X,Y,G){if(X.toString(8).length>11)vY7(X,Y,G);else n5.write(Y,qT(X,11),G)}function fY7(X){let Y;if(X[0]===128)Y=!0;else if(X[0]===255)Y=!1;else return null;let G=[],Q;for(Q=X.length-1;Q>0;Q--){let Z=X[Q];if(Y)G.push(Z);else G.push(255-Z)}let J=0,W=G.length;for(Q=0;Q<W;Q++)J+=G[Q]*Math.pow(256,Q);return Y?J:-1*J}function PT(X,Y,G){if(X=X.subarray(Y,Y+G),Y=0,X[Y]&128)return fY7(X);else{while(Y<X.length&&X[Y]===32)Y++;let Q=SY7(QQ8(X,32,Y,X.length),X.length,X.length);while(Y<Q&&X[Y]===0)Y++;if(Q===Y)return 0;return parseInt(n5.toString(X.subarray(Y,Q)),8)}}function Cs(X,Y,G,Q){return n5.toString(X.subarray(Y,QQ8(X,0,Y,Y+G)),Q)}function Cb0(X){let Y=n5.byteLength(X),G=Math.floor(Math.log(Y)/Math.log(10))+1;if(Y+G>=Math.pow(10,G))G++;return Y+G+X}});var NQ8=C((QrG,UQ8)=>{var{Writable:lY7,Readable:mY7,getStreamError:ZQ8}=Sb0(),dY7=Tb0(),WQ8=Ss(),ks=kb0(),cY7=WQ8.alloc(0);class $Q8{constructor(){this.buffered=0,this.shifted=0,this.queue=new dY7,this._offset=0}push(X){this.buffered+=X.byteLength,this.queue.push(X)}shiftFirst(X){return this._buffered===0?null:this._next(X)}shift(X){if(X>this.buffered)return null;if(X===0)return cY7;let Y=this._next(X);if(X===Y.byteLength)return Y;let G=[Y];while((X-=Y.byteLength)>0)Y=this._next(X),G.push(Y);return WQ8.concat(G)}_next(X){let Y=this.queue.peek(),G=Y.byteLength-this._offset;if(X>=G){let Q=this._offset?Y.subarray(this._offset,Y.byteLength):Y;return this.queue.shift(),this._offset=0,this.buffered-=G,this.shifted+=G,Q}return this.buffered-=X,this.shifted+=X,Y.subarray(this._offset,this._offset+=X)}}class KQ8 extends mY7{constructor(X,Y,G){super();this.header=Y,this.offset=G,this._parent=X}_read(X){if(this.header.size===0)this.push(null);if(this._parent._stream===this)this._parent._update();X(null)}_predestroy(){this._parent.destroy(ZQ8(this))}_detach(){if(this._parent._stream===this)this._parent._stream=null,this._parent._missing=FQ8(this.header.size),this._parent._update()}_destroy(X){this._detach(),X(null)}}class HQ8 extends lY7{constructor(X){super(X);if(!X)X={};this._buffer=new $Q8,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=vb0,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=X.filenameEncoding||"utf-8",this._allowUnknownFormat=!!X.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(X){if(this._locked=!1,X){this.destroy(X),this._continueWrite(X);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=ks.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(X){return this._continueWrite(X),!1}if(!this._header)return!0;switch(this._header.type){case"gnu-long-path":case"gnu-long-link-path":case"pax-global-header":case"pax-header":return this._longHeader=!0,this._missing=this._header.size,!0}if(this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type==="directory")return this.emit("entry",this._header,this._createStream(),this._unlockBound),!0;return this._stream=this._createStream(),this._missing=this._header.size,this.emit("entry",this._header,this._stream,this._unlockBound),!0}_applyLongHeaders(){if(this._gnuLongPath)this._header.name=this._gnuLongPath,this._gnuLongPath=null;if(this._gnuLongLinkPath)this._header.linkname=this._gnuLongLinkPath,this._gnuLongLinkPath=null;if(this._pax){if(this._pax.path)this._header.name=this._pax.path;if(this._pax.linkpath)this._header.linkname=this._pax.linkpath;if(this._pax.size)this._header.size=parseInt(this._pax.size,10);this._header.pax=this._pax,this._pax=null}}_decodeLongHeader(X){switch(this._header.type){case"gnu-long-path":this._gnuLongPath=ks.decodeLongPath(X,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=ks.decodeLongPath(X,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=ks.decodePax(X);break;case"pax-header":this._pax=this._paxGlobal===null?ks.decodePax(X):Object.assign({},this._paxGlobal,ks.decodePax(X));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=FQ8(this._header.size);let X=this._buffer.shift(this._header.size);try{this._decodeLongHeader(X)}catch(Y){return this._continueWrite(Y),!1}return!0}_consumeStream(){let X=this._buffer.shiftFirst(this._missing);if(X===null)return!1;this._missing-=X.byteLength;let Y=this._stream.push(X);if(this._missing===0){if(this._stream.push(null),Y)this._stream._detach();return Y&&this._locked===!1}return Y}_createStream(){return new KQ8(this,this._header,this._offset)}_update(){while(this._buffer.buffered>0&&!this.destroying){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let X=this._buffer.shiftFirst(this._missing);if(X!==null)this._missing-=X.byteLength;continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(X){let Y=this._callback;this._callback=vb0,Y(X)}_write(X,Y){this._callback=Y,this._buffer.push(X),this._update()}_final(X){this._finished=this._missing===0&&this._buffer.buffered===0,X(this._finished?null:Error("Unexpected end of data"))}_predestroy(){this._continueWrite(null)}_destroy(X){if(this._stream)this._stream.destroy(ZQ8(this));X(null)}[Symbol.asyncIterator](){let X=null,Y=null,G=null,Q=null,J=null,W=this;return this.on("entry",K),this.on("error",(N)=>{X=N}),this.on("close",H),{[Symbol.asyncIterator](){return this},next(){return new Promise($)},return(){return U(null)},throw(N){return U(N)}};function Z(N){if(!J)return;let B=J;J=null,B(N)}function $(N,B){if(X)return B(X);if(Q){N({value:Q,done:!1}),Q=null;return}if(Y=N,G=B,Z(null),W._finished&&Y)Y({value:void 0,done:!0}),Y=G=null}function K(N,B,z){if(J=z,B.on("error",vb0),Y)Y({value:B,done:!1}),Y=G=null;else Q=B}function H(){if(Z(X),!Y)return;if(X)G(X);else Y({value:void 0,done:!0});Y=G=null}function U(N){return W.destroy(N),Z(N),new Promise((B,z)=>{if(W.destroyed)return B({value:void 0,done:!0});W.once("close",function(){if(N)z(N);else B({value:void 0,done:!0})})})}}}UQ8.exports=function(Y){return new HQ8(Y)};function vb0(){}function FQ8(X){return X&=511,X&&512-X}});var zQ8=C((JrG,_b0)=>{var BQ8={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{_b0.exports=I1("fs").constants||BQ8}catch{_b0.exports=BQ8}});var qQ8=C((ZrG,PQ8)=>{var{Readable:iY7,Writable:pY7,getStreamError:OQ8}=Sb0(),Mm=Ss(),vs=zQ8(),fc1=kb0(),DQ8=Mm.alloc(1024);class wQ8 extends pY7{constructor(X,Y,G){super({mapWritable:aY7,eagerOpen:!0});if(this.written=0,this.header=Y,this._callback=G,this._linkname=null,this._isLinkname=Y.type==="symlink"&&!Y.linkname,this._isVoid=Y.type!=="file"&&Y.type!=="contiguous-file",this._finished=!1,this._pack=X,this._openCallback=null,this._pack._stream===null)this._pack._stream=this;else this._pack._pending.push(this)}_open(X){if(this._openCallback=X,this._pack._stream===this)this._continueOpen()}_continuePack(X){if(this._callback===null)return;let Y=this._callback;this._callback=null,Y(X)}_continueOpen(){if(this._pack._stream===null)this._pack._stream=this;let X=this._openCallback;if(this._openCallback=null,X===null)return;if(this._pack.destroying)return X(Error("pack stream destroyed"));if(this._pack._finalized)return X(Error("pack stream is already finalized"));if(this._pack._stream=this,!this._isLinkname)this._pack._encode(this.header);if(this._isVoid)this._finish(),this._continuePack(null);X(null)}_write(X,Y){if(this._isLinkname)return this._linkname=this._linkname?Mm.concat([this._linkname,X]):X,Y(null);if(this._isVoid){if(X.byteLength>0)return Y(Error("No body allowed for this entry"));return Y()}if(this.written+=X.byteLength,this._pack.push(X))return Y();this._pack._drain=Y}_finish(){if(this._finished)return;if(this._finished=!0,this._isLinkname)this.header.linkname=this._linkname?Mm.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header);EQ8(this._pack,this.header.size),this._pack._done(this)}_final(X){if(this.written!==this.header.size)return X(Error("Size mismatch"));this._finish(),X(null)}_getError(){return OQ8(this)||Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy(X){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),X()}}class LQ8 extends iY7{constructor(X){super(X);this._drain=fb0,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(X,Y,G){if(this._finalized||this.destroying)throw Error("already finalized or destroyed");if(typeof Y==="function")G=Y,Y=null;if(!G)G=fb0;if(!X.size||X.type==="symlink")X.size=0;if(!X.type)X.type=nY7(X.mode);if(!X.mode)X.mode=X.type==="directory"?493:420;if(!X.uid)X.uid=0;if(!X.gid)X.gid=0;if(!X.mtime)X.mtime=new Date;if(typeof Y==="string")Y=Mm.from(Y);let Q=new wQ8(this,X,G);if(Mm.isBuffer(Y))return X.size=Y.byteLength,Q.write(Y),Q.end(),Q;if(Q._isVoid)return Q;return Q}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}if(this._finalized)return;this._finalized=!0,this.push(DQ8),this.push(null)}_done(X){if(X!==this._stream)return;if(this._stream=null,this._finalizing)this.finalize();if(this._pending.length)this._pending.shift()._continueOpen()}_encode(X){if(!X.pax){let Y=fc1.encode(X);if(Y){this.push(Y);return}}this._encodePax(X)}_encodePax(X){let Y=fc1.encodePax({name:X.name,linkname:X.linkname,pax:X.pax}),G={name:"PaxHeader",mode:X.mode,uid:X.uid,gid:X.gid,size:Y.byteLength,mtime:X.mtime,type:"pax-header",linkname:X.linkname&&"PaxHeader",uname:X.uname,gname:X.gname,devmajor:X.devmajor,devminor:X.devminor};this.push(fc1.encode(G)),this.push(Y),EQ8(this,Y.byteLength),G.size=X.size,G.type=X.type,this.push(fc1.encode(G))}_doDrain(){let X=this._drain;this._drain=fb0,X()}_predestroy(){let X=OQ8(this);if(this._stream)this._stream.destroy(X);while(this._pending.length){let Y=this._pending.shift();Y.destroy(X),Y._continueOpen()}this._doDrain()}_read(X){this._doDrain(),X()}}PQ8.exports=function(Y){return new LQ8(Y)};function nY7(X){switch(X&vs.S_IFMT){case vs.S_IFBLK:return"block-device";case vs.S_IFCHR:return"character-device";case vs.S_IFDIR:return"directory";case vs.S_IFIFO:return"fifo";case vs.S_IFLNK:return"symlink"}return"file"}function fb0(){}function EQ8(X,Y){if(Y&=511,Y)X.push(DQ8.subarray(0,512-Y))}function aY7(X){return Mm.isBuffer(X)?X:Mm.from(X)}});var AQ8=C((tY7)=>{tY7.extract=NQ8();tY7.pack=qQ8()});var VQ8=C(($rG,IQ8)=>{IQ8.exports=TQ8;function TQ8(X,Y){if(X&&Y)return TQ8(X)(Y);if(typeof X!=="function")throw TypeError("need wrapper function");return Object.keys(X).forEach(function(Q){G[Q]=X[Q]}),G;function G(){var Q=Array(arguments.length);for(var J=0;J<Q.length;J++)Q[J]=arguments[J];var W=X.apply(this,Q),Z=Q[Q.length-1];if(typeof W==="function"&&W!==Z)Object.keys(Z).forEach(function($){W[$]=Z[$]});return W}}});var yb0=C((KrG,bb0)=>{var jQ8=VQ8();bb0.exports=jQ8(bc1);bb0.exports.strict=jQ8(MQ8);bc1.proto=bc1(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return bc1(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return MQ8(this)},configurable:!0})});function bc1(X){var Y=function(){if(Y.called)return Y.value;return Y.called=!0,Y.value=X.apply(this,arguments)};return Y.called=!1,Y}function MQ8(X){var Y=function(){if(Y.called)throw Error(Y.onceError);return Y.called=!0,Y.value=X.apply(this,arguments)},G=X.name||"Function wrapped with `once`";return Y.onceError=G+" shouldn't be called more than once",Y.called=!1,Y}});var CQ8=C((HrG,SQ8)=>{var sY7=yb0(),eY7=function(){},XG7=global.Bare?queueMicrotask:process.nextTick.bind(process),YG7=function(X){return X.setHeader&&typeof X.abort==="function"},GG7=function(X){return X.stdio&&Array.isArray(X.stdio)&&X.stdio.length===3},RQ8=function(X,Y,G){if(typeof Y==="function")return RQ8(X,null,Y);if(!Y)Y={};G=sY7(G||eY7);var{_writableState:Q,_readableState:J}=X,W=Y.readable||Y.readable!==!1&&X.readable,Z=Y.writable||Y.writable!==!1&&X.writable,$=!1,K=function(){if(!X.writable)H()},H=function(){if(Z=!1,!W)G.call(X)},U=function(){if(W=!1,!Z)G.call(X)},N=function(E){G.call(X,E?Error("exited with error code: "+E):null)},B=function(E){G.call(X,E)},z=function(){XG7(O)},O=function(){if($)return;if(W&&!(J&&(J.ended&&!J.destroyed)))return G.call(X,Error("premature close"));if(Z&&!(Q&&(Q.ended&&!Q.destroyed)))return G.call(X,Error("premature close"))},w=function(){X.req.on("finish",H)};if(YG7(X))if(X.on("complete",H),X.on("abort",z),X.req)w();else X.on("request",w);else if(Z&&!Q)X.on("end",K),X.on("close",K);if(GG7(X))X.on("exit",N);if(X.on("end",U),X.on("finish",H),Y.error!==!1)X.on("error",B);return X.on("close",z),function(){if($=!0,X.removeListener("complete",H),X.removeListener("abort",z),X.removeListener("request",w),X.req)X.req.removeListener("finish",H);X.removeListener("end",K),X.removeListener("close",K),X.removeListener("finish",H),X.removeListener("exit",N),X.removeListener("end",U),X.removeListener("error",B),X.removeListener("close",z)}};SQ8.exports=RQ8});var _Q8=C((FrG,vQ8)=>{var QG7=yb0(),JG7=CQ8(),yc1;try{yc1=I1("fs")}catch(X){}var y31=function(){},ZG7=typeof process>"u"?!1:/^v?\.0/.test(process.version),xc1=function(X){return typeof X==="function"},WG7=function(X){if(!ZG7)return!1;if(!yc1)return!1;return(X instanceof(yc1.ReadStream||y31)||X instanceof(yc1.WriteStream||y31))&&xc1(X.close)},$G7=function(X){return X.setHeader&&xc1(X.abort)},KG7=function(X,Y,G,Q){Q=QG7(Q);var J=!1;X.on("close",function(){J=!0}),JG7(X,{readable:Y,writable:G},function(Z){if(Z)return Q(Z);J=!0,Q()});var W=!1;return function(Z){if(J)return;if(W)return;if(W=!0,WG7(X))return X.close(y31);if($G7(X))return X.abort();if(xc1(X.destroy))return X.destroy();Q(Z||Error("stream was destroyed"))}},kQ8=function(X){X()},HG7=function(X,Y){return X.pipe(Y)},FG7=function(){var X=Array.prototype.slice.call(arguments),Y=xc1(X[X.length-1]||y31)&&X.pop()||y31;if(Array.isArray(X[0]))X=X[0];if(X.length<2)throw Error("pump requires two streams per minimum");var G,Q=X.map(function(J,W){var Z=W<X.length-1,$=W>0;return KG7(J,Z,$,function(K){if(!G)G=K;if(K)Q.forEach(kQ8);if(Z)return;Q.forEach(kQ8),Y(G)})});return X.reduce(HG7)};vQ8.exports=FG7});var mQ8=C((zG7)=>{var fQ8=AQ8(),bQ8=_Q8(),yQ8=I1("fs"),ZY=I1("path"),x31=(global.Bare?global.Bare.platform:process.platform)==="win32";zG7.pack=function(Y,G){if(!Y)Y=".";if(!G)G={};let Q=G.fs||yQ8,J=G.ignore||G.filter||h31,W=G.mapStream||uQ8,Z=BG7(Q,G.dereference?Q.stat:Q.lstat,Y,J,G.entries,G.sort),$=G.strict!==!1,K=typeof G.umask==="number"?~G.umask:~xQ8(),H=G.pack||fQ8.pack(),U=G.finish||h31,N=G.map||h31,B=typeof G.dmode==="number"?G.dmode:0,z=typeof G.fmode==="number"?G.fmode:0;if(G.strip)N=lQ8(N,G.strip);if(G.readable)B|=parseInt(555,8),z|=parseInt(444,8);if(G.writable)B|=parseInt(333,8),z|=parseInt(222,8);E();function O(P,q){Q.readlink(ZY.join(Y,P),function(j,M){if(j)return H.destroy(j);q.linkname=xb0(M),H.entry(q,E)})}function w(P,q,j){if(H.destroyed)return;if(P)return H.destroy(P);if(!q){if(G.finalize!==!1)H.finalize();return U(H)}if(j.isSocket())return E();let M={name:xb0(q),mode:(j.mode|(j.isDirectory()?B:z))&K,mtime:j.mtime,size:j.size,type:"file",uid:j.uid,gid:j.gid};if(j.isDirectory())return M.size=0,M.type="directory",M=N(M)||M,H.entry(M,E);if(j.isSymbolicLink())return M.size=0,M.type="symlink",M=N(M)||M,O(q,M);if(M=N(M)||M,!j.isFile()){if($)return H.destroy(Error("unsupported type for "+q));return E()}let V=H.entry(M,E),R=W(Q.createReadStream(ZY.join(Y,q),{start:0,end:M.size>0?M.size-1:M.size}),M);R.on("error",function(k){V.destroy(k)}),bQ8(R,V)}function E(P){if(P)return H.destroy(P);Z(w)}return H};function UG7(X){return X.length?X[X.length-1]:null}function NG7(){return!global.Bare&&process.getuid?process.getuid():-1}function xQ8(){return!global.Bare&&process.umask?process.umask():0}zG7.extract=function(Y,G){if(!Y)Y=".";if(!G)G={};Y=ZY.resolve(Y);let Q=G.fs||yQ8,J=G.ignore||G.filter||h31,W=G.mapStream||uQ8,Z=G.chown!==!1&&!x31&&NG7()===0,$=G.extract||fQ8.extract(),K=[],H=new Date,U=typeof G.umask==="number"?~G.umask:~xQ8(),N=G.strict!==!1,B=G.validateSymlinks!==!1,z=G.map||h31,O=typeof G.dmode==="number"?G.dmode:0,w=typeof G.fmode==="number"?G.fmode:0;if(G.strip)z=lQ8(z,G.strip);if(G.readable)O|=parseInt(555,8),w|=parseInt(444,8);if(G.writable)O|=parseInt(333,8),w|=parseInt(222,8);if($.on("entry",E),G.finish)$.on("finish",G.finish);return $;function E(V,R,k){V=z(V)||V,V.name=xb0(V.name);let _=ZY.join(Y,ZY.join("/",V.name));if(J(_,V))return R.resume(),k();let v=ZY.join(_,".")===ZY.join(Y,".")?Y:ZY.dirname(_);gQ8(Q,v,ZY.join(Y,"."),function(u,r){if(u)return k(u);if(!r)return k(Error(v+" is not a valid path"));if(V.type==="directory")return K.push([_,V.mtime]),M(_,{fs:Q,own:Z,uid:V.uid,gid:V.gid,mode:V.mode},y);M(v,{fs:Q,own:Z,uid:V.uid,gid:V.gid,mode:493},function(o){if(o)return k(o);switch(V.type){case"file":return f();case"link":return i();case"symlink":return h()}if(N)return k(Error("unsupported type for "+_+" ("+V.type+")"));R.resume(),k()})});function y(u){if(u)return k(u);q(_,V,function(r){if(r)return k(r);if(x31)return k();j(_,V,k)})}function h(){if(x31)return k();Q.unlink(_,function(){let u=ZY.resolve(ZY.dirname(_),V.linkname);if(!p(u)&&B)return k(Error(_+" is not a valid symlink"));hQ8(Q,u,ZY.join(Y,"."),function(r,o){if(r)return k(r);if(!o&&B)return k(Error(_+" is not a valid symlink"));Q.symlink(V.linkname,_,y)})})}function i(){if(x31)return k();Q.unlink(_,function(){let u=ZY.join(Y,ZY.join("/",V.linkname));Q.realpath(u,function(r,o){if(r||!p(o))return k(Error(_+" is not a valid hardlink"));Q.link(o,_,function(N1){if(N1&&N1.code==="EPERM"&&G.hardlinkAsFilesFallback)return R=Q.createReadStream(o),f();y(N1)})})})}function p(u){return u===Y||u.startsWith(Y+ZY.sep)}function f(){let u=Q.createWriteStream(_),r=W(R,V);u.on("error",function(o){r.destroy(o)}),bQ8(r,u,function(o){if(o)return k(o);u.on("close",y)})}}function P(V,R){let k;while((k=UG7(K))&&V.slice(0,k[0].length)!==k[0])K.pop();if(!k)return R();Q.utimes(k[0],H,k[1],R)}function q(V,R,k){if(G.utimes===!1)return k();if(R.type==="directory")return Q.utimes(V,H,R.mtime,k);if(R.type==="symlink")return P(V,k);Q.utimes(V,H,R.mtime,function(_){if(_)return k(_);P(V,k)})}function j(V,R,k){let _=R.type==="symlink",v=_?Q.lchmod:Q.chmod,y=_?Q.lchown:Q.chown;if(!v)return k();let h=(R.mode|(R.type==="directory"?O:w))&U;if(y&&Z)y.call(Q,V,R.uid,R.gid,i);else i(null);function i(p){if(p)return k(p);if(!v)return k();v.call(Q,V,h,k)}}function M(V,R,k){Q.stat(V,function(_){if(!_)return k(null);if(_.code!=="ENOENT")return k(_);Q.mkdir(V,{mode:R.mode,recursive:!0},function(v,y){if(v)return k(v);j(V,R,k)})})}};function hQ8(X,Y,G,Q){if(Y===G)return Q(null,!0);if(!Y.startsWith(G+ZY.sep))return Q(null,!1);X.lstat(Y,function(J,W){if(J&&J.code!=="ENOENT"&&J.code!=="EPERM")return Q(J);if(J||!W.isSymbolicLink())return hQ8(X,ZY.join(Y,".."),G,Q);Q(null,!1)})}function gQ8(X,Y,G,Q){if(Y===G)return Q(null,!0);X.lstat(Y,function(J,W){if(J&&J.code!=="ENOENT"&&J.code!=="EPERM")return Q(J);if(J||W.isDirectory())return gQ8(X,ZY.join(Y,".."),G,Q);Q(null,!1)})}function h31(){}function uQ8(X){return X}function xb0(X){return x31?X.replace(/\\/g,"/").replace(/[:?<>|]/g,"_"):X}function BG7(X,Y,G,Q,J,W){if(!J)J=["."];let Z=J.slice(0);return function(K){if(!Z.length)return K(null);let H=Z.shift(),U=ZY.join(G,H);Y.call(X,U,function(N,B){if(N)return K(J.indexOf(H)===-1&&N.code==="ENOENT"?null:N);if(!B.isDirectory())return K(null,H,B);X.readdir(U,function(z,O){if(z)return K(z);if(W)O.sort();for(let w=0;w<O.length;w++)if(!Q(ZY.join(G,H,O[w])))Z.push(ZY.join(H,O[w]));K(null,H,B)})})}}function lQ8(X,Y){return function(G){G.name=G.name.split("/").slice(Y).join("/");let Q=G.linkname;if(Q&&(G.type==="link"||ZY.isAbsolute(Q)))G.linkname=Q.split("/").slice(Y).join("/");return X(G)}}});var wG7,LG7;var dQ8=D(()=>{qb0();wG7=Y1(CG8(),1),LG7=Y1(mQ8(),1)});var hc1=()=>{};var cQ8=D(()=>{sd1()});var iQ8=D(()=>{Vc1();Ic1();hc1()});var pQ8=()=>{};var nQ8=()=>{};var hb0=D(()=>{UG8();Eb0();Vc1();DG8();wb0();qb0();wG8();LG8();EG8();PG8();Lb0();qG8();dQ8();hc1();cQ8();iQ8();pQ8();nQ8();hc1()});var C3,rY,_s,g31;var gc1=D(()=>{C3={CLAIM_API_GROUP:"extensions.agents.x-k8s.io",CLAIM_API_VERSION:"v1alpha1",CLAIM_PLURAL:"sandboxclaims",SANDBOX_API_GROUP:"agents.x-k8s.io",SANDBOX_API_VERSION:"v1alpha1",SANDBOX_PLURAL:"sandboxes",POD_NAME_ANNOTATION:"agents.x-k8s.io/pod-name"};rY=class rY extends Error{cause;constructor(X,Y){super(X);if(this.name="SandboxError",this.cause=Y,Y instanceof Error&&Y.stack)this.stack=`${this.stack}
|
|
5029
|
-
Caused by: ${Y.stack}`}};_s=class _s extends rY{constructor(X,Y){super(X,Y);this.name="SandboxTimeoutError"}};g31=class g31 extends rY{constructor(X,Y){super(X,Y);this.name="SandboxAlreadyExistsError"}}});async function EG7(X){let Y=X.getCurrentCluster();if(!Y)throw new rY("No active cluster in kubeconfig");let G={};await X.applyToHTTPSOptions(G);let Q={},J=G.headers??{};for(let[W,Z]of Object.entries(J))if(Array.isArray(Z))Q[W]=Z.join(", ");else if(Z!==void 0)Q[W]=String(Z);if(typeof G.auth==="string"&&!Q.Authorization)Q.Authorization=`Basic ${Buffer.from(G.auth).toString("base64")}`;return{server:Y.server.replace(/\/+$/,""),headers:Q,tls:{cert:gb0(G.cert),key:gb0(G.key),ca:gb0(G.ca),rejectUnauthorized:Y.skipTLSVerify?!1:void 0}}}function gb0(X){if(X==null)return;if(typeof X==="string")return X;if(Buffer.isBuffer(X))return X.toString("utf8");return String(X)}async function u31(X,Y){let G=await EG7(X),Q={...G.headers,...Y.headers};if(Y.method==="PATCH")Q["content-type"]=Y.patchType==="apply"?"application/apply-patch+yaml":Y.patchType==="strategic-merge"?"application/strategic-merge-patch+json":"application/merge-patch+json";else if(Y.body!==void 0&&!("content-type"in Q))Q["content-type"]="application/json";let J={method:Y.method,headers:Q,body:Y.body===void 0?void 0:JSON.stringify(Y.body),signal:Y.signal,tls:G.tls};return fetch(`${G.server}${Y.path}`,J)}async function lb0(X){try{return await X.json()}catch{return null}}async function mb0(X,Y){if(X.ok)return;let G=await lb0(X),Q=G?.message??`${Y} failed: ${X.status} ${X.statusText}`;throw new ub0(X.status,G,Q)}async function l31(X,Y,G,Q,J="none"){try{let W=await u31(X,Y);if(W.status===404)return null;if(await mb0(W,G),J==="json")return await W.json();return null}catch(W){throw new rY(Q,W)}}async function m31(X,Y,G){let Q=`${aQ8}/${encodeURIComponent(Y)}/${C3.CLAIM_PLURAL}`,J;try{J=await u31(X,{method:"POST",path:Q,body:G})}catch(H){throw new rY(`Failed to create SandboxClaim: ${G.metadata.name}`,H)}if(J.ok)return;let W=await lb0(J),Z=W?.reason?` ${W.reason}`:"",$=W?.message??J.statusText,K=`Failed to create SandboxClaim: ${G.metadata.name} (${J.status}${Z}: ${$})`;if(console.warn(`[agent-sandbox/client] createSandboxClaim ${G.metadata.name} rejected: status=${J.status} reason=${W?.reason??"<none>"} message=${$}`),J.status===409)throw new g31(K);throw new rY(K)}async function uc1(X,Y,G,Q=60000){let J=Date.now()+Q,W=500,Z;while(!0){let $=await Sm(X,Y,G).catch(()=>{return});if(!$)return;if(Z=$,Date.now()>=J){let K=Z.metadata?.finalizers??[],H=Z.metadata?.deletionTimestamp??"<unknown>";throw new _s(`SandboxClaim ${G} still terminating after ${Q}ms (deletionTimestamp=${H}, finalizers=[${K.join(", ")}])`)}await new Promise((K)=>setTimeout(K,500))}}function db0(X,Y){return`${aQ8}/${encodeURIComponent(X)}/${C3.CLAIM_PLURAL}/${encodeURIComponent(Y)}`}async function tQ8(X,Y,G,Q){await l31(X,{method:"PATCH",path:db0(Y,G),patchType:"merge",body:{spec:{lifecycle:{shutdownPolicy:"Delete",shutdownTime:Q}}}},"patchSandboxClaimShutdown",`Failed to patch SandboxClaim shutdownTime: ${G}`)}async function Rm(X,Y,G){await l31(X,{method:"DELETE",path:db0(Y,G)},"deleteSandboxClaim",`Failed to delete SandboxClaim: ${G}`)}async function Sm(X,Y,G){return await l31(X,{method:"GET",path:db0(Y,G)},"getSandboxClaim",`Failed to get SandboxClaim: ${G}`,"json")??void 0}function eQ8(X,Y){return`${sQ8}/${encodeURIComponent(X)}/${cb0}/${encodeURIComponent(Y)}`}function PG7(X){return`${sQ8}/${encodeURIComponent(X)}/${cb0}`}async function lc1(X,Y,G){try{let Q=await u31(X,{method:"POST",path:PG7(Y),body:G});if(Q.status===409)return;await mb0(Q,"createHttpRoute")}catch(Q){if(Q instanceof ub0&&Q.status===409)return;throw new rY(`Failed to create HTTPRoute: ${G.metadata.name}`,Q)}}async function mc1(X,Y,G){await l31(X,{method:"DELETE",path:eQ8(Y,G)},"deleteHttpRoute",`Failed to delete HTTPRoute: ${G}`)}async function XJ8(X,Y,G){return await l31(X,{method:"GET",path:eQ8(Y,G)},"getHttpRoute",`Failed to get HTTPRoute: ${G}`,"json")??void 0}async function YJ8(X,Y,G,Q){let J={apiVersion:"v1",kind:"Service",metadata:{name:G},spec:{ports:[{name:Q.name,port:Q.port,targetPort:Q.targetPort,protocol:Q.protocol??"TCP"}]}},W=new URLSearchParams({fieldManager:qG7,force:"true"}),Z=`/api/v1/namespaces/${encodeURIComponent(Y)}/services/${encodeURIComponent(G)}?${W}`;try{let $=await u31(X,{method:"PATCH",path:Z,patchType:"apply",body:J});await mb0($,"ensureServicePort")}catch($){throw new rY(`Failed to apply Service ports: ${G}`,$)}}function dc1(X,Y,G,Q=180){let J=`/apis/${C3.SANDBOX_API_GROUP}/${C3.SANDBOX_API_VERSION}/namespaces/${encodeURIComponent(Y)}/${C3.SANDBOX_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${G}`)}`,{resolve:W,reject:Z,promise:$}=Promise.withResolvers(),K=new AbortController,H=!1,U=setTimeout(()=>{if(H)return;H=!0,K.abort(),Z(new _s(`Sandbox did not become ready within ${Q} seconds`))},Q*1000),N=(B)=>{if(H)return;H=!0,clearTimeout(U),K.abort(),B()};return(async()=>{let B;try{B=await u31(X,{method:"GET",path:J,signal:K.signal,headers:{accept:"application/json"}})}catch(z){N(()=>Z(new rY("Failed to start watch for sandbox readiness",z)));return}if(!B.ok||!B.body){let z=await lb0(B).catch(()=>null);N(()=>Z(new rY(`Watch handshake failed (${B.status}): ${z?.message??B.statusText}`)));return}try{for await(let z of AG7(B.body)){if(H)return;if(z.type==="ERROR"){let q=z.object;N(()=>Z(new rY(`Watch stream error while waiting for sandbox: ${q.message??"unknown"}`)));return}if(z.type!=="ADDED"&&z.type!=="MODIFIED")continue;let O=z.object;if(!O.status?.conditions?.find((q)=>q.type==="Ready"&&q.status==="True"))continue;let E=O.metadata?.name;if(!E){N(()=>Z(new rY("Sandbox metadata or name is missing")));return}let P=O.metadata?.annotations?.[C3.POD_NAME_ANNOTATION]??E;N(()=>W({sandboxName:E,podName:P}));return}N(()=>Z(new rY("Watch stream closed before sandbox became ready")))}catch(z){if(H)return;if(z instanceof Error&&(z.name==="AbortError"||K.signal.aborted))return;N(()=>Z(new rY("Watch stream error while waiting for sandbox",z)))}})(),$}async function*AG7(X){let Y=X.getReader(),G=new TextDecoder,Q="";try{while(!0){let{value:W,done:Z}=await Y.read();if(Z)break;Q+=G.decode(W,{stream:!0});let $;while(($=Q.indexOf(`
|
|
5029
|
+
Caused by: ${Y.stack}`}};_s=class _s extends rY{constructor(X,Y){super(X,Y);this.name="SandboxTimeoutError"}};g31=class g31 extends rY{constructor(X,Y){super(X,Y);this.name="SandboxAlreadyExistsError"}}});async function EG7(X){let Y=X.getCurrentCluster();if(!Y)throw new rY("No active cluster in kubeconfig");let G={};await X.applyToHTTPSOptions(G);let Q={},J=G.headers??{};for(let[W,Z]of Object.entries(J))if(Array.isArray(Z))Q[W]=Z.join(", ");else if(Z!==void 0)Q[W]=String(Z);if(typeof G.auth==="string"&&!Q.Authorization)Q.Authorization=`Basic ${Buffer.from(G.auth).toString("base64")}`;return{server:Y.server.replace(/\/+$/,""),headers:Q,tls:{cert:gb0(G.cert),key:gb0(G.key),ca:gb0(G.ca),rejectUnauthorized:Y.skipTLSVerify?!1:void 0}}}function gb0(X){if(X==null)return;if(typeof X==="string")return X;if(Buffer.isBuffer(X))return X.toString("utf8");return String(X)}async function u31(X,Y){let G=await EG7(X),Q={...G.headers,...Y.headers};if(Y.method==="PATCH")Q["content-type"]=Y.patchType==="apply"?"application/apply-patch+yaml":Y.patchType==="strategic-merge"?"application/strategic-merge-patch+json":"application/merge-patch+json";else if(Y.body!==void 0&&!("content-type"in Q))Q["content-type"]="application/json";let J={method:Y.method,headers:Q,body:Y.body===void 0?void 0:JSON.stringify(Y.body),signal:Y.signal,tls:G.tls};return fetch(`${G.server}${Y.path}`,J)}async function lb0(X){try{return await X.json()}catch{return null}}async function mb0(X,Y){if(X.ok)return;let G=await lb0(X),Q=G?.message??`${Y} failed: ${X.status} ${X.statusText}`;throw new ub0(X.status,G,Q)}async function l31(X,Y,G,Q,J="none"){try{let W=await u31(X,Y);if(W.status===404)return null;if(await mb0(W,G),J==="json")return await W.json();return null}catch(W){throw new rY(Q,W)}}async function m31(X,Y,G){let Q=`${aQ8}/${encodeURIComponent(Y)}/${C3.CLAIM_PLURAL}`,J;try{J=await u31(X,{method:"POST",path:Q,body:G})}catch(H){let U=H instanceof Error?H.message:String(H);throw console.warn(`[agent-sandbox/client] createSandboxClaim ${G.metadata.name} transport error: ${U}`),new rY(`Failed to create SandboxClaim: ${G.metadata.name} (transport error: ${U})`,H)}if(J.ok)return;let W=await lb0(J),Z=W?.reason?` ${W.reason}`:"",$=W?.message??J.statusText,K=`Failed to create SandboxClaim: ${G.metadata.name} (${J.status}${Z}: ${$})`;if(console.warn(`[agent-sandbox/client] createSandboxClaim ${G.metadata.name} rejected: status=${J.status} reason=${W?.reason??"<none>"} message=${$}`),J.status===409)throw new g31(K);throw new rY(K)}async function uc1(X,Y,G,Q=60000){let J=Date.now()+Q,W=500,Z;while(!0){let $=await Sm(X,Y,G).catch(()=>{return});if(!$)return;if(Z=$,Date.now()>=J){let K=Z.metadata?.finalizers??[],H=Z.metadata?.deletionTimestamp??"<unknown>";throw new _s(`SandboxClaim ${G} still terminating after ${Q}ms (deletionTimestamp=${H}, finalizers=[${K.join(", ")}])`)}await new Promise((K)=>setTimeout(K,500))}}function db0(X,Y){return`${aQ8}/${encodeURIComponent(X)}/${C3.CLAIM_PLURAL}/${encodeURIComponent(Y)}`}async function tQ8(X,Y,G,Q){await l31(X,{method:"PATCH",path:db0(Y,G),patchType:"merge",body:{spec:{lifecycle:{shutdownPolicy:"Delete",shutdownTime:Q}}}},"patchSandboxClaimShutdown",`Failed to patch SandboxClaim shutdownTime: ${G}`)}async function Rm(X,Y,G){await l31(X,{method:"DELETE",path:db0(Y,G)},"deleteSandboxClaim",`Failed to delete SandboxClaim: ${G}`)}async function Sm(X,Y,G){return await l31(X,{method:"GET",path:db0(Y,G)},"getSandboxClaim",`Failed to get SandboxClaim: ${G}`,"json")??void 0}function eQ8(X,Y){return`${sQ8}/${encodeURIComponent(X)}/${cb0}/${encodeURIComponent(Y)}`}function PG7(X){return`${sQ8}/${encodeURIComponent(X)}/${cb0}`}async function lc1(X,Y,G){try{let Q=await u31(X,{method:"POST",path:PG7(Y),body:G});if(Q.status===409)return;await mb0(Q,"createHttpRoute")}catch(Q){if(Q instanceof ub0&&Q.status===409)return;throw new rY(`Failed to create HTTPRoute: ${G.metadata.name}`,Q)}}async function mc1(X,Y,G){await l31(X,{method:"DELETE",path:eQ8(Y,G)},"deleteHttpRoute",`Failed to delete HTTPRoute: ${G}`)}async function XJ8(X,Y,G){return await l31(X,{method:"GET",path:eQ8(Y,G)},"getHttpRoute",`Failed to get HTTPRoute: ${G}`,"json")??void 0}async function YJ8(X,Y,G,Q){let J={apiVersion:"v1",kind:"Service",metadata:{name:G},spec:{ports:[{name:Q.name,port:Q.port,targetPort:Q.targetPort,protocol:Q.protocol??"TCP"}]}},W=new URLSearchParams({fieldManager:qG7,force:"true"}),Z=`/api/v1/namespaces/${encodeURIComponent(Y)}/services/${encodeURIComponent(G)}?${W}`;try{let $=await u31(X,{method:"PATCH",path:Z,patchType:"apply",body:J});await mb0($,"ensureServicePort")}catch($){throw new rY(`Failed to apply Service ports: ${G}`,$)}}function dc1(X,Y,G,Q=180){let J=`/apis/${C3.SANDBOX_API_GROUP}/${C3.SANDBOX_API_VERSION}/namespaces/${encodeURIComponent(Y)}/${C3.SANDBOX_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${G}`)}`,{resolve:W,reject:Z,promise:$}=Promise.withResolvers(),K=new AbortController,H=!1,U=setTimeout(()=>{if(H)return;H=!0,K.abort(),Z(new _s(`Sandbox did not become ready within ${Q} seconds`))},Q*1000),N=(B)=>{if(H)return;H=!0,clearTimeout(U),K.abort(),B()};return(async()=>{let B;try{B=await u31(X,{method:"GET",path:J,signal:K.signal,headers:{accept:"application/json"}})}catch(z){N(()=>Z(new rY("Failed to start watch for sandbox readiness",z)));return}if(!B.ok||!B.body){let z=await lb0(B).catch(()=>null);N(()=>Z(new rY(`Watch handshake failed (${B.status}): ${z?.message??B.statusText}`)));return}try{for await(let z of AG7(B.body)){if(H)return;if(z.type==="ERROR"){let q=z.object;N(()=>Z(new rY(`Watch stream error while waiting for sandbox: ${q.message??"unknown"}`)));return}if(z.type!=="ADDED"&&z.type!=="MODIFIED")continue;let O=z.object;if(!O.status?.conditions?.find((q)=>q.type==="Ready"&&q.status==="True"))continue;let E=O.metadata?.name;if(!E){N(()=>Z(new rY("Sandbox metadata or name is missing")));return}let P=O.metadata?.annotations?.[C3.POD_NAME_ANNOTATION]??E;N(()=>W({sandboxName:E,podName:P}));return}N(()=>Z(new rY("Watch stream closed before sandbox became ready")))}catch(z){if(H)return;if(z instanceof Error&&(z.name==="AbortError"||K.signal.aborted))return;N(()=>Z(new rY("Watch stream error while waiting for sandbox",z)))}})(),$}async function*AG7(X){let Y=X.getReader(),G=new TextDecoder,Q="";try{while(!0){let{value:W,done:Z}=await Y.read();if(Z)break;Q+=G.decode(W,{stream:!0});let $;while(($=Q.indexOf(`
|
|
5030
5030
|
`))>=0){let K=Q.slice(0,$).trim();if(Q=Q.slice($+1),!K)continue;yield JSON.parse(K)}}let J=Q.trim();if(J)yield JSON.parse(J)}finally{Y.releaseLock()}}var ub0,aQ8,rQ8="gateway.networking.k8s.io",oQ8="v1",cb0="httproutes",sQ8,d31,qG7="mesh-sandbox-runner";var ib0=D(()=>{gc1();ub0=class ub0 extends Error{status;body;constructor(X,Y,G){super(G);this.status=X;this.body=Y;this.name="KubeHttpError"}};aQ8=`/apis/${C3.CLAIM_API_GROUP}/${C3.CLAIM_API_VERSION}/namespaces`;sQ8=`/apis/${rQ8}/${oQ8}/namespaces`;d31={API_GROUP:rQ8,API_VERSION:oQ8,PLURAL:cb0}});import{createHash as TG7,randomBytes as IG7,randomUUID as VG7}from"crypto";import*as ZJ8 from"net";import{PassThrough as jG7}from"stream";class sb0{kind=pz;records=new Map;inflight=new mL;stateStore;previewUrlPattern;kubeConfig;portForward;namespace;sandboxTemplateName;tokenGenerator;idleTtlMs;metrics;previewGateway;constructor(X={}){this.stateStore=X.stateStore??null,this.previewUrlPattern=X.previewUrlPattern??null,this.kubeConfig=X.kubeConfig??xG7(),this.portForward=new Ab0(this.kubeConfig),this.namespace=X.namespace??MG7,this.sandboxTemplateName=X.sandboxTemplateName??RG7,this.tokenGenerator=X.tokenGenerator??(()=>IG7(CG7).toString("hex")),this.idleTtlMs=X.idleTtlMs??vG7,this.metrics=X.meter?yG7(X.meter):null,this.previewGateway=X.previewGateway&&X.previewUrlPattern?{...X.previewGateway}:null}async ensure(X,Y={}){let G=this.computeHandle(X,Y.repo?.branch??null);return this.inflight.run(G,()=>nT(this.stateStore,X,pz,(Q)=>this.ensureLocked(X,G,Y,Q)))}async exec(X,Y){let G=await this.requireRecord(X);return A$1(G.daemonUrl,G.token,Y)}async delete(X){let Y=await this.getRecord(X);if(this.records.delete(X),Y)this.closeForwarder(Y.daemonForward),this.metrics?.active.add(-1,rb0(Y.tenant));if(await this.deleteHttpRouteIfManaged(X).catch((G)=>{console.warn(`[${iW}] HTTPRoute delete failed for ${X}: ${G instanceof Error?G.message:String(G)}`)}),await Rm(this.kubeConfig,this.namespace,X),this.stateStore)if(Y)await this.stateStore.delete(Y.id,pz);else await this.stateStore.deleteByHandle(pz,X)}async alive(X){let Y=await Sm(this.kubeConfig,this.namespace,X).catch(()=>{return});return Y?nb0(Y):!1}async getPreviewUrl(X){let Y=await this.getRecord(X);if(!Y)return null;return this.composePreviewUrl(Y)}async proxyDaemonRequest(X,Y,G){let Q=await this.getRecord(X);if(!Q)return new Response(JSON.stringify({error:"sandbox not found"}),{status:404,headers:{"content-type":"application/json"}});let J=performance.now(),W=0;try{let Z=await T$1(Q.daemonUrl,Q.token,Y,G);return W=Z.status,Z}finally{this.recordProxyDuration("daemon",W,Q,performance.now()-J)}}async resolvePreviewUpstreamUrl(X){if(this.previewUrlPattern)return`http://${X}.${this.namespace}.svc.cluster.local:${Cm}`;let Y=await this.getRecord(X);if(Y)return Y.daemonUrl;let G=await this.resurrectByHandle(X);return G?G.daemonUrl:null}async proxyPreviewRequest(X,Y){let G=performance.now(),Q=this.records.get(X)??null,J=0;try{let W=await this.resolvePreviewUpstreamUrl(X);if(!W)return J=404,ab0(404,{error:"sandbox not found"});let Z=new URL(Y.url);if((Z.pathname==="/_decopilot_vm"||Z.pathname.startsWith("/_decopilot_vm/"))&&Y.method!=="GET")return J=404,ab0(404,{error:"not found"});let K=(O)=>`${O}${Z.pathname}${Z.search}`,H=new Headers(Y.headers);for(let O of fG7)H.delete(O);let U=Y.method!=="GET"&&Y.method!=="HEAD",N={method:Y.method,headers:H,body:U?Y.body:void 0,redirect:"manual",signal:Y.signal,duplex:U?"half":void 0},B;try{B=await fetch(K(W),N)}catch(O){let w=`${W}${Z.pathname}`;if(console.warn(`[${iW}] preview fetch to ${w} failed: ${O instanceof Error?O.message:String(O)}`),Y.method==="GET"||Y.method==="HEAD"){if(this.invalidateRecord(X),await this.resurrectByHandle(X).catch(()=>null)){let P=await this.resolvePreviewUpstreamUrl(X);if(P)try{B=await fetch(K(P),N);let q=new Headers;for(let[j,M]of B.headers.entries())if(!GJ8.includes(j.toLowerCase()))q.set(j,M);return J=B.status,new Response(B.body,{status:B.status,statusText:B.statusText,headers:q})}catch(q){console.warn(`[${iW}] preview fetch retry to ${w} failed: ${q instanceof Error?q.message:String(q)}`)}}}else this.invalidateRecord(X);return J=502,ab0(502,{error:"sandbox daemon unreachable"})}let z=new Headers;for(let[O,w]of B.headers.entries())if(!GJ8.includes(O.toLowerCase()))z.set(O,w);return J=B.status,new Response(B.body,{status:B.status,statusText:B.statusText,headers:z})}finally{this.recordProxyDuration("preview",J,Q,performance.now()-G,X)}}async ensureLocked(X,Y,G,Q){if(G.image)console.warn(`[${iW}] opts.image ignored (template ${this.sandboxTemplateName} pins image): got ${G.image}`);if(Q){let Z=await Q.get(X,pz);if(Z){let $=await this.rehydrate(X,Y,Z);if($)return this.finish($,Q,!1,!0,"resume");await Q.delete(X,pz)}}let J=await Sm(this.kubeConfig,this.namespace,Y).catch(()=>{return});if(J)if(J.metadata?.deletionTimestamp)await uc1(this.kubeConfig,this.namespace,Y).catch((Z)=>{console.warn(`[${iW}] wait for terminating claim ${Y} failed: ${Z instanceof Error?Z.message:String(Z)}`)});else{let Z=await this.adopt(X,Y,J).catch(($)=>{return console.warn(`[${iW}] adopt ${Y} failed, recreating: ${$ instanceof Error?$.message:String($)}`),null});if(Z)return this.finish(Z,Q,!0,!0,"adopt");await Rm(this.kubeConfig,this.namespace,Y).catch(()=>{}),await uc1(this.kubeConfig,this.namespace,Y).catch(($)=>{console.warn(`[${iW}] wait for deleted claim ${Y} failed: ${$ instanceof Error?$.message:String($)}`)})}let W=await this.provision(X,Y,G);return this.finish(W,Q,!0,!1,"fresh")}async finish(X,Y,G,Q,J){let W=this.records.has(X.handle);if(this.records.set(X.handle,X),G)await this.persist(Y,X);if(Q)await tQ8(this.kubeConfig,this.namespace,X.handle,this.computeShutdownTime()).catch((Z)=>console.warn(`[${iW}] TTL refresh failed for ${X.handle}: ${Z instanceof Error?Z.message:String(Z)}`));if(this.metrics){let Z=rb0(X.tenant);if(this.metrics.ensureOutcome.add(1,{...Z,outcome:J}),!W)this.metrics.active.add(1,Z)}return this.toSandbox(X)}buildEnvMap(X,Y){let G={},Q=[];for(let[Z,$]of Object.entries(X.env??{}))if(kG7.has(Z))Q.push(Z);else G[Z]=$;if(Q.length>0)console.warn(`[${iW}] opts.env keys overlap reserved bootstrap names and were dropped: ${Q.join(",")}`);let J=X.repo,W=J?J.displayName??iG7(J.cloneUrl):null;return{...G,DAEMON_TOKEN:Y.token,DAEMON_BOOT_ID:Y.daemonBootId,APP_ROOT:Y.workdir,PROXY_PORT:String(Cm),DEV_PORT:String(X.workload?.devPort??SG7),RUNTIME:X.workload?.runtime??"node",...J?{CLONE_URL:J.cloneUrl,REPO_NAME:W??"",BRANCH:J.branch??"",GIT_USER_NAME:J.userName,GIT_USER_EMAIL:J.userEmail}:{},...X.workload?.packageManager?{PACKAGE_MANAGER:X.workload.packageManager}:{}}}buildClaim(X,Y,G){let Q=this.buildEnvMap(Y,G);return{apiVersion:`${C3.CLAIM_API_GROUP}/${C3.CLAIM_API_VERSION}`,kind:"SandboxClaim",metadata:{name:X,namespace:this.namespace,labels:{"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...tb0(Y.tenant)}},spec:{sandboxTemplateRef:{name:this.sandboxTemplateName},additionalPodMetadata:{labels:tb0(Y.tenant,{[AT.role]:"claimed",[AT.sandboxHandle]:X})},env:Object.entries(Q).sort(([J],[W])=>J<W?-1:J>W?1:0).map(([J,W])=>({name:J,value:W})),warmpool:"none",lifecycle:{shutdownPolicy:"Delete",shutdownTime:this.computeShutdownTime()}}}}async provision(X,Y,G){let Q=this.tokenGenerator(),J=VG7(),W=pb0,Z=this.buildClaim(Y,G,{token:Q,daemonBootId:J,workdir:W});try{await m31(this.kubeConfig,this.namespace,Z)}catch(U){if(U instanceof g31)await uc1(this.kubeConfig,this.namespace,Y),await m31(this.kubeConfig,this.namespace,Z);else throw U}let{podName:$}=await dc1(this.kubeConfig,this.namespace,Y);try{await this.ensureServicePortForHandle(Y),await this.ensureHttpRouteForHandle(Y,G.tenant??null)}catch(U){throw await Rm(this.kubeConfig,this.namespace,Y).catch(()=>{}),U}let K=await this.openForwarder($,Cm,Y),H=`http://127.0.0.1:${K.localPort}`;try{await q$1(H)}catch(U){throw this.closeForwarder(K),await this.deleteHttpRouteIfManaged(Y).catch(()=>{}),await Rm(this.kubeConfig,this.namespace,Y).catch(()=>{}),U}return{id:X,handle:Y,podName:$,token:Q,workdir:W,daemonUrl:H,daemonForward:K,workload:G.workload??null,daemonBootId:J,tenant:G.tenant??null,ensureOpts:dG7(G)}}async ensureServicePortForHandle(X){if(!this.previewGateway||!this.previewUrlPattern)return;await YJ8(this.kubeConfig,this.namespace,X,{name:"daemon",port:Cm,targetPort:Cm})}async ensureHttpRouteForHandle(X,Y){if(!this.previewGateway||!this.previewUrlPattern)return;let G=cG7(this.previewUrlPattern,X);if(!G)throw new rY(`Unable to derive preview hostname for ${X} from pattern: ${this.previewUrlPattern}`);let Q={apiVersion:`${d31.API_GROUP}/${d31.API_VERSION}`,kind:"HTTPRoute",metadata:{name:X,namespace:this.namespace,labels:tb0(Y??void 0,{[AT.role]:"claimed",[AT.sandboxHandle]:X,"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio"})},spec:{parentRefs:[{kind:"Gateway",group:"gateway.networking.k8s.io",name:this.previewGateway.name,namespace:this.previewGateway.namespace}],hostnames:[G],rules:[{backendRefs:[{group:"",kind:"Service",name:X,port:Cm}]}]}};await lc1(this.kubeConfig,this.namespace,Q)}async deleteHttpRouteIfManaged(X){if(!this.previewGateway)return;await mc1(this.kubeConfig,this.namespace,X)}async rehydrate(X,Y,G){let Q=G.state;if(!Q.podName||!Q.token)return null;let J=await Sm(this.kubeConfig,this.namespace,Y).catch(()=>{return});if(!J||!nb0(J))return null;let W=QJ8(J)??Q.podName,Z=await this.openAndProbeDaemon(W,Y);if(!Z)return null;if(Q.daemonBootId&&Q.daemonBootId!==Z.bootId)console.warn(`[${iW}] daemon restart detected (handle=${Y}): stored bootId=${Q.daemonBootId} live bootId=${Z.bootId}`);return{id:X,handle:Y,podName:W,token:Q.token,workdir:Q.workdir??pb0,daemonUrl:Z.daemonUrl,daemonForward:Z.daemonForward,workload:Q.workload??null,daemonBootId:Z.bootId,tenant:Q.tenant??null,ensureOpts:Q.ensureOpts??null}}async adopt(X,Y,G){if(!nb0(G))return null;let Q=QJ8(G);if(!Q)return null;let J=hG7(G);if(!J)return null;let W=await this.openAndProbeDaemon(Q,Y);if(!W)return null;let Z=mG7(G);if(this.previewGateway)await this.ensureServicePortForHandle(Y).catch(($)=>{console.warn(`[${iW}] Service port backfill failed for ${Y}: ${$ instanceof Error?$.message:String($)}`)}),await this.ensureHttpRouteForHandle(Y,Z).catch(($)=>{console.warn(`[${iW}] HTTPRoute backfill failed for ${Y}: ${$ instanceof Error?$.message:String($)}`)});return{id:X,handle:Y,podName:Q,token:J,workdir:pb0,daemonUrl:W.daemonUrl,daemonForward:W.daemonForward,workload:null,daemonBootId:W.bootId,tenant:Z,ensureOpts:null}}async openAndProbeDaemon(X,Y){let G=await this.openForwarder(X,Cm,Y).catch(()=>null);if(!G)return null;let Q=`http://127.0.0.1:${G.localPort}`,J=await Pd(Q);if(!J)return this.closeForwarder(G),null;return{daemonForward:G,daemonUrl:Q,bootId:J.bootId}}async getRecord(X){let Y=this.records.get(X);if(Y)return Y;if(!this.stateStore)return null;let G=await this.stateStore.getByHandle(pz,X);if(!G)return null;let Q=await this.rehydrate(G.id,X,G);if(Q)this.records.set(X,Q);return Q}async resurrectByHandle(X){if(!this.stateStore)return null;let Y=await this.stateStore.getByHandle(pz,X);if(!Y)return null;let G=Y.state.ensureOpts;if(!G)return null;return await this.ensure(Y.id,G),this.records.get(X)??null}async requireRecord(X){let Y=await this.getRecord(X);if(Y)return Y;let G=await this.resurrectByHandle(X);if(G)return G;throw Error(`unknown sandbox handle ${X}`)}invalidateRecord(X){let Y=this.records.get(X);if(!Y)return;this.records.delete(X),this.closeForwarder(Y.daemonForward)}recordProxyDuration(X,Y,G,Q,J){if(!this.metrics)return;this.metrics.proxyDurationMs.record(Q,{...rb0(G?.tenant??null),source:X,sandbox_handle:G?.handle??J??"",status_code:Y||0})}computeHandle(X,Y){return`${c31}${aT(X,Y,{hashLen:_G7})}`}composePreviewUrl(X){if(this.previewUrlPattern)return tT(this.previewUrlPattern,X.handle);return`http://127.0.0.1:${X.daemonForward.localPort}/`}toSandbox(X){return{handle:X.handle,workdir:X.workdir,previewUrl:this.composePreviewUrl(X)}}async persist(X,Y){if(!X)return;let G={podName:Y.podName,token:Y.token,workdir:Y.workdir,workload:Y.workload,daemonBootId:Y.daemonBootId,tenant:Y.tenant,...Y.ensureOpts?{ensureOpts:Y.ensureOpts}:{}};await X.put(Y.id,pz,{handle:Y.handle,state:G})}computeShutdownTime(){return new Date(Date.now()+this.idleTtlMs).toISOString()}openForwarder(X,Y,G=X){let Q=gG7(G,Y);return new Promise((J,W)=>{let Z=($,K)=>{let H=ZJ8.createServer((U)=>this.handleForwardedConnection(U,X,Y));H.once("error",(U)=>{if(U.code==="EADDRINUSE"&&K<bG7){try{H.close()}catch{}let N=ob0+($-ob0+1)%WJ8;Z(N,K+1);return}W(U)}),H.listen($,"127.0.0.1",()=>{let U=H.address();if(!U||typeof U==="string"){H.close(),W(Error("port-forward listener failed to bind"));return}J({server:H,localPort:U.port})})};Z(Q,0)})}handleForwardedConnection(X,Y,G){let Q=new jG7,J=null,W=!1,Z=()=>{if(W)return;if(W=!0,Q.destroy(),J)try{J.close()}catch{}if(!X.destroyed)X.destroy()};X.pipe(Q),X.on("error",Z),X.on("close",Z),this.portForward.portForward(this.namespace,Y,[G],X,null,Q).then(($)=>{let K=typeof $==="function"?$():$;if(!K){Z();return}if(J=K,J.on("close",Z),J.on("error",Z),W)try{J.close()}catch{}}).catch(($)=>{console.warn(`[${iW}] port-forward to ${Y}:${G} failed: ${$ instanceof Error?$.message:String($)}`),Z()})}closeForwarder(X){X.server.close((Y)=>{if(Y)console.warn(`[${iW}] port-forward close on :${X.localPort} errored: ${Y instanceof Error?Y.message:String(Y)}`)})}}function yG7(X){return{active:X.createUpDownCounter("studio.sandbox.active",{description:"Active sandbox count, by runner kind and owning org. Cross-checks the cAdvisor-derived count from the cluster \u2014 divergence between the two indicates orphaned claims (mesh deleted but K8s didn't reap) or unattributed pods.",unit:"{sandbox}"}),ensureOutcome:X.createCounter("studio.sandbox.ensure.outcome",{description:"Outcome of each ensure() call: fresh provision, resume from state-store after restart, or adopt of a cluster-side claim mesh didn't know about. Cold-start ratio is the primary input for warm-pool sizing.",unit:"{call}"}),proxyDurationMs:X.createHistogram("studio.sandbox.proxy.duration_ms",{description:"Wall-clock latency of mesh-mediated requests to the sandbox daemon: tool exec proxies (source=daemon) and preview iframe traffic (source=preview).",unit:"ms"})}}function xG7(){let X=new Rs;return X.loadFromDefault(),X}function nb0(X){return Boolean(X.status?.conditions?.some((Y)=>Y.type==="Ready"&&Y.status==="True"))}function hG7(X){let Y=X.spec?.env;if(!Y)return null;for(let G of Y)if(G.name==="DAEMON_TOKEN"&&G.value)return G.value;return null}function QJ8(X){return X.metadata?.annotations?.[C3.POD_NAME_ANNOTATION]??X.metadata?.name??null}function gG7(X,Y){let G=TG7("sha256").update(`${X}:${Y}`).digest();return ob0+G.readUInt32BE(0)%WJ8}function ab0(X,Y){return new Response(JSON.stringify(Y),{status:X,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function JJ8(X){let Y=X.slice(0,lG7);return uG7.test(Y)?Y:""}function tb0(X,Y={}){let G={...Y};if(X){let Q=JJ8(X.orgId),J=JJ8(X.userId);if(Q)G[AT.orgId]=Q;if(J)G[AT.userId]=J}return G}function mG7(X){let Y=X.metadata?.labels;if(!Y)return null;let G=Y[AT.orgId],Q=Y[AT.userId];if(!G||!Q)return null;return{orgId:G,userId:Q}}function rb0(X){return{org_id:X?.orgId??"",user_id:X?.userId??"",runner_kind:pz}}function dG7(X){let Y={};if(X.repo)Y.repo=X.repo;if(X.workload)Y.workload=X.workload;if(X.env&&Object.keys(X.env).length>0)Y.env=X.env;if(X.tenant)Y.tenant=X.tenant;return Object.keys(Y).length>0?Y:null}function cG7(X,Y){try{return new URL(tT(X,Y)).hostname||null}catch{return null}}function iG7(X){try{let Y=new URL(X);return Y.pathname.replace(/^\/+/,"").replace(/\.git$/,"")||Y.hostname}catch{return X}}var pz="agent-sandbox",iW="AgentSandboxRunner",MG7="agent-sandbox-system",RG7="studio-sandbox",Cm=9000,SG7=3000,pb0="/app",CG7=32,kG7,vG7=900000,c31="studio-sb-",_G7=16,fG7,GJ8,ob0=40000,WJ8=1e4,bG7=256,AT,uG7,lG7=63;var $J8=D(()=>{hb0();bn1();M$1();ib0();gc1();kG7=new Set(["DAEMON_TOKEN","DAEMON_BOOT_ID","APP_ROOT","PROXY_PORT","DEV_PORT","RUNTIME","CLONE_URL","REPO_NAME","BRANCH","GIT_USER_NAME","GIT_USER_EMAIL","PACKAGE_MANAGER"]),fG7=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length","upgrade"],GJ8=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];AT={role:"studio.decocms.com/role",sandboxHandle:"studio.decocms.com/sandbox-handle",orgId:"studio.decocms.com/org-id",userId:"studio.decocms.com/user-id"},uG7=/^([A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?)?$/});var KJ8={};M0(KJ8,{waitForSandboxReady:()=>dc1,getSandboxClaim:()=>Sm,getHttpRoute:()=>XJ8,deleteSandboxClaim:()=>Rm,deleteHttpRoute:()=>mc1,createSandboxClaim:()=>m31,createHttpRoute:()=>lc1,SandboxTimeoutError:()=>_s,SandboxError:()=>rY,KubeConfig:()=>Rs,K8S_CONSTANTS:()=>C3,HTTPROUTE_CONSTANTS:()=>d31,HANDLE_PREFIX:()=>c31,AgentSandboxRunner:()=>sb0});var eb0=D(()=>{hb0();gc1();ib0();$J8()});var Jy0={};M0(Jy0,{getSharedRunnerIfInit:()=>Gy0,getSharedRunner:()=>i31,getRunnerByKind:()=>fs,getOrInitSharedRunner:()=>tG7,asDockerRunner:()=>Qy0});function HJ8(X,Y){let G=Yy0[X];if(G)return Promise.resolve(G);let Q=Xy0[X];if(Q)return Q;let J=Y().then((W)=>{return Yy0[X]=W,W}).finally(()=>{delete Xy0[X]});return Xy0[X]=J,J}function pG7(){let X=process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN;return X&&X.trim()!==""?X:void 0}function nG7(){let X=process.env.STUDIO_SANDBOX_TEMPLATE_NAME;return X&&X.trim()!==""?X:void 0}function aG7(){let X=process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME?.trim(),Y=process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE?.trim();if(!X&&!Y)return;if(!X||!Y)throw Error("STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME and STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE must both be set, or both unset. Half-configured per-claim HTTPRoute routing would silently fail to attach.");return{name:X,namespace:Y}}async function FJ8(X,Y){let G=new N_0(Y),Q=pG7();switch(X){case"docker":return new QF({stateStore:G,previewUrlPattern:Q});case"freestyle":{let{FreestyleSandboxRunner:J}=await Promise.resolve().then(() => (T58(),A58));return new J({stateStore:G})}case"agent-sandbox":{let{AgentSandboxRunner:J}=await Promise.resolve().then(() => (eb0(),KJ8));return new J({stateStore:G,previewUrlPattern:Q,sandboxTemplateName:nG7(),previewGateway:aG7(),meter:QU})}default:throw Error(`Unknown runner kind: ${String(X)}`)}}function i31(X){return fs(X,Td())}function fs(X,Y){return HJ8(Y,()=>FJ8(Y,X.db))}async function tG7(){let X=ve();if(!X)return null;return HJ8(X,()=>FJ8(X,t7().db))}function Gy0(){let X=ve();if(!X)return null;return Yy0[X]??null}function Qy0(X){return X instanceof QF?X:null}var Yy0,Xy0;var km=D(()=>{rT();JU();A$();xp4();Yy0={},Xy0={}});async function UJ8(X,Y){N0(Y);let G=s1(Y),Q=T4(Y);if(!Q)throw Error("User ID required");let J=await Y.storage.virtualMcps.findById(X.virtualMcpId);if(!J||J.organization_id!==G.id)throw Error("Virtual MCP not found");let W=J.metadata??{},Z=UC1(Us(W),Q,X.branch),$=Td();if(Z&&(Z.runnerKind??"freestyle")===$)return Z;await NJ8(Y,Z,$);let K=W.githubRepo??null,{entry:H}=await BJ8({ctx:Y,userId:Q,orgId:G.id,virtualMcpId:X.virtualMcpId,branch:X.branch,metadata:W,githubRepo:K,existing:Z});return H}async function NJ8(X,Y,G){if(!Y)return;let Q=Y.runnerKind??"freestyle";if(Q===G)return;if(Q==="freestyle")return;try{await(await fs(X,Q)).delete(Y.vmId)}catch(J){console.error(`[VM_START] stale ${Q} ${Y.vmId}: ${J instanceof Error?J.message:String(J)}`)}}async function BJ8(X){let{ctx:Y,userId:G,orgId:Q,virtualMcpId:J,branch:W,metadata:Z,githubRepo:$,existing:K}=X;if($&&!$.connectionId)throw Error("GitHub connection id missing on virtual MCP metadata");let{runtime:H,packageManager:U,port:N}=Ip4(Z),B;if($){let{cloneUrl:V,gitUserName:R,gitUserEmail:k}=await Vp4($.connectionId,$.owner,$.name,Y.db,Y.vault);if(!U){let _=await Sp4($.connectionId,$.owner,$.name,Y.db,Y.vault);if(_)U=_.packageManager,H=B31[_.packageManager].runtime,N=_.devPort??N,await rG7(Y,J,G,_.packageManager,_.devPort)}B={cloneUrl:V,userName:R,userEmail:k,branch:W,displayName:`${$.owner}/${$.name}`}}let z=H&&U?{runtime:H,packageManager:U,devPort:Number(N)}:void 0,O=S$1({orgId:Q,virtualMcpId:J,branch:W}),w=await i31(Y),E=await w.ensure({userId:G,projectRef:O},{repo:B,workload:z,tenant:{orgId:Q,userId:G}}),q=!!K&&K.vmId===E.handle&&K?.createdAt?K.createdAt:Date.now(),j={vmId:E.handle,previewUrl:E.previewUrl,runnerKind:w.kind,createdAt:q};await Ap4(Y.storage.virtualMcps,J,G,G,W,j);let M=!K||K.vmId!==E.handle;return{entry:j,isNewVm:M}}async function rG7(X,Y,G,Q,J){let W=await X.storage.virtualMcps.findById(Y);if(!W)return;let Z=W.metadata??{};await X.storage.virtualMcps.update(Y,G,{metadata:{...Z,runtime:{selected:Q,port:J}}})}var Zy0;var Wy0=D(()=>{H0();rT();x0();U_0();jp4();Cp4();BC0();F_0();km();Zy0=m1({name:"VM_START",description:"Start a sandbox with the connected GitHub repo and dev server.",annotations:{title:"Start VM Preview",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:F.object({virtualMcpId:F.string().describe("Virtual MCP ID"),branch:F.string().min(1).optional().describe("Optional git branch to check out. When omitted the handler generates `deco/<adjective>-<noun>` and uses it. The resolved branch is returned in the response so callers can persist it.")}),outputSchema:F.object({previewUrl:F.string().nullable(),vmId:F.string(),branch:F.string(),isNewVm:F.boolean(),runnerKind:F.enum(["docker","freestyle","agent-sandbox"])}),handler:async(X,Y)=>{let G=X.branch??PS1(),{metadata:Q,userId:J,organization:W,entry:Z}=await NC1({virtualMcpId:X.virtualMcpId,branch:G},Y),$=Q.githubRepo;if(!$)throw Error("No GitHub repo connected");let K=Td();await NJ8(Y,Z,K);let{entry:H,isNewVm:U}=await BJ8({ctx:Y,userId:J,orgId:W.id,virtualMcpId:X.virtualMcpId,branch:G,metadata:Q,githubRepo:$,existing:Z});return{...H,branch:G,isNewVm:U,runnerKind:K}}})});var $y0;var zJ8=D(()=>{H0();x0();U_0();km();$y0=m1({name:"VM_DELETE",description:"Delete a sandbox.",annotations:{title:"Delete VM Preview",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:F.object({virtualMcpId:F.string().describe("Virtual MCP ID that owns this VM"),branch:F.string().min(1).describe("Branch whose vm should be deleted (vmMap[userId][branch])")}),outputSchema:F.object({success:F.boolean()}),handler:async(X,Y)=>{let G;try{G=await NC1(X,Y)}catch($){if($ instanceof Error&&$.message==="Virtual MCP not found")return{success:!0};throw $}let{entry:Q,userId:J}=G;if(!Q)return{success:!0};await Tp4(Y.storage.virtualMcps,X.virtualMcpId,J,J,X.branch);let W=Q.runnerKind??"freestyle";return await(await fs(Y,W)).delete(Q.vmId).catch(($)=>console.error(`[VM_DELETE] ${W} ${Q.vmId}: ${$ instanceof Error?$.message:String($)}`)),{success:!0}}})});var OJ8=D(()=>{Wy0();zJ8()});var sG7="https://api.github.com",Ky0;var DJ8=D(()=>{H0();x0();lI1();_R();Ky0=m1({name:"GITHUB_LIST_USER_ORGS",description:"List GitHub App installations (orgs/accounts) accessible to the authenticated user.",annotations:{title:"List GitHub User Orgs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:F.object({connectionId:F.string().describe("ID of the mcp-github connection to use")}),outputSchema:F.object({installations:F.array(F.object({installationId:F.number(),login:F.string(),avatarUrl:F.string(),type:F.string()})),appSlug:F.string().optional()}),handler:async(X,Y)=>{await Y.access.check();let G=new T3(Y.db,Y.vault),Q=await G.get(X.connectionId);if(!Q)throw Error("No GitHub token found. Ensure the mcp-github connection is authenticated.");let J=Q.accessToken;if(mY1(Q)&&G.isExpired(Q,uI1)){let U=await dY1(Q,G);if(!U)throw Error(QM);J=U,Q=await G.get(X.connectionId)??Q}let W=[],Z,$=1,K=100,H=async(U)=>fetch(`${sG7}/user/installations?per_page=${K}&page=${$}`,{headers:{Authorization:`Bearer ${U}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}});while(!0){let U=await H(J);if(U.status===401){let B=await G.get(X.connectionId);if(!B||!mY1(B))throw Error(QM);let z=await dY1(B,G);if(!z)throw Error(QM);if(J=z,U=await H(J),U.status===401)throw Error(QM)}if(!U.ok)throw Error(`GitHub /user/installations failed: ${U.status}`);let N=await U.json();for(let B of N.installations){if(!Z)Z=B.app_slug??B.app?.slug;W.push({installationId:B.id,login:B.account.login,avatarUrl:B.account.avatar_url,type:B.account.type})}if(N.installations.length<K)break;$++}return{installations:W,...Z?{appSlug:Z}:{}}}})});var wJ8=D(()=>{DJ8()});var wS1={};M0(wS1,{managementMCP:()=>no,listManagementTools:()=>GQ7,ALL_TOOLS:()=>LJ8});async function GQ7(X){let Y=await no(X),[G,Q]=QY1.createLinkedPair();await Y.connect(Q);let J=new hY({name:"tools-hydration",version:"1.0.0"});try{return await J.connect(G),(await J.listTools()).tools}finally{await J.close().catch(()=>{})}}var XQ7,YQ7,LJ8,no=async(X)=>{let Y=null;if(X.organization){let Z=await X.storage.organizationSettings.get(X.organization.id),$=await X.storage.virtualMcps.list(X.organization.id),K=new Set(Z?.enabled_plugins??[]);for(let H of $){let U=H.metadata?.enabled_plugins;if(U&&Array.isArray(U))for(let N of U)K.add(N)}Y=K.size>0?[...K]:null}let G=Yr6(LJ8,Y),Q=new cD({name:"mcp-cms-management",version:"1.0.0"},{capabilities:{tools:{},prompts:{},resources:{}}});for(let Z of G){let $=Z.inputSchema&&typeof Z.inputSchema==="object"&&"shape"in Z.inputSchema?Z.inputSchema:F.object({}),K=Z.outputSchema&&typeof Z.outputSchema==="object"&&"shape"in Z.outputSchema?Z.outputSchema:void 0,H=$.shape,U=K?.shape;Q.registerTool(Z.name,{description:Z.description??"",inputSchema:H,outputSchema:U,annotations:Z.annotations,_meta:Z._meta},async(N)=>{X.access.setToolName(Z.name);try{let B=await Z.execute(N,X);return{content:[{type:"text",text:JSON.stringify(B)}],structuredContent:B}}catch(B){return{content:[{type:"text",text:`Error: ${B.message}`}],isError:!0}}})}let J=Fx4();for(let Z of J)Q.registerPrompt(Z.name,{title:Z.title,description:Z.description},()=>({messages:[{role:"user",content:{type:"text",text:Z.text}}]}));if(X.organization?.id){let Z=await X.storage.brandContext.list(X.organization.id),$=new Set;for(let K of Z){let H=K.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),U=H?`brand-${H}`:`brand-${K.id}`;if($.has(U))U=`${U}-${K.id.slice(0,8)}`;$.add(U);let N=[`# Brand: ${K.name}`,"",`**Domain:** ${K.domain}`,"","## Overview",K.overview];if(K.colors){let z=Object.entries(K.colors).filter(([,O])=>O);if(z.length>0){N.push("","## Colors");for(let[O,w]of z)N.push(`- **${O}:** ${w}`)}}if(K.fonts){let z=Object.entries(K.fonts).filter(([,O])=>O);if(z.length>0){N.push("","## Fonts");for(let[O,w]of z)N.push(`- ${w} (${O})`)}}if(K.logo)N.push("",`**Logo:** ${K.logo}`);if(K.favicon)N.push(`**Favicon:** ${K.favicon}`);if(K.ogImage)N.push(`**OG Image:** ${K.ogImage}`);if(K.images&&K.images.length>0){N.push("","## Images");for(let z of K.images){let O=Object.entries(z).map(([w,E])=>`${w}: ${E}`).join(", ");N.push(`- ${O}`)}}let B=N.join(`
|
|
5031
5031
|
`);Q.prompt(U,`Brand context for ${K.name}`,()=>({messages:[{role:"user",content:{type:"text",text:B}}]}))}}let W=Ux4();for(let Z of W)Q.resource(Z.name,Z.uri,{description:Z.description,mimeType:Z.mimeType??"text/markdown"},async($)=>{return{contents:[{uri:typeof $==="string"?$:$.href,mimeType:Z.mimeType??"text/markdown",text:Z.text}]}});return Q};var co=D(()=>{ya();uB();M71();H0();n84();if4();tf4();Zb4();Db4();Pb4();lb4();nb4();Ky4();Iy4();jy4();dy4();Nx4();xx4();qp4();OJ8();wJ8();XQ7=[hS0,gS0,uS0,lS0,mS0,dS0,cS0,iS0,pS0,nS0,aS0,tS0,oS0,sS0,eS0,XC0,YC0,GC0,QC0,JC0,ZC0,WC0,$C0,LD0,zS0,OS0,DS0,wS0,LS0,jS0,RS0,SS0,CS0,kS0,af4,bS0,yS0,xS0,Sz0,kz0,vz0,Cz0,ES0,PS0,qS0,AS0,TS0,IS0,VS0,fC0,zC0,OC0,DC0,wC0,LC0,EC0,KC0,HC0,FC0,UC0,NC0,PC0,qC0,AC0,jC0,MC0,kC0,vC0,_C0,vS0,_S0,fS0,bC0,yC0,xC0,hC0,gC0,uC0,lC0,mC0,dC0,cC0,iC0,pC0,nC0,aC0,tC0,rC0,oC0,sC0,...Pp4,Zy0,$y0,Ky0],YQ7=Gr6(),LJ8=[...XQ7,...YQ7]});function QQ7(X){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Y}=await Promise.resolve().then(() => (co(),wS1));return Y.map((G)=>{return{name:G.name,inputSchema:F.toJSONSchema(G.inputSchema,{unrepresentable:"any"}),outputSchema:G.outputSchema?F.toJSONSchema(G.outputSchema,{unrepresentable:"any"}):void 0,description:G.description}})},data:DH0(u$(),X)},{data:OH0()},{data:zH0(X)}]}async function EJ8(X,Y){try{let G=t7(),Q=v6(),J=new yj(Q.encryptionKey),W=new sX1(G.db,J),Z=QQ7(X);await Promise.all(Z.map(async($)=>{let K=null;if($.permissions)K=(await RY.api.createApiKey({body:{name:`${$.data.app_name??crypto.randomUUID()}-mcp`,userId:Y,permissions:$.permissions,rateLimitEnabled:!1,metadata:{organization:{id:X},purpose:"default-org-connections"}}}))?.key;let H=await jq({id:"pending",title:$.data.title,connection_type:$.data.connection_type,connection_url:$.data.connection_url,connection_token:$.data.connection_token,connection_headers:$.data.connection_headers}).catch(()=>null),U=await $.getTools?.()??H?.tools??null,N=H?.scopes?.length?H.scopes:null,B=$.data.id?$.data.id.startsWith(`${X}_`)?$.data.id:`${X}_${$.data.id}`:void 0;await W.create({...$.data,id:B,tools:U,configuration_scopes:N,organization_id:X,created_by:Y,connection_token:$.data.connection_token??K})}));try{let $=new eX1(G.db);await S84(X,Y,$)}catch($){console.error("Failed to install studio pack agents:",$)}if(Q.aiGatewayEnabled&&aX1.provisionKey)try{let $=await Mq(Y),K=await aX1.provisionKey($,X);await new rX1(G.db,J).upsert({providerId:"deco",label:"Auto-provisioned",apiKey:K,organizationId:X,createdBy:Y})}catch($){console.error("Failed to auto-provision Deco AI Gateway key:",$)}}catch(G){console.error("Error creating default MCP connections:",G)}}var PJ8=D(()=>{s9();Uz0();Fw();JU();PT1();Nz0();zz0();Oz0();YY1();C84();H0();m9();yR();xj()});function JQ7(X,Y){let G=X.email.split("@")[1]?.toLowerCase()??null;return{distinctId:X.id,properties:{$set:{email:X.email,name:X.name,email_verified:X.emailVerified},$set_once:{first_seen_at:Y.toISOString(),signup_email_domain:G}}}}function Hy0(X){j4.identify(JQ7(X,new Date))}var qJ8=D(()=>{RX()});async function WQ7(X){let{user:Y,token:G}=X;if(!G?.idToken)return;let Q;try{Q=i9(G.idToken)}catch{return}let{preferred_username:J,upn:W}=Q,Z=[J,W].filter((H)=>typeof H==="string"&&H.length>0&&H.toLowerCase()!==Y.email.toLowerCase()).map((H)=>H.toLowerCase());if(Z.length===0)return;let{db:$}=t7(),K=await $.selectFrom("user").selectAll().where("email","in",Z).where("id","!=",Y.id).executeTakeFirst();if(!K)return;try{await $.transaction().execute(async(H)=>{await O1`UPDATE "account" SET "userId" = ${K.id} WHERE "userId" = ${Y.id}`.execute(H),await O1`UPDATE "session" SET "userId" = ${K.id} WHERE "userId" = ${Y.id}`.execute(H),await O1`
|
|
5032
5032
|
UPDATE "member" SET "userId" = ${K.id}
|