decocms 2.293.4 → 2.293.5
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-BjOZmb3_.js → AlertCircle-BzwZh4Zl.js} +1 -1
- package/dist/client/assets/{ArrowNarrowLeft-BcLjzBdj.js → ArrowNarrowLeft-DU3JdF0_.js} +1 -1
- package/dist/client/assets/{ArrowUpRight-K-qOhs5U.js → ArrowUpRight-C84Vhba5.js} +1 -1
- package/dist/client/assets/{CheckCircle-idEJRWqm.js → CheckCircle-C8G8LwxI.js} +1 -1
- package/dist/client/assets/{ChevronDown-8gFfkCAT.js → ChevronDown-B1KJEunc.js} +1 -1
- package/dist/client/assets/{ChevronRight-jn2TY6bg.js → ChevronRight-pxra21qH.js} +1 -1
- package/dist/client/assets/{ChevronUp-GCRvOXUm.js → ChevronUp-DBmcocMx.js} +1 -1
- package/dist/client/assets/{Container-Oz2YNmUh.js → Container-B3xcDrr9.js} +1 -1
- package/dist/client/assets/{DotsVertical-Db4taJ9K.js → DotsVertical-M7OP_kdi.js} +1 -1
- package/dist/client/assets/{LinkExternal01-BCvnibSo.js → LinkExternal01-Dq-dCCCw.js} +1 -1
- package/dist/client/assets/{Lock01-Q6LUoAej.js → Lock01-CVUwQODJ.js} +1 -1
- package/dist/client/assets/{Palette-DeXO2UD-.js → Palette-Czyfskax.js} +1 -1
- package/dist/client/assets/{Play-DQtgluIz.js → Play-BgS-BLqI.js} +1 -1
- package/dist/client/assets/{Plus--NQ8Lzv-.js → Plus-BEIPlAug.js} +1 -1
- package/dist/client/assets/{RefreshCcw01-C_DCJmlp.js → RefreshCcw01-D49W2KKP.js} +1 -1
- package/dist/client/assets/{SearchMd-BSaOo_JL.js → SearchMd-CQmi0vTD.js} +1 -1
- package/dist/client/assets/{Settings02-Dqsstum2.js → Settings02-CvWJhznv.js} +1 -1
- package/dist/client/assets/{Shield01-s7fnlBYV.js → Shield01-D_PgpXDU.js} +1 -1
- package/dist/client/assets/{Star01-UkNlRUFe.js → Star01-O454dIt4.js} +1 -1
- package/dist/client/assets/{Sun-BbHWHHyR.js → Sun-C3hG-7_j.js} +1 -1
- package/dist/client/assets/{Tool01-DbnLjlM2.js → Tool01-DaOorIYv.js} +1 -1
- package/dist/client/assets/{Trash01-zq3BxN1h.js → Trash01-Dj97eTWF.js} +1 -1
- package/dist/client/assets/{User01-BMocx1Ia.js → User01-xJrFa-5i.js} +1 -1
- package/dist/client/assets/{Users03-C4e5uWHr.js → Users03-Dq9QO4iD.js} +1 -1
- package/dist/client/assets/{X-D3ENSJsC.js → X-bXKeRXer.js} +1 -1
- package/dist/client/assets/{XCircle-CaQruiTo.js → XCircle-D52NGz2j.js} +1 -1
- package/dist/client/assets/{XClose-CgOLivFw.js → XClose-sHlfiFPJ.js} +1 -1
- package/dist/client/assets/{Zap-1gz6p0Ma.js → Zap-BuQ1Mub6.js} +1 -1
- package/dist/client/assets/{ZapSquare-BfOpflPt.js → ZapSquare-DlhcZHZC.js} +1 -1
- package/dist/client/assets/{accordion-W_paWQqo.js → accordion-BL_cObLl.js} +1 -1
- package/dist/client/assets/{agent-icon-Cn5oclCs.js → agent-icon-CYCsLMY8.js} +1 -1
- package/dist/client/assets/{agents-list-Bq1lupYm.js → agents-list-wf1-JXYG.js} +1 -1
- package/dist/client/assets/ai-providers-5Oh8bAI9.js +1 -0
- package/dist/client/assets/{alert-dialog-D3pi5b6N.js → alert-dialog-gD-y-16H.js} +1 -1
- package/dist/client/assets/{auth-catchall-fKkOuHdo.js → auth-catchall-CVgWV0bX.js} +1 -1
- package/dist/client/assets/{automation-list-row-DMHIeTUi.js → automation-list-row-BRwFIQ6n.js} +1 -1
- package/dist/client/assets/{automations-BXoe1Q0T.js → automations-JVOMglnF.js} +1 -1
- package/dist/client/assets/{avatar-BhPS0sEl.js → avatar-DFtLsn4k.js} +1 -1
- package/dist/client/assets/{badge-CDfiJQQR.js → badge-9rYE5D0k.js} +1 -1
- package/dist/client/assets/{brand-context-DoPWwJ4r.js → brand-context-m0MAWa6T.js} +1 -1
- package/dist/client/assets/{card-CP805zsI.js → card-DhVwh0JB.js} +1 -1
- package/dist/client/assets/{chat-context-DI872wNm.js → chat-context-CJt5mvhM.js} +1 -1
- package/dist/client/assets/{checkbox-CKpV5oyn.js → checkbox-Co1RL5s6.js} +1 -1
- package/dist/client/assets/{collection-detail-DbpaXe2t.js → collection-detail-C6DXw69j.js} +1 -1
- package/dist/client/assets/{collection-display-button-k9crQV9d.js → collection-display-button-yd9SLQKA.js} +1 -1
- package/dist/client/assets/{collection-search-BpswMTjk.js → collection-search-B84D_FVY.js} +1 -1
- package/dist/client/assets/{collection-search-4JBAiA2C.js → collection-search-eJBrKq3k.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-BHZQvL_J.js → collection-table-wrapper-DVDH_cyl.js} +1 -1
- package/dist/client/assets/{collection-tabs-B3lthMg8.js → collection-tabs-Dk5F4rCw.js} +1 -1
- package/dist/client/assets/{collections-DBXLtq3P.js → collections-DIWSRpRc.js} +1 -1
- package/dist/client/assets/{command-CRl-8DjA.js → command-CsAjukV5.js} +1 -1
- package/dist/client/assets/{connection-card-CdhlAzve.js → connection-card-2KzXnvEe.js} +1 -1
- package/dist/client/assets/{connection-detail-Cf4BNVC3.js → connection-detail-RcoR1uYz.js} +1 -1
- package/dist/client/assets/{connection-form-helpers-Dj6Xs5eA.js → connection-form-helpers-3mXWA4iM.js} +1 -1
- package/dist/client/assets/{connections-C72dpEi8.js → connections-DpXrmeb_.js} +1 -1
- package/dist/client/assets/{constants-tJ81fG25.js → constants-Cf5QbDCh.js} +1 -1
- package/dist/client/assets/{constants-BXf9ANTR.js → constants-ratRqg73.js} +1 -1
- package/dist/client/assets/{dialog-RLyF4eg5.js → dialog-BuC4uwKW.js} +1 -1
- package/dist/client/assets/{domain-settings-BfKS_avD.js → domain-settings-C6ZYhRL9.js} +1 -1
- package/dist/client/assets/{drawer-CG78q1nt.js → drawer-Bl05iru7.js} +1 -1
- package/dist/client/assets/{dropdown-menu-BDa5fLDC.js → dropdown-menu-CEE4ZMkb.js} +1 -1
- package/dist/client/assets/{dynamic-plugin-layout-wXXoe_5G.js → dynamic-plugin-layout-BB4q2C2r.js} +1 -1
- package/dist/client/assets/{empty-state-ErnajtAj.js → empty-state-DidTtVmj.js} +1 -1
- package/dist/client/assets/{empty-state-L95wna48.js → empty-state-UPZNWdZx.js} +1 -1
- package/dist/client/assets/{extract-connection-data-BPBT-cx0.js → extract-connection-data-DbsvqD5Y.js} +1 -1
- package/dist/client/assets/{features-DMy2j_1-.js → features-BU1R__DA.js} +1 -1
- package/dist/client/assets/{form-BhTWNirH.js → form-B9LcVw9F.js} +1 -1
- package/dist/client/assets/{general-X1U_18Wj.js → general-DNpYZ6EL.js} +1 -1
- package/dist/client/assets/{index-D1bA9zIu.js → index-B9TaiaI8.js} +1 -1
- package/dist/client/assets/index-BDaakylR.js +1 -0
- package/dist/client/assets/{index-SvQIjOEI.js → index-Bb0xkdWO.js} +1 -1
- package/dist/client/assets/{index-CBpHmYGS.js → index-BibArEPs.js} +1 -1
- package/dist/client/assets/{index-BKqtR3N2.js → index-CDUWTUlI.js} +2 -2
- package/dist/client/assets/{index-DCHTg4LB.js → index-Ck9cg_5e.js} +1 -1
- package/dist/client/assets/{index-DO0uF7Gp.js → index-D8Xx8vq1.js} +1 -1
- package/dist/client/assets/{index-BSi_7pdx.js → index-D8fB6LIK.js} +1 -1
- package/dist/client/assets/{index-CycJh0eW.js → index-D8zM056i.js} +1 -1
- package/dist/client/assets/{index-DsGCV5t1.js → index-DJJnwTGq.js} +1 -1
- package/dist/client/assets/{index-kw8l6ykm.js → index-DSqlqHtR.js} +3 -3
- package/dist/client/assets/{index-C3bqKLs_.js → index-DeYhLxte.js} +1 -1
- package/dist/client/assets/{index-DlmBTdhU.js → index-DnlpEh__.js} +1 -1
- package/dist/client/assets/{index-C4mKQp91.js → index-axEutp6C.js} +1 -1
- package/dist/client/assets/{index-DyOW0RUm.js → index-lAT0a-lp.js} +1 -1
- package/dist/client/assets/{index-DfvjXpA6.js → index-nCei82Pv.js} +1 -1
- package/dist/client/assets/{infiniteQueryObserver-BDzPf9xQ.js → infiniteQueryObserver-CdlVSD6U.js} +1 -1
- package/dist/client/assets/{input-DdZFm5QD.js → input-B9YRLZzT.js} +1 -1
- package/dist/client/assets/{integration-icon-GgmeOaov.js → integration-icon-BT3MTkMk.js} +1 -1
- package/dist/client/assets/{label-BfGjYD3l.js → label-BnJEOV4m.js} +1 -1
- package/dist/client/assets/{layout-C8Q8lJIU.js → layout-BMrv9IJk.js} +1 -1
- package/dist/client/assets/{lean-canvas-recruit-modal-DS8lrn_0.js → lean-canvas-recruit-modal-Clo5pXS8.js} +1 -1
- package/dist/client/assets/{login-3GauQMNJ.js → login-Ba2KjTcs.js} +1 -1
- package/dist/client/assets/{members-wC3LaYXM.js → members-BUslCVys.js} +1 -1
- package/dist/client/assets/{monaco-editor-DEH3BQYV.js → monaco-editor-DY7iVY5q.js} +1 -1
- package/dist/client/assets/{monitoring-stats-row-p4rwLqzV.js → monitoring-stats-row-T-DBfNKc.js} +1 -1
- package/dist/client/assets/{oauth-callback-cXl4wz4V.js → oauth-callback-C7vFEfz2.js} +1 -1
- package/dist/client/assets/{oauth-callback-ai-provider-fZrOq5Z5.js → oauth-callback-ai-provider-CItODIeI.js} +1 -1
- package/dist/client/assets/{onboarding-pK8C-td_.js → onboarding-DnXzTisH.js} +1 -1
- package/dist/client/assets/{org-layout-BjvDCQaj.js → org-layout-C6RdEBDI.js} +1 -1
- package/dist/client/assets/{org-plugin-layout-BsxDAG3R.js → org-plugin-layout-B1gZZHFJ.js} +1 -1
- package/dist/client/assets/{pair-BjuR1Vev.js → pair-D7_5CZbo.js} +1 -1
- package/dist/client/assets/{plugin-empty-state-Yj66KVWm.js → plugin-empty-state-B8bGa_3C.js} +1 -1
- package/dist/client/assets/{plugin-header-Cl0DmTkb.js → plugin-header-BmY5QXZp.js} +1 -1
- package/dist/client/assets/{plugin-layout-DyHctLfj.js → plugin-layout-Da9PGtnW.js} +1 -1
- package/dist/client/assets/{popover-Ck8t9DNd.js → popover-CoIn4MCb.js} +1 -1
- package/dist/client/assets/{profile-ClJRsqlz.js → profile-CPbUULaF.js} +1 -1
- package/dist/client/assets/{project-app-view-PrZuri_l.js → project-app-view-CzPIl-hq.js} +1 -1
- package/dist/client/assets/registry-BjoC1aBP.js +2 -0
- package/dist/client/assets/{registry-layout-CzSdO28_.js → registry-layout-acF_MpdN.js} +1 -1
- package/dist/client/assets/{required-auth-layout-CXpY2cQd.js → required-auth-layout-HXCzQjRG.js} +1 -1
- package/dist/client/assets/{reset-password-CMm6pkup.js → reset-password-8qLTz3V8.js} +1 -1
- package/dist/client/assets/{roles-O8p4CFWf.js → roles-CTSAC5Vc.js} +1 -1
- package/dist/client/assets/{scroll-area-DJUXiZ9b.js → scroll-area-DBfE0bZp.js} +1 -1
- package/dist/client/assets/{search-input-D9rgJLcT.js → search-input-y8HgveN3.js} +1 -1
- package/dist/client/assets/{select-BtT3gpc8.js → select-DDVbfw52.js} +1 -1
- package/dist/client/assets/{select-model-BYU8vEdG.js → select-model-BcOKSvAJ.js} +1 -1
- package/dist/client/assets/{settings-layout-DVDnaToH.js → settings-layout-BvaDpRCp.js} +1 -1
- package/dist/client/assets/{settings-section-A8NDDpFq.js → settings-section-2oSIvsU8.js} +1 -1
- package/dist/client/assets/{shell-layout-BzqO6QrK.js → shell-layout-BjUFPe81.js} +1 -1
- package/dist/client/assets/{skeleton-BkW87z8Y.js → skeleton-B9B8q_Po.js} +1 -1
- package/dist/client/assets/{sso-DtYY3WTz.js → sso-qsKGi1As.js} +1 -1
- package/dist/client/assets/{store-CbZ5JO_W.js → store-N6Hq49_J.js} +1 -1
- package/dist/client/assets/store-registry-yaXg4QLv.js +2 -0
- package/dist/client/assets/{switch-CeIz4a0t.js → switch-B_u1vojZ.js} +1 -1
- package/dist/client/assets/{table-BW-rIPEf.js → table-DvbyCaYw.js} +1 -1
- package/dist/client/assets/{tabs-C5GRvtY8.js → tabs-McHIAn-A.js} +1 -1
- package/dist/client/assets/{task-status-ChvkxFoN.js → task-status-CEq9fKdf.js} +1 -1
- package/dist/client/assets/{textarea-DLbi42IX.js → textarea-DHpnAboW.js} +1 -1
- package/dist/client/assets/{toggle-group-D9s6Qnlj.js → toggle-group-D8MGreiA.js} +1 -1
- package/dist/client/assets/{tools-list-Bl0UtEt-.js → tools-list-rfSyOhU9.js} +1 -1
- package/dist/client/assets/{tooltip-Dmy1JK40.js → tooltip-BrE5dSu8.js} +1 -1
- package/dist/client/assets/{types-BJMFxBFM.js → types-Mo8TVbbA.js} +1 -1
- package/dist/client/assets/{use-ai-providers-CrOxHqDh.js → use-ai-providers-CQe5dDDP.js} +1 -1
- package/dist/client/assets/{use-collections-D6UN6Et8.js → use-collections-C-WSpVk0.js} +1 -1
- package/dist/client/assets/{use-connection-okJtNg-z.js → use-connection-BaC0qG5N.js} +1 -1
- package/dist/client/assets/{use-copy-GhMNNjgc.js → use-copy-CwireOyz.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-BK5MfCsr.js → use-create-virtual-mcp-O_UjHYAk.js} +1 -1
- package/dist/client/assets/{use-decopilot-events-CH_hOp3h.js → use-decopilot-events-CUiJ-4dG.js} +1 -1
- package/dist/client/assets/{use-delete-connection-CFVqRzdi.js → use-delete-connection-BIlpbYGx.js} +1 -1
- package/dist/client/assets/{use-infinite-scroll-BJayiynP.js → use-infinite-scroll-DerRN4-q.js} +1 -1
- package/dist/client/assets/{use-list-state-jGWeHOcg.js → use-list-state-zKA7fSBh.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-DrTCTUYm.js → use-mcp-tools-DLLCCWMt.js} +1 -1
- package/dist/client/assets/{use-members-DdbTjqv-.js → use-members-CtpKVKUl.js} +1 -1
- package/dist/client/assets/{use-navigate-to-agent-BYNqqJQ5.js → use-navigate-to-agent-CWsNVcm6.js} +1 -1
- package/dist/client/assets/{use-org-sso-Bsg_IZFZ.js → use-org-sso-BUvrwtPm.js} +1 -1
- package/dist/client/assets/{use-organization-roles-BmLHoXKs.js → use-organization-roles-DImXXICa.js} +1 -1
- package/dist/client/assets/{use-organization-settings-j6PDzIGz.js → use-organization-settings-Bj7t39ti.js} +1 -1
- package/dist/client/assets/{use-registry-connections-CgQyGHAH.js → use-registry-connections-_yyeoUB2.js} +1 -1
- package/dist/client/assets/{use-status-sounds-_L8GZOUh.js → use-status-sounds-BTnx4_U2.js} +1 -1
- package/dist/client/assets/{use-tasks-DK2by51E.js → use-tasks-DMo7I-VJ.js} +1 -1
- package/dist/client/assets/{use-view-mode-DZXCRWHN.js → use-view-mode-DDTQ72i6.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-D50Foh5R.js → use-virtual-mcp-RThtSAmZ.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-37elVpOp.js +1 -0
- package/dist/client/assets/useSuspenseInfiniteQuery-DQSo9Er3.js +1 -0
- package/dist/client/assets/{user-DLXr9rpE.js → user-CTmtoSZB.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-C03hOMgr.js → view-mode-toggle-BWe0qZ6h.js} +1 -1
- package/dist/client/assets/{workflow-CX2neNEp.js → workflow-C1Sjdebj.js} +1 -1
- package/dist/client/assets/workflow-detail-BJCHk7qV.js +1 -0
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +2 -2
- 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/package.json +54 -0
- package/dist/server/node_modules/ansi-styles/readme.md +173 -0
- package/dist/server/node_modules/mimic-fn/index.d.ts +54 -0
- package/dist/server/node_modules/mimic-fn/index.js +13 -0
- package/dist/server/node_modules/mimic-fn/license +9 -0
- package/dist/server/node_modules/mimic-fn/package.json +42 -0
- package/dist/server/node_modules/mimic-fn/readme.md +69 -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/{xtend/LICENSE → postgres-array/license} +2 -1
- 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/server.js +1 -1
- package/package.json +1 -1
- package/dist/client/assets/ai-providers-FTRlEUdE.js +0 -1
- package/dist/client/assets/index-BIAsUusp.js +0 -1
- package/dist/client/assets/registry-ChBuKs9l.js +0 -2
- package/dist/client/assets/store-registry-gwif4zfV.js +0 -2
- package/dist/client/assets/useInfiniteQuery-DXe6VMYm.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-CO9lgsHl.js +0 -1
- package/dist/client/assets/workflow-detail-ichjN1O3.js +0 -1
- package/dist/server/node_modules/is-fullwidth-code-point/index.d.ts +0 -17
- package/dist/server/node_modules/is-fullwidth-code-point/index.js +0 -12
- package/dist/server/node_modules/is-fullwidth-code-point/package.json +0 -53
- package/dist/server/node_modules/is-fullwidth-code-point/readme.md +0 -31
- package/dist/server/node_modules/xtend/.jshintrc +0 -30
- package/dist/server/node_modules/xtend/README.md +0 -32
- package/dist/server/node_modules/xtend/immutable.js +0 -19
- package/dist/server/node_modules/xtend/mutable.js +0 -17
- package/dist/server/node_modules/xtend/package.json +0 -55
- package/dist/server/node_modules/xtend/test.js +0 -103
- /package/dist/server/node_modules/{is-fullwidth-code-point → ansi-styles}/license +0 -0
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 jA1(X){let Y={...process.env},G=f$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(() => (E$1(),L$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(() => (U30(),Px6));await K(W.databaseUrl);let{createDatabase:H}=await Promise.resolve().then(() => (JU(),Ex6)),{migrateToLatest:U}=await Promise.resolve().then(() => (Vr6(),Ir6)),B=H(W.databaseUrl);await U({keepOpen:!0,database:B,skipBetterAuth:!0})}if(G.settings.clickhouseUrl){let{ensureClickHouseRollup:K}=await Promise.resolve().then(() => js6);await K(G.settings.clickhouseUrl)}let $={...G.settings,databaseUrl:W.databaseUrl,natsUrls:W.natsUrls};return Pl0($),{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 yB0=D(()=>{an1();m9()});import{createServer as Ms6}from"net";function oi5(X){return new Promise((Y)=>{let G=Ms6();G.once("error",()=>Y(!1)),G.listen(X,"0.0.0.0",()=>{G.close(()=>Y(!0))})})}async function MA1(X){if(await oi5(X))return X;let Y=await new Promise((G,Q)=>{let J=Ms6();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 xB0=()=>{};var hB0={};M0(hB0,{startDevServer:()=>ei5});import{join as si5}from"path";function Rs6(X){return X.replace(/\x1b\[[0-9;]*m/g,"")}function Ss6(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 $=Rs6(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=Rs6(Q).replace(/^\[\d+\]\s*/,"").trim();if(W)EK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:W})}})()}async function ei5(X){let{vitePort:Y,baseUrl:G,noTui:Q}=X,J=await MA1(Number(X.port)),{settings:W,services:Z,managedServiceNames:$}=await jA1({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)Ad({name:z.name,status:"ready",port:z.port});Ce(W),Re();let K=si5(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)Ss6(U.stdout),Ss6(U.stderr);let B=G||`http://localhost:${W.port}`;Se(B),Ad({name:"Vite",status:"ready",port:Number(Y)});let N=async(z)=>{if(U.kill(z),$.length>0){let{stopServices:O}=await Promise.resolve().then(() => (E$1(),L$1));await O(W.dataDir)}};return process.on("SIGINT",()=>N("SIGINT")),process.on("SIGTERM",()=>N("SIGTERM")),{port:Number(W.port),process:U}}var gB0=D(()=>{yB0();GF();xB0()});import{Box as uB0,Text as lB0}from"ink";import{jsx as ks6,jsxs as RA1}from"react/jsx-runtime";function Cs6(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 Gp5(X,Y){if(Xp5.has(X))return Y?{text:"\u25CF\u25CF\u25CF\u25CF\u25CF\u25CF",dimColor:!0}:{text:"not set",dimColor:!0};if(Yp5.has(X)){if(Array.isArray(Y)){if(Y.length===0)return{text:"not set",dimColor:!0};return{text:Y.map((W)=>Cs6(W)).join(", "),color:"cyan"}}let Q=Cs6(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 Qp5(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 vs6({env:X}){let Y=Qp5(X);return ks6(uB0,{flexDirection:"column",children:Y.map((G)=>RA1(uB0,{flexDirection:"column",marginTop:1,children:[RA1(lB0,{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=Gp5(Q,J);return RA1(uB0,{children:[RA1(lB0,{dimColor:!0,children:[" ",Q.padEnd(36)]}),ks6(lB0,{color:W.color,dimColor:W.dimColor,children:W.text})]},Q)})]},G.title))})}var Xp5,Yp5;var _s6=D(()=>{Xp5=new Set(["BETTER_AUTH_SECRET","ENCRYPTION_KEY","MESH_JWT_SECRET","STUDIO_PROVISION_SECRET_KEY"]),Yp5=new Set(["DATABASE_URL","CLICKHOUSE_URL","NATS_URL"])});var mB0;var fs6=D(()=>{mB0={name:"decocms",version:"2.293.4",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 Zp5}from"@inkjs/ui";import{useSyncExternalStore as bs6}from"react";import{jsx as qY,jsxs as oQ}from"react/jsx-runtime";function Fp5(X,Y){if(!X||!Hp5.has(X))return X;let G=dB0[Y]??dB0[dB0.length-1];return X==="#875f00"?G[0]:G[1]}function ys6({status:X}){if(X==="pending")return qY(Zp5,{label:""});return qY(MX,{color:"green",children:"\u2713"})}function xs6({services:X,migrationsStatus:Y,home:G,serverUrl:Q,vibe:J}){let W=bs6(du0,mu0),Z=bs6(tu0,au0);return oQ(AU,{flexDirection:"column",paddingBottom:1,children:[J?oQ(AU,{flexDirection:"column",children:[W.map(($,K)=>{let H=Z[K],U=$.reduce((N,z)=>N+z.text.length,0),B=Math.max(0,Kp5-U);return oQ(AU,{flexDirection:"row",children:[$.map((N,z)=>{let O=Fp5(N.color,K);return O?qY(MX,{color:O,children:N.text},z):qY(MX,{children:N.text},z)}),qY(MX,{children:" ".repeat(B+2)}),H?.map((N,z)=>N.color?qY(MX,{color:N.color,children:N.char},z):qY(MX,{children:N.char},z))]},K)}),oQ(MX,{dimColor:!0,children:[" v",mB0.version]})]}):oQ(AU,{flexDirection:"column",marginTop:1,children:[Wp5.map(($,K)=>qY(MX,{color:$p5[K],children:$},K)),oQ(MX,{dimColor:!0,children:[" v",mB0.version]})]}),qY(AU,{marginBottom:1,children:qY(MX,{dimColor:!0,children:"\u2500".repeat(80)})}),qY(AU,{children:oQ(MX,{dimColor:!0,children:["Home: ",G]})}),oQ(AU,{gap:2,children:[X.map(($)=>oQ(AU,{gap:1,children:[oQ(MX,{children:[$.name," :",$.port||"...."]}),qY(ys6,{status:$.status})]},$.name)),oQ(AU,{gap:1,children:[qY(MX,{children:"Migrations"}),qY(ys6,{status:Y})]})]}),qY(AU,{children:Q?oQ(MX,{children:["Open in browser: ",qY(MX,{color:"cyan",children:Q})]}):qY(MX,{dimColor:!0,children:"Starting..."})}),oQ(AU,{gap:2,children:[oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"K"})," ","toggle config"]}),oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"L"})," ","toggle log flow"]}),oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"V"})," ","toggle vibe ",J?"\u266A Nihilore \xB7 CC BY 4.0":""]}),J&&oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"N"})," ","skip song"]})]})]})}var Wp5,$p5,dB0,Kp5=30,Hp5;var hs6=D(()=>{fs6();In1();Cn1();Wp5=[" \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 "],$p5=["#00ff64","#00ee5e","#00dc56","#00c84e","#00b444","#00a03c","#008832","#006e28"],dB0=[["#00ff64","#00cc50"],["#00f060","#00c04c"],["#00e05c","#00b448"],["#00d058","#00a844"],["#00c054","#009c40"],["#00b050","#00903c"],["#00a04c","#008438"],["#009048","#007834"],["#008044","#006c30"],["#007040","#00602c"],["#00603c","#005428"]],Hp5=new Set(["#875f00","#5f3800"])});import{useSyncExternalStore as Up5}from"react";function Bp5(){let X=process.stdout.rows||24,Y=process.stdout.columns||80;if(X!==SA1.rows||Y!==SA1.columns)SA1={rows:X,columns:Y};return SA1}function Np5(X){return process.stdout.on("resize",X),()=>{process.stdout.off("resize",X)}}function gs6(){return Up5(Np5,Bp5)}var SA1;var us6=D(()=>{SA1={rows:process.stdout.rows||24,columns:process.stdout.columns||80}});import{Box as zp5,Text as jX1}from"ink";import{useSyncExternalStore as Op5}from"react";import{jsx as cB0,jsxs as iB0}from"react/jsx-runtime";function Dp5(X){if(X>=500)return"red";if(X>=400)return"yellow";if(X>=300)return"cyan";return"green"}function ls6({logs:X,headerHeight:Y}){let{rows:G}=gs6(),{logFlow:Q}=Op5(Me,je),J=Math.max(1,G-Y-1),W=Q?X:X.slice(-J);return cB0(zp5,{flexDirection:"column",children:W.map((Z,$)=>{if(Z.rawLine)return cB0(jX1,{dimColor:!0,children:Z.rawLine},$);let K=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return iB0(jX1,{children:[iB0(jX1,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),cB0(jX1,{color:Dp5(Z.status),children:Z.status}),iB0(jX1,{dimColor:!0,children:[" ",K.padStart(8)]})]},$)})})}var ms6=D(()=>{GF();us6()});var pB0={};M0(pB0,{App:()=>Tp5});import{Box as wp5,Text as Lp5,useInput as Ep5}from"ink";import{useSyncExternalStore as Pp5}from"react";import{jsx as CA1,jsxs as Ip5}from"react/jsx-runtime";function Tp5({home:X}){let Y=Pp5(Me,je);return Ep5((G)=>{if(G==="k"||G==="K")yn1();if(G==="l"||G==="L")xn1();if((G==="v"||G==="V")&&Y.dataDir)fn1(Y.dataDir),hn1();if((G==="n"||G==="N")&&Y.vibe)_n1()}),Ip5(wp5,{flexDirection:"column",children:[CA1(xs6,{services:Y.services,migrationsStatus:Y.migrationsStatus,home:X,serverUrl:Y.serverUrl,vibe:Y.vibe}),Y.viewMode==="config"?Y.env?CA1(vs6,{env:Y.env}):CA1(Lp5,{dimColor:!0,children:"Loading configuration..."}):CA1(ls6,{logs:Y.logs,headerHeight:Y.vibe?Ap5:qp5})]})}var qp5=15,Ap5=19;var nB0=D(()=>{_s6();hs6();ms6();GF();qd()});function ds6(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_ENV:process.env.STUDIO_ENV,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 is6(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 cs6="https://studio.decocms.com/org/deco/registry/mcp";var aB0=(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(B){if(B instanceof Error&&Y)Q.error=B,K=await Y(B,Q),H=!0;else throw B}else if(Q.finalized===!1&&G)K=await G(Q);if(K&&(Q.finalized===!1||H))Q.res=K;return Q}}};var ps6=()=>{};var M9;var Pq=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 ns6;var as6=D(()=>{ns6=Symbol()});async function Vp5(X,Y){let G=await X.formData();if(G)return jp5(G,Y);return{}}function jp5(X,Y){let G=Object.create(null);if(X.forEach((Q,J)=>{if(!(Y.all||J.endsWith("[]")))G[J]=Q;else Mp5(G,J,Q)}),Y.dot)Object.entries(G).forEach(([Q,J])=>{if(Q.includes("."))Rp5(G,Q,J),delete G[Q]});return G}var ts6=async(X,Y=Object.create(null))=>{let{all:G=!1,dot:Q=!1}=Y,W=(X instanceof kA1?X.raw.headers:X.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return Vp5(X,{all:G,dot:Q});return{}},Mp5=(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]},Rp5=(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 rs6=D(()=>{tB0()});var oB0=(X)=>{let Y=X.split("/");if(Y[0]==="")Y.shift();return Y},os6=(X)=>{let{groups:Y,path:G}=Sp5(X),Q=oB0(G);return Cp5(Q,Y)},Sp5=(X)=>{let Y=[];return X=X.replace(/\{[^}]+\}/g,(G,Q)=>{let J=`@${Q}`;return Y.push([J,G]),J}),{groups:Y,path:X}},Cp5=(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},vA1,ss6=(X,Y)=>{if(X==="*")return"*";let G=X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(G){let Q=`${X}#${Y}`;if(!vA1[Q])if(G[2])vA1[Q]=Y&&Y[0]!==":"&&Y[0]!=="*"?[Q,G[1],new RegExp(`^${G[2]}(?=/${Y})`)]:[X,G[1],new RegExp(`^${G[2]}$`)];else vA1[Q]=[X,G[1],!0];return vA1[Q]}return null},ra=(X,Y)=>{try{return Y(X)}catch{return X.replace(/(?:%[0-9A-Fa-f]{2})+/g,(G)=>{try{return Y(G)}catch{return G}})}},es6=(X)=>ra(X,decodeURI),sB0=(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 es6(K.includes("%25")?K.replace(/%25/g,"%2525"):K)}else if(J===63||J===35)break}return Y.slice(G,Q)},Xe6=(X)=>{let Y=sB0(X);return Y.length>1&&Y.at(-1)==="/"?Y.slice(0,-1):Y},Mj=(X,Y,...G)=>{if(G.length)Y=Mj(Y,...G);return`${X?.[0]==="/"?"":"/"}${X}${Y==="/"?"":`${X?.at(-1)==="/"?"":"/"}${Y?.[0]==="/"?Y.slice(1):Y}`}`},_A1=(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)},rB0=(X)=>{if(!/[%+]/.test(X))return X;if(X.indexOf("+")!==-1)X=X.replace(/\+/g," ");return X.indexOf("%")!==-1?ra(X,MX1):X},Ye6=(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 rB0(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=rB0(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=X.slice($+1,Z===-1?void 0:Z),Q)H=rB0(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},Ge6,Qe6=(X,Y)=>{return Ye6(X,Y,!0)},MX1;var qq=D(()=>{vA1={},Ge6=Ye6,MX1=decodeURIComponent});var Je6=(X)=>ra(X,MX1),kA1;var tB0=D(()=>{Pq();as6();rs6();qq();kA1=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)?Je6(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)?Je6(Q):Q}return X}#J(X){return this.#Y[1]?this.#Y[1][X]:X}query(X){return Ge6(this.url,X)}queries(X){return Qe6(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 ts6(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[ns6](){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 fA1,Ze6=(X,Y)=>{let G=new String(X);return G.isEscaped=!0,G.callbacks=Y,G},RX1=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)=>RX1(K,Y,!1,Q,J))).then(()=>J[0]));if(G)return Ze6(await Z,W);else return Z};var bA1=D(()=>{fA1={Stringify:1,BeforeStream:2,Stream:3}});var We6="text/plain; charset=UTF-8",eB0=(X,Y)=>{return{"Content-Type":X,...Y}},SX1=(X,Y)=>new Response(X,Y),$e6=class{#X;#Y;env={};#G;finalized=!1;error;#Q;#J;#Z;#$;#W;#K;#H;#U;#B;constructor(X,Y){if(this.#X=X,Y)this.#J=Y.executionCtx,this.env=Y.env,this.#K=Y.notFoundHandler,this.#B=Y.path,this.#U=Y.matchResult}get req(){return this.#Y??=new kA1(this.#X,this.#B,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||=SX1(null,{headers:this.#H??=new Headers})}set res(X){if(this.#Z&&X){X=SX1(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=SX1(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 SX1(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,eB0(We6,G))};json=(X,Y,G)=>{return this.#F(JSON.stringify(X),Y,eB0("application/json",G))};html=(X,Y,G)=>{let Q=(J)=>this.#F(J,Y,eB0("text/html; charset=UTF-8",G));return typeof X==="object"?RX1(X,fA1.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??=()=>SX1(),this.#K(this)}};var yA1=D(()=>{tB0();bA1()});var T7="ALL",Ke6="all",He6,xA1="Can not add a route since the matcher is already built.",hA1;var Aq=D(()=>{He6=["get","post","put","delete","options","patch"],hA1=class extends Error{}});var XN0="__COMPOSED_HANDLER";var YN0=()=>{};var kp5=(X)=>{return X.text("404 Not Found",404)},Fe6=(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)},Ue6=class X{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#X="/";routes=[];constructor(Y={}){[...He6,Ke6].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??sB0:Xe6}#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=kp5;errorHandler=Fe6;route(Y,G){let Q=this.basePath(Y);return G.routes.map((J)=>{let W;if(G.errorHandler===Fe6)W=J.handler;else W=async(Z,$)=>(await aB0([],G.errorHandler)(Z,()=>J.handler(Z,$))).res,W[XN0]=J.handler;Q.#Q(J.method,J.path,W)}),this}basePath(Y){let G=this.#Y();return G._basePath=Mj(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=Mj(this._basePath,Y),H=K==="/"?0:K.length;return(U)=>{let B=new URL(U.url);return B.pathname=B.pathname.slice(H)||"/",new Request(B,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,Mj(Y,"*"),$),this}#Q(Y,G,Q){Y=Y.toUpperCase(),G=Mj(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 $e6(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=aB0(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${Mj("/",Y)}`,G),Q,J)};fire=()=>{addEventListener("fetch",(Y)=>{Y.respondWith(this.#Z(Y.request,Y,void 0,Y.request.method))})}};var Be6=D(()=>{ps6();yA1();Aq();YN0();qq()});function gA1(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[[],CX1];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=Q,Q(X,Y)}var CX1;var GN0=D(()=>{Aq();CX1=[]});function _p5(X,Y){if(X.length===1)return Y.length===1?X<Y?-1:1:-1;if(Y.length===1)return 1;if(X===kX1||X===vX1)return 1;else if(Y===kX1||Y===vX1)return-1;if(X===uA1)return 1;else if(Y===uA1)return-1;return X.length===Y.length?X<Y?-1:1:Y.length-X.length}var uA1="[^/]+",kX1=".*",vX1="(?:|/.*)",Rj,vp5,Ne6=class X{#X;#Y;#G=Object.create(null);insert(Y,G,Q,J,W){if(Y.length===0){if(this.#X!==void 0)throw Rj;if(W)return;this.#X=G;return}let[Z,...$]=Y,K=Z==="*"?$.length===0?["","",kX1]:["","",uA1]:Z==="/*"?["","",vX1]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let U=K[1],B=K[2]||uA1;if(U&&K[2]){if(B===".*")throw Rj;if(B=B.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(B))throw Rj}if(H=this.#G[B],!H){if(Object.keys(this.#G).some((N)=>N!==kX1&&N!==vX1))throw Rj;if(W)return;if(H=this.#G[B]=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!==kX1&&U!==vX1))throw Rj;if(W)return;H=this.#G[Z]=new X}H.insert($,G,Q,J,W)}buildRegExpStr(){let G=Object.keys(this.#G).sort(_p5).map((Q)=>{let J=this.#G[Q];return(typeof J.#Y==="number"?`(${Q})@${J.#Y}`:vp5.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 QN0=D(()=>{Rj=Symbol(),vp5=new Set(".\\+*[^]$()")});var ze6=class{#X={varIndex:0};#Y=new Ne6;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 Oe6=D(()=>{QN0()});function we6(X){return De6[X]??=new RegExp(X==="*"?"":`^${X.replace(/\/\*$|([.\\+*[^\]$()])/g,(Y,G)=>G?`\\${G}`:"(?:|/.*)")}$`)}function bp5(){De6=Object.create(null)}function yp5(X){let Y=new ze6,G=[];if(X.length===0)return fp5;let Q=X.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,U],[B,N])=>H?1:B?-1:U.length-N.length),J=Object.create(null);for(let H=0,U=-1,B=Q.length;H<B;H++){let[N,z,O]=Q[H];if(N)J[z]=[O.map(([E])=>[E,Object.create(null)]),CX1];else U++;let w;try{w=Y.insert(z,U,N)}catch(E){throw E===Rj?new hA1(z):E}if(N)continue;G[U]=O.map(([E,P])=>{let q=Object.create(null);P-=1;for(;P>=0;P--){let[M,j]=w[P];q[M]=j}return[E,q]})}let[W,Z,$]=Y.buildRegExp();for(let H=0,U=G.length;H<U;H++)for(let B=0,N=G[H].length;B<N;B++){let z=G[H][B]?.[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 oa(X,Y){if(!X)return;for(let G of Object.keys(X).sort((Q,J)=>J.length-Q.length))if(we6(G).test(Y))return[...X[G]];return}var fp5,De6,lA1=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(xA1);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 $=we6(Y);if(X===T7)Object.keys(Q).forEach((K)=>{Q[K][Y]||=oa(Q[K],Y)||oa(Q[T7],Y)||[]});else Q[X][Y]||=oa(Q[X],Y)||oa(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=_A1(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]||=[...oa(Q[U],H)||oa(Q[T7],H)||[]],J[U][H].push([G,W-K+$+1])})}}match=gA1;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,bp5(),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 yp5(Y)}};var JN0=D(()=>{Aq();qq();GN0();QN0();Oe6();fp5=[/^$/,[],Object.create(null)],De6=Object.create(null)});var xp5=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(),CX1];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=gA1};var Le6=D(()=>{Aq();GN0();JN0()});var Ee6=D(()=>{JN0();Le6()});var ZN0=class{name="SmartRouter";#X=[];#Y=[];constructor(X){this.#X=X.routers}add(X,Y,G){if(!this.#Y)throw Error(xA1);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 hA1)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 Pe6=D(()=>{Aq()});var qe6=D(()=>{Pe6()});var _X1,hp5=(X)=>{for(let Y in X)return!0;return!1},Ae6=class X{#X;#Y;#G;#Q=0;#J=_X1;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=os6(G),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],U=W[$+1],B=ss6(H,U),N=Array.isArray(B)?B[0]:H;if(N in J.#Y){if(J=J.#Y[N],B)Z.push(B[1]);continue}if(J.#Y[N]=new X,B)J.#G.push(B),Z.push(B[1]);J=J.#Y[N]}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!==_X1||W&&W!==_X1)for(let B=0,N=H.possibleKeys.length;B<N;B++){let z=H.possibleKeys[B],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=_X1;let W=[this],Z=oB0(G),$=[],K=Z.length,H=null;for(let U=0;U<K;U++){let B=Z[U],N=U===K-1,z=[];for(let w=0,E=W.length;w<E;w++){let P=W[w],q=P.#Y[B];if(q)if(q.#J=P.#J,N){if(q.#Y["*"])this.#Z(Q,q.#Y["*"],Y,P.#J);this.#Z(Q,q,Y,P.#J)}else z.push(q);for(let M=0,j=P.#G.length;M<j;M++){let V=P.#G[M],R=P.#J===_X1?{}:{...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(!B&&!(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),hp5(y.#Y)){y.#J=R;let p=i[0].match(/\//)?.length??0;($[p]||=[]).push(y)}continue}}if(v===!0||v.test(B))if(R[_]=B,N){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,B)=>{return U.score-B.score});return[Q.map(({handler:U,params:B})=>[U,B])]}};var Te6=D(()=>{Aq();qq();_X1=Object.create(null)});var WN0=class{name="TrieRouter";#X;constructor(){this.#X=new Ae6}add(X,Y,G){let Q=_A1(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 Ie6=D(()=>{qq();Te6()});var Ve6=D(()=>{Ie6()});var U5;var je6=D(()=>{Be6();Ee6();qe6();Ve6();U5=class extends Ue6{constructor(X={}){super(X);this.router=X.router??new ZN0({routers:[new lA1,new WN0]})}}});var NG=D(()=>{je6()});var Re6,gp5,Me6=(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)},$N0=(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=Me6(J.substring(0,W));if(Y&&Y!==Z||!Re6.test(Z))continue;let $=Me6(J.substring(W+1));if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(gp5.test($)){if(Q[Z]=$.indexOf("%")!==-1?ra($,MX1):$,Y)break}}return Q},up5=(X,Y,G={})=>{if(!Re6.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},mA1=(X,Y,G)=>{return Y=encodeURIComponent(Y),up5(X,Y,G)};var Se6=D(()=>{qq();Re6=/^[\w!#$%&'*.^`|~+-]+$/,gp5=/^[ !#-:<-[\]-~]*$/});var dA1=(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 $N0(Q,W)[W]}if(!Q)return{};return $N0(Q)},lp5=(X,Y,G)=>{let Q;if(G?.prefix==="secure")Q=mA1("__Secure-"+X,Y,{path:"/",...G,secure:!0});else if(G?.prefix==="host")Q=mA1("__Host-"+X,Y,{...G,path:"/",secure:!0,domain:void 0});else Q=mA1(X,Y,{path:"/",...G});return Q},KN0=(X,Y,G,Q)=>{let J=lp5(Y,G,Q);X.header("Set-Cookie",J,{append:!0})};var HN0=D(()=>{Se6()});var Ce6=(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,B){Z.res.headers.set(U,B)}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 B=G.allowHeaders;if(!B?.length){let N=Z.req.header("Access-Control-Request-Headers");if(N)B=N.split(/\s*,\s*/)}if(B?.length)K("Access-Control-Allow-Headers",B.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 ke6=()=>{};var ve6=()=>{try{return performance.now()}catch{}return Date.now()},FN0=(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:"*")}}},_e6=(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:ve6()})},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,$=ve6()-Z;_e6(X,Y,$,W,G),Q.timers.delete(Y)};var fe6=D(()=>{yA1()});var UN0=D(()=>{fe6()});function fX1(){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 BN0)X[Y.category]?.push(Y);return X}var BN0;var NN0=D(()=>{BN0=[{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 be6=D(()=>{Gp();ez1()});function ye6(){return dp5.parse(process.env)}var zN0=(X)=>F.enum(["true","false","1","0"]).optional().transform((Y)=>Y===void 0?X:Y==="true"||Y==="1"),mp5=(X)=>F.string().optional().transform((Y)=>Y?Y.split(",").map((G)=>G.trim()):X),dp5;var xe6=D(()=>{H0();dp5=F.object({AUTH_EMAIL_PASSWORD_ENABLED:zN0(!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:zN0(!1),AUTH_MAGIC_LINK_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_ENABLED:zN0(!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:mp5(["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 cA1;var he6=D(()=>{cA1={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"}});import{existsSync as cp5,readFileSync as ip5}from"fs";function pp5(){let X=ye6(),Y=v6().configPath;if(!cp5(Y))return{auth:X,monitoring:cA1};try{let G=JSON.parse(ip5(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??cA1,theme:G.theme,logo:G.logo,autoCreateOrganizationOnSignup:G.autoCreateOrganizationOnSignup}}catch{return{auth:X,monitoring:cA1}}}function Sj(){if(!ON0)ON0=pp5();return ON0}function ge6(){return Sj().theme}var ON0=null;var DN0=D(()=>{xe6();he6();m9()});import{dirname as np5,posix as ap5,sep as tp5}from"path";function le6(){let X=rp5();return async(Y)=>{for(let G of Y)G.module=X(G.filename);return Y}}function rp5(X=process.argv[1]?np5(process.argv[1]):process.cwd(),Y=tp5==="\\"){let G=Y?ue6(X):X;return(Q)=>{if(!Q)return;let J=Y?ue6(Q):Q,{dir:W,base:Z,ext:$}=ap5.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 ue6(X){return X.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var me6=()=>{};function op5(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 wN0=(X)=>{if("flags"in X){let Y=de6(X.flags),G=ce6(X.flags);return{...X,featureFlags:Y,featureFlagPayloads:G}}{let Y=X.featureFlags??{},G=Object.fromEntries(Object.entries(X.featureFlagPayloads||{}).map(([J,W])=>[J,LN0(W)])),Q=Object.fromEntries(Object.entries(Y).map(([J,W])=>[J,op5(J,W,G[J])]));return{...X,featureFlags:Y,featureFlagPayloads:G,flags:Q}}},de6=(X)=>Object.fromEntries(Object.entries(X??{}).map(([Y,G])=>[Y,bX1(G)]).filter(([,Y])=>Y!==void 0)),ce6=(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?LN0(Q):void 0]}))},bX1=(X)=>X===void 0?void 0:X.variant??X.enabled,LN0=(X)=>{if(typeof X!="string")return X;try{return JSON.parse(X)}catch{return X}};var iA1=()=>{};function ie6(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}async function pA1(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 EN0=()=>{};var sp5,pe6=function(X,Y=[]){if(!X)return!1;let G=X.toLowerCase();return sp5.concat(Y).some((Q)=>{let J=Q.toLowerCase();return G.indexOf(J)!==-1})};var ne6=D(()=>{sp5=["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 aJ;var Cj=D(()=>{aJ=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 nA1=()=>{};function tA1(X){return X===null||typeof X!="object"}function kj(X,Y){return Object.prototype.toString.call(X)===`[object ${Y}]`}function re6(X){return kj(X,"ErrorEvent")}function ea(X){return typeof Event<"u"&&Yn5(X,Event)}function oe6(X){return kj(X,"Object")}function Yn5(X,Y){try{return X instanceof Y}catch{return!1}}var Xn5,ae6,TmX,PN0,aA1,yX1=(X)=>X===Object(X)&&!aA1(X),sa=(X)=>X===void 0,Tq=(X)=>PN0.call(X)=="[object String]",te6=(X)=>Tq(X)&&X.trim().length===0,xX1=(X)=>PN0.call(X)=="[object Number]"&&X===X,qN0=(X)=>X instanceof Error;var hX1=D(()=>{Cj();nA1();Xn5=Array.isArray,ae6=Object.prototype,TmX=ae6.hasOwnProperty,PN0=ae6.toString,aA1=Xn5||function(X){return PN0.call(X)==="[object Array]"}});function gX1(X,Y,G,Q,J){if(Y>G)Q.warn("min cannot be greater than max."),Y=G;if(xX1(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),gX1(J||G,Y,G,Q)}var AN0=D(()=>{hX1()});class TN0{constructor(X){this._buckets={},this._onBucketRateLimited=X._onBucketRateLimited,this._bucketSize=gX1(X.bucketSize,0,100,X._logger),this._refillRate=gX1(X.refillRate,0,this._bucketSize,X._logger),this._refillInterval=gX1(X.refillInterval,0,Gn5,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 Gn5=86400000;var se6=D(()=>{AN0()});class vj{constructor(X){this.bytes=X}static ofInner(X){if(X.length===16)return new vj(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 vj(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 vj(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 vj(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 X14{constructor(X){this.timestamp=0,this.counter=0,this.random=X??Qn5()}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 vj.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,vj.ofInner(X)}}var Qn5=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),ee6,Iq=()=>Jn5().toString(),Jn5=()=>(ee6||(ee6=new X14)).generate();var uX1=D(()=>{/*! For license information please see uuidv7.mjs.LICENSE.txt */});class IN0{add(X){let Y=Iq();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 Y14=D(()=>{uX1()});function Zn5(X=console){return{log:X.log.bind(X),warn:X.warn.bind(X),error:X.error.bind(X),debug:X.debug.bind(X)}}function Q14(X,Y=Wn5){return G14(X,Y,Zn5())}var G14=(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)=>G14(`${X} ${W}`,Y,G)}},Wn5=(X)=>X();var J14=()=>{};var Yt="Mobile",oA1="iOS",Xt="Android",Z14="Tablet",bmX,Kn5="Apple",ymX,W14="Safari",sA1="BlackBerry",$14="Samsung",Hn5,Fn5,eA1="Chrome",Un5,Bn5,K14="Internet Explorer",Nn5,jN0="Opera",xmX,H14="Edge",zn5,MN0="Firefox",On5,RN0="Nintendo",SN0="PlayStation",rA1="Xbox",Dn5,wn5,lX1="Windows",Ln5,F14="Generic",hmX,gmX,En5="Konqueror",F3="(\\d+(\\.\\d+)?)",VN0,umX,lmX,mmX,Pn5,qn5,dmX,cmX;var U14=D(()=>{nA1();hX1();bmX=Xt+" "+Z14,ymX=Kn5+" Watch",Hn5=$14+"Browser",Fn5=$14+" Internet",Un5=eA1+" OS",Bn5=eA1+" "+oA1,Nn5=K14+" "+Yt,xmX=jN0+" Mini",zn5="Microsoft "+H14,On5=MN0+" "+oA1,Dn5=Xt+" "+Yt,wn5=Yt+" "+W14,Ln5=lX1+" Phone",hmX=F14+" "+Yt.toLowerCase(),gmX=F14+" "+Z14.toLowerCase(),VN0=new RegExp("Version/"+F3),umX=new RegExp(rA1,"i"),lmX=new RegExp(SN0+" \\w+","i"),mmX=new RegExp(RN0+" \\w+","i"),Pn5=new RegExp(sA1+"|PlayBook|BB10","i"),qn5={"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"},dmX={[Nn5]:[new RegExp("rv:"+F3)],[zn5]:[new RegExp(H14+"?\\/"+F3)],[eA1]:[new RegExp("("+eA1+"|CrMo)\\/"+F3)],[Bn5]:[new RegExp("CriOS\\/"+F3)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+F3)],[W14]:[VN0],[wn5]:[VN0],[jN0]:[new RegExp("("+jN0+"|OPR)\\/"+F3)],[MN0]:[new RegExp(MN0+"\\/"+F3)],[On5]:[new RegExp("FxiOS\\/"+F3)],[En5]:[new RegExp("Konqueror[:/]?"+F3,"i")],[sA1]:[new RegExp(sA1+" "+F3),VN0],[Dn5]:[new RegExp("android\\s"+F3,"i")],[Fn5]:[new RegExp(Hn5+"\\/"+F3)],[K14]:[new RegExp("(rv:|MSIE )"+F3)],Mozilla:[new RegExp("rv:"+F3)]},cmX=[[new RegExp(rA1+"; "+rA1+" (.*?)[);]","i"),(X)=>[rA1,X&&X[1]||""]],[new RegExp(RN0,"i"),[RN0,""]],[new RegExp(SN0,"i"),[SN0,""]],[Pn5,[sA1,""]],[new RegExp(lX1,"i"),(X,Y)=>{if(/Phone/.test(Y)||/WPDesktop/.test(Y))return[Ln5,""];if(new RegExp(Yt).test(Y)&&!/IEMobile\b/.test(Y))return[lX1+" "+Yt,""];let G=/Windows NT ([0-9.]+)/i.exec(Y);if(G&&G[1]){let Q=G[1],J=qn5[Q]||"";if(/arm/i.test(Y))J="RT";return[lX1,J]}return[lX1,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(X)=>{if(X&&X[3]){let Y=[X[3],X[4],X[5]||"0"];return[oA1,Y.join(".")]}return[oA1,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(X)=>{let Y="";if(X&&X.length>=3)Y=sa(X[2])?X[3]:X[2];return["watchOS",Y]}],[new RegExp("("+Xt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Xt+")","i"),(X)=>{if(X&&X[2]){let Y=[X[2],X[3],X[4]||"0"];return[Xt,Y.join(".")]}return[Xt,""]}],[/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/,[Un5,""]],[/Linux|debian/i,["Linux",""]]]});function N14(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 XT1(){return new Date().toISOString()}function Fw(X,Y){let G=setTimeout(X,Y);return G?.unref&&G?.unref(),G}function CN0(X){return Promise.all(X.map((Y)=>(Y??Promise.resolve()).then((G)=>({status:"fulfilled",value:G}),(G)=>({status:"rejected",reason:G}))))}var B14="utf8",O14=(X)=>X instanceof Error;var U3=D(()=>{ne6();se6();AN0();nA1();hX1();Y14();J14();U14()});var An5,JdX;var kN0=D(()=>{U3();An5={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}},JdX=An5.info});var D14=D(()=>{kN0();Cj()});var w14=D(()=>{Cj()});class vN0{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 L14=()=>{};async function E14(X){if(X instanceof Gt){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 _N0(X){return typeof X=="object"&&(X instanceof Gt||X instanceof mX1)}function P14(X){return typeof X=="object"&&X instanceof Gt&&X.status===413}class YT1{constructor(X,Y={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new IN0,this._events=new vN0,this._isInitialized=!1;let G=typeof X=="string"?X.trim():"",Q=typeof Y.host=="string"?Y.host.trim():"",J=!G;if(this._logger=Q14("[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=N14(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:_N0},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=!ie6()||(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(aJ.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(aJ.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(aJ.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:wN0(U)})).catch((U)=>{return this._events.emit("error",U),{success:!1,error:this.categorizeRequestError(U)}})}categorizeRequestError(X){if(X instanceof Gt)return{type:"api_error",statusCode:X.status};if(X instanceof mX1){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 $=bX1(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(aJ.Props);return this._props||{}}set props(X){this._props=X}async register(X){this.wrap(()=>{this.props={...this.props,...X},this.setPersistedProperty(aJ.Props,this.props)})}async unregister(X){this.wrap(()=>{delete this.props[X],this.setPersistedProperty(aJ.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(aJ.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(aJ.Queue,J),this._events.emit(X,Q),J.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=Fw(()=>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:XT1()};if(this.historicalMigration)J.historical_migration=!0;let W=JSON.stringify(J),Z=`${this.host}/batch/`,$=this.disableCompression?null:await pA1(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:XT1(),uuid:G?.uuid?G.uuid:Iq()};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 E14(X)})}async flush(){let X=CN0([this.flushPromise]).then(()=>this._flush());return this.flushPromise=X,this.addPendingPromise(X),CN0([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(aJ.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((N)=>N.message),W=async()=>{let z=(this.getPersistedProperty(aJ.Queue)||[]).slice(Q.length);this.setPersistedProperty(aJ.Queue,z),X=z,await this.flushStorage()},Z={api_key:this.apiKey,batch:J,sent_at:XT1()};if(this.historicalMigration)Z.historical_migration=!0;let $=JSON.stringify(Z),K=`${this.host}/batch/`,H=this.disableCompression?null:await pA1($,this.isDebug),U={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...H!==null&&{"Content-Encoding":"gzip"}},body:H||$},B={retryCheck:(N)=>{if(P14(N))return!1;return _N0(N)}};try{await this.fetchWithRetry(K,U,B)}catch(N){if(P14(N)&&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(!(N instanceof mX1))await W();throw this._events.emit("error",N),N}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,B14)}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=Fw(()=>Z.abort(),$),H=null;try{H=await this.fetch(X,{signal:Z.signal,...Y})}catch(B){throw new mX1(B)}finally{clearTimeout(K)}if(Y.mode!=="no-cors"&&(H.status<200||H.status>=400))throw new Gt(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(aJ.Queue)||[]).length===0)break;if(await this.flush(),Y)break}}catch(J){if(!_N0(J))throw J;await E14(J)}},Q;try{return await Promise.race([new Promise((J,W)=>{Q=Fw(()=>{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 Gt,mX1;var fN0=D(()=>{L14();iA1();EN0();Cj();U3();uX1();Gt=class Gt 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()}};mX1=class mX1 extends Error{constructor(X){super("Network error while fetching PostHog",X instanceof Error?{cause:X}:{}),this.error=X,this.name="PostHogFetchNetworkError"}}});var q14=D(()=>{iA1();Cj();fN0();uX1();U3()});var A14=D(()=>{hX1()});function I14(X){let Y=globalThis._posthogChunkIds;if(!Y)return;let G=Object.keys(Y);if(QT1&&G.length===T14)return QT1;return T14=G.length,QT1=G.reduce((Q,J)=>{if(!GT1)GT1={};let W=GT1[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,GT1[J]=[H,U];break}}}return Q},{}),QT1}var GT1,T14,QT1;var V14=()=>{};class j14{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&&aA1(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:I14(this.stackParser),skipFirstLines:X.skipFirstLines??1}}buildCoercingContext(X,Y,G=0){let Q=(W,Z)=>{if(!(Z<=Vn5))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 Vn5=4;var M14=D(()=>{U3();V14()});function Qz(X,Y,G,Q,J){let W={platform:X,filename:Y,function:G==="<anonymous>"?sQ:G,in_app:!0};if(!sa(Q))W.lineno=Q;if(!sa(J))W.colno=J;return W}var sQ="?";var Vq=D(()=>{U3()});var JT1=(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]:sQ,G?`safari-extension:${Y}`:`safari-web-extension:${Y}`]:[X,Y]};var bN0=D(()=>{Vq()});var jn5,Mn5,Rn5,yN0=(X,Y)=>{let G=jn5.exec(X);if(G){let[,J,W,Z]=G;return Qz(Y,J,sQ,+W,+Z)}let Q=Mn5.exec(X);if(Q){if(Q[2]&&Q[2].indexOf("eval")===0){let $=Rn5.exec(Q[2]);if($)Q[2]=$[1],Q[3]=$[2],Q[4]=$[3]}let[W,Z]=JT1(Q[1]||sQ,Q[2]);return Qz(Y,Z,W,Q[3]?+Q[3]:void 0,Q[4]?+Q[4]:void 0)}};var R14=D(()=>{Vq();bN0();jn5=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Mn5=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Rn5=/\((\S*)(?::(\d+))(?::(\d+))\)/});var Sn5,Cn5,xN0=(X,Y)=>{let G=Sn5.exec(X);if(G){if(G[3]&&G[3].indexOf(" > eval")>-1){let Z=Cn5.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]||sQ;return[W,J]=JT1(W,J),Qz(Y,J,W,G[4]?+G[4]:void 0,G[5]?+G[5]:void 0)}};var S14=D(()=>{Vq();bN0();Sn5=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Cn5=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i});var kn5,C14=(X,Y)=>{let G=kn5.exec(X);return G?Qz(Y,G[2],G[1]||sQ,+G[3],G[4]?+G[4]:void 0):void 0};var k14=D(()=>{Vq();kn5=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i});var vn5,v14=(X,Y)=>{let G=vn5.exec(X);return G?Qz(Y,G[2],G[3]||sQ,+G[1]):void 0},_n5,_14=(X,Y)=>{let G=_n5.exec(X);return G?Qz(Y,G[5],G[3]||G[4]||sQ,+G[1],+G[2]):void 0};var f14=D(()=>{Vq();vn5=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,_n5=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i});function yn5(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 b14(X){return parseInt(X||"",10)||void 0}var fn5,bn5,y14=(X,Y)=>{let G=X.match(bn5);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 B=Q.indexOf(".Module");if(B>0)W=W.slice(B+1),Q=Q.slice(0,B)}Z=void 0}if(J)Z=Q,$=J;if(J==="<anonymous>")$=void 0,W=void 0;if(W===void 0)$=$||sQ,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:b14(G[3]),colno:b14(G[4]),in_app:yn5(K||"",H),platform:Y}}if(X.match(fn5))return{filename:X,platform:Y}};var x14=D(()=>{Vq();fn5=/^\s*[-]{4,}$/,bn5=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/});function u14(X){if(!X.length)return[];let Y=Array.from(X);return Y.reverse(),Y.slice(0,g14).map((G)=>({...G,filename:G.filename||xn5(Y).filename,function:G.function||sQ}))}function xn5(X){return X[X.length-1]||{}}function hn5(){return l14("web:javascript",yN0,xN0)}function l14(X,...Y){return(G,Q=0)=>{let J=[],W=G.split(`
|
|
1639
|
+
`);Q=W.pop()??"";for(let Z of W){let $=Rs6(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=Rs6(Q).replace(/^\[\d+\]\s*/,"").trim();if(W)EK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:W})}})()}async function ei5(X){let{vitePort:Y,baseUrl:G,noTui:Q}=X,J=await MA1(Number(X.port)),{settings:W,services:Z,managedServiceNames:$}=await jA1({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)Ad({name:z.name,status:"ready",port:z.port});Ce(W),Re();let K=si5(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)Ss6(U.stdout),Ss6(U.stderr);let B=G||`http://localhost:${W.port}`;Se(B),Ad({name:"Vite",status:"ready",port:Number(Y)});let N=async(z)=>{if(U.kill(z),$.length>0){let{stopServices:O}=await Promise.resolve().then(() => (E$1(),L$1));await O(W.dataDir)}};return process.on("SIGINT",()=>N("SIGINT")),process.on("SIGTERM",()=>N("SIGTERM")),{port:Number(W.port),process:U}}var gB0=D(()=>{yB0();GF();xB0()});import{Box as uB0,Text as lB0}from"ink";import{jsx as ks6,jsxs as RA1}from"react/jsx-runtime";function Cs6(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 Gp5(X,Y){if(Xp5.has(X))return Y?{text:"\u25CF\u25CF\u25CF\u25CF\u25CF\u25CF",dimColor:!0}:{text:"not set",dimColor:!0};if(Yp5.has(X)){if(Array.isArray(Y)){if(Y.length===0)return{text:"not set",dimColor:!0};return{text:Y.map((W)=>Cs6(W)).join(", "),color:"cyan"}}let Q=Cs6(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 Qp5(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 vs6({env:X}){let Y=Qp5(X);return ks6(uB0,{flexDirection:"column",children:Y.map((G)=>RA1(uB0,{flexDirection:"column",marginTop:1,children:[RA1(lB0,{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=Gp5(Q,J);return RA1(uB0,{children:[RA1(lB0,{dimColor:!0,children:[" ",Q.padEnd(36)]}),ks6(lB0,{color:W.color,dimColor:W.dimColor,children:W.text})]},Q)})]},G.title))})}var Xp5,Yp5;var _s6=D(()=>{Xp5=new Set(["BETTER_AUTH_SECRET","ENCRYPTION_KEY","MESH_JWT_SECRET","STUDIO_PROVISION_SECRET_KEY"]),Yp5=new Set(["DATABASE_URL","CLICKHOUSE_URL","NATS_URL"])});var mB0;var fs6=D(()=>{mB0={name:"decocms",version:"2.293.5",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 Zp5}from"@inkjs/ui";import{useSyncExternalStore as bs6}from"react";import{jsx as qY,jsxs as oQ}from"react/jsx-runtime";function Fp5(X,Y){if(!X||!Hp5.has(X))return X;let G=dB0[Y]??dB0[dB0.length-1];return X==="#875f00"?G[0]:G[1]}function ys6({status:X}){if(X==="pending")return qY(Zp5,{label:""});return qY(MX,{color:"green",children:"\u2713"})}function xs6({services:X,migrationsStatus:Y,home:G,serverUrl:Q,vibe:J}){let W=bs6(du0,mu0),Z=bs6(tu0,au0);return oQ(AU,{flexDirection:"column",paddingBottom:1,children:[J?oQ(AU,{flexDirection:"column",children:[W.map(($,K)=>{let H=Z[K],U=$.reduce((N,z)=>N+z.text.length,0),B=Math.max(0,Kp5-U);return oQ(AU,{flexDirection:"row",children:[$.map((N,z)=>{let O=Fp5(N.color,K);return O?qY(MX,{color:O,children:N.text},z):qY(MX,{children:N.text},z)}),qY(MX,{children:" ".repeat(B+2)}),H?.map((N,z)=>N.color?qY(MX,{color:N.color,children:N.char},z):qY(MX,{children:N.char},z))]},K)}),oQ(MX,{dimColor:!0,children:[" v",mB0.version]})]}):oQ(AU,{flexDirection:"column",marginTop:1,children:[Wp5.map(($,K)=>qY(MX,{color:$p5[K],children:$},K)),oQ(MX,{dimColor:!0,children:[" v",mB0.version]})]}),qY(AU,{marginBottom:1,children:qY(MX,{dimColor:!0,children:"\u2500".repeat(80)})}),qY(AU,{children:oQ(MX,{dimColor:!0,children:["Home: ",G]})}),oQ(AU,{gap:2,children:[X.map(($)=>oQ(AU,{gap:1,children:[oQ(MX,{children:[$.name," :",$.port||"...."]}),qY(ys6,{status:$.status})]},$.name)),oQ(AU,{gap:1,children:[qY(MX,{children:"Migrations"}),qY(ys6,{status:Y})]})]}),qY(AU,{children:Q?oQ(MX,{children:["Open in browser: ",qY(MX,{color:"cyan",children:Q})]}):qY(MX,{dimColor:!0,children:"Starting..."})}),oQ(AU,{gap:2,children:[oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"K"})," ","toggle config"]}),oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"L"})," ","toggle log flow"]}),oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"V"})," ","toggle vibe ",J?"\u266A Nihilore \xB7 CC BY 4.0":""]}),J&&oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"N"})," ","skip song"]})]})]})}var Wp5,$p5,dB0,Kp5=30,Hp5;var hs6=D(()=>{fs6();In1();Cn1();Wp5=[" \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 "],$p5=["#00ff64","#00ee5e","#00dc56","#00c84e","#00b444","#00a03c","#008832","#006e28"],dB0=[["#00ff64","#00cc50"],["#00f060","#00c04c"],["#00e05c","#00b448"],["#00d058","#00a844"],["#00c054","#009c40"],["#00b050","#00903c"],["#00a04c","#008438"],["#009048","#007834"],["#008044","#006c30"],["#007040","#00602c"],["#00603c","#005428"]],Hp5=new Set(["#875f00","#5f3800"])});import{useSyncExternalStore as Up5}from"react";function Bp5(){let X=process.stdout.rows||24,Y=process.stdout.columns||80;if(X!==SA1.rows||Y!==SA1.columns)SA1={rows:X,columns:Y};return SA1}function Np5(X){return process.stdout.on("resize",X),()=>{process.stdout.off("resize",X)}}function gs6(){return Up5(Np5,Bp5)}var SA1;var us6=D(()=>{SA1={rows:process.stdout.rows||24,columns:process.stdout.columns||80}});import{Box as zp5,Text as jX1}from"ink";import{useSyncExternalStore as Op5}from"react";import{jsx as cB0,jsxs as iB0}from"react/jsx-runtime";function Dp5(X){if(X>=500)return"red";if(X>=400)return"yellow";if(X>=300)return"cyan";return"green"}function ls6({logs:X,headerHeight:Y}){let{rows:G}=gs6(),{logFlow:Q}=Op5(Me,je),J=Math.max(1,G-Y-1),W=Q?X:X.slice(-J);return cB0(zp5,{flexDirection:"column",children:W.map((Z,$)=>{if(Z.rawLine)return cB0(jX1,{dimColor:!0,children:Z.rawLine},$);let K=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return iB0(jX1,{children:[iB0(jX1,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),cB0(jX1,{color:Dp5(Z.status),children:Z.status}),iB0(jX1,{dimColor:!0,children:[" ",K.padStart(8)]})]},$)})})}var ms6=D(()=>{GF();us6()});var pB0={};M0(pB0,{App:()=>Tp5});import{Box as wp5,Text as Lp5,useInput as Ep5}from"ink";import{useSyncExternalStore as Pp5}from"react";import{jsx as CA1,jsxs as Ip5}from"react/jsx-runtime";function Tp5({home:X}){let Y=Pp5(Me,je);return Ep5((G)=>{if(G==="k"||G==="K")yn1();if(G==="l"||G==="L")xn1();if((G==="v"||G==="V")&&Y.dataDir)fn1(Y.dataDir),hn1();if((G==="n"||G==="N")&&Y.vibe)_n1()}),Ip5(wp5,{flexDirection:"column",children:[CA1(xs6,{services:Y.services,migrationsStatus:Y.migrationsStatus,home:X,serverUrl:Y.serverUrl,vibe:Y.vibe}),Y.viewMode==="config"?Y.env?CA1(vs6,{env:Y.env}):CA1(Lp5,{dimColor:!0,children:"Loading configuration..."}):CA1(ls6,{logs:Y.logs,headerHeight:Y.vibe?Ap5:qp5})]})}var qp5=15,Ap5=19;var nB0=D(()=>{_s6();hs6();ms6();GF();qd()});function ds6(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_ENV:process.env.STUDIO_ENV,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 is6(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 cs6="https://studio.decocms.com/org/deco/registry/mcp";var aB0=(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(B){if(B instanceof Error&&Y)Q.error=B,K=await Y(B,Q),H=!0;else throw B}else if(Q.finalized===!1&&G)K=await G(Q);if(K&&(Q.finalized===!1||H))Q.res=K;return Q}}};var ps6=()=>{};var M9;var Pq=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 ns6;var as6=D(()=>{ns6=Symbol()});async function Vp5(X,Y){let G=await X.formData();if(G)return jp5(G,Y);return{}}function jp5(X,Y){let G=Object.create(null);if(X.forEach((Q,J)=>{if(!(Y.all||J.endsWith("[]")))G[J]=Q;else Mp5(G,J,Q)}),Y.dot)Object.entries(G).forEach(([Q,J])=>{if(Q.includes("."))Rp5(G,Q,J),delete G[Q]});return G}var ts6=async(X,Y=Object.create(null))=>{let{all:G=!1,dot:Q=!1}=Y,W=(X instanceof kA1?X.raw.headers:X.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return Vp5(X,{all:G,dot:Q});return{}},Mp5=(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]},Rp5=(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 rs6=D(()=>{tB0()});var oB0=(X)=>{let Y=X.split("/");if(Y[0]==="")Y.shift();return Y},os6=(X)=>{let{groups:Y,path:G}=Sp5(X),Q=oB0(G);return Cp5(Q,Y)},Sp5=(X)=>{let Y=[];return X=X.replace(/\{[^}]+\}/g,(G,Q)=>{let J=`@${Q}`;return Y.push([J,G]),J}),{groups:Y,path:X}},Cp5=(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},vA1,ss6=(X,Y)=>{if(X==="*")return"*";let G=X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(G){let Q=`${X}#${Y}`;if(!vA1[Q])if(G[2])vA1[Q]=Y&&Y[0]!==":"&&Y[0]!=="*"?[Q,G[1],new RegExp(`^${G[2]}(?=/${Y})`)]:[X,G[1],new RegExp(`^${G[2]}$`)];else vA1[Q]=[X,G[1],!0];return vA1[Q]}return null},ra=(X,Y)=>{try{return Y(X)}catch{return X.replace(/(?:%[0-9A-Fa-f]{2})+/g,(G)=>{try{return Y(G)}catch{return G}})}},es6=(X)=>ra(X,decodeURI),sB0=(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 es6(K.includes("%25")?K.replace(/%25/g,"%2525"):K)}else if(J===63||J===35)break}return Y.slice(G,Q)},Xe6=(X)=>{let Y=sB0(X);return Y.length>1&&Y.at(-1)==="/"?Y.slice(0,-1):Y},Mj=(X,Y,...G)=>{if(G.length)Y=Mj(Y,...G);return`${X?.[0]==="/"?"":"/"}${X}${Y==="/"?"":`${X?.at(-1)==="/"?"":"/"}${Y?.[0]==="/"?Y.slice(1):Y}`}`},_A1=(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)},rB0=(X)=>{if(!/[%+]/.test(X))return X;if(X.indexOf("+")!==-1)X=X.replace(/\+/g," ");return X.indexOf("%")!==-1?ra(X,MX1):X},Ye6=(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 rB0(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=rB0(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=X.slice($+1,Z===-1?void 0:Z),Q)H=rB0(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},Ge6,Qe6=(X,Y)=>{return Ye6(X,Y,!0)},MX1;var qq=D(()=>{vA1={},Ge6=Ye6,MX1=decodeURIComponent});var Je6=(X)=>ra(X,MX1),kA1;var tB0=D(()=>{Pq();as6();rs6();qq();kA1=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)?Je6(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)?Je6(Q):Q}return X}#J(X){return this.#Y[1]?this.#Y[1][X]:X}query(X){return Ge6(this.url,X)}queries(X){return Qe6(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 ts6(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[ns6](){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 fA1,Ze6=(X,Y)=>{let G=new String(X);return G.isEscaped=!0,G.callbacks=Y,G},RX1=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)=>RX1(K,Y,!1,Q,J))).then(()=>J[0]));if(G)return Ze6(await Z,W);else return Z};var bA1=D(()=>{fA1={Stringify:1,BeforeStream:2,Stream:3}});var We6="text/plain; charset=UTF-8",eB0=(X,Y)=>{return{"Content-Type":X,...Y}},SX1=(X,Y)=>new Response(X,Y),$e6=class{#X;#Y;env={};#G;finalized=!1;error;#Q;#J;#Z;#$;#W;#K;#H;#U;#B;constructor(X,Y){if(this.#X=X,Y)this.#J=Y.executionCtx,this.env=Y.env,this.#K=Y.notFoundHandler,this.#B=Y.path,this.#U=Y.matchResult}get req(){return this.#Y??=new kA1(this.#X,this.#B,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||=SX1(null,{headers:this.#H??=new Headers})}set res(X){if(this.#Z&&X){X=SX1(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=SX1(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 SX1(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,eB0(We6,G))};json=(X,Y,G)=>{return this.#F(JSON.stringify(X),Y,eB0("application/json",G))};html=(X,Y,G)=>{let Q=(J)=>this.#F(J,Y,eB0("text/html; charset=UTF-8",G));return typeof X==="object"?RX1(X,fA1.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??=()=>SX1(),this.#K(this)}};var yA1=D(()=>{tB0();bA1()});var T7="ALL",Ke6="all",He6,xA1="Can not add a route since the matcher is already built.",hA1;var Aq=D(()=>{He6=["get","post","put","delete","options","patch"],hA1=class extends Error{}});var XN0="__COMPOSED_HANDLER";var YN0=()=>{};var kp5=(X)=>{return X.text("404 Not Found",404)},Fe6=(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)},Ue6=class X{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#X="/";routes=[];constructor(Y={}){[...He6,Ke6].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??sB0:Xe6}#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=kp5;errorHandler=Fe6;route(Y,G){let Q=this.basePath(Y);return G.routes.map((J)=>{let W;if(G.errorHandler===Fe6)W=J.handler;else W=async(Z,$)=>(await aB0([],G.errorHandler)(Z,()=>J.handler(Z,$))).res,W[XN0]=J.handler;Q.#Q(J.method,J.path,W)}),this}basePath(Y){let G=this.#Y();return G._basePath=Mj(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=Mj(this._basePath,Y),H=K==="/"?0:K.length;return(U)=>{let B=new URL(U.url);return B.pathname=B.pathname.slice(H)||"/",new Request(B,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,Mj(Y,"*"),$),this}#Q(Y,G,Q){Y=Y.toUpperCase(),G=Mj(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 $e6(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=aB0(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${Mj("/",Y)}`,G),Q,J)};fire=()=>{addEventListener("fetch",(Y)=>{Y.respondWith(this.#Z(Y.request,Y,void 0,Y.request.method))})}};var Be6=D(()=>{ps6();yA1();Aq();YN0();qq()});function gA1(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[[],CX1];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=Q,Q(X,Y)}var CX1;var GN0=D(()=>{Aq();CX1=[]});function _p5(X,Y){if(X.length===1)return Y.length===1?X<Y?-1:1:-1;if(Y.length===1)return 1;if(X===kX1||X===vX1)return 1;else if(Y===kX1||Y===vX1)return-1;if(X===uA1)return 1;else if(Y===uA1)return-1;return X.length===Y.length?X<Y?-1:1:Y.length-X.length}var uA1="[^/]+",kX1=".*",vX1="(?:|/.*)",Rj,vp5,Ne6=class X{#X;#Y;#G=Object.create(null);insert(Y,G,Q,J,W){if(Y.length===0){if(this.#X!==void 0)throw Rj;if(W)return;this.#X=G;return}let[Z,...$]=Y,K=Z==="*"?$.length===0?["","",kX1]:["","",uA1]:Z==="/*"?["","",vX1]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let U=K[1],B=K[2]||uA1;if(U&&K[2]){if(B===".*")throw Rj;if(B=B.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(B))throw Rj}if(H=this.#G[B],!H){if(Object.keys(this.#G).some((N)=>N!==kX1&&N!==vX1))throw Rj;if(W)return;if(H=this.#G[B]=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!==kX1&&U!==vX1))throw Rj;if(W)return;H=this.#G[Z]=new X}H.insert($,G,Q,J,W)}buildRegExpStr(){let G=Object.keys(this.#G).sort(_p5).map((Q)=>{let J=this.#G[Q];return(typeof J.#Y==="number"?`(${Q})@${J.#Y}`:vp5.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 QN0=D(()=>{Rj=Symbol(),vp5=new Set(".\\+*[^]$()")});var ze6=class{#X={varIndex:0};#Y=new Ne6;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 Oe6=D(()=>{QN0()});function we6(X){return De6[X]??=new RegExp(X==="*"?"":`^${X.replace(/\/\*$|([.\\+*[^\]$()])/g,(Y,G)=>G?`\\${G}`:"(?:|/.*)")}$`)}function bp5(){De6=Object.create(null)}function yp5(X){let Y=new ze6,G=[];if(X.length===0)return fp5;let Q=X.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,U],[B,N])=>H?1:B?-1:U.length-N.length),J=Object.create(null);for(let H=0,U=-1,B=Q.length;H<B;H++){let[N,z,O]=Q[H];if(N)J[z]=[O.map(([E])=>[E,Object.create(null)]),CX1];else U++;let w;try{w=Y.insert(z,U,N)}catch(E){throw E===Rj?new hA1(z):E}if(N)continue;G[U]=O.map(([E,P])=>{let q=Object.create(null);P-=1;for(;P>=0;P--){let[M,j]=w[P];q[M]=j}return[E,q]})}let[W,Z,$]=Y.buildRegExp();for(let H=0,U=G.length;H<U;H++)for(let B=0,N=G[H].length;B<N;B++){let z=G[H][B]?.[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 oa(X,Y){if(!X)return;for(let G of Object.keys(X).sort((Q,J)=>J.length-Q.length))if(we6(G).test(Y))return[...X[G]];return}var fp5,De6,lA1=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(xA1);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 $=we6(Y);if(X===T7)Object.keys(Q).forEach((K)=>{Q[K][Y]||=oa(Q[K],Y)||oa(Q[T7],Y)||[]});else Q[X][Y]||=oa(Q[X],Y)||oa(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=_A1(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]||=[...oa(Q[U],H)||oa(Q[T7],H)||[]],J[U][H].push([G,W-K+$+1])})}}match=gA1;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,bp5(),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 yp5(Y)}};var JN0=D(()=>{Aq();qq();GN0();QN0();Oe6();fp5=[/^$/,[],Object.create(null)],De6=Object.create(null)});var xp5=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(),CX1];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=gA1};var Le6=D(()=>{Aq();GN0();JN0()});var Ee6=D(()=>{JN0();Le6()});var ZN0=class{name="SmartRouter";#X=[];#Y=[];constructor(X){this.#X=X.routers}add(X,Y,G){if(!this.#Y)throw Error(xA1);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 hA1)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 Pe6=D(()=>{Aq()});var qe6=D(()=>{Pe6()});var _X1,hp5=(X)=>{for(let Y in X)return!0;return!1},Ae6=class X{#X;#Y;#G;#Q=0;#J=_X1;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=os6(G),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],U=W[$+1],B=ss6(H,U),N=Array.isArray(B)?B[0]:H;if(N in J.#Y){if(J=J.#Y[N],B)Z.push(B[1]);continue}if(J.#Y[N]=new X,B)J.#G.push(B),Z.push(B[1]);J=J.#Y[N]}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!==_X1||W&&W!==_X1)for(let B=0,N=H.possibleKeys.length;B<N;B++){let z=H.possibleKeys[B],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=_X1;let W=[this],Z=oB0(G),$=[],K=Z.length,H=null;for(let U=0;U<K;U++){let B=Z[U],N=U===K-1,z=[];for(let w=0,E=W.length;w<E;w++){let P=W[w],q=P.#Y[B];if(q)if(q.#J=P.#J,N){if(q.#Y["*"])this.#Z(Q,q.#Y["*"],Y,P.#J);this.#Z(Q,q,Y,P.#J)}else z.push(q);for(let M=0,j=P.#G.length;M<j;M++){let V=P.#G[M],R=P.#J===_X1?{}:{...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(!B&&!(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),hp5(y.#Y)){y.#J=R;let p=i[0].match(/\//)?.length??0;($[p]||=[]).push(y)}continue}}if(v===!0||v.test(B))if(R[_]=B,N){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,B)=>{return U.score-B.score});return[Q.map(({handler:U,params:B})=>[U,B])]}};var Te6=D(()=>{Aq();qq();_X1=Object.create(null)});var WN0=class{name="TrieRouter";#X;constructor(){this.#X=new Ae6}add(X,Y,G){let Q=_A1(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 Ie6=D(()=>{qq();Te6()});var Ve6=D(()=>{Ie6()});var U5;var je6=D(()=>{Be6();Ee6();qe6();Ve6();U5=class extends Ue6{constructor(X={}){super(X);this.router=X.router??new ZN0({routers:[new lA1,new WN0]})}}});var NG=D(()=>{je6()});var Re6,gp5,Me6=(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)},$N0=(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=Me6(J.substring(0,W));if(Y&&Y!==Z||!Re6.test(Z))continue;let $=Me6(J.substring(W+1));if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(gp5.test($)){if(Q[Z]=$.indexOf("%")!==-1?ra($,MX1):$,Y)break}}return Q},up5=(X,Y,G={})=>{if(!Re6.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},mA1=(X,Y,G)=>{return Y=encodeURIComponent(Y),up5(X,Y,G)};var Se6=D(()=>{qq();Re6=/^[\w!#$%&'*.^`|~+-]+$/,gp5=/^[ !#-:<-[\]-~]*$/});var dA1=(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 $N0(Q,W)[W]}if(!Q)return{};return $N0(Q)},lp5=(X,Y,G)=>{let Q;if(G?.prefix==="secure")Q=mA1("__Secure-"+X,Y,{path:"/",...G,secure:!0});else if(G?.prefix==="host")Q=mA1("__Host-"+X,Y,{...G,path:"/",secure:!0,domain:void 0});else Q=mA1(X,Y,{path:"/",...G});return Q},KN0=(X,Y,G,Q)=>{let J=lp5(Y,G,Q);X.header("Set-Cookie",J,{append:!0})};var HN0=D(()=>{Se6()});var Ce6=(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,B){Z.res.headers.set(U,B)}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 B=G.allowHeaders;if(!B?.length){let N=Z.req.header("Access-Control-Request-Headers");if(N)B=N.split(/\s*,\s*/)}if(B?.length)K("Access-Control-Allow-Headers",B.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 ke6=()=>{};var ve6=()=>{try{return performance.now()}catch{}return Date.now()},FN0=(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:"*")}}},_e6=(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:ve6()})},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,$=ve6()-Z;_e6(X,Y,$,W,G),Q.timers.delete(Y)};var fe6=D(()=>{yA1()});var UN0=D(()=>{fe6()});function fX1(){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 BN0)X[Y.category]?.push(Y);return X}var BN0;var NN0=D(()=>{BN0=[{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 be6=D(()=>{Gp();ez1()});function ye6(){return dp5.parse(process.env)}var zN0=(X)=>F.enum(["true","false","1","0"]).optional().transform((Y)=>Y===void 0?X:Y==="true"||Y==="1"),mp5=(X)=>F.string().optional().transform((Y)=>Y?Y.split(",").map((G)=>G.trim()):X),dp5;var xe6=D(()=>{H0();dp5=F.object({AUTH_EMAIL_PASSWORD_ENABLED:zN0(!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:zN0(!1),AUTH_MAGIC_LINK_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_ENABLED:zN0(!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:mp5(["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 cA1;var he6=D(()=>{cA1={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"}});import{existsSync as cp5,readFileSync as ip5}from"fs";function pp5(){let X=ye6(),Y=v6().configPath;if(!cp5(Y))return{auth:X,monitoring:cA1};try{let G=JSON.parse(ip5(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??cA1,theme:G.theme,logo:G.logo,autoCreateOrganizationOnSignup:G.autoCreateOrganizationOnSignup}}catch{return{auth:X,monitoring:cA1}}}function Sj(){if(!ON0)ON0=pp5();return ON0}function ge6(){return Sj().theme}var ON0=null;var DN0=D(()=>{xe6();he6();m9()});import{dirname as np5,posix as ap5,sep as tp5}from"path";function le6(){let X=rp5();return async(Y)=>{for(let G of Y)G.module=X(G.filename);return Y}}function rp5(X=process.argv[1]?np5(process.argv[1]):process.cwd(),Y=tp5==="\\"){let G=Y?ue6(X):X;return(Q)=>{if(!Q)return;let J=Y?ue6(Q):Q,{dir:W,base:Z,ext:$}=ap5.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 ue6(X){return X.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var me6=()=>{};function op5(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 wN0=(X)=>{if("flags"in X){let Y=de6(X.flags),G=ce6(X.flags);return{...X,featureFlags:Y,featureFlagPayloads:G}}{let Y=X.featureFlags??{},G=Object.fromEntries(Object.entries(X.featureFlagPayloads||{}).map(([J,W])=>[J,LN0(W)])),Q=Object.fromEntries(Object.entries(Y).map(([J,W])=>[J,op5(J,W,G[J])]));return{...X,featureFlags:Y,featureFlagPayloads:G,flags:Q}}},de6=(X)=>Object.fromEntries(Object.entries(X??{}).map(([Y,G])=>[Y,bX1(G)]).filter(([,Y])=>Y!==void 0)),ce6=(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?LN0(Q):void 0]}))},bX1=(X)=>X===void 0?void 0:X.variant??X.enabled,LN0=(X)=>{if(typeof X!="string")return X;try{return JSON.parse(X)}catch{return X}};var iA1=()=>{};function ie6(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}async function pA1(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 EN0=()=>{};var sp5,pe6=function(X,Y=[]){if(!X)return!1;let G=X.toLowerCase();return sp5.concat(Y).some((Q)=>{let J=Q.toLowerCase();return G.indexOf(J)!==-1})};var ne6=D(()=>{sp5=["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 aJ;var Cj=D(()=>{aJ=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 nA1=()=>{};function tA1(X){return X===null||typeof X!="object"}function kj(X,Y){return Object.prototype.toString.call(X)===`[object ${Y}]`}function re6(X){return kj(X,"ErrorEvent")}function ea(X){return typeof Event<"u"&&Yn5(X,Event)}function oe6(X){return kj(X,"Object")}function Yn5(X,Y){try{return X instanceof Y}catch{return!1}}var Xn5,ae6,TmX,PN0,aA1,yX1=(X)=>X===Object(X)&&!aA1(X),sa=(X)=>X===void 0,Tq=(X)=>PN0.call(X)=="[object String]",te6=(X)=>Tq(X)&&X.trim().length===0,xX1=(X)=>PN0.call(X)=="[object Number]"&&X===X,qN0=(X)=>X instanceof Error;var hX1=D(()=>{Cj();nA1();Xn5=Array.isArray,ae6=Object.prototype,TmX=ae6.hasOwnProperty,PN0=ae6.toString,aA1=Xn5||function(X){return PN0.call(X)==="[object Array]"}});function gX1(X,Y,G,Q,J){if(Y>G)Q.warn("min cannot be greater than max."),Y=G;if(xX1(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),gX1(J||G,Y,G,Q)}var AN0=D(()=>{hX1()});class TN0{constructor(X){this._buckets={},this._onBucketRateLimited=X._onBucketRateLimited,this._bucketSize=gX1(X.bucketSize,0,100,X._logger),this._refillRate=gX1(X.refillRate,0,this._bucketSize,X._logger),this._refillInterval=gX1(X.refillInterval,0,Gn5,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 Gn5=86400000;var se6=D(()=>{AN0()});class vj{constructor(X){this.bytes=X}static ofInner(X){if(X.length===16)return new vj(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 vj(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 vj(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 vj(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 X14{constructor(X){this.timestamp=0,this.counter=0,this.random=X??Qn5()}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 vj.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,vj.ofInner(X)}}var Qn5=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),ee6,Iq=()=>Jn5().toString(),Jn5=()=>(ee6||(ee6=new X14)).generate();var uX1=D(()=>{/*! For license information please see uuidv7.mjs.LICENSE.txt */});class IN0{add(X){let Y=Iq();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 Y14=D(()=>{uX1()});function Zn5(X=console){return{log:X.log.bind(X),warn:X.warn.bind(X),error:X.error.bind(X),debug:X.debug.bind(X)}}function Q14(X,Y=Wn5){return G14(X,Y,Zn5())}var G14=(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)=>G14(`${X} ${W}`,Y,G)}},Wn5=(X)=>X();var J14=()=>{};var Yt="Mobile",oA1="iOS",Xt="Android",Z14="Tablet",bmX,Kn5="Apple",ymX,W14="Safari",sA1="BlackBerry",$14="Samsung",Hn5,Fn5,eA1="Chrome",Un5,Bn5,K14="Internet Explorer",Nn5,jN0="Opera",xmX,H14="Edge",zn5,MN0="Firefox",On5,RN0="Nintendo",SN0="PlayStation",rA1="Xbox",Dn5,wn5,lX1="Windows",Ln5,F14="Generic",hmX,gmX,En5="Konqueror",F3="(\\d+(\\.\\d+)?)",VN0,umX,lmX,mmX,Pn5,qn5,dmX,cmX;var U14=D(()=>{nA1();hX1();bmX=Xt+" "+Z14,ymX=Kn5+" Watch",Hn5=$14+"Browser",Fn5=$14+" Internet",Un5=eA1+" OS",Bn5=eA1+" "+oA1,Nn5=K14+" "+Yt,xmX=jN0+" Mini",zn5="Microsoft "+H14,On5=MN0+" "+oA1,Dn5=Xt+" "+Yt,wn5=Yt+" "+W14,Ln5=lX1+" Phone",hmX=F14+" "+Yt.toLowerCase(),gmX=F14+" "+Z14.toLowerCase(),VN0=new RegExp("Version/"+F3),umX=new RegExp(rA1,"i"),lmX=new RegExp(SN0+" \\w+","i"),mmX=new RegExp(RN0+" \\w+","i"),Pn5=new RegExp(sA1+"|PlayBook|BB10","i"),qn5={"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"},dmX={[Nn5]:[new RegExp("rv:"+F3)],[zn5]:[new RegExp(H14+"?\\/"+F3)],[eA1]:[new RegExp("("+eA1+"|CrMo)\\/"+F3)],[Bn5]:[new RegExp("CriOS\\/"+F3)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+F3)],[W14]:[VN0],[wn5]:[VN0],[jN0]:[new RegExp("("+jN0+"|OPR)\\/"+F3)],[MN0]:[new RegExp(MN0+"\\/"+F3)],[On5]:[new RegExp("FxiOS\\/"+F3)],[En5]:[new RegExp("Konqueror[:/]?"+F3,"i")],[sA1]:[new RegExp(sA1+" "+F3),VN0],[Dn5]:[new RegExp("android\\s"+F3,"i")],[Fn5]:[new RegExp(Hn5+"\\/"+F3)],[K14]:[new RegExp("(rv:|MSIE )"+F3)],Mozilla:[new RegExp("rv:"+F3)]},cmX=[[new RegExp(rA1+"; "+rA1+" (.*?)[);]","i"),(X)=>[rA1,X&&X[1]||""]],[new RegExp(RN0,"i"),[RN0,""]],[new RegExp(SN0,"i"),[SN0,""]],[Pn5,[sA1,""]],[new RegExp(lX1,"i"),(X,Y)=>{if(/Phone/.test(Y)||/WPDesktop/.test(Y))return[Ln5,""];if(new RegExp(Yt).test(Y)&&!/IEMobile\b/.test(Y))return[lX1+" "+Yt,""];let G=/Windows NT ([0-9.]+)/i.exec(Y);if(G&&G[1]){let Q=G[1],J=qn5[Q]||"";if(/arm/i.test(Y))J="RT";return[lX1,J]}return[lX1,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(X)=>{if(X&&X[3]){let Y=[X[3],X[4],X[5]||"0"];return[oA1,Y.join(".")]}return[oA1,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(X)=>{let Y="";if(X&&X.length>=3)Y=sa(X[2])?X[3]:X[2];return["watchOS",Y]}],[new RegExp("("+Xt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Xt+")","i"),(X)=>{if(X&&X[2]){let Y=[X[2],X[3],X[4]||"0"];return[Xt,Y.join(".")]}return[Xt,""]}],[/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/,[Un5,""]],[/Linux|debian/i,["Linux",""]]]});function N14(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 XT1(){return new Date().toISOString()}function Fw(X,Y){let G=setTimeout(X,Y);return G?.unref&&G?.unref(),G}function CN0(X){return Promise.all(X.map((Y)=>(Y??Promise.resolve()).then((G)=>({status:"fulfilled",value:G}),(G)=>({status:"rejected",reason:G}))))}var B14="utf8",O14=(X)=>X instanceof Error;var U3=D(()=>{ne6();se6();AN0();nA1();hX1();Y14();J14();U14()});var An5,JdX;var kN0=D(()=>{U3();An5={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}},JdX=An5.info});var D14=D(()=>{kN0();Cj()});var w14=D(()=>{Cj()});class vN0{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 L14=()=>{};async function E14(X){if(X instanceof Gt){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 _N0(X){return typeof X=="object"&&(X instanceof Gt||X instanceof mX1)}function P14(X){return typeof X=="object"&&X instanceof Gt&&X.status===413}class YT1{constructor(X,Y={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new IN0,this._events=new vN0,this._isInitialized=!1;let G=typeof X=="string"?X.trim():"",Q=typeof Y.host=="string"?Y.host.trim():"",J=!G;if(this._logger=Q14("[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=N14(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:_N0},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=!ie6()||(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(aJ.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(aJ.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(aJ.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:wN0(U)})).catch((U)=>{return this._events.emit("error",U),{success:!1,error:this.categorizeRequestError(U)}})}categorizeRequestError(X){if(X instanceof Gt)return{type:"api_error",statusCode:X.status};if(X instanceof mX1){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 $=bX1(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(aJ.Props);return this._props||{}}set props(X){this._props=X}async register(X){this.wrap(()=>{this.props={...this.props,...X},this.setPersistedProperty(aJ.Props,this.props)})}async unregister(X){this.wrap(()=>{delete this.props[X],this.setPersistedProperty(aJ.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(aJ.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(aJ.Queue,J),this._events.emit(X,Q),J.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=Fw(()=>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:XT1()};if(this.historicalMigration)J.historical_migration=!0;let W=JSON.stringify(J),Z=`${this.host}/batch/`,$=this.disableCompression?null:await pA1(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:XT1(),uuid:G?.uuid?G.uuid:Iq()};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 E14(X)})}async flush(){let X=CN0([this.flushPromise]).then(()=>this._flush());return this.flushPromise=X,this.addPendingPromise(X),CN0([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(aJ.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((N)=>N.message),W=async()=>{let z=(this.getPersistedProperty(aJ.Queue)||[]).slice(Q.length);this.setPersistedProperty(aJ.Queue,z),X=z,await this.flushStorage()},Z={api_key:this.apiKey,batch:J,sent_at:XT1()};if(this.historicalMigration)Z.historical_migration=!0;let $=JSON.stringify(Z),K=`${this.host}/batch/`,H=this.disableCompression?null:await pA1($,this.isDebug),U={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...H!==null&&{"Content-Encoding":"gzip"}},body:H||$},B={retryCheck:(N)=>{if(P14(N))return!1;return _N0(N)}};try{await this.fetchWithRetry(K,U,B)}catch(N){if(P14(N)&&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(!(N instanceof mX1))await W();throw this._events.emit("error",N),N}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,B14)}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=Fw(()=>Z.abort(),$),H=null;try{H=await this.fetch(X,{signal:Z.signal,...Y})}catch(B){throw new mX1(B)}finally{clearTimeout(K)}if(Y.mode!=="no-cors"&&(H.status<200||H.status>=400))throw new Gt(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(aJ.Queue)||[]).length===0)break;if(await this.flush(),Y)break}}catch(J){if(!_N0(J))throw J;await E14(J)}},Q;try{return await Promise.race([new Promise((J,W)=>{Q=Fw(()=>{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 Gt,mX1;var fN0=D(()=>{L14();iA1();EN0();Cj();U3();uX1();Gt=class Gt 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()}};mX1=class mX1 extends Error{constructor(X){super("Network error while fetching PostHog",X instanceof Error?{cause:X}:{}),this.error=X,this.name="PostHogFetchNetworkError"}}});var q14=D(()=>{iA1();Cj();fN0();uX1();U3()});var A14=D(()=>{hX1()});function I14(X){let Y=globalThis._posthogChunkIds;if(!Y)return;let G=Object.keys(Y);if(QT1&&G.length===T14)return QT1;return T14=G.length,QT1=G.reduce((Q,J)=>{if(!GT1)GT1={};let W=GT1[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,GT1[J]=[H,U];break}}}return Q},{}),QT1}var GT1,T14,QT1;var V14=()=>{};class j14{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&&aA1(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:I14(this.stackParser),skipFirstLines:X.skipFirstLines??1}}buildCoercingContext(X,Y,G=0){let Q=(W,Z)=>{if(!(Z<=Vn5))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 Vn5=4;var M14=D(()=>{U3();V14()});function Qz(X,Y,G,Q,J){let W={platform:X,filename:Y,function:G==="<anonymous>"?sQ:G,in_app:!0};if(!sa(Q))W.lineno=Q;if(!sa(J))W.colno=J;return W}var sQ="?";var Vq=D(()=>{U3()});var JT1=(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]:sQ,G?`safari-extension:${Y}`:`safari-web-extension:${Y}`]:[X,Y]};var bN0=D(()=>{Vq()});var jn5,Mn5,Rn5,yN0=(X,Y)=>{let G=jn5.exec(X);if(G){let[,J,W,Z]=G;return Qz(Y,J,sQ,+W,+Z)}let Q=Mn5.exec(X);if(Q){if(Q[2]&&Q[2].indexOf("eval")===0){let $=Rn5.exec(Q[2]);if($)Q[2]=$[1],Q[3]=$[2],Q[4]=$[3]}let[W,Z]=JT1(Q[1]||sQ,Q[2]);return Qz(Y,Z,W,Q[3]?+Q[3]:void 0,Q[4]?+Q[4]:void 0)}};var R14=D(()=>{Vq();bN0();jn5=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Mn5=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Rn5=/\((\S*)(?::(\d+))(?::(\d+))\)/});var Sn5,Cn5,xN0=(X,Y)=>{let G=Sn5.exec(X);if(G){if(G[3]&&G[3].indexOf(" > eval")>-1){let Z=Cn5.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]||sQ;return[W,J]=JT1(W,J),Qz(Y,J,W,G[4]?+G[4]:void 0,G[5]?+G[5]:void 0)}};var S14=D(()=>{Vq();bN0();Sn5=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Cn5=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i});var kn5,C14=(X,Y)=>{let G=kn5.exec(X);return G?Qz(Y,G[2],G[1]||sQ,+G[3],G[4]?+G[4]:void 0):void 0};var k14=D(()=>{Vq();kn5=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i});var vn5,v14=(X,Y)=>{let G=vn5.exec(X);return G?Qz(Y,G[2],G[3]||sQ,+G[1]):void 0},_n5,_14=(X,Y)=>{let G=_n5.exec(X);return G?Qz(Y,G[5],G[3]||G[4]||sQ,+G[1],+G[2]):void 0};var f14=D(()=>{Vq();vn5=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,_n5=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i});function yn5(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 b14(X){return parseInt(X||"",10)||void 0}var fn5,bn5,y14=(X,Y)=>{let G=X.match(bn5);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 B=Q.indexOf(".Module");if(B>0)W=W.slice(B+1),Q=Q.slice(0,B)}Z=void 0}if(J)Z=Q,$=J;if(J==="<anonymous>")$=void 0,W=void 0;if(W===void 0)$=$||sQ,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:b14(G[3]),colno:b14(G[4]),in_app:yn5(K||"",H),platform:Y}}if(X.match(fn5))return{filename:X,platform:Y}};var x14=D(()=>{Vq();fn5=/^\s*[-]{4,}$/,bn5=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/});function u14(X){if(!X.length)return[];let Y=Array.from(X);return Y.reverse(),Y.slice(0,g14).map((G)=>({...G,filename:G.filename||xn5(Y).filename,function:G.function||sQ}))}function xn5(X){return X[X.length-1]||{}}function hn5(){return l14("web:javascript",yN0,xN0)}function l14(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=h14.test($)?$.replace(h14,"$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>=g14)break}}return u14(J)}}var h14,g14=50;var m14=D(()=>{Vq();R14();S14();k14();f14();x14();h14=/\(error: (.*)\)/});class d14{match(X){return this.isDOMException(X)||this.isDOMError(X)}coerce(X,Y){let G=Tq(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 kj(X,"DOMException")}isDOMError(X){return kj(X,"DOMError")}}var c14=D(()=>{U3()});class i14{match(X){return qN0(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 p14=D(()=>{U3()});class n14{constructor(){}match(X){return re6(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 a14=D(()=>{U3()});class t14{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(gn5);if(Q)Y=Q[1],G=Q[2];return[Y,G]}}var gn5;var r14=D(()=>{gn5=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i});var o14;var s14=D(()=>{o14=["fatal","error","warning","log","info","debug"]});function ZT1(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 hN0=()=>{};class e14{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 ea(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=ZT1(X);return`${Y&&Y!=="Object"?`'${Y}'`:"Object"} captured as exception with keys: ${G}`}isSeverityLevel(X){return Tq(X)&&!te6(X)&&o14.indexOf(X)>=0}getErrorPropertyFromObject(X){for(let Y in X)if(Object.prototype.hasOwnProperty.call(X,Y)){let G=X[Y];if(O14(G))return G}}getObjectClassName(X){try{let Y=Object.getPrototypeOf(X);return Y?Y.constructor.name:void 0}catch(Y){return}}}var X04=D(()=>{U3();s14();hN0()});class Y04{match(X){return ea(X)}coerce(X,Y){let G=X.constructor.name;return{type:G,value:`${G} captured as exception with keys: ${ZT1(X)}`,stack:Y.syntheticException?.stack,synthetic:!0}}}var G04=D(()=>{U3();hN0()});class Q04{match(X){return tA1(X)}coerce(X,Y){return{type:"Error",value:`Primitive value captured as exception: ${String(X)}`,stack:Y.syntheticException?.stack,synthetic:!0}}}var J04=D(()=>{U3()});class Z04{match(X){return kj(X,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(X)}isCustomEventWrappingRejection(X){if(!ea(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(tA1(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 W04=D(()=>{U3()});var $04=D(()=>{c14();p14();a14();r14();X04();G04();J04();W04()});class K04{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 H04=()=>{};function gN0(X){if(!X)return{...WT1};return{enabled:X.enabled??WT1.enabled,max_bytes:mn5(X.max_bytes,WT1.max_bytes)}}function ln5(X){if(!X)return{sanitizedProperties:{},droppedKeys:[]};let Y=[];return{sanitizedProperties:Object.keys(X).reduce((Q,J)=>{if(un5.has(J))return Y.push(J),Q;return Q[J]=X[J],Q},{}),droppedKeys:Y}}class F04{constructor(X){this._entries=[],this._totalBytes=0,this._config=gN0(X)}setConfig(X){this._config=gN0(X),this._trimToMaxBytes()}add(X){let Y=dn5(X);if(!Y)return;let G=U04(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 mn5(X,Y){if(!xX1(X)||X===1/0||X===-1/0)return Y;let G=Math.floor(X);if(G<0)return Y;return G}function dn5(X){let Y=cn5(X);if(!Y)return;try{let G=JSON.parse(Y);if(!yX1(G))return;let Q=G,J=Q[dX1.MESSAGE],W=Q[dX1.TIMESTAMP];if(!Tq(J)||J.trim().length===0)return;if(!Tq(W)&&!xX1(W))return;return{step:Q,json:Y}}catch{return}}function cn5(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 U04(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 dX1,un5,WT1;var B04=D(()=>{U3();dX1={MESSAGE:"$message",TIMESTAMP:"$timestamp"},un5=new Set([dX1.MESSAGE,dX1.TIMESTAMP]),WT1={enabled:!0,max_bytes:32768}});var qW={};M0(qW,{winjsStackLineParser:()=>C14,stripReservedExceptionStepFields:()=>ln5,reverseAndStripFrames:()=>u14,resolveExceptionStepsConfig:()=>gN0,opera11StackLineParser:()=>_14,opera10StackLineParser:()=>v14,nodeStackLineParser:()=>y14,getUtf8ByteLength:()=>U04,geckoStackLineParser:()=>xN0,createStackParser:()=>l14,createDefaultStackParser:()=>hn5,chromeStackLineParser:()=>yN0,StringCoercer:()=>t14,ReduceableCache:()=>K04,PromiseRejectionEventCoercer:()=>Z04,PrimitiveCoercer:()=>Q04,ObjectCoercer:()=>e14,ExceptionStepsBuffer:()=>F04,EventCoercer:()=>Y04,ErrorPropertiesBuilder:()=>j14,ErrorEventCoercer:()=>n14,ErrorCoercer:()=>i14,EXCEPTION_STEP_INTERNAL_FIELDS:()=>dX1,DOMExceptionCoercer:()=>d14,DEFAULT_EXCEPTION_STEPS_CONFIG:()=>WT1});var N04=D(()=>{M14();m14();$04();H04();B04()});var _j=D(()=>{iA1();EN0();kN0();D14();uX1();w14();N04();U3();q14();fN0();A14();Cj()});import{createReadStream as in5}from"fs";import{createInterface as pn5}from"readline";async function w04(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"||sn5(Z)||en5(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(D04.get(J))continue;let W=Y[J];if(!W)continue;W.sort((K,H)=>K-H);let Z=Ya5(W);if(Z.every((K)=>Xa5(J,K)))continue;let $=Ga5($T1,J,{});Q.push(tn5(J,Z,$))}if(await Promise.all(Q).catch(()=>{}),X&&X.length>0)rn5(X,$T1);return $T1.reduce(),X}function tn5(X,Y,G){return new Promise((Q)=>{let J=in5(X),W=pn5({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],B=H[1];function N(){D04.set(X,1),W.close(),W.removeAllListeners(),Z()}J.on("error",N),W.on("error",N),W.on("close",Z),W.on("line",(z)=>{if($++,$<U)return;if(G[$]=Qa5(z,0),$>=B){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],B=O[1]}})})}function rn5(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;on5(G.lineno,G,Q)}}function on5(X,Y,G){if(Y.lineno===void 0||G===void 0)return;Y.pre_context=[];for(let J=L04(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=E04(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 sn5(X){return X.startsWith("node:")||X.endsWith(".min.js")||X.endsWith(".min.cjs")||X.endsWith(".min.mjs")||X.startsWith("data:")}function en5(X){if(X.lineno!==void 0&&X.lineno>an5)return!0;if(X.colno!==void 0&&X.colno>nn5)return!0;return!1}function Xa5(X,Y){let G=$T1.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 Ya5(X){if(!X.length)return[];let Y=0,G=X[0];if(typeof G!="number")return[];let Q=O04(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+uN0;else J.push(Q),Q=O04(W);Y++}return J}function O04(X){return[L04(X),E04(X)]}function L04(X){return Math.max(1,X-uN0)}function E04(X){return X+uN0}function Ga5(X,Y,G){let Q=X.get(Y);if(Q===void 0)return X.set(Y,G),G;return Q}function Qa5(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 $T1,D04,uN0=7,nn5=1000,an5=1e4;var P04=D(()=>{_j();$T1=new qW.ReduceableCache(25),D04=new qW.ReduceableCache(20)});import{isAbsolute as Ja5,relative as Za5,sep as Wa5}from"path";function q04(X=process.cwd()){let Y=Wa5==="\\",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(Ja5(W.filename))W.filename=G(Za5(Q,G(W.filename)))}return J}}var A04=()=>{};function $a5(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 T04(X,Y){globalThis.process?.on("uncaughtException",$a5(X,Y))}function I04(X){globalThis.process?.on("unhandledRejection",(Y)=>X(Y,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var V04=()=>{};class DH{constructor(X,Y,G){this.client=X,this._exceptionAutocaptureEnabled=Y.enableExceptionAutocapture||!1,this._logger=G,this._rateLimiter=new TN0({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(X){return yX1(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())T04(this.onException.bind(this),this.onFatalError.bind(this)),I04(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(Ka5),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}var Ka5=2000;var KT1=D(()=>{V04();_j()});var j04="5.30.6";var M04=()=>{};var cX1;var lN0=D(()=>{cX1={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"}});async function R04(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 S04=()=>{};class mN0{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 Jz||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 Jz||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((B)=>B.key===H)?H:await this.getMatchingVariant(X,Y)||!0;break}}catch(H){if(H instanceof Jz)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"?f04($,Q,this.cohorts,this.debugMode):K==="flag"?await this.evaluateFlagDependency($,Q,J):_04($,Q,Z),!H)return!1}if(W==null)return!0}if(W!=null&&await C04(X.key,Y)>W/100)return!1;return!0}async getMatchingVariant(X,Y){let G=await C04(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(Ha5,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 Qt(`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 Qt(`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 Qt(`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 Qt)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=Fw(()=>{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 C04(X,Y,G=""){let Q=await R04(`${X}.${Y}${G}`);return parseInt(Q.slice(0,15),16)/Fa5}function _04(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&&!Ua5.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((B)=>String(B).toLowerCase()).includes(String(U).toLowerCase());return String(H).toLowerCase()===String(U).toLowerCase()}function K(H,U,B){if(B==="gt")return H>U;if(B==="gte")return H>=U;if(B==="lt")return H<U;if(B==="lte")return H<=U;throw Error(`Invalid operator: ${B}`)}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 k04(String(J))&&String(Z).match(String(J))!==null;case"not_regex":return k04(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=Da5(String(J));if(H==null)H=v04(J);if(H==null)throw new d5(`Invalid date: ${J}`);let U=v04(Z);if(["is_date_before"].includes(W))return U<H;return U>H}case"semver_eq":return wH(eQ(String(Z)),eQ(String(J)))===0;case"semver_neq":return wH(eQ(String(Z)),eQ(String(J)))!==0;case"semver_gt":return wH(eQ(String(Z)),eQ(String(J)))>0;case"semver_gte":return wH(eQ(String(Z)),eQ(String(J)))>=0;case"semver_lt":return wH(eQ(String(Z)),eQ(String(J)))<0;case"semver_lte":return wH(eQ(String(Z)),eQ(String(J)))<=0;case"semver_tilde":{let H=eQ(String(Z)),{lower:U,upper:B}=Na5(String(J));return wH(H,U)>=0&&wH(H,B)<0}case"semver_caret":{let H=eQ(String(Z)),{lower:U,upper:B}=za5(String(J));return wH(H,U)>=0&&wH(H,B)<0}case"semver_wildcard":{let H=eQ(String(Z)),{lower:U,upper:B}=Oa5(String(J));return wH(H,U)>=0&&wH(H,B)<0}default:throw new d5(`Unknown operator: ${W}`)}}function Ba5(X,Y){if(!(X in Y))throw new Jz(`cohort ${X} not found in local cohorts - likely a static cohort that requires server evaluation`)}function f04(X,Y,G,Q=!1){let J=String(X.value);Ba5(J,G);let W=G[J];return b04(W,Y,G,Q)}function b04(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=b04($,Y,G,Q);if(J==="AND"){if(!K)return!1}else if(K)return!0}catch(K){if(K instanceof Jz)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=f04($,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=_04($,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 Jz)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 k04(X){try{return new RegExp(X),!0}catch(Y){return!1}}function eQ(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 Na5(X){let Y=eQ(X),G=[Y[0],Y[1],Y[2]],Q=[Y[0],Y[1]+1,0];return{lower:G,upper:Q}}function za5(X){let Y=eQ(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 Oa5(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 v04(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 Da5(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 Ha5=60000,Fa5=1152921504606847000,Ua5,Qt,d5,Jz;var y04=D(()=>{_j();S04();Ua5=["is_not"];Qt=class Qt extends Error{constructor(X){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=X,Object.setPrototypeOf(this,Qt.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)}};Jz=class Jz extends Error{constructor(X){super(X);this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,Jz.prototype)}}});class dN0{getProperty(X){return this._memoryStorage[X]}setProperty(X,Y){this._memoryStorage[X]=Y!==null?Y:void 0}constructor(){this._memoryStorage={}}}var x04=()=>{};function Aa5(X){return typeof X=="string"?X.trim():""}function Ta5(X){return(typeof X=="string"?X.trim():"")||void 0}function Ia5(X){return(typeof X=="string"?X.trim():"")||qa5}var wa5=100,h04=30000,La5=50000,Ea5=50,Pa5=500,qa5="https://us.i.posthog.com",cN0;var g04=D(()=>{M04();_j();lN0();y04();KT1();x04();cN0=class cN0 extends YT1{constructor(X,Y={}){let G=Aa5(X),Q={...Y,host:Ia5(Y.host),personalApiKey:Ta5(Y.personalApiKey)};if(super(G,Q),this._memoryStorage=new dN0,this.options=Q,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof Q.featureFlagsPollingInterval=="number"?Math.max(Q.featureFlagsPollingInterval,wa5):h04,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 mN0({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||La5}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??Pa5,Q=Y>=G;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(Q)return void this.resolveWaitUntilFlush();let J=this.options.waitUntilDebounceMs??Ea5;this._waitUntilCycle.timer=Fw(()=>{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 j04}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=h04){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 B=this.createFeatureFlagEvaluationContext(Y,W,K,H);if($==null)$=this.options.strictLocalEvaluation??!1;let N,z=!1,O,w,E,P,q,M;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,B,{matchValue:Q});if(R){z=!0;let k=R.value;P=V.id,M="Evaluated locally",N={key:X,enabled:k!==!1,variant:typeof k=="string"?k:void 0,payload:R.payload??void 0}}}catch(R){if(R instanceof Jz||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(B.distinctId,B.groups,B.personProperties,B.groupProperties,Z,[X]);if(V===void 0)E=cX1.UNKNOWN_ERROR;else{O=V.requestId,w=V.evaluatedAt;let R=[];if(V.errorsWhileComputingFlags)R.push(cX1.ERRORS_WHILE_COMPUTING);if(V.quotaLimited?.includes("feature_flags"))R.push(cX1.QUOTA_LIMITED);let k=V.flags[X];if(k===void 0)R.push(cX1.FLAG_MISSING);else{P=k.metadata?.id,q=k.metadata?.version,M=k.reason?.description??k.reason?.code;let _;if(k.metadata?.payload!==void 0)try{_=JSON.parse(k.metadata.payload)}catch{_=k.metadata.payload}N={key:X,enabled:k.enabled,variant:k.variant,payload:_}}if(R.length>0)E=R.join(",")}}if(J){let V=N===void 0?void 0:N.enabled===!1?!1:N.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:M,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(N!==void 0&&this._payloadOverrides!==void 0&&X in this._payloadOverrides)N={...N,payload:this._payloadOverrides[X]};return N}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 B=this.createFeatureFlagEvaluationContext(G,J,K,H);if($==null)$=this.options.strictLocalEvaluation??!1;let N=await this.featureFlagsPoller?.getAllFlagsAndPayloads(B,Z),z={},O={},w=!0;if(N)z=N.response,O=N.payloads,w=N.fallbackToFlags;if(w&&!$){let E=await super.getFeatureFlagsAndPayloadsStateless(B.distinctId,B.groups,B.personProperties,B.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=Fw(()=>{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(oe6(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,B={...this.props,...H?.properties||{},...Q||{}};if(!U)U=Iq(),B.$process_person_profile=!1;if(H?.sessionId&&!B.$session_id)B.$session_id=H.sessionId;let N=this._runBeforeSend({distinctId:U,event:G,properties:B,groups:J,sendFeatureFlags:W,timestamp:Z,disableGeoip:$,uuid:K});if(!N)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(N.distinctId,J,$,O)}return N.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,...N.properties||{},$groups:N.groups||J}});if(N.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof z.$raw_user_agent=="string"){if(pe6(z.$raw_user_agent,this.options.custom_blocked_useragents||[]))N.event="$bot_pageview",z.$browser_type="bot"}return{distinctId:N.distinctId,event:N.event,properties:z,options:{timestamp:N.timestamp,disableGeoip:N.disableGeoip,uuid:N.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 Va5}from"async_hooks";class iN0{constructor(){this.storage=new Va5}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 u04=()=>{};function ja5(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[l04.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 B=Z.exception?.values||[],N=B.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:B[0]?.value||Z.message,$exception_type:B[0]?.type,$exception_level:Z.level,$exception_list:N,$sentry_event_id:Z.event_id,$sentry_exception:Z.exception,$sentry_exception_message:B[0]?.value||Z.message,$sentry_exception_type:B[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 l04;var m04=D(()=>{l04=class l04{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(ja5(X,{organization:Y,projectId:$,prefix:G,severityAllowList:Q,sendExceptionsToPostHog:J??!0}))}}}});var d04=D(()=>{KT1()});var c04=D(()=>{_j();m04();d04();lN0()});var pN0;var i04=D(()=>{me6();P04();A04();KT1();g04();_j();u04();c04();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),[le6(),w04,q04()]);pN0=class pN0 extends cN0{getLibraryId(){return"posthog-node"}initializeContext(){return new iN0}}});function Ma5(){return{capture:()=>{},identify:()=>{},captureException:()=>{},groupIdentify:()=>{},shutdown:async()=>{}}}var nN0,p04,j4;var RX=D(()=>{i04();nN0=process.env.POSTHOG_KEY,p04=process.env.POSTHOG_HOST;j4=nN0?new pN0(nN0,{...p04?{host:p04}:{},enableExceptionAutocapture:!0,flushAt:1,flushInterval:0}):Ma5();if(nN0){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 iX1(){return`http://localhost:${v6().port??3000}`}var Uw=D(()=>{m9()});var n04=D(()=>{bV()});function a04(X){return{organizationId:X.organization_id,domain:X.domain,autoJoinEnabled:X.auto_join_enabled,createdAt:X.created_at,updatedAt:X.updated_at}}class Bw{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?a04(Y):null}async getByOrganizationId(X){let Y=await this.db.selectFrom("organization_domains").selectAll().where("organization_id","=",X).executeTakeFirst();return Y?a04(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 aN0{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 tN0{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 fj(X){let Y=Ca5[X.provider];if(!Y)throw Error(`Unknown email provider: ${X.provider}`);return Y(X)}function bj(X,Y){return X.find((G)=>G.id===Y)}var Ra5=(X)=>{let Y=new aN0(X.config.apiKey);return async({to:G,subject:Q,html:J})=>{await Y.sendEmail({to:G,from:X.config.fromEmail,subject:Q,html:J})}},Sa5=(X)=>{let Y=new tN0(X.config.apiKey);return async({to:G,subject:Q,html:J})=>{await Y.sendEmail({to:G,from:X.config.fromEmail,subject:Q,html:J})}},Ca5;var HT1=D(()=>{Ca5={resend:Ra5,sendgrid:Sa5}});function yj({preheader:X="",heading:Y,subheading:G,body:Q,footnote:J}){return`<!DOCTYPE html>
|
|
1641
1641
|
<html lang="en">
|
|
1642
1642
|
<head>
|
|
@@ -5058,7 +5058,7 @@ Caused by: ${Y.stack}`}};hs=class hs extends rY{constructor(X,Y){super(X,Y);this
|
|
|
5058
5058
|
AND "organizationId" NOT IN (
|
|
5059
5059
|
SELECT "organizationId" FROM "member" WHERE "userId" = ${K.id}
|
|
5060
5060
|
)
|
|
5061
|
-
`.execute(H),await O1`DELETE FROM "member" WHERE "userId" = ${Y.id}`.execute(H),await O1`DELETE FROM "user" WHERE "id" = ${Y.id}`.execute(H)})}catch(H){console.error("[SSO] Failed to merge duplicate user:",H)}}var xQ7=(X)=>{return{trustEmailVerified:!0,provisionUser:hQ7,defaultSSO:[{domain:X.domain,providerId:X.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:X.MS_CLIENT_ID,clientSecret:X.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:X.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified",oid:"oid"}}}}]}},yJ8=(X)=>{if(X.providerId==="microsoft")return xQ7(X);throw Error(`Unsupported provider: ${X.providerId}`)};var xJ8=D(()=>{MJ();A4();JU()});var dJ8={};M0(dJ8,{resetPasswordEnabled:()=>rc1,authConfig:()=>a5,auth:()=>RY,GENERIC_EMAIL_DOMAINS:()=>eA});function gQ7(X){return X.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function uQ7(){let X=Math.floor(Math.random()*gJ8.length),Y=Math.floor(Math.random()*hJ8.length),G=gJ8[X]??"deco",Q=hJ8[Y]??"studio";return`${G}-${Q}`}function tQ7(){let X=[o31];try{let Y=new URL(o31);if(Y.hostname==="localhost")X.push(o31.replace("localhost","127.0.0.1"));else if(Y.hostname==="127.0.0.1")X.push(o31.replace("127.0.0.1","localhost"))}catch{}return X}var hJ8,gJ8,lQ7,mQ7,tc1,dQ7,cQ7,iQ7,uJ8,a5,mJ8=void 0,Ey0=void 0,rc1=!1,pQ7,eA,nQ7,aQ7,o31,lJ8,RY;var uR=D(()=>{m9();NN0();F80();W50();H80();BO1();j50();be6();DN0();RX();Uw();n04();JU();o04();HT1();e04();fJ8();bJ8();QQ1();xJ8();hJ8=["labs","agent","studio","workspace","systems","core","cloud","works"],gJ8=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];lQ7=Object.values(fX1()).map((X)=>X.map((Y)=>Y.name)).flat(),mQ7={...oz1,self:["*",...lQ7]},tc1=ZN(mQ7),dQ7=tc1.newRole({self:["*"],...g41.statements}),cQ7=tc1.newRole({self:["*"],...g41.statements}),iQ7=tc1.newRole({self:["*"],...g41.statements}),uJ8=Object.values(fX1()).map((X)=>X.map((Y)=>`self:${Y.name}`)).flat(),a5=Sj().auth;if(a5.inviteEmailProviderId&&a5.emailProviders&&a5.emailProviders.length>0){let X=bj(a5.emailProviders,a5.inviteEmailProviderId);if(X){let Y=fj(X);mJ8=async(G)=>{let Q=G.inviter.user?.name||G.inviter.user?.email,J=`${u$()}/auth/accept-invitation?invitationId=${G.invitation.id}&redirectTo=/`;await Y({to:G.email,subject:`You've been invited to join ${G.organization.name}`,html:yj({preheader:`${Q} has invited you to join ${G.organization.name} on deco Studio.`,heading:"You've been invited",subheading:`<strong>${Q}</strong> has invited you to join <strong>${G.organization.name}</strong> on deco Studio.`,body:pX1("Accept invitation",J),footnote:"If you weren\u2019t expecting an invitation, you can safely ignore this email."})})}}}if(a5.resetPasswordEmailProviderId&&a5.emailProviders&&a5.emailProviders.length>0){let X=bj(a5.emailProviders,a5.resetPasswordEmailProviderId);if(X){let Y=fj(X);rc1=!0,Ey0=async({user:G,url:Q})=>{await Y({to:G.email,subject:"Reset your password",html:yj({preheader:"We received a request to reset the password on your deco Studio account.",heading:"Reset your password",subheading:"We received a password reset request for your account. Click the button below to choose a new password.",body:pX1("Reset password",Q)+FT1("This link expires in 24\xA0hours. If you didn\u2019t request a password reset, no action is needed.",!0),footnote:"If you didn\u2019t request a password reset, you can safely ignore this email."})})}}}pQ7=[y41({organizationCreation:{afterCreate:async(X)=>{await _J8(X.organization.id,X.member.userId)}},ac:tc1,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:Pr,resourceNameValidation:(X)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(X)}}},roles:{user:dQ7,admin:cQ7,owner:iQ7},sendInvitationEmail:mJ8}),o41({loginPage:"/login",oidcConfig:{scopes:uJ8,metadata:{scopes_supported:uJ8},loginPage:"/login"}}),r41({enableMetadata:!0,maximumNameLength:64,keyExpiration:{minExpiresIn:0.003472222222222222},enableSessionForAPIKeys:!0,customAPIKeyGetter:(X)=>{if(X.headers?.get("X-MCP-Session-Auth")==="true")return null;let G=X.headers?.get("Authorization");if(G?.startsWith("Bearer "))return G.replace("Bearer ","").trim();return null},permissions:{defaultPermissions:{self:["ORGANIZATION_LIST","ORGANIZATION_GET","ORGANIZATION_MEMBER_LIST","COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","API_KEY_CREATE","API_KEY_LIST"]}},rateLimit:{enabled:!1}}),l41({defaultRole:"user",adminRoles:["admin","owner"]}),Y81(),d41({jwt:{expirationTime:"5m"}}),Ez1(a5.ssoConfig?yJ8(a5.ssoConfig):void 0),...a5.magicLinkConfig?.enabled&&a5.emailProviders&&a5.emailProviders.length>0?[X81(s04(a5.magicLinkConfig,a5.emailProviders))]:[],...a5.emailOtpConfig?.enabled&&a5.emailProviders&&a5.emailProviders.length>0?[Jp(r04(a5.emailOtpConfig,a5.emailProviders))]:[]],eA=new Set(["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","yahoo.com","yahoo.co.uk","icloud.com","me.com","mac.com","aol.com","protonmail.com","proton.me","zoho.com","yandex.com","mail.com","gmx.com","gmx.net","tutanota.com","fastmail.com"]),nQ7=lP(),aQ7=q91(nQ7),o31=u$();lJ8=v6(),RY=K80({secret:lJ8.betterAuthSecret||"deco-default-secret-k7x9m2p4q8w3n5v6",baseURL:o31,trustedOrigins:tQ7(),database:aQ7,socialProviders:a5.socialProviders,...a5.ssoConfig&&{account:{accountLinking:{trustedProviders:[a5.ssoConfig.providerId]}}},emailAndPassword:{enabled:a5.emailAndPassword.enabled,...Ey0&&{sendResetPassword:Ey0}},rateLimit:{enabled:!lJ8.disableRateLimit,window:60,max:1e4},plugins:pQ7,databaseHooks:{user:{create:{after:async(X)=>{if(Ly0({id:X.id,email:X.email,name:X.name??null,emailVerified:!!X.emailVerified}),j4.capture({distinctId:X.id,event:"user_signed_up",properties:{email:X.email,email_domain:X.email?.split("@")[1]?.toLowerCase()??null,email_verified:!!X.emailVerified,has_name:!!X.name}}),X.emailVerified){let Q=X.email?.split("@")[1]?.toLowerCase();if(Q&&!eA.has(Q)){let J=!1;try{let Z=await new Bw(t7().db).getByDomain(Q);if(Z?.autoJoinEnabled){await RY.api.addMember({body:{userId:X.id,role:"user",organizationId:Z.organizationId}});return}J=!0}catch(W){console.error("[Auth] Domain auto-join check failed:",W)}if(J)return}}if(Sj().autoCreateOrganizationOnSignup===!1)return;let Y=X.name?X.name.split(" ")[0]:X.email.split("@")[0],G=3;for(let Q=0;Q<G;Q++){let J=`${Y} ${uQ7()}`,W=gQ7(J);try{let $=(await RY.api.createOrganization({body:{name:J,slug:W,userId:X.id}}))?.id??void 0;if($)j4.groupIdentify({groupType:"organization",groupKey:$,properties:{name:J,slug:W,created_at:new Date().toISOString(),created_via:"signup_default"}}),j4.capture({distinctId:X.id,event:"organization_created",groups:{organization:$},properties:{organization_id:$,organization_slug:W,created_via:"signup_default"}});return}catch(Z){if(!(Z instanceof Error&&("body"in Z)&&Z.body?.code==="ORGANIZATION_ALREADY_EXISTS")||Q===G-1){console.error("Failed to create default organization:",Z);return}}}}}},session:{create:{after:async(X)=>{let Y=await t7().db.selectFrom("user").select(["id","email","name","emailVerified"]).where("id","=",X.userId).executeTakeFirst();if(!Y)return;Ly0({id:Y.id,email:Y.email,name:Y.name??null,emailVerified:!!Y.emailVerified})}}}}})});function Py0(X,Y){return`${X}:${Y}`}function cJ8(X){let Y=X?.ttlMs??120000,G=X?.maxSize??1e4,Q=new Map;function J(){if(Q.size<=G)return;let W=Date.now();for(let[Z,$]of Q)if($.expiresAt<=W)Q.delete(Z);if(Q.size>G){let Z=Q.size-G,$=0;for(let K of Q.keys()){if($>=Z)break;Q.delete(K),$++}}}return{get(W,Z){let $=Py0(W,Z),K=Q.get($);if(!K)return;if(K.expiresAt<=Date.now()){Q.delete($);return}return K.role},set(W,Z,$){let K=Py0(W,Z);Q.set(K,{role:$,expiresAt:Date.now()+Y,organizationId:Z}),J()},invalidate(W,Z){Q.delete(Py0(W,Z))},invalidateOrg(W){for(let[Z,$]of Q)if($.organizationId===W)Q.delete(Z)}}}class iJ8{db;constructor(X){this.db=X}mapRowToSubscription(X){return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:Boolean(X.enabled),createdAt:X.created_at,updatedAt:X.updated_at}}async publishEvent(X){let Y=new Date().toISOString();return await this.db.insertInto("events").values({id:X.id,organization_id:X.organizationId,type:X.type,source:X.source,specversion:"1.0",subject:X.subject??null,time:X.time,datacontenttype:X.datacontenttype??"application/json",dataschema:X.dataschema??null,data:X.data?JSON.stringify(X.data):null,cron:X.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Y,updated_at:Y}).execute(),{id:X.id,organizationId:X.organizationId,type:X.type,source:X.source,specversion:"1.0",subject:X.subject??null,time:X.time,datacontenttype:X.datacontenttype??"application/json",dataschema:X.dataschema??null,data:X.data??null,cron:X.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:Y,updatedAt:Y}}async subscribe(X){let Y=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X.organizationId).where("connection_id","=",X.connectionId).where("event_type","=",X.eventType);if(X.publisher)Y=Y.where("publisher","=",X.publisher);else Y=Y.where("publisher","is",null);if(X.filter)Y=Y.where("filter","=",X.filter);else Y=Y.where("filter","is",null);let G=await Y.executeTakeFirst();if(G)return this.mapRowToSubscription(G);let Q=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:X.id,organization_id:X.organizationId,connection_id:X.connectionId,publisher:X.publisher??null,event_type:X.eventType,filter:X.filter??null,enabled:!0,created_at:Q,updated_at:Q}).execute(),{id:X.id,organizationId:X.organizationId,connectionId:X.connectionId,publisher:X.publisher??null,eventType:X.eventType,filter:X.filter??null,enabled:!0,createdAt:Q,updatedAt:Q}}async unsubscribe(X,Y){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",X).where("organization_id","=",Y).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(X,Y){let G=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X);if(Y)G=G.where("connection_id","=",Y);return(await G.execute()).map((J)=>this.mapRowToSubscription(J))}async getSubscription(X,Y){let G=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",X).where("organization_id","=",Y).executeTakeFirst();if(!G)return null;return this.mapRowToSubscription(G)}async getMatchingSubscriptions(X){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X.organizationId).where("enabled","=",!0).where("event_type","=",X.type).where((G)=>G.or([G("publisher","is",null),G("publisher","=",X.source)])).execute()).map((G)=>this.mapRowToSubscription(G))}async createDeliveries(X,Y,G){if(Y.length===0)return;let Q=new Date().toISOString(),J=G??null,W=Y.map((Z)=>({id:crypto.randomUUID(),event_id:X,subscription_id:Z,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:J,created_at:Q}));await this.db.insertInto("event_deliveries").values(W).execute()}async claimPendingDeliveries(X){let Y=new Date().toISOString(),Q=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",O1`(
|
|
5061
|
+
`.execute(H),await O1`DELETE FROM "member" WHERE "userId" = ${Y.id}`.execute(H),await O1`DELETE FROM "user" WHERE "id" = ${Y.id}`.execute(H)})}catch(H){console.error("[SSO] Failed to merge duplicate user:",H)}}var xQ7=(X)=>{return{trustEmailVerified:!0,provisionUser:hQ7,defaultSSO:[{domain:X.domain,providerId:X.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:X.MS_CLIENT_ID,clientSecret:X.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:X.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified",oid:"oid"}}}}]}},yJ8=(X)=>{if(X.providerId==="microsoft")return xQ7(X);throw Error(`Unsupported provider: ${X.providerId}`)};var xJ8=D(()=>{MJ();A4();JU()});var dJ8={};M0(dJ8,{resetPasswordEnabled:()=>rc1,authConfig:()=>a5,auth:()=>RY,GENERIC_EMAIL_DOMAINS:()=>eA});function gQ7(X){return X.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function uQ7(){let X=Math.floor(Math.random()*gJ8.length),Y=Math.floor(Math.random()*hJ8.length),G=gJ8[X]??"deco",Q=hJ8[Y]??"studio";return`${G}-${Q}`}function tQ7(){let X=[o31];try{let Y=new URL(o31);if(Y.hostname==="localhost")X.push(o31.replace("localhost","127.0.0.1"));else if(Y.hostname==="127.0.0.1")X.push(o31.replace("127.0.0.1","localhost"))}catch{}return X}var hJ8,gJ8,lQ7,mQ7,tc1,dQ7,cQ7,iQ7,uJ8,a5,mJ8=void 0,Ey0=void 0,rc1=!1,pQ7,eA,nQ7,aQ7,o31,lJ8,RY;var uR=D(()=>{m9();NN0();F80();W50();H80();BO1();j50();be6();DN0();RX();Uw();n04();JU();o04();HT1();e04();fJ8();bJ8();QQ1();xJ8();hJ8=["labs","agent","studio","workspace","systems","core","cloud","works"],gJ8=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];lQ7=Object.values(fX1()).map((X)=>X.map((Y)=>Y.name)).flat(),mQ7={...oz1,self:["*",...lQ7]},tc1=ZN(mQ7),dQ7=tc1.newRole({self:["*"],...g41.statements}),cQ7=tc1.newRole({self:["*"],...g41.statements}),iQ7=tc1.newRole({self:["*"],...g41.statements}),uJ8=Object.values(fX1()).map((X)=>X.map((Y)=>`self:${Y.name}`)).flat(),a5=Sj().auth;if(a5.inviteEmailProviderId&&a5.emailProviders&&a5.emailProviders.length>0){let X=bj(a5.emailProviders,a5.inviteEmailProviderId);if(X){let Y=fj(X);mJ8=async(G)=>{let Q=G.inviter.user?.name||G.inviter.user?.email,J=`${u$()}/auth/accept-invitation?invitationId=${G.invitation.id}&redirectTo=/${G.organization.slug}`;await Y({to:G.email,subject:`You've been invited to join ${G.organization.name}`,html:yj({preheader:`${Q} has invited you to join ${G.organization.name} on deco Studio.`,heading:"You've been invited",subheading:`<strong>${Q}</strong> has invited you to join <strong>${G.organization.name}</strong> on deco Studio.`,body:pX1("Accept invitation",J),footnote:"If you weren\u2019t expecting an invitation, you can safely ignore this email."})})}}}if(a5.resetPasswordEmailProviderId&&a5.emailProviders&&a5.emailProviders.length>0){let X=bj(a5.emailProviders,a5.resetPasswordEmailProviderId);if(X){let Y=fj(X);rc1=!0,Ey0=async({user:G,url:Q})=>{await Y({to:G.email,subject:"Reset your password",html:yj({preheader:"We received a request to reset the password on your deco Studio account.",heading:"Reset your password",subheading:"We received a password reset request for your account. Click the button below to choose a new password.",body:pX1("Reset password",Q)+FT1("This link expires in 24\xA0hours. If you didn\u2019t request a password reset, no action is needed.",!0),footnote:"If you didn\u2019t request a password reset, you can safely ignore this email."})})}}}pQ7=[y41({organizationCreation:{afterCreate:async(X)=>{await _J8(X.organization.id,X.member.userId)}},ac:tc1,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:Pr,resourceNameValidation:(X)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(X)}}},roles:{user:dQ7,admin:cQ7,owner:iQ7},sendInvitationEmail:mJ8}),o41({loginPage:"/login",oidcConfig:{scopes:uJ8,metadata:{scopes_supported:uJ8},loginPage:"/login"}}),r41({enableMetadata:!0,maximumNameLength:64,keyExpiration:{minExpiresIn:0.003472222222222222},enableSessionForAPIKeys:!0,customAPIKeyGetter:(X)=>{if(X.headers?.get("X-MCP-Session-Auth")==="true")return null;let G=X.headers?.get("Authorization");if(G?.startsWith("Bearer "))return G.replace("Bearer ","").trim();return null},permissions:{defaultPermissions:{self:["ORGANIZATION_LIST","ORGANIZATION_GET","ORGANIZATION_MEMBER_LIST","COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","API_KEY_CREATE","API_KEY_LIST"]}},rateLimit:{enabled:!1}}),l41({defaultRole:"user",adminRoles:["admin","owner"]}),Y81(),d41({jwt:{expirationTime:"5m"}}),Ez1(a5.ssoConfig?yJ8(a5.ssoConfig):void 0),...a5.magicLinkConfig?.enabled&&a5.emailProviders&&a5.emailProviders.length>0?[X81(s04(a5.magicLinkConfig,a5.emailProviders))]:[],...a5.emailOtpConfig?.enabled&&a5.emailProviders&&a5.emailProviders.length>0?[Jp(r04(a5.emailOtpConfig,a5.emailProviders))]:[]],eA=new Set(["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","yahoo.com","yahoo.co.uk","icloud.com","me.com","mac.com","aol.com","protonmail.com","proton.me","zoho.com","yandex.com","mail.com","gmx.com","gmx.net","tutanota.com","fastmail.com"]),nQ7=lP(),aQ7=q91(nQ7),o31=u$();lJ8=v6(),RY=K80({secret:lJ8.betterAuthSecret||"deco-default-secret-k7x9m2p4q8w3n5v6",baseURL:o31,trustedOrigins:tQ7(),database:aQ7,socialProviders:a5.socialProviders,...a5.ssoConfig&&{account:{accountLinking:{trustedProviders:[a5.ssoConfig.providerId]}}},emailAndPassword:{enabled:a5.emailAndPassword.enabled,...Ey0&&{sendResetPassword:Ey0}},rateLimit:{enabled:!lJ8.disableRateLimit,window:60,max:1e4},plugins:pQ7,databaseHooks:{user:{create:{after:async(X)=>{if(Ly0({id:X.id,email:X.email,name:X.name??null,emailVerified:!!X.emailVerified}),j4.capture({distinctId:X.id,event:"user_signed_up",properties:{email:X.email,email_domain:X.email?.split("@")[1]?.toLowerCase()??null,email_verified:!!X.emailVerified,has_name:!!X.name}}),X.emailVerified){let Q=X.email?.split("@")[1]?.toLowerCase();if(Q&&!eA.has(Q)){let J=!1;try{let Z=await new Bw(t7().db).getByDomain(Q);if(Z?.autoJoinEnabled){await RY.api.addMember({body:{userId:X.id,role:"user",organizationId:Z.organizationId}});return}J=!0}catch(W){console.error("[Auth] Domain auto-join check failed:",W)}if(J)return}}if(Sj().autoCreateOrganizationOnSignup===!1)return;let Y=X.name?X.name.split(" ")[0]:X.email.split("@")[0],G=3;for(let Q=0;Q<G;Q++){let J=`${Y} ${uQ7()}`,W=gQ7(J);try{let $=(await RY.api.createOrganization({body:{name:J,slug:W,userId:X.id}}))?.id??void 0;if($)j4.groupIdentify({groupType:"organization",groupKey:$,properties:{name:J,slug:W,created_at:new Date().toISOString(),created_via:"signup_default"}}),j4.capture({distinctId:X.id,event:"organization_created",groups:{organization:$},properties:{organization_id:$,organization_slug:W,created_via:"signup_default"}});return}catch(Z){if(!(Z instanceof Error&&("body"in Z)&&Z.body?.code==="ORGANIZATION_ALREADY_EXISTS")||Q===G-1){console.error("Failed to create default organization:",Z);return}}}}}},session:{create:{after:async(X)=>{let Y=await t7().db.selectFrom("user").select(["id","email","name","emailVerified"]).where("id","=",X.userId).executeTakeFirst();if(!Y)return;Ly0({id:Y.id,email:Y.email,name:Y.name??null,emailVerified:!!Y.emailVerified})}}}}})});function Py0(X,Y){return`${X}:${Y}`}function cJ8(X){let Y=X?.ttlMs??120000,G=X?.maxSize??1e4,Q=new Map;function J(){if(Q.size<=G)return;let W=Date.now();for(let[Z,$]of Q)if($.expiresAt<=W)Q.delete(Z);if(Q.size>G){let Z=Q.size-G,$=0;for(let K of Q.keys()){if($>=Z)break;Q.delete(K),$++}}}return{get(W,Z){let $=Py0(W,Z),K=Q.get($);if(!K)return;if(K.expiresAt<=Date.now()){Q.delete($);return}return K.role},set(W,Z,$){let K=Py0(W,Z);Q.set(K,{role:$,expiresAt:Date.now()+Y,organizationId:Z}),J()},invalidate(W,Z){Q.delete(Py0(W,Z))},invalidateOrg(W){for(let[Z,$]of Q)if($.organizationId===W)Q.delete(Z)}}}class iJ8{db;constructor(X){this.db=X}mapRowToSubscription(X){return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:Boolean(X.enabled),createdAt:X.created_at,updatedAt:X.updated_at}}async publishEvent(X){let Y=new Date().toISOString();return await this.db.insertInto("events").values({id:X.id,organization_id:X.organizationId,type:X.type,source:X.source,specversion:"1.0",subject:X.subject??null,time:X.time,datacontenttype:X.datacontenttype??"application/json",dataschema:X.dataschema??null,data:X.data?JSON.stringify(X.data):null,cron:X.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Y,updated_at:Y}).execute(),{id:X.id,organizationId:X.organizationId,type:X.type,source:X.source,specversion:"1.0",subject:X.subject??null,time:X.time,datacontenttype:X.datacontenttype??"application/json",dataschema:X.dataschema??null,data:X.data??null,cron:X.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:Y,updatedAt:Y}}async subscribe(X){let Y=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X.organizationId).where("connection_id","=",X.connectionId).where("event_type","=",X.eventType);if(X.publisher)Y=Y.where("publisher","=",X.publisher);else Y=Y.where("publisher","is",null);if(X.filter)Y=Y.where("filter","=",X.filter);else Y=Y.where("filter","is",null);let G=await Y.executeTakeFirst();if(G)return this.mapRowToSubscription(G);let Q=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:X.id,organization_id:X.organizationId,connection_id:X.connectionId,publisher:X.publisher??null,event_type:X.eventType,filter:X.filter??null,enabled:!0,created_at:Q,updated_at:Q}).execute(),{id:X.id,organizationId:X.organizationId,connectionId:X.connectionId,publisher:X.publisher??null,eventType:X.eventType,filter:X.filter??null,enabled:!0,createdAt:Q,updatedAt:Q}}async unsubscribe(X,Y){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",X).where("organization_id","=",Y).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(X,Y){let G=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X);if(Y)G=G.where("connection_id","=",Y);return(await G.execute()).map((J)=>this.mapRowToSubscription(J))}async getSubscription(X,Y){let G=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",X).where("organization_id","=",Y).executeTakeFirst();if(!G)return null;return this.mapRowToSubscription(G)}async getMatchingSubscriptions(X){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X.organizationId).where("enabled","=",!0).where("event_type","=",X.type).where((G)=>G.or([G("publisher","is",null),G("publisher","=",X.source)])).execute()).map((G)=>this.mapRowToSubscription(G))}async createDeliveries(X,Y,G){if(Y.length===0)return;let Q=new Date().toISOString(),J=G??null,W=Y.map((Z)=>({id:crypto.randomUUID(),event_id:X,subscription_id:Z,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:J,created_at:Q}));await this.db.insertInto("event_deliveries").values(W).execute()}async claimPendingDeliveries(X){let Y=new Date().toISOString(),Q=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",O1`(
|
|
5062
5062
|
SELECT d.id
|
|
5063
5063
|
FROM event_deliveries d
|
|
5064
5064
|
INNER JOIN event_subscriptions s ON s.id = d.subscription_id
|