decocms 2.288.0 → 2.289.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{AlertCircle--Y_xi7pz.js → AlertCircle-BCfEJcld.js} +1 -1
- package/dist/client/assets/{ArrowNarrowLeft-adl7K_Ob.js → ArrowNarrowLeft-dDBZy2uy.js} +1 -1
- package/dist/client/assets/{ArrowUpRight-DrcSZgbj.js → ArrowUpRight-DR20SS60.js} +1 -1
- package/dist/client/assets/{CheckCircle-DeN4Arf9.js → CheckCircle-C29ChaU6.js} +1 -1
- package/dist/client/assets/{ChevronDown-aTqoLskN.js → ChevronDown-CAze57fI.js} +1 -1
- package/dist/client/assets/{ChevronRight-D_eqesT2.js → ChevronRight-Df7bIxwE.js} +1 -1
- package/dist/client/assets/{ChevronUp-BJsJc2K_.js → ChevronUp-CTU6V7Q0.js} +1 -1
- package/dist/client/assets/{Container-RTpXHcc_.js → Container-Ckr-D4x-.js} +1 -1
- package/dist/client/assets/{DotsVertical-DU62Ovco.js → DotsVertical-BooYL5-r.js} +1 -1
- package/dist/client/assets/{LinkExternal01-CZ54w6Ys.js → LinkExternal01-BF4nSmdO.js} +1 -1
- package/dist/client/assets/{Lock01-C1fACGdb.js → Lock01-D_RqxNIk.js} +1 -1
- package/dist/client/assets/{Palette-CSi1xvBX.js → Palette-Du_aKlJW.js} +1 -1
- package/dist/client/assets/{Play-ZwqBA0Gj.js → Play-hp4nCWPw.js} +1 -1
- package/dist/client/assets/{Plus-DgDw4N5v.js → Plus-C-OJiAlg.js} +1 -1
- package/dist/client/assets/{RefreshCcw01-BQD-u-1H.js → RefreshCcw01-Bw_4FSKr.js} +1 -1
- package/dist/client/assets/{SearchMd-DIPAhwlI.js → SearchMd-DRU7KH2R.js} +1 -1
- package/dist/client/assets/{Settings02-NWpe6nkq.js → Settings02-tDR0R-7r.js} +1 -1
- package/dist/client/assets/{Shield01-yW6P30XX.js → Shield01-CyMbm-kt.js} +1 -1
- package/dist/client/assets/{Star01-BNCw32N6.js → Star01-BSV4P3zw.js} +1 -1
- package/dist/client/assets/{Sun-BIhz6_CP.js → Sun-NTsERAnx.js} +1 -1
- package/dist/client/assets/{Tool01-DK8Fhe6_.js → Tool01-JkKJ-VBh.js} +1 -1
- package/dist/client/assets/{Trash01-CLPACLPe.js → Trash01-5isrbkO6.js} +1 -1
- package/dist/client/assets/{User01-C_p7EKq6.js → User01-CtVgwrxn.js} +1 -1
- package/dist/client/assets/{Users03-C5Wav_Yh.js → Users03-kskEQmar.js} +1 -1
- package/dist/client/assets/{X-BI3qXgCM.js → X-KZf37p0i.js} +1 -1
- package/dist/client/assets/{XCircle-C15LvzjS.js → XCircle-0jhuLEi-.js} +1 -1
- package/dist/client/assets/{XClose-xaUxE8BL.js → XClose-DmXYRRRU.js} +1 -1
- package/dist/client/assets/{Zap-DUrCsyVy.js → Zap-CjGMKfBw.js} +1 -1
- package/dist/client/assets/{ZapSquare-CzhlLfPR.js → ZapSquare-Q_j-wpZU.js} +1 -1
- package/dist/client/assets/{accordion-PgILOgmD.js → accordion-LhYuXsvn.js} +1 -1
- package/dist/client/assets/{agent-icon-Dwc2UhoB.js → agent-icon-CJBSrXXa.js} +1 -1
- package/dist/client/assets/{agents-list-DtDkfiBL.js → agents-list-Bj1ZEySf.js} +1 -1
- package/dist/client/assets/ai-providers-NZdL0YY1.js +1 -0
- package/dist/client/assets/{alert-dialog-P1MELuo2.js → alert-dialog-DGf6p6RH.js} +2 -2
- package/dist/client/assets/{auth-catchall-DXBvhnpI.js → auth-catchall-mJXjaGjq.js} +1 -1
- package/dist/client/assets/{automation-list-row-ZhJERDs5.js → automation-list-row-i7idsf84.js} +1 -1
- package/dist/client/assets/{automations-BKo3NXeb.js → automations-D5L5OUmd.js} +1 -1
- package/dist/client/assets/{avatar-C4Xk2I9Z.js → avatar-BiQlJs5k.js} +1 -1
- package/dist/client/assets/{badge-LkPgBUqp.js → badge-BiDYflRu.js} +1 -1
- package/dist/client/assets/{brand-context-B0xNT0Kl.js → brand-context-1aiu9Hp5.js} +1 -1
- package/dist/client/assets/{card-oTGN-YLV.js → card-kpHhMcOo.js} +1 -1
- package/dist/client/assets/{chat-context-yRGYHam2.js → chat-context-C5B4JHNW.js} +1 -1
- package/dist/client/assets/{checkbox-COiFtX5D.js → checkbox-DVSlEbBg.js} +1 -1
- package/dist/client/assets/{collection-detail-D7_Iw3uk.js → collection-detail-8OxmAVZx.js} +1 -1
- package/dist/client/assets/{collection-display-button-cYrSfrMz.js → collection-display-button-DJUi1nr2.js} +1 -1
- package/dist/client/assets/{collection-search-Biy5fWyC.js → collection-search-Cauf3WLX.js} +1 -1
- package/dist/client/assets/{collection-search-D8Ek-RA1.js → collection-search-G428te1f.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-D7Avuad7.js → collection-table-wrapper-CgJ-IWGp.js} +1 -1
- package/dist/client/assets/{collection-tabs-Ez6xggyp.js → collection-tabs-ImMH44oz.js} +1 -1
- package/dist/client/assets/{collections-h5KZ86rd.js → collections-CgvQVGim.js} +1 -1
- package/dist/client/assets/{command-BcjbHr_r.js → command-DUlueOVl.js} +1 -1
- package/dist/client/assets/{connection-card-Tvf09fuE.js → connection-card-CfcNRXjD.js} +1 -1
- package/dist/client/assets/{connection-detail-BOee_bXK.js → connection-detail-ZbjzvLjZ.js} +1 -1
- package/dist/client/assets/{connection-form-helpers-BML8fV-T.js → connection-form-helpers-CLdsDsnf.js} +1 -1
- package/dist/client/assets/{connections-BE48nDv7.js → connections-Db7XXBzz.js} +1 -1
- package/dist/client/assets/{constants-n9yTcILK.js → constants-D21LrFJ4.js} +1 -1
- package/dist/client/assets/{constants-Dsh71ijv.js → constants-DV1Uc_8Q.js} +2 -2
- package/dist/client/assets/{dialog-Dv_lEigV.js → dialog-eYBbNtPx.js} +1 -1
- package/dist/client/assets/{domain-settings-BcSGKzwX.js → domain-settings-5yGQjw4b.js} +1 -1
- package/dist/client/assets/{drawer-WXY2u6pv.js → drawer-BnROsLEL.js} +1 -1
- package/dist/client/assets/{dropdown-menu-B9QIvjxH.js → dropdown-menu-BeTlEYH5.js} +1 -1
- package/dist/client/assets/{dynamic-plugin-layout-CjDWcYO9.js → dynamic-plugin-layout-BvdykXHY.js} +1 -1
- package/dist/client/assets/{empty-state-DIMeCEjD.js → empty-state-B2VGunPR.js} +1 -1
- package/dist/client/assets/{empty-state-JxMlNoaR.js → empty-state-Dyal5Xfo.js} +1 -1
- package/dist/client/assets/{extract-connection-data-Cvlutde4.js → extract-connection-data-CSJgZrtD.js} +1 -1
- package/dist/client/assets/{features-YbryDu0n.js → features-B-66Obp6.js} +1 -1
- package/dist/client/assets/{form-BNoUlod_.js → form-CIMdOf9q.js} +1 -1
- package/dist/client/assets/{general-b6CUcDdB.js → general-D6CyCDN-.js} +1 -1
- package/dist/client/assets/{github-repo-picker-CP7-EChX.js → github-repo-picker-CvkiRKr8.js} +1 -1
- package/dist/client/assets/{index-Dig_TVyF.js → index-B07jP2sp.js} +1 -1
- package/dist/client/assets/{index-BVkdH26T.js → index-B0qIbTFl.js} +1 -1
- package/dist/client/assets/{index-Cw8cSB3k.js → index-CKiHh8tq.js} +1 -1
- package/dist/client/assets/{index-FXohrF1g.js → index-CQ6k5P_g.js} +1 -1
- package/dist/client/assets/{index-C-fdRcaZ.js → index-CQJ0POFk.js} +4 -4
- package/dist/client/assets/{index-CdjpBOmP.js → index-Ciwyai62.js} +1 -1
- package/dist/client/assets/{index-BZtydI_4.js → index-Cqh-Pw0g.js} +1 -1
- package/dist/client/assets/{index-CVUETRIB.js → index-D3dcRy4-.js} +28 -28
- package/dist/client/assets/{index-B0_K5fYx.js → index-DdZX0aDg.js} +1 -1
- package/dist/client/assets/{index-CjZGXiUn.js → index-Duvlh7HC.js} +1 -1
- package/dist/client/assets/{infiniteQueryObserver-BYD3scla.js → infiniteQueryObserver-DNXrDhz0.js} +1 -1
- package/dist/client/assets/{input-CL-LUIlC.js → input-BTdB8RPC.js} +1 -1
- package/dist/client/assets/{integration-icon-BXMU-Z0-.js → integration-icon-DJHy4-lT.js} +1 -1
- package/dist/client/assets/{label-Do_qw_q4.js → label-HfwUkinD.js} +1 -1
- package/dist/client/assets/{layout-DrFXNrUJ.js → layout-Blu93q33.js} +1 -1
- package/dist/client/assets/{login-B6O4fD8Q.js → login-YFb2t01p.js} +1 -1
- package/dist/client/assets/{members-L61ME1MY.js → members-qoLnAp5E.js} +1 -1
- package/dist/client/assets/{monaco-editor-BRexmFrU.js → monaco-editor-BFeXzORV.js} +1 -1
- package/dist/client/assets/{monitoring-stats-row-DpDZn9jY.js → monitoring-stats-row-B8LpUgZ3.js} +1 -1
- package/dist/client/assets/{oauth-callback-_ywR3sFa.js → oauth-callback-CXbpsVJh.js} +1 -1
- package/dist/client/assets/{oauth-callback-ai-provider-CpjecUsU.js → oauth-callback-ai-provider-CHi0ZwiA.js} +1 -1
- package/dist/client/assets/{onboarding-BHrMLfDa.js → onboarding-CS_9vzjQ.js} +1 -1
- package/dist/client/assets/{org-layout-BkXZ1gvy.js → org-layout-DzWFCFrp.js} +1 -1
- package/dist/client/assets/{org-plugin-layout-DQZ2g3kO.js → org-plugin-layout-C1udHyJg.js} +1 -1
- package/dist/client/assets/{plugin-empty-state-vwtahL68.js → plugin-empty-state-uSy8H1wz.js} +1 -1
- package/dist/client/assets/{plugin-header-BsB_du51.js → plugin-header-Y9KGqpf-.js} +1 -1
- package/dist/client/assets/{plugin-layout-Buej05e7.js → plugin-layout-BMUI6aZk.js} +1 -1
- package/dist/client/assets/{popover-C4684neQ.js → popover-0rGXbfVv.js} +1 -1
- package/dist/client/assets/{profile-DDmHWY6_.js → profile-Dxc4PLoS.js} +1 -1
- package/dist/client/assets/{project-app-view-BNwkzuii.js → project-app-view-rhNtxAKM.js} +1 -1
- package/dist/client/assets/registry-3CD149WE.js +2 -0
- package/dist/client/assets/{registry-layout-CZd2B4C7.js → registry-layout-20jGjbo6.js} +1 -1
- package/dist/client/assets/{required-auth-layout-SaQW2h7l.js → required-auth-layout-BrXS6Et-.js} +1 -1
- package/dist/client/assets/{reset-password-DDLCghhj.js → reset-password-KHQpUmrP.js} +1 -1
- package/dist/client/assets/{roles-DmqW3xZU.js → roles-QJpAwLWN.js} +1 -1
- package/dist/client/assets/{scroll-area-BmiP98pu.js → scroll-area-Cmb2U-GX.js} +1 -1
- package/dist/client/assets/{search-input-DQ1Xzm_b.js → search-input-Cxdo8FJH.js} +1 -1
- package/dist/client/assets/{select-model-CX8VF4-p.js → select-model-CepjGove.js} +1 -1
- package/dist/client/assets/{select-DaM3TY5t.js → select-pbe1Tw3i.js} +1 -1
- package/dist/client/assets/{settings-layout-DNFV8Oix.js → settings-layout-C_jpXJmC.js} +1 -1
- package/dist/client/assets/{settings-section-BS3Z4RWi.js → settings-section-zap-Boy4.js} +1 -1
- package/dist/client/assets/shell-layout-YcfNni5N.js +1 -0
- package/dist/client/assets/{skeleton-C8RqYCI9.js → skeleton-cT9-y8hq.js} +1 -1
- package/dist/client/assets/{sso-CZDbiXIw.js → sso-Bbte0m6W.js} +1 -1
- package/dist/client/assets/{store-CeeuB26r.js → store-CdJMoZz8.js} +1 -1
- package/dist/client/assets/store-registry-BT7eie06.js +2 -0
- package/dist/client/assets/{switch-DGYFt_K8.js → switch-CrRugnBx.js} +1 -1
- package/dist/client/assets/{table-BJ_I6wc6.js → table-Chd-IJRh.js} +1 -1
- package/dist/client/assets/{tabs-O35WvzjF.js → tabs-DvsJVzb1.js} +1 -1
- package/dist/client/assets/{task-status-BKkJIb6H.js → task-status-KWWNTm4M.js} +1 -1
- package/dist/client/assets/{textarea-CjtgfBdH.js → textarea-CWhJ3Xwe.js} +1 -1
- package/dist/client/assets/{toggle-group-ComSgZAp.js → toggle-group-B06Rml5A.js} +1 -1
- package/dist/client/assets/{tools-list-CurMUG9t.js → tools-list-DT1hnay8.js} +1 -1
- package/dist/client/assets/{types-DlC_80GR.js → types-DsDrkXAr.js} +1 -1
- package/dist/client/assets/{use-ai-providers-C3mVVuRV.js → use-ai-providers-oEGyGWt1.js} +1 -1
- package/dist/client/assets/{use-collections-DcKD6Qxv.js → use-collections-D8VuBtQu.js} +1 -1
- package/dist/client/assets/{use-connection-PZAuCSXO.js → use-connection-DATDvleR.js} +1 -1
- package/dist/client/assets/{use-copy-Bj-MTwaa.js → use-copy-C4JHTA85.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-B_irsl9D.js → use-create-virtual-mcp-CPp3t7Vk.js} +1 -1
- package/dist/client/assets/{use-decopilot-events-CDeh99iZ.js → use-decopilot-events-BmJPvHjL.js} +1 -1
- package/dist/client/assets/{use-delete-connection-BR9ISSGY.js → use-delete-connection-Cs_pBxVJ.js} +1 -1
- package/dist/client/assets/{use-infinite-scroll-D-2l__Cz.js → use-infinite-scroll-42GyaTNJ.js} +1 -1
- package/dist/client/assets/{use-list-state-BV21WFDK.js → use-list-state-B_acXswQ.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-Bv5yUcCZ.js → use-mcp-tools-Bp4N36ES.js} +1 -1
- package/dist/client/assets/{use-members-BAhIl5n0.js → use-members-egBMdDNQ.js} +1 -1
- package/dist/client/assets/{use-mobile-BpBXbl16.js → use-mobile-BwJlvmat.js} +1 -1
- package/dist/client/assets/{use-navigate-to-agent-CG7-kp4S.js → use-navigate-to-agent-CeIX1obd.js} +1 -1
- package/dist/client/assets/{use-org-sso-4JoNv6HV.js → use-org-sso-D35VQct2.js} +1 -1
- package/dist/client/assets/{use-organization-roles-Bpj16cC4.js → use-organization-roles-DewFhO3_.js} +1 -1
- package/dist/client/assets/{use-organization-settings-axiNM6Y6.js → use-organization-settings-DlzwYRHw.js} +1 -1
- package/dist/client/assets/{use-registry-connections-fdW_5JrJ.js → use-registry-connections-BMDx5SL4.js} +1 -1
- package/dist/client/assets/{use-status-sounds-BYcGwXOW.js → use-status-sounds-CnYkx9X0.js} +1 -1
- package/dist/client/assets/{use-tasks-CEbKlK-w.js → use-tasks-BtgjavUX.js} +1 -1
- package/dist/client/assets/{use-view-mode-DXGS7T6x.js → use-view-mode-ni8MVEBL.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-C8FeHhCA.js → use-virtual-mcp-CLK92_-L.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-NxzX8_KV.js +1 -0
- package/dist/client/assets/useSuspenseInfiniteQuery-BTse9xwX.js +1 -0
- package/dist/client/assets/{user-1OxcID9o.js → user-K40phdtq.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-BiIaP24A.js → view-mode-toggle-Co7HEZDI.js} +1 -1
- package/dist/client/assets/{workflow-Dx23L5rN.js → workflow-CuFWe7ID.js} +1 -1
- package/dist/client/assets/workflow-detail-CoSxU_nR.js +1 -0
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +1 -1
- package/dist/server/node_modules/{xtend → pg}/LICENSE +7 -6
- package/dist/server/node_modules/pg/README.md +95 -0
- package/dist/server/node_modules/pg/esm/index.mjs +20 -0
- package/dist/server/node_modules/pg/lib/client.js +743 -0
- package/dist/server/node_modules/pg/lib/connection-parameters.js +171 -0
- package/dist/server/node_modules/pg/lib/connection.js +221 -0
- package/dist/server/node_modules/pg/lib/crypto/cert-signatures.js +122 -0
- package/dist/server/node_modules/pg/lib/crypto/sasl.js +212 -0
- package/dist/server/node_modules/pg/lib/crypto/utils-legacy.js +43 -0
- package/dist/server/node_modules/pg/lib/crypto/utils-webcrypto.js +89 -0
- package/dist/server/node_modules/pg/lib/crypto/utils.js +9 -0
- package/dist/server/node_modules/pg/lib/defaults.js +91 -0
- package/dist/server/node_modules/pg/lib/index.js +73 -0
- package/dist/server/node_modules/pg/lib/native/client.js +323 -0
- package/dist/server/node_modules/pg/lib/native/index.js +2 -0
- package/dist/server/node_modules/pg/lib/native/query.js +165 -0
- package/dist/server/node_modules/pg/lib/query.js +252 -0
- package/dist/server/node_modules/pg/lib/result.js +109 -0
- package/dist/server/node_modules/pg/lib/stream.js +83 -0
- package/dist/server/node_modules/pg/lib/type-overrides.js +35 -0
- package/dist/server/node_modules/pg/lib/utils.js +217 -0
- package/dist/server/node_modules/pg/package.json +76 -0
- package/package.json +1 -1
- package/dist/client/assets/ai-providers-dl8LgpRM.js +0 -1
- package/dist/client/assets/registry-B2nAdztj.js +0 -2
- package/dist/client/assets/shell-layout-DifA2CaM.js +0 -1
- package/dist/client/assets/store-registry-Db_sa3Jy.js +0 -2
- package/dist/client/assets/useInfiniteQuery-D8Ti3aNB.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-BOcz1SDi.js +0 -1
- package/dist/client/assets/workflow-detail-BMaclVeL.js +0 -1
- package/dist/server/node_modules/ansi-styles/index.d.ts +0 -236
- package/dist/server/node_modules/ansi-styles/index.js +0 -223
- package/dist/server/node_modules/ansi-styles/license +0 -9
- package/dist/server/node_modules/ansi-styles/package.json +0 -54
- package/dist/server/node_modules/ansi-styles/readme.md +0 -173
- 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/license +0 -9
- 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/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 DA1(X){let Y={...process.env},G=I$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(() => (H$1(),K$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(() => (X30(),Xx6));await K(W.databaseUrl);let{createDatabase:H}=await Promise.resolve().then(() => (QU(),ey6)),{migrateToLatest:U}=await Promise.resolve().then(() => (Zr6(),Jr6)),N=H(W.databaseUrl);await U({keepOpen:!0,database:N,skipBetterAuth:!0})}if(G.settings.clickhouseUrl){let{ensureClickHouseRollup:K}=await Promise.resolve().then(() => Ws6);await K(G.settings.clickhouseUrl)}let $={...G.settings,databaseUrl:W.databaseUrl,natsUrls:W.natsUrls};return Xl0($),{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 IN0=D(()=>{xn1();m9()});import{createServer as $s6}from"net";function Di5(X){return new Promise((Y)=>{let G=$s6();G.once("error",()=>Y(!1)),G.listen(X,"0.0.0.0",()=>{G.close(()=>Y(!0))})})}async function wA1(X){if(await Di5(X))return X;let Y=await new Promise((G,Q)=>{let J=$s6();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 VN0=()=>{};var jN0={};R0(jN0,{startDevServer:()=>Li5});import{join as wi5}from"path";function Ks6(X){return X.replace(/\x1b\[[0-9;]*m/g,"")}function Hs6(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 $=Ks6(Z).replace(/^\[\d+\]\s*/,"").trim();if(!$)continue;LK({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=Ks6(Q).replace(/^\[\d+\]\s*/,"").trim();if(W)LK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:W})}})()}async function Li5(X){let{vitePort:Y,baseUrl:G,noTui:Q}=X,J=await wA1(Number(X.port)),{settings:W,services:Z,managedServiceNames:$}=await DA1({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)Nd({name:z.name,status:"ready",port:z.port});Te(W),qe();let K=wi5(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)Hs6(U.stdout),Hs6(U.stderr);let N=G||`http://localhost:${W.port}`;Ae(N),Nd({name:"Vite",status:"ready",port:Number(Y)});let B=async(z)=>{if(U.kill(z),$.length>0){let{stopServices:O}=await Promise.resolve().then(() => (H$1(),K$1));await O(W.dataDir)}};return process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM")),{port:Number(W.port),process:U}}var MN0=D(()=>{IN0();YF();VN0()});import{Box as RN0,Text as SN0}from"ink";import{jsx as Us6,jsxs as LA1}from"react/jsx-runtime";function Fs6(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 qi5(X,Y){if(Ei5.has(X))return Y?{text:"\u25CF\u25CF\u25CF\u25CF\u25CF\u25CF",dimColor:!0}:{text:"not set",dimColor:!0};if(Pi5.has(X)){if(Array.isArray(Y)){if(Y.length===0)return{text:"not set",dimColor:!0};return{text:Y.map((W)=>Fs6(W)).join(", "),color:"cyan"}}let Q=Fs6(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 Ai5(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 Ns6({env:X}){let Y=Ai5(X);return Us6(RN0,{flexDirection:"column",children:Y.map((G)=>LA1(RN0,{flexDirection:"column",marginTop:1,children:[LA1(SN0,{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=qi5(Q,J);return LA1(RN0,{children:[LA1(SN0,{dimColor:!0,children:[" ",Q.padEnd(36)]}),Us6(SN0,{color:W.color,dimColor:W.dimColor,children:W.text})]},Q)})]},G.title))})}var Ei5,Pi5;var Bs6=D(()=>{Ei5=new Set(["BETTER_AUTH_SECRET","ENCRYPTION_KEY","MESH_JWT_SECRET","STUDIO_PROVISION_SECRET_KEY"]),Pi5=new Set(["DATABASE_URL","CLICKHOUSE_URL","NATS_URL"])});var CN0;var zs6=D(()=>{CN0={name:"decocms",version:"2.288.0",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/mesh"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:'bun run migrate && concurrently "bun run dev:client" "bun run dev:server"',"dev:servers":'concurrently "bun run dev:client" "bun run dev:server"',"dev:client":"bun --bun vite dev","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts","build:client":"bun --bun vite build","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","db:migrate":"bun run ./dist/server/migrate.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts",test:"bun test","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run build:client && bun run build:server"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1","@freestyle-sh/with-bun":"^0.2.12","@freestyle-sh/with-deno":"^0.0.4","@freestyle-sh/with-nodejs":"^0.2.9","freestyle-sandboxes":"^0.1.46"},dependencies:{"@ai-sdk/anthropic":"^3.0.58","@ai-sdk/google":"^3.0.60","@ai-sdk/openai":"^3.0.50","@anthropic-ai/sdk":"^0.79.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dnd-kit/core":"^6.3.1","@dnd-kit/sortable":"^10.0.0","@dnd-kit/utilities":"^3.2.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/ext-apps":"^1.2.2","@openrouter/ai-sdk-provider":"^2.2.5","@opentelemetry/core":"^2.6.0","@tanstack/react-virtual":"^3.13.21","@xterm/addon-fit":"^0.11.0","@xterm/xterm":"^6.0.0","ai-sdk-provider-claude-code":"^3.4.4","ai-sdk-provider-codex-cli":"^1.1.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12",nats:"^2.29.3","posthog-js":"^1.371.1","posthog-node":"^5.0.0",react:"^19.2.0","react-dom":"^19.2.0"},devDependencies:{"@ai-sdk/provider":"^3.0.8","@ai-sdk/react":"^3.0.118","@anthropic-ai/claude-agent-sdk":"^0.2.80","@better-auth/sso":"1.4.1","@daveyplate/better-auth-ui":"^3.2.7","@deco/ui":"workspace:*","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/mesh-sdk":"workspace:*","@decocms/runtime":"workspace:*","@decocms/vite-plugin":"workspace:*","@electric-sql/pglite":"^0.3.15","@floating-ui/react":"^0.27.16","@hookform/resolvers":"^5.2.2","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.27.1","@monaco-editor/react":"^4.7.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@playwright/test":"^1.58.2","@radix-ui/react-avatar":"^1.1.10","@radix-ui/react-checkbox":"^1.3.3","@radix-ui/react-dialog":"^1.1.15","@radix-ui/react-dropdown-menu":"^2.1.16","@radix-ui/react-label":"^2.1.7","@radix-ui/react-select":"^2.2.6","@radix-ui/react-separator":"^1.1.7","@radix-ui/react-slot":"^1.2.3","@radix-ui/react-tabs":"^1.1.13","@rjsf/core":"^6.1.2","@rjsf/shadcn":"^6.1.2","@rjsf/utils":"^6.1.2","@rjsf/validator-ajv8":"^6.1.2","@tailwindcss/vite":"^4.1.17","@tanstack/react-query":"5.90.11","@tanstack/react-router":"^1.139.7","@tiptap/core":"3.20.2","@tiptap/extension-mention":"3.20.2","@tiptap/extension-placeholder":"3.20.2","@tiptap/pm":"3.20.2","@tiptap/react":"3.20.2","@tiptap/starter-kit":"3.20.2","@tiptap/suggestion":"3.20.2","@types/bun":"^1.3.1","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@untitledui/icons":"^0.0.19","@vercel/nft":"^1.1.1","@vitejs/plugin-react":"^5.1.0",ai:"^6.0.116","babel-plugin-react-compiler":"^1.0.0","better-auth":"1.4.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",concurrently:"^9.2.1",croner:"^9.1.0","date-fns":"^4.1.0",degit:"^2.8.4",hono:"^4.10.7","input-otp":"^1.4.2",jose:"^6.0.11","kysely-pglite":"^0.6.1","lucide-react":"^0.468.0",marked:"^15.0.6","@decocms/sandbox":"workspace:*","mesh-plugin-workflows":"workspace:*",nanoid:"^5.1.6",pg:"^8.16.3",prettier:"^3.4.2","react-hook-form":"^7.66.0","react-markdown":"^10.1.0","react-resizable-panels":"^2.1.7","react-syntax-highlighter":"^15.6.1",recharts:"^3.6.0","rehype-raw":"^7.0.0","remark-gfm":"^4.0.0","sass-embedded":"^1.97.2",sonner:"^2.0.7","tailwind-merge":"^3.3.1",tailwindcss:"^4.1.17",typescript:"^5.9.3",vite:"^7.2.1","vite-tsconfig-paths":"^5.1.4",zod:"^4.0.0",zustand:"^5.0.9"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","mesh","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as qU,Text as MX}from"ink";import{Spinner as Ii5}from"@inkjs/ui";import{useSyncExternalStore as Os6}from"react";import{jsx as qY,jsxs as tQ}from"react/jsx-runtime";function Si5(X,Y){if(!X||!Ri5.has(X))return X;let G=kN0[Y]??kN0[kN0.length-1];return X==="#875f00"?G[0]:G[1]}function Ds6({status:X}){if(X==="pending")return qY(Ii5,{label:""});return qY(MX,{color:"green",children:"\u2713"})}function ws6({services:X,migrationsStatus:Y,home:G,serverUrl:Q,vibe:J}){let W=Os6(Tu0,Au0),Z=Os6(Su0,Ru0);return tQ(qU,{flexDirection:"column",paddingBottom:1,children:[J?tQ(qU,{flexDirection:"column",children:[W.map(($,K)=>{let H=Z[K],U=$.reduce((B,z)=>B+z.text.length,0),N=Math.max(0,Mi5-U);return tQ(qU,{flexDirection:"row",children:[$.map((B,z)=>{let O=Si5(B.color,K);return O?qY(MX,{color:O,children:B.text},z):qY(MX,{children:B.text},z)}),qY(MX,{children:" ".repeat(N+2)}),H?.map((B,z)=>B.color?qY(MX,{color:B.color,children:B.char},z):qY(MX,{children:B.char},z))]},K)}),tQ(MX,{dimColor:!0,children:[" v",CN0.version]})]}):tQ(qU,{flexDirection:"column",marginTop:1,children:[Vi5.map(($,K)=>qY(MX,{color:ji5[K],children:$},K)),tQ(MX,{dimColor:!0,children:[" v",CN0.version]})]}),qY(qU,{marginBottom:1,children:qY(MX,{dimColor:!0,children:"\u2500".repeat(80)})}),qY(qU,{children:tQ(MX,{dimColor:!0,children:["Home: ",G]})}),tQ(qU,{gap:2,children:[X.map(($)=>tQ(qU,{gap:1,children:[tQ(MX,{children:[$.name," :",$.port||"...."]}),qY(Ds6,{status:$.status})]},$.name)),tQ(qU,{gap:1,children:[qY(MX,{children:"Migrations"}),qY(Ds6,{status:Y})]})]}),qY(qU,{children:Q?tQ(MX,{children:["Open in browser: ",qY(MX,{color:"cyan",children:Q})]}):qY(MX,{dimColor:!0,children:"Starting..."})}),tQ(qU,{gap:2,children:[tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"K"})," ","toggle config"]}),tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"L"})," ","toggle log flow"]}),tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"V"})," ","toggle vibe ",J?"\u266A Nihilore \xB7 CC BY 4.0":""]}),J&&tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"N"})," ","skip song"]})]})]})}var Vi5,ji5,kN0,Mi5=30,Ri5;var Ls6=D(()=>{zs6();Bn1();En1();Vi5=[" \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 "],ji5=["#00ff64","#00ee5e","#00dc56","#00c84e","#00b444","#00a03c","#008832","#006e28"],kN0=[["#00ff64","#00cc50"],["#00f060","#00c04c"],["#00e05c","#00b448"],["#00d058","#00a844"],["#00c054","#009c40"],["#00b050","#00903c"],["#00a04c","#008438"],["#009048","#007834"],["#008044","#006c30"],["#007040","#00602c"],["#00603c","#005428"]],Ri5=new Set(["#875f00","#5f3800"])});import{useSyncExternalStore as Ci5}from"react";function ki5(){let X=process.stdout.rows||24,Y=process.stdout.columns||80;if(X!==EA1.rows||Y!==EA1.columns)EA1={rows:X,columns:Y};return EA1}function vi5(X){return process.stdout.on("resize",X),()=>{process.stdout.off("resize",X)}}function Es6(){return Ci5(vi5,ki5)}var EA1;var Ps6=D(()=>{EA1={rows:process.stdout.rows||24,columns:process.stdout.columns||80}});import{Box as _i5,Text as qX1}from"ink";import{useSyncExternalStore as fi5}from"react";import{jsx as vN0,jsxs as _N0}from"react/jsx-runtime";function bi5(X){if(X>=500)return"red";if(X>=400)return"yellow";if(X>=300)return"cyan";return"green"}function qs6({logs:X,headerHeight:Y}){let{rows:G}=Es6(),{logFlow:Q}=fi5(Pe,Ee),J=Math.max(1,G-Y-1),W=Q?X:X.slice(-J);return vN0(_i5,{flexDirection:"column",children:W.map((Z,$)=>{if(Z.rawLine)return vN0(qX1,{dimColor:!0,children:Z.rawLine},$);let K=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return _N0(qX1,{children:[_N0(qX1,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),vN0(qX1,{color:bi5(Z.status),children:Z.status}),_N0(qX1,{dimColor:!0,children:[" ",K.padStart(8)]})]},$)})})}var As6=D(()=>{YF();Ps6()});var fN0={};R0(fN0,{App:()=>mi5});import{Box as yi5,Text as xi5,useInput as hi5}from"ink";import{useSyncExternalStore as gi5}from"react";import{jsx as PA1,jsxs as di5}from"react/jsx-runtime";function mi5({home:X}){let Y=gi5(Pe,Ee);return hi5((G)=>{if(G==="k"||G==="K")Vn1();if(G==="l"||G==="L")jn1();if((G==="v"||G==="V")&&Y.dataDir)Tn1(Y.dataDir),Mn1();if((G==="n"||G==="N")&&Y.vibe)An1()}),di5(yi5,{flexDirection:"column",children:[PA1(ws6,{services:Y.services,migrationsStatus:Y.migrationsStatus,home:X,serverUrl:Y.serverUrl,vibe:Y.vibe}),Y.viewMode==="config"?Y.env?PA1(Ns6,{env:Y.env}):PA1(xi5,{dimColor:!0,children:"Loading configuration..."}):PA1(qs6,{logs:Y.logs,headerHeight:Y.vibe?li5:ui5})]})}var ui5=15,li5=19;var bN0=D(()=>{Bs6();Ls6();As6();YF();Ud()});function Ts6(X,Y={}){return{PORT:String(X.port),NODE_ENV:X.nodeEnv,BASE_URL:X.baseUrl,DATA_DIR:X.dataDir,DECOCMS_HOME:X.dataDir,DATABASE_URL:X.databaseUrl,DATABASE_PG_SSL:String(X.databasePgSsl),DATABASE_POOL_MAX:String(X.databasePoolMax),NATS_URL:X.natsUrls.join(","),BETTER_AUTH_SECRET:X.betterAuthSecret,ENCRYPTION_KEY:X.encryptionKey,MESH_JWT_SECRET:X.meshJwtSecret,DECOCMS_LOCAL_MODE:String(X.localMode),DECOCMS_ALLOW_LOCAL_PROD:String(X.allowLocalProd),DISABLE_RATE_LIMIT:String(X.disableRateLimit),STUDIO_PROVISION_SECRET_KEY:X.studioProvisionSecretKey,CONFIG_PATH:X.configPath,...Object.fromEntries(Object.entries(process.env).filter(([G])=>G.startsWith("AUTH_"))),UNSAFE_ALLOW_STDIO_TRANSPORT:String(X.unsafeAllowStdioTransport),DECO_AI_GATEWAY_ENABLED:String(X.aiGatewayEnabled),DECO_AI_GATEWAY_URL:X.aiGatewayUrl,ENABLE_DECO_IMPORT:String(X.enableDecoImport),S3_ENDPOINT:X.s3Endpoint,S3_BUCKET:X.s3Bucket,S3_REGION:X.s3Region,S3_ACCESS_KEY_ID:X.s3AccessKeyId,S3_SECRET_ACCESS_KEY:X.s3SecretAccessKey,S3_FORCE_PATH_STYLE:String(X.s3ForcePathStyle),OTEL_SERVICE_NAME:X.otelServiceName,CLICKHOUSE_URL:X.clickhouseUrl,DECO_SUPABASE_URL:X.decoSupabaseUrl,DECO_SUPABASE_SERVICE_KEY:X.decoSupabaseServiceKey,FIRECRAWL_API_KEY:X.firecrawlApiKey,STUDIO_SANDBOX_RUNNER:process.env.STUDIO_SANDBOX_RUNNER,STUDIO_SANDBOX_TEMPLATE_NAME:process.env.STUDIO_SANDBOX_TEMPLATE_NAME,FREESTYLE_API_KEY:process.env.FREESTYLE_API_KEY,BROWSERLESS_TOKEN:process.env.BROWSERLESS_TOKEN,NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS,DECO_CLI:"1",DECO_NO_TUI:"true",...Y}}function Vs6(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 Is6="https://studio.decocms.com/org/deco/registry/mcp";var yN0=(X,Y,G)=>{return(Q,J)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,U;if(X[$])U=X[$][0][0],Q.req.routeIndex=$;else U=$===X.length&&J||void 0;if(U)try{K=await U(Q,()=>Z($+1))}catch(N){if(N instanceof Error&&Y)Q.error=N,K=await Y(N,Q),H=!0;else throw N}else if(Q.finalized===!1&&G)K=await G(Q);if(K&&(Q.finalized===!1||H))Q.res=K;return Q}}};var js6=()=>{};var M9;var Lq=D(()=>{M9=class extends Error{res;status;constructor(X=500,Y){super(Y?.message,{cause:Y?.cause});this.res=Y?.res,this.status=X}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var Ms6;var Rs6=D(()=>{Ms6=Symbol()});async function ci5(X,Y){let G=await X.formData();if(G)return ii5(G,Y);return{}}function ii5(X,Y){let G=Object.create(null);if(X.forEach((Q,J)=>{if(!(Y.all||J.endsWith("[]")))G[J]=Q;else pi5(G,J,Q)}),Y.dot)Object.entries(G).forEach(([Q,J])=>{if(Q.includes("."))ni5(G,Q,J),delete G[Q]});return G}var Ss6=async(X,Y=Object.create(null))=>{let{all:G=!1,dot:Q=!1}=Y,W=(X instanceof qA1?X.raw.headers:X.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return ci5(X,{all:G,dot:Q});return{}},pi5=(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]},ni5=(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 Cs6=D(()=>{xN0()});var gN0=(X)=>{let Y=X.split("/");if(Y[0]==="")Y.shift();return Y},ks6=(X)=>{let{groups:Y,path:G}=ai5(X),Q=gN0(G);return ti5(Q,Y)},ai5=(X)=>{let Y=[];return X=X.replace(/\{[^}]+\}/g,(G,Q)=>{let J=`@${Q}`;return Y.push([J,G]),J}),{groups:Y,path:X}},ti5=(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},AA1,vs6=(X,Y)=>{if(X==="*")return"*";let G=X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(G){let Q=`${X}#${Y}`;if(!AA1[Q])if(G[2])AA1[Q]=Y&&Y[0]!==":"&&Y[0]!=="*"?[Q,G[1],new RegExp(`^${G[2]}(?=/${Y})`)]:[X,G[1],new RegExp(`^${G[2]}$`)];else AA1[Q]=[X,G[1],!0];return AA1[Q]}return null},la=(X,Y)=>{try{return Y(X)}catch{return X.replace(/(?:%[0-9A-Fa-f]{2})+/g,(G)=>{try{return Y(G)}catch{return G}})}},_s6=(X)=>la(X,decodeURI),uN0=(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 _s6(K.includes("%25")?K.replace(/%25/g,"%2525"):K)}else if(J===63||J===35)break}return Y.slice(G,Q)},fs6=(X)=>{let Y=uN0(X);return Y.length>1&&Y.at(-1)==="/"?Y.slice(0,-1):Y},Pj=(X,Y,...G)=>{if(G.length)Y=Pj(Y,...G);return`${X?.[0]==="/"?"":"/"}${X}${Y==="/"?"":`${X?.at(-1)==="/"?"":"/"}${Y?.[0]==="/"?Y.slice(1):Y}`}`},TA1=(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)},hN0=(X)=>{if(!/[%+]/.test(X))return X;if(X.indexOf("+")!==-1)X=X.replace(/\+/g," ");return X.indexOf("%")!==-1?la(X,AX1):X},bs6=(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 hN0(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=hN0(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=X.slice($+1,Z===-1?void 0:Z),Q)H=hN0(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},ys6,xs6=(X,Y)=>{return bs6(X,Y,!0)},AX1;var Eq=D(()=>{AA1={},ys6=bs6,AX1=decodeURIComponent});var hs6=(X)=>la(X,AX1),qA1;var xN0=D(()=>{Lq();Rs6();Cs6();Eq();qA1=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)?hs6(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)?hs6(Q):Q}return X}#J(X){return this.#Y[1]?this.#Y[1][X]:X}query(X){return ys6(this.url,X)}queries(X){return xs6(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 Ss6(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[Ms6](){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 IA1,gs6=(X,Y)=>{let G=new String(X);return G.isEscaped=!0,G.callbacks=Y,G},TX1=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)=>TX1(K,Y,!1,Q,J))).then(()=>J[0]));if(G)return gs6(await Z,W);else return Z};var VA1=D(()=>{IA1={Stringify:1,BeforeStream:2,Stream:3}});var us6="text/plain; charset=UTF-8",lN0=(X,Y)=>{return{"Content-Type":X,...Y}},IX1=(X,Y)=>new Response(X,Y),ls6=class{#X;#Y;env={};#G;finalized=!1;error;#Q;#J;#Z;#$;#W;#K;#H;#U;#N;constructor(X,Y){if(this.#X=X,Y)this.#J=Y.executionCtx,this.env=Y.env,this.#K=Y.notFoundHandler,this.#N=Y.path,this.#U=Y.matchResult}get req(){return this.#Y??=new qA1(this.#X,this.#N,this.#U),this.#Y}get event(){if(this.#J&&"respondWith"in this.#J)return this.#J;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#J)return this.#J;else throw Error("This context has no ExecutionContext")}get res(){return this.#Z||=IX1(null,{headers:this.#H??=new Headers})}set res(X){if(this.#Z&&X){X=IX1(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=IX1(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 IX1(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,lN0(us6,G))};json=(X,Y,G)=>{return this.#F(JSON.stringify(X),Y,lN0("application/json",G))};html=(X,Y,G)=>{let Q=(J)=>this.#F(J,Y,lN0("text/html; charset=UTF-8",G));return typeof X==="object"?TX1(X,IA1.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??=()=>IX1(),this.#K(this)}};var jA1=D(()=>{xN0();VA1()});var T7="ALL",ms6="all",ds6,MA1="Can not add a route since the matcher is already built.",RA1;var Pq=D(()=>{ds6=["get","post","put","delete","options","patch"],RA1=class extends Error{}});var mN0="__COMPOSED_HANDLER";var dN0=()=>{};var ri5=(X)=>{return X.text("404 Not Found",404)},cs6=(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)},is6=class X{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#X="/";routes=[];constructor(Y={}){[...ds6,ms6].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??uN0:fs6}#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=ri5;errorHandler=cs6;route(Y,G){let Q=this.basePath(Y);return G.routes.map((J)=>{let W;if(G.errorHandler===cs6)W=J.handler;else W=async(Z,$)=>(await yN0([],G.errorHandler)(Z,()=>J.handler(Z,$))).res,W[mN0]=J.handler;Q.#Q(J.method,J.path,W)}),this}basePath(Y){let G=this.#Y();return G._basePath=Pj(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=Pj(this._basePath,Y),H=K==="/"?0:K.length;return(U)=>{let N=new URL(U.url);return N.pathname=N.pathname.slice(H)||"/",new Request(N,U)}})();let $=async(K,H)=>{let U=await G(J(K.req.raw),...Z(K));if(U)return U;await H()};return this.#Q(T7,Pj(Y,"*"),$),this}#Q(Y,G,Q){Y=Y.toUpperCase(),G=Pj(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 ls6(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=yN0(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${Pj("/",Y)}`,G),Q,J)};fire=()=>{addEventListener("fetch",(Y)=>{Y.respondWith(this.#Z(Y.request,Y,void 0,Y.request.method))})}};var ps6=D(()=>{js6();jA1();Pq();dN0();Eq()});function SA1(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[[],VX1];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=Q,Q(X,Y)}var VX1;var cN0=D(()=>{Pq();VX1=[]});function si5(X,Y){if(X.length===1)return Y.length===1?X<Y?-1:1:-1;if(Y.length===1)return 1;if(X===jX1||X===MX1)return 1;else if(Y===jX1||Y===MX1)return-1;if(X===CA1)return 1;else if(Y===CA1)return-1;return X.length===Y.length?X<Y?-1:1:Y.length-X.length}var CA1="[^/]+",jX1=".*",MX1="(?:|/.*)",qj,oi5,ns6=class X{#X;#Y;#G=Object.create(null);insert(Y,G,Q,J,W){if(Y.length===0){if(this.#X!==void 0)throw qj;if(W)return;this.#X=G;return}let[Z,...$]=Y,K=Z==="*"?$.length===0?["","",jX1]:["","",CA1]:Z==="/*"?["","",MX1]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let U=K[1],N=K[2]||CA1;if(U&&K[2]){if(N===".*")throw qj;if(N=N.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(N))throw qj}if(H=this.#G[N],!H){if(Object.keys(this.#G).some((B)=>B!==jX1&&B!==MX1))throw qj;if(W)return;if(H=this.#G[N]=new X,U!=="")H.#Y=J.varIndex++}if(!W&&U!=="")Q.push([U,H.#Y])}else if(H=this.#G[Z],!H){if(Object.keys(this.#G).some((U)=>U.length>1&&U!==jX1&&U!==MX1))throw qj;if(W)return;H=this.#G[Z]=new X}H.insert($,G,Q,J,W)}buildRegExpStr(){let G=Object.keys(this.#G).sort(si5).map((Q)=>{let J=this.#G[Q];return(typeof J.#Y==="number"?`(${Q})@${J.#Y}`:oi5.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 iN0=D(()=>{qj=Symbol(),oi5=new Set(".\\+*[^]$()")});var as6=class{#X={varIndex:0};#Y=new ns6;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 ts6=D(()=>{iN0()});function os6(X){return rs6[X]??=new RegExp(X==="*"?"":`^${X.replace(/\/\*$|([.\\+*[^\]$()])/g,(Y,G)=>G?`\\${G}`:"(?:|/.*)")}$`)}function Xp5(){rs6=Object.create(null)}function Yp5(X){let Y=new as6,G=[];if(X.length===0)return ei5;let Q=X.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,U],[N,B])=>H?1:N?-1:U.length-B.length),J=Object.create(null);for(let H=0,U=-1,N=Q.length;H<N;H++){let[B,z,O]=Q[H];if(B)J[z]=[O.map(([E])=>[E,Object.create(null)]),VX1];else U++;let w;try{w=Y.insert(z,U,B)}catch(E){throw E===qj?new RA1(z):E}if(B)continue;G[U]=O.map(([E,P])=>{let q=Object.create(null);P-=1;for(;P>=0;P--){let[j,M]=w[P];q[j]=M}return[E,q]})}let[W,Z,$]=Y.buildRegExp();for(let H=0,U=G.length;H<U;H++)for(let N=0,B=G[H].length;N<B;N++){let z=G[H][N]?.[1];if(!z)continue;let O=Object.keys(z);for(let w=0,E=O.length;w<E;w++)z[O[w]]=$[z[O[w]]]}let K=[];for(let H in Z)K[H]=G[Z[H]];return[W,K,J]}function ma(X,Y){if(!X)return;for(let G of Object.keys(X).sort((Q,J)=>J.length-Q.length))if(os6(G).test(Y))return[...X[G]];return}var ei5,rs6,kA1=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(MA1);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 $=os6(Y);if(X===T7)Object.keys(Q).forEach((K)=>{Q[K][Y]||=ma(Q[K],Y)||ma(Q[T7],Y)||[]});else Q[X][Y]||=ma(Q[X],Y)||ma(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=TA1(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]||=[...ma(Q[U],H)||ma(Q[T7],H)||[]],J[U][H].push([G,W-K+$+1])})}}match=SA1;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,Xp5(),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 pN0=D(()=>{Pq();Eq();cN0();iN0();ts6();ei5=[/^$/,[],Object.create(null)],rs6=Object.create(null)});var Gp5=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(),VX1];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=SA1};var ss6=D(()=>{Pq();cN0();pN0()});var es6=D(()=>{pN0();ss6()});var nN0=class{name="SmartRouter";#X=[];#Y=[];constructor(X){this.#X=X.routers}add(X,Y,G){if(!this.#Y)throw Error(MA1);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 RA1)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 Xe6=D(()=>{Pq()});var Ye6=D(()=>{Xe6()});var RX1,Qp5=(X)=>{for(let Y in X)return!0;return!1},Ge6=class X{#X;#Y;#G;#Q=0;#J=RX1;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=ks6(G),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],U=W[$+1],N=vs6(H,U),B=Array.isArray(N)?N[0]:H;if(B in J.#Y){if(J=J.#Y[B],N)Z.push(N[1]);continue}if(J.#Y[B]=new X,N)J.#G.push(N),Z.push(N[1]);J=J.#Y[B]}return J.#X.push({[Y]:{handler:Q,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#Q}}),J}#Z(Y,G,Q,J,W){for(let Z=0,$=G.#X.length;Z<$;Z++){let K=G.#X[Z],H=K[Q]||K[T7],U={};if(H!==void 0){if(H.params=Object.create(null),Y.push(H),J!==RX1||W&&W!==RX1)for(let N=0,B=H.possibleKeys.length;N<B;N++){let z=H.possibleKeys[N],O=U[H.score];H.params[z]=W?.[z]&&!O?W[z]:J[z]??W?.[z],U[H.score]=!0}}}}search(Y,G){let Q=[];this.#J=RX1;let W=[this],Z=gN0(G),$=[],K=Z.length,H=null;for(let U=0;U<K;U++){let N=Z[U],B=U===K-1,z=[];for(let w=0,E=W.length;w<E;w++){let P=W[w],q=P.#Y[N];if(q)if(q.#J=P.#J,B){if(q.#Y["*"])this.#Z(Q,q.#Y["*"],Y,P.#J);this.#Z(Q,q,Y,P.#J)}else z.push(q);for(let j=0,M=P.#G.length;j<M;j++){let V=P.#G[j],R=P.#J===RX1?{}:{...P.#J};if(V==="*"){let h=P.#Y["*"];if(h)this.#Z(Q,h,Y,P.#J),h.#J=R,z.push(h);continue}let[k,_,v]=V;if(!N&&!(v instanceof RegExp))continue;let y=P.#Y[k];if(v instanceof RegExp){if(H===null){H=Array(K);let p=G[0]==="/"?1:0;for(let f=0;f<K;f++)H[f]=p,p+=Z[f].length+1}let h=G.substring(H[U]),i=v.exec(h);if(i){if(R[_]=i[0],this.#Z(Q,y,Y,P.#J,R),Qp5(y.#Y)){y.#J=R;let p=i[0].match(/\//)?.length??0;($[p]||=[]).push(y)}continue}}if(v===!0||v.test(N))if(R[_]=N,B){if(this.#Z(Q,y,Y,R,P.#J),y.#Y["*"])this.#Z(Q,y.#Y["*"],Y,R,P.#J)}else y.#J=R,z.push(y)}}let O=$.shift();W=O?z.concat(O):z}if(Q.length>1)Q.sort((U,N)=>{return U.score-N.score});return[Q.map(({handler:U,params:N})=>[U,N])]}};var Qe6=D(()=>{Pq();Eq();RX1=Object.create(null)});var aN0=class{name="TrieRouter";#X;constructor(){this.#X=new Ge6}add(X,Y,G){let Q=TA1(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 Je6=D(()=>{Eq();Qe6()});var Ze6=D(()=>{Je6()});var R5;var We6=D(()=>{ps6();es6();Ye6();Ze6();R5=class extends is6{constructor(X={}){super(X);this.router=X.router??new nN0({routers:[new kA1,new aN0]})}}});var JQ=D(()=>{We6()});var Ke6,Jp5,$e6=(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)},tN0=(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=$e6(J.substring(0,W));if(Y&&Y!==Z||!Ke6.test(Z))continue;let $=$e6(J.substring(W+1));if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(Jp5.test($)){if(Q[Z]=$.indexOf("%")!==-1?la($,AX1):$,Y)break}}return Q},Zp5=(X,Y,G={})=>{if(!Ke6.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},vA1=(X,Y,G)=>{return Y=encodeURIComponent(Y),Zp5(X,Y,G)};var He6=D(()=>{Eq();Ke6=/^[\w!#$%&'*.^`|~+-]+$/,Jp5=/^[ !#-:<-[\]-~]*$/});var _A1=(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 tN0(Q,W)[W]}if(!Q)return{};return tN0(Q)},Wp5=(X,Y,G)=>{let Q;if(G?.prefix==="secure")Q=vA1("__Secure-"+X,Y,{path:"/",...G,secure:!0});else if(G?.prefix==="host")Q=vA1("__Host-"+X,Y,{...G,path:"/",secure:!0,domain:void 0});else Q=vA1(X,Y,{path:"/",...G});return Q},rN0=(X,Y,G,Q)=>{let J=Wp5(Y,G,Q);X.header("Set-Cookie",J,{append:!0})};var oN0=D(()=>{He6()});var Fe6=(X)=>{let G={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...X},Q=((W)=>{if(typeof W==="string")if(W==="*"){if(G.credentials)return(Z)=>Z||null;return()=>W}else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(G.origin),J=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(G.allowMethods);return async function(Z,$){function K(U,N){Z.res.headers.set(U,N)}let H=await Q(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(G.credentials)K("Access-Control-Allow-Credentials","true");if(G.exposeHeaders?.length)K("Access-Control-Expose-Headers",G.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(G.origin!=="*"||G.credentials)K("Vary","Origin");if(G.maxAge!=null)K("Access-Control-Max-Age",G.maxAge.toString());let U=await J(Z.req.header("origin")||"",Z);if(U.length)K("Access-Control-Allow-Methods",U.join(","));let N=G.allowHeaders;if(!N?.length){let B=Z.req.header("Access-Control-Request-Headers");if(B)N=B.split(/\s*,\s*/)}if(N?.length)K("Access-Control-Allow-Headers",N.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),G.origin!=="*"||G.credentials)Z.header("Vary","Origin",{append:!0})}};var Ue6=()=>{};var Ne6=()=>{try{return performance.now()}catch{}return Date.now()},sN0=(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)zH(Q,"total",Y.totalDescription);if(await J(),Y.total)h$(Q,"total");if(Y.autoEnd)Z.forEach((K,H)=>h$(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:"*")}}},Be6=(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)}},zH=(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:Ne6()})},h$=(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,$=Ne6()-Z;Be6(X,Y,$,W,G),Q.timers.delete(Y)};var ze6=D(()=>{jA1()});var eN0=D(()=>{ze6()});function SX1(){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 XB0)X[Y.category]?.push(Y);return X}var XB0;var YB0=D(()=>{XB0=[{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 Oe6=D(()=>{ni();dz1()});function De6(){return Kp5.parse(process.env)}var GB0=(X)=>F.enum(["true","false","1","0"]).optional().transform((Y)=>Y===void 0?X:Y==="true"||Y==="1"),$p5=(X)=>F.string().optional().transform((Y)=>Y?Y.split(",").map((G)=>G.trim()):X),Kp5;var we6=D(()=>{H0();Kp5=F.object({AUTH_EMAIL_PASSWORD_ENABLED:GB0(!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:GB0(!1),AUTH_MAGIC_LINK_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_ENABLED:GB0(!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:$p5(["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 fA1;var Le6=D(()=>{fA1={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"}});import{existsSync as Hp5,readFileSync as Fp5}from"fs";function Up5(){let X=De6(),Y=v6().configPath;if(!Hp5(Y))return{auth:X,monitoring:fA1};try{let G=JSON.parse(Fp5(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??fA1,theme:G.theme,logo:G.logo,autoCreateOrganizationOnSignup:G.autoCreateOrganizationOnSignup}}catch{return{auth:X,monitoring:fA1}}}function Aj(){if(!QB0)QB0=Up5();return QB0}function Ee6(){return Aj().theme}var QB0=null;var JB0=D(()=>{we6();Le6();m9()});import{dirname as Np5,posix as Bp5,sep as zp5}from"path";function qe6(){let X=Op5();return async(Y)=>{for(let G of Y)G.module=X(G.filename);return Y}}function Op5(X=process.argv[1]?Np5(process.argv[1]):process.cwd(),Y=zp5==="\\"){let G=Y?Pe6(X):X;return(Q)=>{if(!Q)return;let J=Y?Pe6(Q):Q,{dir:W,base:Z,ext:$}=Bp5.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 Pe6(X){return X.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Ae6=()=>{};function Dp5(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 ZB0=(X)=>{if("flags"in X){let Y=Te6(X.flags),G=Ie6(X.flags);return{...X,featureFlags:Y,featureFlagPayloads:G}}{let Y=X.featureFlags??{},G=Object.fromEntries(Object.entries(X.featureFlagPayloads||{}).map(([J,W])=>[J,WB0(W)])),Q=Object.fromEntries(Object.entries(Y).map(([J,W])=>[J,Dp5(J,W,G[J])]));return{...X,featureFlags:Y,featureFlagPayloads:G,flags:Q}}},Te6=(X)=>Object.fromEntries(Object.entries(X??{}).map(([Y,G])=>[Y,CX1(G)]).filter(([,Y])=>Y!==void 0)),Ie6=(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?WB0(Q):void 0]}))},CX1=(X)=>X===void 0?void 0:X.variant??X.enabled,WB0=(X)=>{if(typeof X!="string")return X;try{return JSON.parse(X)}catch{return X}};var bA1=()=>{};function Ve6(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}async function yA1(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 $B0=()=>{};var wp5,je6=function(X,Y=[]){if(!X)return!1;let G=X.toLowerCase();return wp5.concat(Y).some((Q)=>{let J=Q.toLowerCase();return G.indexOf(J)!==-1})};var Me6=D(()=>{wp5=["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 pJ;var Tj=D(()=>{pJ=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 xA1=()=>{};function gA1(X){return X===null||typeof X!="object"}function Ij(X,Y){return Object.prototype.toString.call(X)===`[object ${Y}]`}function Ce6(X){return Ij(X,"ErrorEvent")}function ca(X){return typeof Event<"u"&&Pp5(X,Event)}function ke6(X){return Ij(X,"Object")}function Pp5(X,Y){try{return X instanceof Y}catch{return!1}}var Ep5,Re6,AlX,KB0,hA1,kX1=(X)=>X===Object(X)&&!hA1(X),da=(X)=>X===void 0,qq=(X)=>KB0.call(X)=="[object String]",Se6=(X)=>qq(X)&&X.trim().length===0,vX1=(X)=>KB0.call(X)=="[object Number]"&&X===X,HB0=(X)=>X instanceof Error;var _X1=D(()=>{Tj();xA1();Ep5=Array.isArray,Re6=Object.prototype,AlX=Re6.hasOwnProperty,KB0=Re6.toString,hA1=Ep5||function(X){return KB0.call(X)==="[object Array]"}});function fX1(X,Y,G,Q,J){if(Y>G)Q.warn("min cannot be greater than max."),Y=G;if(vX1(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),fX1(J||G,Y,G,Q)}var FB0=D(()=>{_X1()});class UB0{constructor(X){this._buckets={},this._onBucketRateLimited=X._onBucketRateLimited,this._bucketSize=fX1(X.bucketSize,0,100,X._logger),this._refillRate=fX1(X.refillRate,0,this._bucketSize,X._logger),this._refillInterval=fX1(X.refillInterval,0,qp5,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 qp5=86400000;var ve6=D(()=>{FB0()});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 fe6{constructor(X){this.timestamp=0,this.counter=0,this.random=X??Ap5()}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 Ap5=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),_e6,Aq=()=>Tp5().toString(),Tp5=()=>(_e6||(_e6=new fe6)).generate();var bX1=D(()=>{/*! For license information please see uuidv7.mjs.LICENSE.txt */});class NB0{add(X){let Y=Aq();return this.promiseByIds[Y]=X,X.catch(()=>{}).finally(()=>{delete this.promiseByIds[Y]}),X}async join(){let X=Object.values(this.promiseByIds),Y=X.length;while(Y>0)await Promise.all(X),X=Object.values(this.promiseByIds),Y=X.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}}var be6=D(()=>{bX1()});function Ip5(X=console){return{log:X.log.bind(X),warn:X.warn.bind(X),error:X.error.bind(X),debug:X.debug.bind(X)}}function xe6(X,Y=Vp5){return ye6(X,Y,Ip5())}var ye6=(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)=>ye6(`${X} ${W}`,Y,G)}},Vp5=(X)=>X();var he6=()=>{};var pa="Mobile",lA1="iOS",ia="Android",ge6="Tablet",flX,Mp5="Apple",blX,ue6="Safari",mA1="BlackBerry",le6="Samsung",Rp5,Sp5,dA1="Chrome",Cp5,kp5,me6="Internet Explorer",vp5,zB0="Opera",ylX,de6="Edge",_p5,OB0="Firefox",fp5,DB0="Nintendo",wB0="PlayStation",uA1="Xbox",bp5,yp5,yX1="Windows",xp5,ce6="Generic",xlX,hlX,hp5="Konqueror",K3="(\\d+(\\.\\d+)?)",BB0,glX,ulX,llX,gp5,up5,mlX,dlX;var ie6=D(()=>{xA1();_X1();flX=ia+" "+ge6,blX=Mp5+" Watch",Rp5=le6+"Browser",Sp5=le6+" Internet",Cp5=dA1+" OS",kp5=dA1+" "+lA1,vp5=me6+" "+pa,ylX=zB0+" Mini",_p5="Microsoft "+de6,fp5=OB0+" "+lA1,bp5=ia+" "+pa,yp5=pa+" "+ue6,xp5=yX1+" Phone",xlX=ce6+" "+pa.toLowerCase(),hlX=ce6+" "+ge6.toLowerCase(),BB0=new RegExp("Version/"+K3),glX=new RegExp(uA1,"i"),ulX=new RegExp(wB0+" \\w+","i"),llX=new RegExp(DB0+" \\w+","i"),gp5=new RegExp(mA1+"|PlayBook|BB10","i"),up5={"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"},mlX={[vp5]:[new RegExp("rv:"+K3)],[_p5]:[new RegExp(de6+"?\\/"+K3)],[dA1]:[new RegExp("("+dA1+"|CrMo)\\/"+K3)],[kp5]:[new RegExp("CriOS\\/"+K3)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+K3)],[ue6]:[BB0],[yp5]:[BB0],[zB0]:[new RegExp("("+zB0+"|OPR)\\/"+K3)],[OB0]:[new RegExp(OB0+"\\/"+K3)],[fp5]:[new RegExp("FxiOS\\/"+K3)],[hp5]:[new RegExp("Konqueror[:/]?"+K3,"i")],[mA1]:[new RegExp(mA1+" "+K3),BB0],[bp5]:[new RegExp("android\\s"+K3,"i")],[Sp5]:[new RegExp(Rp5+"\\/"+K3)],[me6]:[new RegExp("(rv:|MSIE )"+K3)],Mozilla:[new RegExp("rv:"+K3)]},dlX=[[new RegExp(uA1+"; "+uA1+" (.*?)[);]","i"),(X)=>[uA1,X&&X[1]||""]],[new RegExp(DB0,"i"),[DB0,""]],[new RegExp(wB0,"i"),[wB0,""]],[gp5,[mA1,""]],[new RegExp(yX1,"i"),(X,Y)=>{if(/Phone/.test(Y)||/WPDesktop/.test(Y))return[xp5,""];if(new RegExp(pa).test(Y)&&!/IEMobile\b/.test(Y))return[yX1+" "+pa,""];let G=/Windows NT ([0-9.]+)/i.exec(Y);if(G&&G[1]){let Q=G[1],J=up5[Q]||"";if(/arm/i.test(Y))J="RT";return[yX1,J]}return[yX1,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(X)=>{if(X&&X[3]){let Y=[X[3],X[4],X[5]||"0"];return[lA1,Y.join(".")]}return[lA1,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(X)=>{let Y="";if(X&&X.length>=3)Y=da(X[2])?X[3]:X[2];return["watchOS",Y]}],[new RegExp("("+ia+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+ia+")","i"),(X)=>{if(X&&X[2]){let Y=[X[2],X[3],X[4]||"0"];return[ia,Y.join(".")]}return[ia,""]}],[/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/,[Cp5,""]],[/Linux|debian/i,["Linux",""]]]});function ne6(X){return X?.replace(/\/+$/,"")}async function ae6(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 cA1(){return new Date().toISOString()}function Kw(X,Y){let G=setTimeout(X,Y);return G?.unref&&G?.unref(),G}function LB0(X){return Promise.all(X.map((Y)=>(Y??Promise.resolve()).then((G)=>({status:"fulfilled",value:G}),(G)=>({status:"rejected",reason:G}))))}var pe6="utf8",te6=(X)=>X instanceof Error;var H3=D(()=>{Me6();ve6();FB0();xA1();_X1();be6();he6();ie6()});var lp5,QmX;var EB0=D(()=>{H3();lp5={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}},QmX=lp5.info});var re6=D(()=>{EB0();Tj()});var oe6=D(()=>{Tj()});class PB0{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 se6=()=>{};async function ee6(X){if(X instanceof na){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 qB0(X){return typeof X=="object"&&(X instanceof na||X instanceof xX1)}function X14(X){return typeof X=="object"&&X instanceof na&&X.status===413}class iA1{constructor(X,Y={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new NB0,this._events=new PB0,this._isInitialized=!1;let G=typeof X=="string"?X.trim():"",Q=typeof Y.host=="string"?Y.host.trim():"",J=!G;if(this._logger=xe6("[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=ne6(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:qB0},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=!Ve6()||(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(pJ.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(pJ.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(pJ.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:ZB0(U)})).catch((U)=>{return this._events.emit("error",U),{success:!1,error:this.categorizeRequestError(U)}})}categorizeRequestError(X){if(X instanceof na)return{type:"api_error",statusCode:X.status};if(X instanceof xX1){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 $=CX1(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(pJ.Props);return this._props||{}}set props(X){this._props=X}async register(X){this.wrap(()=>{this.props={...this.props,...X},this.setPersistedProperty(pJ.Props,this.props)})}async unregister(X){this.wrap(()=>{delete this.props[X],this.setPersistedProperty(pJ.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(pJ.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(pJ.Queue,J),this._events.emit(X,Q),J.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=Kw(()=>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:cA1()};if(this.historicalMigration)J.historical_migration=!0;let W=JSON.stringify(J),Z=`${this.host}/batch/`,$=this.disableCompression?null:await yA1(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:cA1(),uuid:G?.uuid?G.uuid:Aq()};if(G?.disableGeoip??this.disableGeoip){if(!Q.properties)Q.properties={};Q.properties.$geoip_disable=!0}if(Q.distinctId)Q.distinct_id=Q.distinctId,delete Q.distinctId;return Q}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){this.flush().catch(async(X)=>{await ee6(X)})}async flush(){let X=LB0([this.flushPromise]).then(()=>this._flush());return this.flushPromise=X,this.addPendingPromise(X),LB0([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(pJ.Queue)||[];if(!X.length)return;let Y=[],G=X.length;while(X.length>0&&Y.length<G){let Q=X.slice(0,this.maxBatchSize),J=Q.map((B)=>B.message),W=async()=>{let z=(this.getPersistedProperty(pJ.Queue)||[]).slice(Q.length);this.setPersistedProperty(pJ.Queue,z),X=z,await this.flushStorage()},Z={api_key:this.apiKey,batch:J,sent_at:cA1()};if(this.historicalMigration)Z.historical_migration=!0;let $=JSON.stringify(Z),K=`${this.host}/batch/`,H=this.disableCompression?null:await yA1($,this.isDebug),U={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...H!==null&&{"Content-Encoding":"gzip"}},body:H||$},N={retryCheck:(B)=>{if(X14(B))return!1;return qB0(B)}};try{await this.fetchWithRetry(K,U,N)}catch(B){if(X14(B)&&J.length>1){this.maxBatchSize=Math.max(1,Math.floor(J.length/2)),this._logger.warn(`Received 413 when sending batch of size ${J.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(B instanceof xX1))await W();throw this._events.emit("error",B),B}await W(),Y.push(...J)}this._events.emit("flush",Y)}async fetchWithRetry(X,Y,G,Q){let J=Y.body?Y.body:"",W=-1;try{W=J instanceof Blob?J.size:Buffer.byteLength(J,pe6)}catch{if(J instanceof Blob)W=J.size;else W=new TextEncoder().encode(J).length}return await ae6(async()=>{let Z=new AbortController,$=Q??this.requestTimeout,K=Kw(()=>Z.abort(),$),H=null;try{H=await this.fetch(X,{signal:Z.signal,...Y})}catch(N){throw new xX1(N)}finally{clearTimeout(K)}if(Y.mode!=="no-cors"&&(H.status<200||H.status>=400))throw new na(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(pJ.Queue)||[]).length===0)break;if(await this.flush(),Y)break}}catch(J){if(!qB0(J))throw J;await ee6(J)}},Q;try{return await Promise.race([new Promise((J,W)=>{Q=Kw(()=>{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 na,xX1;var AB0=D(()=>{se6();bA1();$B0();Tj();H3();bX1();na=class na 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()}};xX1=class xX1 extends Error{constructor(X){super("Network error while fetching PostHog",X instanceof Error?{cause:X}:{}),this.error=X,this.name="PostHogFetchNetworkError"}}});var Y14=D(()=>{bA1();Tj();AB0();bX1();H3()});var G14=D(()=>{_X1()});function J14(X){let Y=globalThis._posthogChunkIds;if(!Y)return;let G=Object.keys(Y);if(nA1&&G.length===Q14)return nA1;return Q14=G.length,nA1=G.reduce((Q,J)=>{if(!pA1)pA1={};let W=pA1[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,pA1[J]=[H,U];break}}}return Q},{}),nA1}var pA1,Q14,nA1;var Z14=()=>{};class W14{constructor(X,Y,G=[]){this.coercers=X,this.stackParser=Y,this.modifiers=G}buildFromUnknown(X,Y={}){let Q=Y&&Y.mechanism||{handled:!0,type:"generic"},W=this.buildCoercingContext(Q,Y,0).apply(X),Z=this.buildParsingContext(Y),$=this.parseStacktrace(W,Z);return{$exception_list:this.convertToExceptionList($,Q),$exception_level:"error"}}async modifyFrames(X){for(let Y of X)if(Y.stacktrace&&Y.stacktrace.frames&&hA1(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:J14(this.stackParser),skipFirstLines:X.skipFirstLines??1}}buildCoercingContext(X,Y,G=0){let Q=(W,Z)=>{if(!(Z<=cp5))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 cp5=4;var $14=D(()=>{H3();Z14()});function Yz(X,Y,G,Q,J){let W={platform:X,filename:Y,function:G==="<anonymous>"?rQ:G,in_app:!0};if(!da(Q))W.lineno=Q;if(!da(J))W.colno=J;return W}var rQ="?";var Tq=D(()=>{H3()});var aA1=(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]:rQ,G?`safari-extension:${Y}`:`safari-web-extension:${Y}`]:[X,Y]};var TB0=D(()=>{Tq()});var ip5,pp5,np5,IB0=(X,Y)=>{let G=ip5.exec(X);if(G){let[,J,W,Z]=G;return Yz(Y,J,rQ,+W,+Z)}let Q=pp5.exec(X);if(Q){if(Q[2]&&Q[2].indexOf("eval")===0){let $=np5.exec(Q[2]);if($)Q[2]=$[1],Q[3]=$[2],Q[4]=$[3]}let[W,Z]=aA1(Q[1]||rQ,Q[2]);return Yz(Y,Z,W,Q[3]?+Q[3]:void 0,Q[4]?+Q[4]:void 0)}};var K14=D(()=>{Tq();TB0();ip5=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,pp5=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,np5=/\((\S*)(?::(\d+))(?::(\d+))\)/});var ap5,tp5,VB0=(X,Y)=>{let G=ap5.exec(X);if(G){if(G[3]&&G[3].indexOf(" > eval")>-1){let Z=tp5.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]||rQ;return[W,J]=aA1(W,J),Yz(Y,J,W,G[4]?+G[4]:void 0,G[5]?+G[5]:void 0)}};var H14=D(()=>{Tq();TB0();ap5=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,tp5=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i});var rp5,F14=(X,Y)=>{let G=rp5.exec(X);return G?Yz(Y,G[2],G[1]||rQ,+G[3],G[4]?+G[4]:void 0):void 0};var U14=D(()=>{Tq();rp5=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i});var op5,N14=(X,Y)=>{let G=op5.exec(X);return G?Yz(Y,G[2],G[3]||rQ,+G[1]):void 0},sp5,B14=(X,Y)=>{let G=sp5.exec(X);return G?Yz(Y,G[5],G[3]||G[4]||rQ,+G[1],+G[2]):void 0};var z14=D(()=>{Tq();op5=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,sp5=/ 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 O14(X){return parseInt(X||"",10)||void 0}var ep5,Xn5,D14=(X,Y)=>{let G=X.match(Xn5);if(G){let Q,J,W,Z,$;if(G[1]){W=G[1];let U=W.lastIndexOf(".");if(W[U-1]===".")U--;if(U>0){Q=W.slice(0,U),J=W.slice(U+1);let N=Q.indexOf(".Module");if(N>0)W=W.slice(N+1),Q=Q.slice(0,N)}Z=void 0}if(J)Z=Q,$=J;if(J==="<anonymous>")$=void 0,W=void 0;if(W===void 0)$=$||rQ,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:O14(G[3]),colno:O14(G[4]),in_app:Yn5(K||"",H),platform:Y}}if(X.match(ep5))return{filename:X,platform:Y}};var w14=D(()=>{Tq();ep5=/^\s*[-]{4,}$/,Xn5=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/});function P14(X){if(!X.length)return[];let Y=Array.from(X);return Y.reverse(),Y.slice(0,E14).map((G)=>({...G,filename:G.filename||Gn5(Y).filename,function:G.function||rQ}))}function Gn5(X){return X[X.length-1]||{}}function Qn5(){return q14("web:javascript",IB0,VB0)}function q14(X,...Y){return(G,Q=0)=>{let J=[],W=G.split(`
|
|
1639
|
+
`);Q=W.pop()??"";for(let Z of W){let $=Ks6(Z).replace(/^\[\d+\]\s*/,"").trim();if(!$)continue;LK({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=Ks6(Q).replace(/^\[\d+\]\s*/,"").trim();if(W)LK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:W})}})()}async function Li5(X){let{vitePort:Y,baseUrl:G,noTui:Q}=X,J=await wA1(Number(X.port)),{settings:W,services:Z,managedServiceNames:$}=await DA1({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)Nd({name:z.name,status:"ready",port:z.port});Te(W),qe();let K=wi5(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)Hs6(U.stdout),Hs6(U.stderr);let N=G||`http://localhost:${W.port}`;Ae(N),Nd({name:"Vite",status:"ready",port:Number(Y)});let B=async(z)=>{if(U.kill(z),$.length>0){let{stopServices:O}=await Promise.resolve().then(() => (H$1(),K$1));await O(W.dataDir)}};return process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM")),{port:Number(W.port),process:U}}var MN0=D(()=>{IN0();YF();VN0()});import{Box as RN0,Text as SN0}from"ink";import{jsx as Us6,jsxs as LA1}from"react/jsx-runtime";function Fs6(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 qi5(X,Y){if(Ei5.has(X))return Y?{text:"\u25CF\u25CF\u25CF\u25CF\u25CF\u25CF",dimColor:!0}:{text:"not set",dimColor:!0};if(Pi5.has(X)){if(Array.isArray(Y)){if(Y.length===0)return{text:"not set",dimColor:!0};return{text:Y.map((W)=>Fs6(W)).join(", "),color:"cyan"}}let Q=Fs6(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 Ai5(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 Ns6({env:X}){let Y=Ai5(X);return Us6(RN0,{flexDirection:"column",children:Y.map((G)=>LA1(RN0,{flexDirection:"column",marginTop:1,children:[LA1(SN0,{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=qi5(Q,J);return LA1(RN0,{children:[LA1(SN0,{dimColor:!0,children:[" ",Q.padEnd(36)]}),Us6(SN0,{color:W.color,dimColor:W.dimColor,children:W.text})]},Q)})]},G.title))})}var Ei5,Pi5;var Bs6=D(()=>{Ei5=new Set(["BETTER_AUTH_SECRET","ENCRYPTION_KEY","MESH_JWT_SECRET","STUDIO_PROVISION_SECRET_KEY"]),Pi5=new Set(["DATABASE_URL","CLICKHOUSE_URL","NATS_URL"])});var CN0;var zs6=D(()=>{CN0={name:"decocms",version:"2.289.0",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/mesh"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:'bun run migrate && concurrently "bun run dev:client" "bun run dev:server"',"dev:servers":'concurrently "bun run dev:client" "bun run dev:server"',"dev:client":"bun --bun vite dev","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts","build:client":"bun --bun vite build","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","db:migrate":"bun run ./dist/server/migrate.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts",test:"bun test","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run build:client && bun run build:server"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1","@freestyle-sh/with-bun":"^0.2.12","@freestyle-sh/with-deno":"^0.0.4","@freestyle-sh/with-nodejs":"^0.2.9","freestyle-sandboxes":"^0.1.46"},dependencies:{"@ai-sdk/anthropic":"^3.0.58","@ai-sdk/google":"^3.0.60","@ai-sdk/openai":"^3.0.50","@anthropic-ai/sdk":"^0.79.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dnd-kit/core":"^6.3.1","@dnd-kit/sortable":"^10.0.0","@dnd-kit/utilities":"^3.2.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/ext-apps":"^1.2.2","@openrouter/ai-sdk-provider":"^2.2.5","@opentelemetry/core":"^2.6.0","@tanstack/react-virtual":"^3.13.21","@xterm/addon-fit":"^0.11.0","@xterm/xterm":"^6.0.0","ai-sdk-provider-claude-code":"^3.4.4","ai-sdk-provider-codex-cli":"^1.1.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12",nats:"^2.29.3","posthog-js":"^1.371.1","posthog-node":"^5.0.0",react:"^19.2.0","react-dom":"^19.2.0"},devDependencies:{"@ai-sdk/provider":"^3.0.8","@ai-sdk/react":"^3.0.118","@anthropic-ai/claude-agent-sdk":"^0.2.80","@better-auth/sso":"1.4.1","@daveyplate/better-auth-ui":"^3.2.7","@deco/ui":"workspace:*","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/mesh-sdk":"workspace:*","@decocms/runtime":"workspace:*","@decocms/vite-plugin":"workspace:*","@electric-sql/pglite":"^0.3.15","@floating-ui/react":"^0.27.16","@hookform/resolvers":"^5.2.2","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.27.1","@monaco-editor/react":"^4.7.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@playwright/test":"^1.58.2","@radix-ui/react-avatar":"^1.1.10","@radix-ui/react-checkbox":"^1.3.3","@radix-ui/react-dialog":"^1.1.15","@radix-ui/react-dropdown-menu":"^2.1.16","@radix-ui/react-label":"^2.1.7","@radix-ui/react-select":"^2.2.6","@radix-ui/react-separator":"^1.1.7","@radix-ui/react-slot":"^1.2.3","@radix-ui/react-tabs":"^1.1.13","@rjsf/core":"^6.1.2","@rjsf/shadcn":"^6.1.2","@rjsf/utils":"^6.1.2","@rjsf/validator-ajv8":"^6.1.2","@tailwindcss/vite":"^4.1.17","@tanstack/react-query":"5.90.11","@tanstack/react-router":"^1.139.7","@tiptap/core":"3.20.2","@tiptap/extension-mention":"3.20.2","@tiptap/extension-placeholder":"3.20.2","@tiptap/pm":"3.20.2","@tiptap/react":"3.20.2","@tiptap/starter-kit":"3.20.2","@tiptap/suggestion":"3.20.2","@types/bun":"^1.3.1","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@untitledui/icons":"^0.0.19","@vercel/nft":"^1.1.1","@vitejs/plugin-react":"^5.1.0",ai:"^6.0.116","babel-plugin-react-compiler":"^1.0.0","better-auth":"1.4.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",concurrently:"^9.2.1",croner:"^9.1.0","date-fns":"^4.1.0",degit:"^2.8.4",hono:"^4.10.7","input-otp":"^1.4.2",jose:"^6.0.11","kysely-pglite":"^0.6.1","lucide-react":"^0.468.0",marked:"^15.0.6","@decocms/sandbox":"workspace:*","mesh-plugin-workflows":"workspace:*",nanoid:"^5.1.6",pg:"^8.16.3",prettier:"^3.4.2","react-hook-form":"^7.66.0","react-markdown":"^10.1.0","react-resizable-panels":"^2.1.7","react-syntax-highlighter":"^15.6.1",recharts:"^3.6.0","rehype-raw":"^7.0.0","remark-gfm":"^4.0.0","sass-embedded":"^1.97.2",sonner:"^2.0.7","tailwind-merge":"^3.3.1",tailwindcss:"^4.1.17",typescript:"^5.9.3",vite:"^7.2.1","vite-tsconfig-paths":"^5.1.4",zod:"^4.0.0",zustand:"^5.0.9"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","mesh","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as qU,Text as MX}from"ink";import{Spinner as Ii5}from"@inkjs/ui";import{useSyncExternalStore as Os6}from"react";import{jsx as qY,jsxs as tQ}from"react/jsx-runtime";function Si5(X,Y){if(!X||!Ri5.has(X))return X;let G=kN0[Y]??kN0[kN0.length-1];return X==="#875f00"?G[0]:G[1]}function Ds6({status:X}){if(X==="pending")return qY(Ii5,{label:""});return qY(MX,{color:"green",children:"\u2713"})}function ws6({services:X,migrationsStatus:Y,home:G,serverUrl:Q,vibe:J}){let W=Os6(Tu0,Au0),Z=Os6(Su0,Ru0);return tQ(qU,{flexDirection:"column",paddingBottom:1,children:[J?tQ(qU,{flexDirection:"column",children:[W.map(($,K)=>{let H=Z[K],U=$.reduce((B,z)=>B+z.text.length,0),N=Math.max(0,Mi5-U);return tQ(qU,{flexDirection:"row",children:[$.map((B,z)=>{let O=Si5(B.color,K);return O?qY(MX,{color:O,children:B.text},z):qY(MX,{children:B.text},z)}),qY(MX,{children:" ".repeat(N+2)}),H?.map((B,z)=>B.color?qY(MX,{color:B.color,children:B.char},z):qY(MX,{children:B.char},z))]},K)}),tQ(MX,{dimColor:!0,children:[" v",CN0.version]})]}):tQ(qU,{flexDirection:"column",marginTop:1,children:[Vi5.map(($,K)=>qY(MX,{color:ji5[K],children:$},K)),tQ(MX,{dimColor:!0,children:[" v",CN0.version]})]}),qY(qU,{marginBottom:1,children:qY(MX,{dimColor:!0,children:"\u2500".repeat(80)})}),qY(qU,{children:tQ(MX,{dimColor:!0,children:["Home: ",G]})}),tQ(qU,{gap:2,children:[X.map(($)=>tQ(qU,{gap:1,children:[tQ(MX,{children:[$.name," :",$.port||"...."]}),qY(Ds6,{status:$.status})]},$.name)),tQ(qU,{gap:1,children:[qY(MX,{children:"Migrations"}),qY(Ds6,{status:Y})]})]}),qY(qU,{children:Q?tQ(MX,{children:["Open in browser: ",qY(MX,{color:"cyan",children:Q})]}):qY(MX,{dimColor:!0,children:"Starting..."})}),tQ(qU,{gap:2,children:[tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"K"})," ","toggle config"]}),tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"L"})," ","toggle log flow"]}),tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"V"})," ","toggle vibe ",J?"\u266A Nihilore \xB7 CC BY 4.0":""]}),J&&tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"N"})," ","skip song"]})]})]})}var Vi5,ji5,kN0,Mi5=30,Ri5;var Ls6=D(()=>{zs6();Bn1();En1();Vi5=[" \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 "],ji5=["#00ff64","#00ee5e","#00dc56","#00c84e","#00b444","#00a03c","#008832","#006e28"],kN0=[["#00ff64","#00cc50"],["#00f060","#00c04c"],["#00e05c","#00b448"],["#00d058","#00a844"],["#00c054","#009c40"],["#00b050","#00903c"],["#00a04c","#008438"],["#009048","#007834"],["#008044","#006c30"],["#007040","#00602c"],["#00603c","#005428"]],Ri5=new Set(["#875f00","#5f3800"])});import{useSyncExternalStore as Ci5}from"react";function ki5(){let X=process.stdout.rows||24,Y=process.stdout.columns||80;if(X!==EA1.rows||Y!==EA1.columns)EA1={rows:X,columns:Y};return EA1}function vi5(X){return process.stdout.on("resize",X),()=>{process.stdout.off("resize",X)}}function Es6(){return Ci5(vi5,ki5)}var EA1;var Ps6=D(()=>{EA1={rows:process.stdout.rows||24,columns:process.stdout.columns||80}});import{Box as _i5,Text as qX1}from"ink";import{useSyncExternalStore as fi5}from"react";import{jsx as vN0,jsxs as _N0}from"react/jsx-runtime";function bi5(X){if(X>=500)return"red";if(X>=400)return"yellow";if(X>=300)return"cyan";return"green"}function qs6({logs:X,headerHeight:Y}){let{rows:G}=Es6(),{logFlow:Q}=fi5(Pe,Ee),J=Math.max(1,G-Y-1),W=Q?X:X.slice(-J);return vN0(_i5,{flexDirection:"column",children:W.map((Z,$)=>{if(Z.rawLine)return vN0(qX1,{dimColor:!0,children:Z.rawLine},$);let K=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return _N0(qX1,{children:[_N0(qX1,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),vN0(qX1,{color:bi5(Z.status),children:Z.status}),_N0(qX1,{dimColor:!0,children:[" ",K.padStart(8)]})]},$)})})}var As6=D(()=>{YF();Ps6()});var fN0={};R0(fN0,{App:()=>mi5});import{Box as yi5,Text as xi5,useInput as hi5}from"ink";import{useSyncExternalStore as gi5}from"react";import{jsx as PA1,jsxs as di5}from"react/jsx-runtime";function mi5({home:X}){let Y=gi5(Pe,Ee);return hi5((G)=>{if(G==="k"||G==="K")Vn1();if(G==="l"||G==="L")jn1();if((G==="v"||G==="V")&&Y.dataDir)Tn1(Y.dataDir),Mn1();if((G==="n"||G==="N")&&Y.vibe)An1()}),di5(yi5,{flexDirection:"column",children:[PA1(ws6,{services:Y.services,migrationsStatus:Y.migrationsStatus,home:X,serverUrl:Y.serverUrl,vibe:Y.vibe}),Y.viewMode==="config"?Y.env?PA1(Ns6,{env:Y.env}):PA1(xi5,{dimColor:!0,children:"Loading configuration..."}):PA1(qs6,{logs:Y.logs,headerHeight:Y.vibe?li5:ui5})]})}var ui5=15,li5=19;var bN0=D(()=>{Bs6();Ls6();As6();YF();Ud()});function Ts6(X,Y={}){return{PORT:String(X.port),NODE_ENV:X.nodeEnv,BASE_URL:X.baseUrl,DATA_DIR:X.dataDir,DECOCMS_HOME:X.dataDir,DATABASE_URL:X.databaseUrl,DATABASE_PG_SSL:String(X.databasePgSsl),DATABASE_POOL_MAX:String(X.databasePoolMax),NATS_URL:X.natsUrls.join(","),BETTER_AUTH_SECRET:X.betterAuthSecret,ENCRYPTION_KEY:X.encryptionKey,MESH_JWT_SECRET:X.meshJwtSecret,DECOCMS_LOCAL_MODE:String(X.localMode),DECOCMS_ALLOW_LOCAL_PROD:String(X.allowLocalProd),DISABLE_RATE_LIMIT:String(X.disableRateLimit),STUDIO_PROVISION_SECRET_KEY:X.studioProvisionSecretKey,CONFIG_PATH:X.configPath,...Object.fromEntries(Object.entries(process.env).filter(([G])=>G.startsWith("AUTH_"))),UNSAFE_ALLOW_STDIO_TRANSPORT:String(X.unsafeAllowStdioTransport),DECO_AI_GATEWAY_ENABLED:String(X.aiGatewayEnabled),DECO_AI_GATEWAY_URL:X.aiGatewayUrl,ENABLE_DECO_IMPORT:String(X.enableDecoImport),S3_ENDPOINT:X.s3Endpoint,S3_BUCKET:X.s3Bucket,S3_REGION:X.s3Region,S3_ACCESS_KEY_ID:X.s3AccessKeyId,S3_SECRET_ACCESS_KEY:X.s3SecretAccessKey,S3_FORCE_PATH_STYLE:String(X.s3ForcePathStyle),OTEL_SERVICE_NAME:X.otelServiceName,CLICKHOUSE_URL:X.clickhouseUrl,DECO_SUPABASE_URL:X.decoSupabaseUrl,DECO_SUPABASE_SERVICE_KEY:X.decoSupabaseServiceKey,FIRECRAWL_API_KEY:X.firecrawlApiKey,STUDIO_SANDBOX_RUNNER:process.env.STUDIO_SANDBOX_RUNNER,STUDIO_SANDBOX_TEMPLATE_NAME:process.env.STUDIO_SANDBOX_TEMPLATE_NAME,FREESTYLE_API_KEY:process.env.FREESTYLE_API_KEY,BROWSERLESS_TOKEN:process.env.BROWSERLESS_TOKEN,NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS,DECO_CLI:"1",DECO_NO_TUI:"true",...Y}}function Vs6(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 Is6="https://studio.decocms.com/org/deco/registry/mcp";var yN0=(X,Y,G)=>{return(Q,J)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,U;if(X[$])U=X[$][0][0],Q.req.routeIndex=$;else U=$===X.length&&J||void 0;if(U)try{K=await U(Q,()=>Z($+1))}catch(N){if(N instanceof Error&&Y)Q.error=N,K=await Y(N,Q),H=!0;else throw N}else if(Q.finalized===!1&&G)K=await G(Q);if(K&&(Q.finalized===!1||H))Q.res=K;return Q}}};var js6=()=>{};var M9;var Lq=D(()=>{M9=class extends Error{res;status;constructor(X=500,Y){super(Y?.message,{cause:Y?.cause});this.res=Y?.res,this.status=X}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var Ms6;var Rs6=D(()=>{Ms6=Symbol()});async function ci5(X,Y){let G=await X.formData();if(G)return ii5(G,Y);return{}}function ii5(X,Y){let G=Object.create(null);if(X.forEach((Q,J)=>{if(!(Y.all||J.endsWith("[]")))G[J]=Q;else pi5(G,J,Q)}),Y.dot)Object.entries(G).forEach(([Q,J])=>{if(Q.includes("."))ni5(G,Q,J),delete G[Q]});return G}var Ss6=async(X,Y=Object.create(null))=>{let{all:G=!1,dot:Q=!1}=Y,W=(X instanceof qA1?X.raw.headers:X.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return ci5(X,{all:G,dot:Q});return{}},pi5=(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]},ni5=(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 Cs6=D(()=>{xN0()});var gN0=(X)=>{let Y=X.split("/");if(Y[0]==="")Y.shift();return Y},ks6=(X)=>{let{groups:Y,path:G}=ai5(X),Q=gN0(G);return ti5(Q,Y)},ai5=(X)=>{let Y=[];return X=X.replace(/\{[^}]+\}/g,(G,Q)=>{let J=`@${Q}`;return Y.push([J,G]),J}),{groups:Y,path:X}},ti5=(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},AA1,vs6=(X,Y)=>{if(X==="*")return"*";let G=X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(G){let Q=`${X}#${Y}`;if(!AA1[Q])if(G[2])AA1[Q]=Y&&Y[0]!==":"&&Y[0]!=="*"?[Q,G[1],new RegExp(`^${G[2]}(?=/${Y})`)]:[X,G[1],new RegExp(`^${G[2]}$`)];else AA1[Q]=[X,G[1],!0];return AA1[Q]}return null},la=(X,Y)=>{try{return Y(X)}catch{return X.replace(/(?:%[0-9A-Fa-f]{2})+/g,(G)=>{try{return Y(G)}catch{return G}})}},_s6=(X)=>la(X,decodeURI),uN0=(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 _s6(K.includes("%25")?K.replace(/%25/g,"%2525"):K)}else if(J===63||J===35)break}return Y.slice(G,Q)},fs6=(X)=>{let Y=uN0(X);return Y.length>1&&Y.at(-1)==="/"?Y.slice(0,-1):Y},Pj=(X,Y,...G)=>{if(G.length)Y=Pj(Y,...G);return`${X?.[0]==="/"?"":"/"}${X}${Y==="/"?"":`${X?.at(-1)==="/"?"":"/"}${Y?.[0]==="/"?Y.slice(1):Y}`}`},TA1=(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)},hN0=(X)=>{if(!/[%+]/.test(X))return X;if(X.indexOf("+")!==-1)X=X.replace(/\+/g," ");return X.indexOf("%")!==-1?la(X,AX1):X},bs6=(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 hN0(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=hN0(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=X.slice($+1,Z===-1?void 0:Z),Q)H=hN0(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},ys6,xs6=(X,Y)=>{return bs6(X,Y,!0)},AX1;var Eq=D(()=>{AA1={},ys6=bs6,AX1=decodeURIComponent});var hs6=(X)=>la(X,AX1),qA1;var xN0=D(()=>{Lq();Rs6();Cs6();Eq();qA1=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)?hs6(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)?hs6(Q):Q}return X}#J(X){return this.#Y[1]?this.#Y[1][X]:X}query(X){return ys6(this.url,X)}queries(X){return xs6(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 Ss6(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[Ms6](){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 IA1,gs6=(X,Y)=>{let G=new String(X);return G.isEscaped=!0,G.callbacks=Y,G},TX1=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)=>TX1(K,Y,!1,Q,J))).then(()=>J[0]));if(G)return gs6(await Z,W);else return Z};var VA1=D(()=>{IA1={Stringify:1,BeforeStream:2,Stream:3}});var us6="text/plain; charset=UTF-8",lN0=(X,Y)=>{return{"Content-Type":X,...Y}},IX1=(X,Y)=>new Response(X,Y),ls6=class{#X;#Y;env={};#G;finalized=!1;error;#Q;#J;#Z;#$;#W;#K;#H;#U;#N;constructor(X,Y){if(this.#X=X,Y)this.#J=Y.executionCtx,this.env=Y.env,this.#K=Y.notFoundHandler,this.#N=Y.path,this.#U=Y.matchResult}get req(){return this.#Y??=new qA1(this.#X,this.#N,this.#U),this.#Y}get event(){if(this.#J&&"respondWith"in this.#J)return this.#J;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#J)return this.#J;else throw Error("This context has no ExecutionContext")}get res(){return this.#Z||=IX1(null,{headers:this.#H??=new Headers})}set res(X){if(this.#Z&&X){X=IX1(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=IX1(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 IX1(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,lN0(us6,G))};json=(X,Y,G)=>{return this.#F(JSON.stringify(X),Y,lN0("application/json",G))};html=(X,Y,G)=>{let Q=(J)=>this.#F(J,Y,lN0("text/html; charset=UTF-8",G));return typeof X==="object"?TX1(X,IA1.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??=()=>IX1(),this.#K(this)}};var jA1=D(()=>{xN0();VA1()});var T7="ALL",ms6="all",ds6,MA1="Can not add a route since the matcher is already built.",RA1;var Pq=D(()=>{ds6=["get","post","put","delete","options","patch"],RA1=class extends Error{}});var mN0="__COMPOSED_HANDLER";var dN0=()=>{};var ri5=(X)=>{return X.text("404 Not Found",404)},cs6=(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)},is6=class X{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#X="/";routes=[];constructor(Y={}){[...ds6,ms6].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??uN0:fs6}#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=ri5;errorHandler=cs6;route(Y,G){let Q=this.basePath(Y);return G.routes.map((J)=>{let W;if(G.errorHandler===cs6)W=J.handler;else W=async(Z,$)=>(await yN0([],G.errorHandler)(Z,()=>J.handler(Z,$))).res,W[mN0]=J.handler;Q.#Q(J.method,J.path,W)}),this}basePath(Y){let G=this.#Y();return G._basePath=Pj(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=Pj(this._basePath,Y),H=K==="/"?0:K.length;return(U)=>{let N=new URL(U.url);return N.pathname=N.pathname.slice(H)||"/",new Request(N,U)}})();let $=async(K,H)=>{let U=await G(J(K.req.raw),...Z(K));if(U)return U;await H()};return this.#Q(T7,Pj(Y,"*"),$),this}#Q(Y,G,Q){Y=Y.toUpperCase(),G=Pj(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 ls6(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=yN0(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${Pj("/",Y)}`,G),Q,J)};fire=()=>{addEventListener("fetch",(Y)=>{Y.respondWith(this.#Z(Y.request,Y,void 0,Y.request.method))})}};var ps6=D(()=>{js6();jA1();Pq();dN0();Eq()});function SA1(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[[],VX1];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=Q,Q(X,Y)}var VX1;var cN0=D(()=>{Pq();VX1=[]});function si5(X,Y){if(X.length===1)return Y.length===1?X<Y?-1:1:-1;if(Y.length===1)return 1;if(X===jX1||X===MX1)return 1;else if(Y===jX1||Y===MX1)return-1;if(X===CA1)return 1;else if(Y===CA1)return-1;return X.length===Y.length?X<Y?-1:1:Y.length-X.length}var CA1="[^/]+",jX1=".*",MX1="(?:|/.*)",qj,oi5,ns6=class X{#X;#Y;#G=Object.create(null);insert(Y,G,Q,J,W){if(Y.length===0){if(this.#X!==void 0)throw qj;if(W)return;this.#X=G;return}let[Z,...$]=Y,K=Z==="*"?$.length===0?["","",jX1]:["","",CA1]:Z==="/*"?["","",MX1]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let U=K[1],N=K[2]||CA1;if(U&&K[2]){if(N===".*")throw qj;if(N=N.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(N))throw qj}if(H=this.#G[N],!H){if(Object.keys(this.#G).some((B)=>B!==jX1&&B!==MX1))throw qj;if(W)return;if(H=this.#G[N]=new X,U!=="")H.#Y=J.varIndex++}if(!W&&U!=="")Q.push([U,H.#Y])}else if(H=this.#G[Z],!H){if(Object.keys(this.#G).some((U)=>U.length>1&&U!==jX1&&U!==MX1))throw qj;if(W)return;H=this.#G[Z]=new X}H.insert($,G,Q,J,W)}buildRegExpStr(){let G=Object.keys(this.#G).sort(si5).map((Q)=>{let J=this.#G[Q];return(typeof J.#Y==="number"?`(${Q})@${J.#Y}`:oi5.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 iN0=D(()=>{qj=Symbol(),oi5=new Set(".\\+*[^]$()")});var as6=class{#X={varIndex:0};#Y=new ns6;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 ts6=D(()=>{iN0()});function os6(X){return rs6[X]??=new RegExp(X==="*"?"":`^${X.replace(/\/\*$|([.\\+*[^\]$()])/g,(Y,G)=>G?`\\${G}`:"(?:|/.*)")}$`)}function Xp5(){rs6=Object.create(null)}function Yp5(X){let Y=new as6,G=[];if(X.length===0)return ei5;let Q=X.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,U],[N,B])=>H?1:N?-1:U.length-B.length),J=Object.create(null);for(let H=0,U=-1,N=Q.length;H<N;H++){let[B,z,O]=Q[H];if(B)J[z]=[O.map(([E])=>[E,Object.create(null)]),VX1];else U++;let w;try{w=Y.insert(z,U,B)}catch(E){throw E===qj?new RA1(z):E}if(B)continue;G[U]=O.map(([E,P])=>{let q=Object.create(null);P-=1;for(;P>=0;P--){let[j,M]=w[P];q[j]=M}return[E,q]})}let[W,Z,$]=Y.buildRegExp();for(let H=0,U=G.length;H<U;H++)for(let N=0,B=G[H].length;N<B;N++){let z=G[H][N]?.[1];if(!z)continue;let O=Object.keys(z);for(let w=0,E=O.length;w<E;w++)z[O[w]]=$[z[O[w]]]}let K=[];for(let H in Z)K[H]=G[Z[H]];return[W,K,J]}function ma(X,Y){if(!X)return;for(let G of Object.keys(X).sort((Q,J)=>J.length-Q.length))if(os6(G).test(Y))return[...X[G]];return}var ei5,rs6,kA1=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(MA1);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 $=os6(Y);if(X===T7)Object.keys(Q).forEach((K)=>{Q[K][Y]||=ma(Q[K],Y)||ma(Q[T7],Y)||[]});else Q[X][Y]||=ma(Q[X],Y)||ma(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=TA1(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]||=[...ma(Q[U],H)||ma(Q[T7],H)||[]],J[U][H].push([G,W-K+$+1])})}}match=SA1;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,Xp5(),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 pN0=D(()=>{Pq();Eq();cN0();iN0();ts6();ei5=[/^$/,[],Object.create(null)],rs6=Object.create(null)});var Gp5=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(),VX1];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=SA1};var ss6=D(()=>{Pq();cN0();pN0()});var es6=D(()=>{pN0();ss6()});var nN0=class{name="SmartRouter";#X=[];#Y=[];constructor(X){this.#X=X.routers}add(X,Y,G){if(!this.#Y)throw Error(MA1);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 RA1)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 Xe6=D(()=>{Pq()});var Ye6=D(()=>{Xe6()});var RX1,Qp5=(X)=>{for(let Y in X)return!0;return!1},Ge6=class X{#X;#Y;#G;#Q=0;#J=RX1;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=ks6(G),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],U=W[$+1],N=vs6(H,U),B=Array.isArray(N)?N[0]:H;if(B in J.#Y){if(J=J.#Y[B],N)Z.push(N[1]);continue}if(J.#Y[B]=new X,N)J.#G.push(N),Z.push(N[1]);J=J.#Y[B]}return J.#X.push({[Y]:{handler:Q,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#Q}}),J}#Z(Y,G,Q,J,W){for(let Z=0,$=G.#X.length;Z<$;Z++){let K=G.#X[Z],H=K[Q]||K[T7],U={};if(H!==void 0){if(H.params=Object.create(null),Y.push(H),J!==RX1||W&&W!==RX1)for(let N=0,B=H.possibleKeys.length;N<B;N++){let z=H.possibleKeys[N],O=U[H.score];H.params[z]=W?.[z]&&!O?W[z]:J[z]??W?.[z],U[H.score]=!0}}}}search(Y,G){let Q=[];this.#J=RX1;let W=[this],Z=gN0(G),$=[],K=Z.length,H=null;for(let U=0;U<K;U++){let N=Z[U],B=U===K-1,z=[];for(let w=0,E=W.length;w<E;w++){let P=W[w],q=P.#Y[N];if(q)if(q.#J=P.#J,B){if(q.#Y["*"])this.#Z(Q,q.#Y["*"],Y,P.#J);this.#Z(Q,q,Y,P.#J)}else z.push(q);for(let j=0,M=P.#G.length;j<M;j++){let V=P.#G[j],R=P.#J===RX1?{}:{...P.#J};if(V==="*"){let h=P.#Y["*"];if(h)this.#Z(Q,h,Y,P.#J),h.#J=R,z.push(h);continue}let[k,_,v]=V;if(!N&&!(v instanceof RegExp))continue;let y=P.#Y[k];if(v instanceof RegExp){if(H===null){H=Array(K);let p=G[0]==="/"?1:0;for(let f=0;f<K;f++)H[f]=p,p+=Z[f].length+1}let h=G.substring(H[U]),i=v.exec(h);if(i){if(R[_]=i[0],this.#Z(Q,y,Y,P.#J,R),Qp5(y.#Y)){y.#J=R;let p=i[0].match(/\//)?.length??0;($[p]||=[]).push(y)}continue}}if(v===!0||v.test(N))if(R[_]=N,B){if(this.#Z(Q,y,Y,R,P.#J),y.#Y["*"])this.#Z(Q,y.#Y["*"],Y,R,P.#J)}else y.#J=R,z.push(y)}}let O=$.shift();W=O?z.concat(O):z}if(Q.length>1)Q.sort((U,N)=>{return U.score-N.score});return[Q.map(({handler:U,params:N})=>[U,N])]}};var Qe6=D(()=>{Pq();Eq();RX1=Object.create(null)});var aN0=class{name="TrieRouter";#X;constructor(){this.#X=new Ge6}add(X,Y,G){let Q=TA1(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 Je6=D(()=>{Eq();Qe6()});var Ze6=D(()=>{Je6()});var R5;var We6=D(()=>{ps6();es6();Ye6();Ze6();R5=class extends is6{constructor(X={}){super(X);this.router=X.router??new nN0({routers:[new kA1,new aN0]})}}});var JQ=D(()=>{We6()});var Ke6,Jp5,$e6=(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)},tN0=(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=$e6(J.substring(0,W));if(Y&&Y!==Z||!Ke6.test(Z))continue;let $=$e6(J.substring(W+1));if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(Jp5.test($)){if(Q[Z]=$.indexOf("%")!==-1?la($,AX1):$,Y)break}}return Q},Zp5=(X,Y,G={})=>{if(!Ke6.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},vA1=(X,Y,G)=>{return Y=encodeURIComponent(Y),Zp5(X,Y,G)};var He6=D(()=>{Eq();Ke6=/^[\w!#$%&'*.^`|~+-]+$/,Jp5=/^[ !#-:<-[\]-~]*$/});var _A1=(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 tN0(Q,W)[W]}if(!Q)return{};return tN0(Q)},Wp5=(X,Y,G)=>{let Q;if(G?.prefix==="secure")Q=vA1("__Secure-"+X,Y,{path:"/",...G,secure:!0});else if(G?.prefix==="host")Q=vA1("__Host-"+X,Y,{...G,path:"/",secure:!0,domain:void 0});else Q=vA1(X,Y,{path:"/",...G});return Q},rN0=(X,Y,G,Q)=>{let J=Wp5(Y,G,Q);X.header("Set-Cookie",J,{append:!0})};var oN0=D(()=>{He6()});var Fe6=(X)=>{let G={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...X},Q=((W)=>{if(typeof W==="string")if(W==="*"){if(G.credentials)return(Z)=>Z||null;return()=>W}else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(G.origin),J=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(G.allowMethods);return async function(Z,$){function K(U,N){Z.res.headers.set(U,N)}let H=await Q(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(G.credentials)K("Access-Control-Allow-Credentials","true");if(G.exposeHeaders?.length)K("Access-Control-Expose-Headers",G.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(G.origin!=="*"||G.credentials)K("Vary","Origin");if(G.maxAge!=null)K("Access-Control-Max-Age",G.maxAge.toString());let U=await J(Z.req.header("origin")||"",Z);if(U.length)K("Access-Control-Allow-Methods",U.join(","));let N=G.allowHeaders;if(!N?.length){let B=Z.req.header("Access-Control-Request-Headers");if(B)N=B.split(/\s*,\s*/)}if(N?.length)K("Access-Control-Allow-Headers",N.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),G.origin!=="*"||G.credentials)Z.header("Vary","Origin",{append:!0})}};var Ue6=()=>{};var Ne6=()=>{try{return performance.now()}catch{}return Date.now()},sN0=(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)zH(Q,"total",Y.totalDescription);if(await J(),Y.total)h$(Q,"total");if(Y.autoEnd)Z.forEach((K,H)=>h$(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:"*")}}},Be6=(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)}},zH=(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:Ne6()})},h$=(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,$=Ne6()-Z;Be6(X,Y,$,W,G),Q.timers.delete(Y)};var ze6=D(()=>{jA1()});var eN0=D(()=>{ze6()});function SX1(){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 XB0)X[Y.category]?.push(Y);return X}var XB0;var YB0=D(()=>{XB0=[{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 Oe6=D(()=>{ni();dz1()});function De6(){return Kp5.parse(process.env)}var GB0=(X)=>F.enum(["true","false","1","0"]).optional().transform((Y)=>Y===void 0?X:Y==="true"||Y==="1"),$p5=(X)=>F.string().optional().transform((Y)=>Y?Y.split(",").map((G)=>G.trim()):X),Kp5;var we6=D(()=>{H0();Kp5=F.object({AUTH_EMAIL_PASSWORD_ENABLED:GB0(!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:GB0(!1),AUTH_MAGIC_LINK_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_ENABLED:GB0(!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:$p5(["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 fA1;var Le6=D(()=>{fA1={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"}});import{existsSync as Hp5,readFileSync as Fp5}from"fs";function Up5(){let X=De6(),Y=v6().configPath;if(!Hp5(Y))return{auth:X,monitoring:fA1};try{let G=JSON.parse(Fp5(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??fA1,theme:G.theme,logo:G.logo,autoCreateOrganizationOnSignup:G.autoCreateOrganizationOnSignup}}catch{return{auth:X,monitoring:fA1}}}function Aj(){if(!QB0)QB0=Up5();return QB0}function Ee6(){return Aj().theme}var QB0=null;var JB0=D(()=>{we6();Le6();m9()});import{dirname as Np5,posix as Bp5,sep as zp5}from"path";function qe6(){let X=Op5();return async(Y)=>{for(let G of Y)G.module=X(G.filename);return Y}}function Op5(X=process.argv[1]?Np5(process.argv[1]):process.cwd(),Y=zp5==="\\"){let G=Y?Pe6(X):X;return(Q)=>{if(!Q)return;let J=Y?Pe6(Q):Q,{dir:W,base:Z,ext:$}=Bp5.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 Pe6(X){return X.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Ae6=()=>{};function Dp5(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 ZB0=(X)=>{if("flags"in X){let Y=Te6(X.flags),G=Ie6(X.flags);return{...X,featureFlags:Y,featureFlagPayloads:G}}{let Y=X.featureFlags??{},G=Object.fromEntries(Object.entries(X.featureFlagPayloads||{}).map(([J,W])=>[J,WB0(W)])),Q=Object.fromEntries(Object.entries(Y).map(([J,W])=>[J,Dp5(J,W,G[J])]));return{...X,featureFlags:Y,featureFlagPayloads:G,flags:Q}}},Te6=(X)=>Object.fromEntries(Object.entries(X??{}).map(([Y,G])=>[Y,CX1(G)]).filter(([,Y])=>Y!==void 0)),Ie6=(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?WB0(Q):void 0]}))},CX1=(X)=>X===void 0?void 0:X.variant??X.enabled,WB0=(X)=>{if(typeof X!="string")return X;try{return JSON.parse(X)}catch{return X}};var bA1=()=>{};function Ve6(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}async function yA1(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 $B0=()=>{};var wp5,je6=function(X,Y=[]){if(!X)return!1;let G=X.toLowerCase();return wp5.concat(Y).some((Q)=>{let J=Q.toLowerCase();return G.indexOf(J)!==-1})};var Me6=D(()=>{wp5=["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 pJ;var Tj=D(()=>{pJ=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 xA1=()=>{};function gA1(X){return X===null||typeof X!="object"}function Ij(X,Y){return Object.prototype.toString.call(X)===`[object ${Y}]`}function Ce6(X){return Ij(X,"ErrorEvent")}function ca(X){return typeof Event<"u"&&Pp5(X,Event)}function ke6(X){return Ij(X,"Object")}function Pp5(X,Y){try{return X instanceof Y}catch{return!1}}var Ep5,Re6,AlX,KB0,hA1,kX1=(X)=>X===Object(X)&&!hA1(X),da=(X)=>X===void 0,qq=(X)=>KB0.call(X)=="[object String]",Se6=(X)=>qq(X)&&X.trim().length===0,vX1=(X)=>KB0.call(X)=="[object Number]"&&X===X,HB0=(X)=>X instanceof Error;var _X1=D(()=>{Tj();xA1();Ep5=Array.isArray,Re6=Object.prototype,AlX=Re6.hasOwnProperty,KB0=Re6.toString,hA1=Ep5||function(X){return KB0.call(X)==="[object Array]"}});function fX1(X,Y,G,Q,J){if(Y>G)Q.warn("min cannot be greater than max."),Y=G;if(vX1(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),fX1(J||G,Y,G,Q)}var FB0=D(()=>{_X1()});class UB0{constructor(X){this._buckets={},this._onBucketRateLimited=X._onBucketRateLimited,this._bucketSize=fX1(X.bucketSize,0,100,X._logger),this._refillRate=fX1(X.refillRate,0,this._bucketSize,X._logger),this._refillInterval=fX1(X.refillInterval,0,qp5,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 qp5=86400000;var ve6=D(()=>{FB0()});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 fe6{constructor(X){this.timestamp=0,this.counter=0,this.random=X??Ap5()}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 Ap5=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),_e6,Aq=()=>Tp5().toString(),Tp5=()=>(_e6||(_e6=new fe6)).generate();var bX1=D(()=>{/*! For license information please see uuidv7.mjs.LICENSE.txt */});class NB0{add(X){let Y=Aq();return this.promiseByIds[Y]=X,X.catch(()=>{}).finally(()=>{delete this.promiseByIds[Y]}),X}async join(){let X=Object.values(this.promiseByIds),Y=X.length;while(Y>0)await Promise.all(X),X=Object.values(this.promiseByIds),Y=X.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}}var be6=D(()=>{bX1()});function Ip5(X=console){return{log:X.log.bind(X),warn:X.warn.bind(X),error:X.error.bind(X),debug:X.debug.bind(X)}}function xe6(X,Y=Vp5){return ye6(X,Y,Ip5())}var ye6=(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)=>ye6(`${X} ${W}`,Y,G)}},Vp5=(X)=>X();var he6=()=>{};var pa="Mobile",lA1="iOS",ia="Android",ge6="Tablet",flX,Mp5="Apple",blX,ue6="Safari",mA1="BlackBerry",le6="Samsung",Rp5,Sp5,dA1="Chrome",Cp5,kp5,me6="Internet Explorer",vp5,zB0="Opera",ylX,de6="Edge",_p5,OB0="Firefox",fp5,DB0="Nintendo",wB0="PlayStation",uA1="Xbox",bp5,yp5,yX1="Windows",xp5,ce6="Generic",xlX,hlX,hp5="Konqueror",K3="(\\d+(\\.\\d+)?)",BB0,glX,ulX,llX,gp5,up5,mlX,dlX;var ie6=D(()=>{xA1();_X1();flX=ia+" "+ge6,blX=Mp5+" Watch",Rp5=le6+"Browser",Sp5=le6+" Internet",Cp5=dA1+" OS",kp5=dA1+" "+lA1,vp5=me6+" "+pa,ylX=zB0+" Mini",_p5="Microsoft "+de6,fp5=OB0+" "+lA1,bp5=ia+" "+pa,yp5=pa+" "+ue6,xp5=yX1+" Phone",xlX=ce6+" "+pa.toLowerCase(),hlX=ce6+" "+ge6.toLowerCase(),BB0=new RegExp("Version/"+K3),glX=new RegExp(uA1,"i"),ulX=new RegExp(wB0+" \\w+","i"),llX=new RegExp(DB0+" \\w+","i"),gp5=new RegExp(mA1+"|PlayBook|BB10","i"),up5={"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"},mlX={[vp5]:[new RegExp("rv:"+K3)],[_p5]:[new RegExp(de6+"?\\/"+K3)],[dA1]:[new RegExp("("+dA1+"|CrMo)\\/"+K3)],[kp5]:[new RegExp("CriOS\\/"+K3)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+K3)],[ue6]:[BB0],[yp5]:[BB0],[zB0]:[new RegExp("("+zB0+"|OPR)\\/"+K3)],[OB0]:[new RegExp(OB0+"\\/"+K3)],[fp5]:[new RegExp("FxiOS\\/"+K3)],[hp5]:[new RegExp("Konqueror[:/]?"+K3,"i")],[mA1]:[new RegExp(mA1+" "+K3),BB0],[bp5]:[new RegExp("android\\s"+K3,"i")],[Sp5]:[new RegExp(Rp5+"\\/"+K3)],[me6]:[new RegExp("(rv:|MSIE )"+K3)],Mozilla:[new RegExp("rv:"+K3)]},dlX=[[new RegExp(uA1+"; "+uA1+" (.*?)[);]","i"),(X)=>[uA1,X&&X[1]||""]],[new RegExp(DB0,"i"),[DB0,""]],[new RegExp(wB0,"i"),[wB0,""]],[gp5,[mA1,""]],[new RegExp(yX1,"i"),(X,Y)=>{if(/Phone/.test(Y)||/WPDesktop/.test(Y))return[xp5,""];if(new RegExp(pa).test(Y)&&!/IEMobile\b/.test(Y))return[yX1+" "+pa,""];let G=/Windows NT ([0-9.]+)/i.exec(Y);if(G&&G[1]){let Q=G[1],J=up5[Q]||"";if(/arm/i.test(Y))J="RT";return[yX1,J]}return[yX1,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(X)=>{if(X&&X[3]){let Y=[X[3],X[4],X[5]||"0"];return[lA1,Y.join(".")]}return[lA1,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(X)=>{let Y="";if(X&&X.length>=3)Y=da(X[2])?X[3]:X[2];return["watchOS",Y]}],[new RegExp("("+ia+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+ia+")","i"),(X)=>{if(X&&X[2]){let Y=[X[2],X[3],X[4]||"0"];return[ia,Y.join(".")]}return[ia,""]}],[/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/,[Cp5,""]],[/Linux|debian/i,["Linux",""]]]});function ne6(X){return X?.replace(/\/+$/,"")}async function ae6(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 cA1(){return new Date().toISOString()}function Kw(X,Y){let G=setTimeout(X,Y);return G?.unref&&G?.unref(),G}function LB0(X){return Promise.all(X.map((Y)=>(Y??Promise.resolve()).then((G)=>({status:"fulfilled",value:G}),(G)=>({status:"rejected",reason:G}))))}var pe6="utf8",te6=(X)=>X instanceof Error;var H3=D(()=>{Me6();ve6();FB0();xA1();_X1();be6();he6();ie6()});var lp5,QmX;var EB0=D(()=>{H3();lp5={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}},QmX=lp5.info});var re6=D(()=>{EB0();Tj()});var oe6=D(()=>{Tj()});class PB0{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 se6=()=>{};async function ee6(X){if(X instanceof na){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 qB0(X){return typeof X=="object"&&(X instanceof na||X instanceof xX1)}function X14(X){return typeof X=="object"&&X instanceof na&&X.status===413}class iA1{constructor(X,Y={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new NB0,this._events=new PB0,this._isInitialized=!1;let G=typeof X=="string"?X.trim():"",Q=typeof Y.host=="string"?Y.host.trim():"",J=!G;if(this._logger=xe6("[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=ne6(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:qB0},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=!Ve6()||(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(pJ.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(pJ.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(pJ.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:ZB0(U)})).catch((U)=>{return this._events.emit("error",U),{success:!1,error:this.categorizeRequestError(U)}})}categorizeRequestError(X){if(X instanceof na)return{type:"api_error",statusCode:X.status};if(X instanceof xX1){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 $=CX1(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(pJ.Props);return this._props||{}}set props(X){this._props=X}async register(X){this.wrap(()=>{this.props={...this.props,...X},this.setPersistedProperty(pJ.Props,this.props)})}async unregister(X){this.wrap(()=>{delete this.props[X],this.setPersistedProperty(pJ.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(pJ.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(pJ.Queue,J),this._events.emit(X,Q),J.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=Kw(()=>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:cA1()};if(this.historicalMigration)J.historical_migration=!0;let W=JSON.stringify(J),Z=`${this.host}/batch/`,$=this.disableCompression?null:await yA1(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:cA1(),uuid:G?.uuid?G.uuid:Aq()};if(G?.disableGeoip??this.disableGeoip){if(!Q.properties)Q.properties={};Q.properties.$geoip_disable=!0}if(Q.distinctId)Q.distinct_id=Q.distinctId,delete Q.distinctId;return Q}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){this.flush().catch(async(X)=>{await ee6(X)})}async flush(){let X=LB0([this.flushPromise]).then(()=>this._flush());return this.flushPromise=X,this.addPendingPromise(X),LB0([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(pJ.Queue)||[];if(!X.length)return;let Y=[],G=X.length;while(X.length>0&&Y.length<G){let Q=X.slice(0,this.maxBatchSize),J=Q.map((B)=>B.message),W=async()=>{let z=(this.getPersistedProperty(pJ.Queue)||[]).slice(Q.length);this.setPersistedProperty(pJ.Queue,z),X=z,await this.flushStorage()},Z={api_key:this.apiKey,batch:J,sent_at:cA1()};if(this.historicalMigration)Z.historical_migration=!0;let $=JSON.stringify(Z),K=`${this.host}/batch/`,H=this.disableCompression?null:await yA1($,this.isDebug),U={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...H!==null&&{"Content-Encoding":"gzip"}},body:H||$},N={retryCheck:(B)=>{if(X14(B))return!1;return qB0(B)}};try{await this.fetchWithRetry(K,U,N)}catch(B){if(X14(B)&&J.length>1){this.maxBatchSize=Math.max(1,Math.floor(J.length/2)),this._logger.warn(`Received 413 when sending batch of size ${J.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(B instanceof xX1))await W();throw this._events.emit("error",B),B}await W(),Y.push(...J)}this._events.emit("flush",Y)}async fetchWithRetry(X,Y,G,Q){let J=Y.body?Y.body:"",W=-1;try{W=J instanceof Blob?J.size:Buffer.byteLength(J,pe6)}catch{if(J instanceof Blob)W=J.size;else W=new TextEncoder().encode(J).length}return await ae6(async()=>{let Z=new AbortController,$=Q??this.requestTimeout,K=Kw(()=>Z.abort(),$),H=null;try{H=await this.fetch(X,{signal:Z.signal,...Y})}catch(N){throw new xX1(N)}finally{clearTimeout(K)}if(Y.mode!=="no-cors"&&(H.status<200||H.status>=400))throw new na(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(pJ.Queue)||[]).length===0)break;if(await this.flush(),Y)break}}catch(J){if(!qB0(J))throw J;await ee6(J)}},Q;try{return await Promise.race([new Promise((J,W)=>{Q=Kw(()=>{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 na,xX1;var AB0=D(()=>{se6();bA1();$B0();Tj();H3();bX1();na=class na 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()}};xX1=class xX1 extends Error{constructor(X){super("Network error while fetching PostHog",X instanceof Error?{cause:X}:{}),this.error=X,this.name="PostHogFetchNetworkError"}}});var Y14=D(()=>{bA1();Tj();AB0();bX1();H3()});var G14=D(()=>{_X1()});function J14(X){let Y=globalThis._posthogChunkIds;if(!Y)return;let G=Object.keys(Y);if(nA1&&G.length===Q14)return nA1;return Q14=G.length,nA1=G.reduce((Q,J)=>{if(!pA1)pA1={};let W=pA1[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,pA1[J]=[H,U];break}}}return Q},{}),nA1}var pA1,Q14,nA1;var Z14=()=>{};class W14{constructor(X,Y,G=[]){this.coercers=X,this.stackParser=Y,this.modifiers=G}buildFromUnknown(X,Y={}){let Q=Y&&Y.mechanism||{handled:!0,type:"generic"},W=this.buildCoercingContext(Q,Y,0).apply(X),Z=this.buildParsingContext(Y),$=this.parseStacktrace(W,Z);return{$exception_list:this.convertToExceptionList($,Q),$exception_level:"error"}}async modifyFrames(X){for(let Y of X)if(Y.stacktrace&&Y.stacktrace.frames&&hA1(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:J14(this.stackParser),skipFirstLines:X.skipFirstLines??1}}buildCoercingContext(X,Y,G=0){let Q=(W,Z)=>{if(!(Z<=cp5))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 cp5=4;var $14=D(()=>{H3();Z14()});function Yz(X,Y,G,Q,J){let W={platform:X,filename:Y,function:G==="<anonymous>"?rQ:G,in_app:!0};if(!da(Q))W.lineno=Q;if(!da(J))W.colno=J;return W}var rQ="?";var Tq=D(()=>{H3()});var aA1=(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]:rQ,G?`safari-extension:${Y}`:`safari-web-extension:${Y}`]:[X,Y]};var TB0=D(()=>{Tq()});var ip5,pp5,np5,IB0=(X,Y)=>{let G=ip5.exec(X);if(G){let[,J,W,Z]=G;return Yz(Y,J,rQ,+W,+Z)}let Q=pp5.exec(X);if(Q){if(Q[2]&&Q[2].indexOf("eval")===0){let $=np5.exec(Q[2]);if($)Q[2]=$[1],Q[3]=$[2],Q[4]=$[3]}let[W,Z]=aA1(Q[1]||rQ,Q[2]);return Yz(Y,Z,W,Q[3]?+Q[3]:void 0,Q[4]?+Q[4]:void 0)}};var K14=D(()=>{Tq();TB0();ip5=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,pp5=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,np5=/\((\S*)(?::(\d+))(?::(\d+))\)/});var ap5,tp5,VB0=(X,Y)=>{let G=ap5.exec(X);if(G){if(G[3]&&G[3].indexOf(" > eval")>-1){let Z=tp5.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]||rQ;return[W,J]=aA1(W,J),Yz(Y,J,W,G[4]?+G[4]:void 0,G[5]?+G[5]:void 0)}};var H14=D(()=>{Tq();TB0();ap5=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,tp5=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i});var rp5,F14=(X,Y)=>{let G=rp5.exec(X);return G?Yz(Y,G[2],G[1]||rQ,+G[3],G[4]?+G[4]:void 0):void 0};var U14=D(()=>{Tq();rp5=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i});var op5,N14=(X,Y)=>{let G=op5.exec(X);return G?Yz(Y,G[2],G[3]||rQ,+G[1]):void 0},sp5,B14=(X,Y)=>{let G=sp5.exec(X);return G?Yz(Y,G[5],G[3]||G[4]||rQ,+G[1],+G[2]):void 0};var z14=D(()=>{Tq();op5=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,sp5=/ 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 O14(X){return parseInt(X||"",10)||void 0}var ep5,Xn5,D14=(X,Y)=>{let G=X.match(Xn5);if(G){let Q,J,W,Z,$;if(G[1]){W=G[1];let U=W.lastIndexOf(".");if(W[U-1]===".")U--;if(U>0){Q=W.slice(0,U),J=W.slice(U+1);let N=Q.indexOf(".Module");if(N>0)W=W.slice(N+1),Q=Q.slice(0,N)}Z=void 0}if(J)Z=Q,$=J;if(J==="<anonymous>")$=void 0,W=void 0;if(W===void 0)$=$||rQ,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:O14(G[3]),colno:O14(G[4]),in_app:Yn5(K||"",H),platform:Y}}if(X.match(ep5))return{filename:X,platform:Y}};var w14=D(()=>{Tq();ep5=/^\s*[-]{4,}$/,Xn5=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/});function P14(X){if(!X.length)return[];let Y=Array.from(X);return Y.reverse(),Y.slice(0,E14).map((G)=>({...G,filename:G.filename||Gn5(Y).filename,function:G.function||rQ}))}function Gn5(X){return X[X.length-1]||{}}function Qn5(){return q14("web:javascript",IB0,VB0)}function q14(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=L14.test($)?$.replace(L14,"$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>=E14)break}}return P14(J)}}var L14,E14=50;var A14=D(()=>{Tq();K14();H14();U14();z14();w14();L14=/\(error: (.*)\)/});class T14{match(X){return this.isDOMException(X)||this.isDOMError(X)}coerce(X,Y){let G=qq(X.stack);return{type:this.getType(X),value:this.getValue(X),stack:G?X.stack:void 0,cause:X.cause?Y.next(X.cause):void 0,synthetic:!1}}getType(X){return this.isDOMError(X)?"DOMError":"DOMException"}getValue(X){let Y=X.name||(this.isDOMError(X)?"DOMError":"DOMException");return X.message?`${Y}: ${X.message}`:Y}isDOMException(X){return Ij(X,"DOMException")}isDOMError(X){return Ij(X,"DOMError")}}var I14=D(()=>{H3()});class V14{match(X){return HB0(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 j14=D(()=>{H3()});class M14{constructor(){}match(X){return Ce6(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 R14=D(()=>{H3()});class S14{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(Jn5);if(Q)Y=Q[1],G=Q[2];return[Y,G]}}var Jn5;var C14=D(()=>{Jn5=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i});var k14;var v14=D(()=>{k14=["fatal","error","warning","log","info","debug"]});function tA1(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 jB0=()=>{};class _14{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 ca(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=tA1(X);return`${Y&&Y!=="Object"?`'${Y}'`:"Object"} captured as exception with keys: ${G}`}isSeverityLevel(X){return qq(X)&&!Se6(X)&&k14.indexOf(X)>=0}getErrorPropertyFromObject(X){for(let Y in X)if(Object.prototype.hasOwnProperty.call(X,Y)){let G=X[Y];if(te6(G))return G}}getObjectClassName(X){try{let Y=Object.getPrototypeOf(X);return Y?Y.constructor.name:void 0}catch(Y){return}}}var f14=D(()=>{H3();v14();jB0()});class b14{match(X){return ca(X)}coerce(X,Y){let G=X.constructor.name;return{type:G,value:`${G} captured as exception with keys: ${tA1(X)}`,stack:Y.syntheticException?.stack,synthetic:!0}}}var y14=D(()=>{H3();jB0()});class x14{match(X){return gA1(X)}coerce(X,Y){return{type:"Error",value:`Primitive value captured as exception: ${String(X)}`,stack:Y.syntheticException?.stack,synthetic:!0}}}var h14=D(()=>{H3()});class g14{match(X){return Ij(X,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(X)}isCustomEventWrappingRejection(X){if(!ca(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(gA1(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 u14=D(()=>{H3()});var l14=D(()=>{I14();j14();R14();C14();f14();y14();h14();u14()});class m14{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 d14=()=>{};function MB0(X){if(!X)return{...rA1};return{enabled:X.enabled??rA1.enabled,max_bytes:$n5(X.max_bytes,rA1.max_bytes)}}function Wn5(X){if(!X)return{sanitizedProperties:{},droppedKeys:[]};let Y=[];return{sanitizedProperties:Object.keys(X).reduce((Q,J)=>{if(Zn5.has(J))return Y.push(J),Q;return Q[J]=X[J],Q},{}),droppedKeys:Y}}class c14{constructor(X){this._entries=[],this._totalBytes=0,this._config=MB0(X)}setConfig(X){this._config=MB0(X),this._trimToMaxBytes()}add(X){let Y=Kn5(X);if(!Y)return;let G=i14(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 $n5(X,Y){if(!vX1(X)||X===1/0||X===-1/0)return Y;let G=Math.floor(X);if(G<0)return Y;return G}function Kn5(X){let Y=Hn5(X);if(!Y)return;try{let G=JSON.parse(Y);if(!kX1(G))return;let Q=G,J=Q[hX1.MESSAGE],W=Q[hX1.TIMESTAMP];if(!qq(J)||J.trim().length===0)return;if(!qq(W)&&!vX1(W))return;return{step:Q,json:Y}}catch{return}}function Hn5(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 i14(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 hX1,Zn5,rA1;var p14=D(()=>{H3();hX1={MESSAGE:"$message",TIMESTAMP:"$timestamp"},Zn5=new Set([hX1.MESSAGE,hX1.TIMESTAMP]),rA1={enabled:!0,max_bytes:32768}});var PW={};R0(PW,{winjsStackLineParser:()=>F14,stripReservedExceptionStepFields:()=>Wn5,reverseAndStripFrames:()=>P14,resolveExceptionStepsConfig:()=>MB0,opera11StackLineParser:()=>B14,opera10StackLineParser:()=>N14,nodeStackLineParser:()=>D14,getUtf8ByteLength:()=>i14,geckoStackLineParser:()=>VB0,createStackParser:()=>q14,createDefaultStackParser:()=>Qn5,chromeStackLineParser:()=>IB0,StringCoercer:()=>S14,ReduceableCache:()=>m14,PromiseRejectionEventCoercer:()=>g14,PrimitiveCoercer:()=>x14,ObjectCoercer:()=>_14,ExceptionStepsBuffer:()=>c14,EventCoercer:()=>b14,ErrorPropertiesBuilder:()=>W14,ErrorEventCoercer:()=>M14,ErrorCoercer:()=>V14,EXCEPTION_STEP_INTERNAL_FIELDS:()=>hX1,DOMExceptionCoercer:()=>T14,DEFAULT_EXCEPTION_STEPS_CONFIG:()=>rA1});var n14=D(()=>{$14();A14();l14();d14();p14()});var jj=D(()=>{bA1();$B0();EB0();re6();bX1();oe6();n14();H3();Y14();AB0();G14();Tj()});import{createReadStream as Fn5}from"fs";import{createInterface as Un5}from"readline";async function o14(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"||wn5(Z)||Ln5(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(r14.get(J))continue;let W=Y[J];if(!W)continue;W.sort((K,H)=>K-H);let Z=Pn5(W);if(Z.every((K)=>En5(J,K)))continue;let $=qn5(oA1,J,{});Q.push(zn5(J,Z,$))}if(await Promise.all(Q).catch(()=>{}),X&&X.length>0)On5(X,oA1);return oA1.reduce(),X}function zn5(X,Y,G){return new Promise((Q)=>{let J=Fn5(X),W=Un5({input:J});function Z(){J.destroy(),Q()}let $=0,K=0,H=Y[K];if(H===void 0)return void Z();let U=H[0],N=H[1];function B(){r14.set(X,1),W.close(),W.removeAllListeners(),Z()}J.on("error",B),W.on("error",B),W.on("close",Z),W.on("line",(z)=>{if($++,$<U)return;if(G[$]=An5(z,0),$>=N){if(K===Y.length-1){W.close(),W.removeAllListeners();return}K++;let O=Y[K];if(O===void 0){W.close(),W.removeAllListeners();return}U=O[0],N=O[1]}})})}function On5(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;Dn5(G.lineno,G,Q)}}function Dn5(X,Y,G){if(Y.lineno===void 0||G===void 0)return;Y.pre_context=[];for(let J=s14(X);J<X;J++){let W=G[J];if(W===void 0)return void a14(Y);Y.pre_context.push(W)}if(G[X]===void 0)return void a14(Y);Y.context_line=G[X];let Q=e14(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 a14(X){delete X.pre_context,delete X.context_line,delete X.post_context}function wn5(X){return X.startsWith("node:")||X.endsWith(".min.js")||X.endsWith(".min.cjs")||X.endsWith(".min.mjs")||X.startsWith("data:")}function Ln5(X){if(X.lineno!==void 0&&X.lineno>Bn5)return!0;if(X.colno!==void 0&&X.colno>Nn5)return!0;return!1}function En5(X,Y){let G=oA1.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 Pn5(X){if(!X.length)return[];let Y=0,G=X[0];if(typeof G!="number")return[];let Q=t14(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+RB0;else J.push(Q),Q=t14(W);Y++}return J}function t14(X){return[s14(X),e14(X)]}function s14(X){return Math.max(1,X-RB0)}function e14(X){return X+RB0}function qn5(X,Y,G){let Q=X.get(Y);if(Q===void 0)return X.set(Y,G),G;return Q}function An5(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 oA1,r14,RB0=7,Nn5=1000,Bn5=1e4;var X04=D(()=>{jj();oA1=new PW.ReduceableCache(25),r14=new PW.ReduceableCache(20)});import{isAbsolute as Tn5,relative as In5,sep as Vn5}from"path";function Y04(X=process.cwd()){let Y=Vn5==="\\",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(Tn5(W.filename))W.filename=G(In5(Q,G(W.filename)))}return J}}var G04=()=>{};function jn5(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 Q04(X,Y){globalThis.process?.on("uncaughtException",jn5(X,Y))}function J04(X){globalThis.process?.on("unhandledRejection",(Y)=>X(Y,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var Z04=()=>{};class OH{constructor(X,Y,G){this.client=X,this._exceptionAutocaptureEnabled=Y.enableExceptionAutocapture||!1,this._logger=G,this._rateLimiter=new UB0({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(X){return kX1(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())Q04(this.onException.bind(this),this.onFatalError.bind(this)),J04(this.onException.bind(this))}onException(X,Y){this.client.addPendingPromise((async()=>{if(!OH.isPreviouslyCapturedError(X)){let G=await OH.buildEventMessage(X,Y),J=G.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(J))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:J});return this.client.capture(G)}})())}async onFatalError(X){console.error(X),await this.client.shutdown(Mn5),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}var Mn5=2000;var sA1=D(()=>{Z04();jj()});var W04="5.30.6";var $04=()=>{};var gX1;var SB0=D(()=>{gX1={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"}});async function K04(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 H04=()=>{};class CB0{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 Gz||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 Gz||K instanceof d5)this.logMsgIfDebug(()=>console.debug(`${K.name} when computing flag locally: ${$.key}: ${K.message}`));else if(K instanceof Error)this.onError?.(Error(`Error computing flag locally: ${$.key}: ${K}`));J=!0}})),{response:G,payloads:Q,fallbackToFlags:J}}async computeFlagAndPayloadLocally(X,Y,G={}){let{matchValue:Q,skipLoadCheck:J=!1}=G;if(!J)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let W;W=Q!==void 0?Q:await this.computeFlagValueLocally(X,Y);let Z=this.getFeatureFlagPayload(X.key,W);return{value:W,payload:Z}}async computeFlagValueLocally(X,Y){let{distinctId:G,groups:Q,personProperties:J,groupProperties:W}=Y;if(X.ensure_experience_continuity)throw new d5("Flag has experience continuity enabled");if(!X.active)return!1;let $=(X.filters||{}).aggregation_group_type_index;if($!=null){let K=this.groupTypeMapping[String($)];if(!K)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${$} for feature flag ${X.key}`)),new d5("Flag has unknown group type index");if(!(K in Q))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${X.key} without group names passed in`)),!1;if(X.bucketing_identifier==="device_id"&&(J?.$device_id===void 0||J?.$device_id===null||J?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${X.key}`));let H=W[K];return await this.matchFeatureFlagProperties(X,Q[K],H,Y)}{let K=this.getBucketingValueForFlag(X,G,J);if(K===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${X.key} without $device_id, falling back to server evaluation`)),new d5(`Can't compute feature flag: ${X.key} without $device_id`);return await this.matchFeatureFlagProperties(X,K,J,Y)}}getBucketingValueForFlag(X,Y,G){if(X.filters?.aggregation_group_type_index!=null)return Y;if(X.bucketing_identifier==="device_id"){let Q=G?.$device_id;if(Q==null||Q==="")return;return Q}return Y}getFeatureFlagPayload(X,Y){let G=null;if(Y!==!1&&Y!=null){if(typeof Y=="boolean")G=this.featureFlagsByKey?.[X]?.filters?.payloads?.[Y.toString()]||null;else if(typeof Y=="string")G=this.featureFlagsByKey?.[X]?.filters?.payloads?.[Y]||null;if(G!=null){if(typeof G=="object")return G;if(typeof G=="string")try{return JSON.parse(G)}catch{}return G}}return null}async evaluateFlagDependency(X,Y,G){let{evaluationCache:Q}=G,J=X.key;if(!this.featureFlagsByKey)throw new d5("Feature flags not available for dependency evaluation");if(!("dependency_chain"in X))throw new d5(`Flag dependency property for '${J}' is missing required 'dependency_chain' field`);let W=X.dependency_chain;if(!Array.isArray(W))throw new d5(`Flag dependency property for '${J}' has an invalid 'dependency_chain' (expected array, got ${typeof W})`);if(W.length===0)throw new d5(`Circular dependency detected for flag '${J}' (empty dependency chain)`);for(let $ of W){if(!($ in Q)){let H=this.featureFlagsByKey[$];if(H)if(H.active)try{let U=await this.computeFlagValueLocally(H,G);Q[$]=U}catch(U){throw new d5(`Error evaluating flag dependency '${$}' for flag '${J}': ${U}`)}else Q[$]=!1;else throw new d5(`Missing flag dependency '${$}' for flag '${J}'`)}if(Q[$]==null)throw new d5(`Dependency '${$}' could not be evaluated`)}let Z=Q[J];return this.flagEvaluatesToExpectedValue(X.value,Z)}flagEvaluatesToExpectedValue(X,Y){if(typeof X=="boolean")return X===Y||typeof Y=="string"&&Y!==""&&X===!0;if(typeof X=="string")return Y===X;return!1}async matchFeatureFlagProperties(X,Y,G,Q){let J=X.filters||{},W=J.groups||[],Z=!1,$;for(let K of W)try{if(await this.isConditionMatch(X,Y,K,G,Q)){let H=K.variant,U=J.multivariate?.variants||[];$=H&&U.some((N)=>N.key===H)?H:await this.getMatchingVariant(X,Y)||!0;break}}catch(H){if(H instanceof Gz)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"?z04($,Q,this.cohorts,this.debugMode):K==="flag"?await this.evaluateFlagDependency($,Q,J):B04($,Q,Z),!H)return!1}if(W==null)return!0}if(W!=null&&await F04(X.key,Y)>W/100)return!1;return!0}async getMatchingVariant(X,Y){let G=await F04(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(Rn5,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 aa(`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 aa(`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 aa(`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 aa)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=Kw(()=>{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 F04(X,Y,G=""){let Q=await K04(`${X}.${Y}${G}`);return parseInt(Q.slice(0,15),16)/Sn5}function B04(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&&!Cn5.includes(W)){if(G)G(`Property ${Q} cannot have a value of null/undefined with the ${W} operator`);return!1}function $(H,U){if(Array.isArray(H))return H.map((N)=>String(N).toLowerCase()).includes(String(U).toLowerCase());return String(H).toLowerCase()===String(U).toLowerCase()}function K(H,U,N){if(N==="gt")return H>U;if(N==="gte")return H>=U;if(N==="lt")return H<U;if(N==="lte")return H<=U;throw Error(`Invalid operator: ${N}`)}switch(W){case"exact":return $(J,Z);case"is_not":return!$(J,Z);case"is_set":return Q in Y;case"icontains":return String(Z).toLowerCase().includes(String(J).toLowerCase());case"not_icontains":return!String(Z).toLowerCase().includes(String(J).toLowerCase());case"regex":return U04(String(J))&&String(Z).match(String(J))!==null;case"not_regex":return U04(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=bn5(String(J));if(H==null)H=N04(J);if(H==null)throw new d5(`Invalid date: ${J}`);let U=N04(Z);if(["is_date_before"].includes(W))return U<H;return U>H}case"semver_eq":return DH(oQ(String(Z)),oQ(String(J)))===0;case"semver_neq":return DH(oQ(String(Z)),oQ(String(J)))!==0;case"semver_gt":return DH(oQ(String(Z)),oQ(String(J)))>0;case"semver_gte":return DH(oQ(String(Z)),oQ(String(J)))>=0;case"semver_lt":return DH(oQ(String(Z)),oQ(String(J)))<0;case"semver_lte":return DH(oQ(String(Z)),oQ(String(J)))<=0;case"semver_tilde":{let H=oQ(String(Z)),{lower:U,upper:N}=vn5(String(J));return DH(H,U)>=0&&DH(H,N)<0}case"semver_caret":{let H=oQ(String(Z)),{lower:U,upper:N}=_n5(String(J));return DH(H,U)>=0&&DH(H,N)<0}case"semver_wildcard":{let H=oQ(String(Z)),{lower:U,upper:N}=fn5(String(J));return DH(H,U)>=0&&DH(H,N)<0}default:throw new d5(`Unknown operator: ${W}`)}}function kn5(X,Y){if(!(X in Y))throw new Gz(`cohort ${X} not found in local cohorts - likely a static cohort that requires server evaluation`)}function z04(X,Y,G,Q=!1){let J=String(X.value);kn5(J,G);let W=G[J];return O04(W,Y,G,Q)}function O04(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=O04($,Y,G,Q);if(J==="AND"){if(!K)return!1}else if(K)return!0}catch(K){if(K instanceof Gz)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=z04($,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=B04($,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 Gz)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 U04(X){try{return new RegExp(X),!0}catch(Y){return!1}}function oQ(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 DH(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 vn5(X){let Y=oQ(X),G=[Y[0],Y[1],Y[2]],Q=[Y[0],Y[1]+1,0];return{lower:G,upper:Q}}function _n5(X){let Y=oQ(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 fn5(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 N04(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 bn5(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 Rn5=60000,Sn5=1152921504606847000,Cn5,aa,d5,Gz;var D04=D(()=>{jj();H04();Cn5=["is_not"];aa=class aa extends Error{constructor(X){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=X,Object.setPrototypeOf(this,aa.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)}};Gz=class Gz extends Error{constructor(X){super(X);this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,Gz.prototype)}}});class kB0{getProperty(X){return this._memoryStorage[X]}setProperty(X,Y){this._memoryStorage[X]=Y!==null?Y:void 0}constructor(){this._memoryStorage={}}}var w04=()=>{};function ln5(X){return typeof X=="string"?X.trim():""}function mn5(X){return(typeof X=="string"?X.trim():"")||void 0}function dn5(X){return(typeof X=="string"?X.trim():"")||un5}var yn5=100,L04=30000,xn5=50000,hn5=50,gn5=500,un5="https://us.i.posthog.com",vB0;var E04=D(()=>{$04();jj();SB0();D04();sA1();w04();vB0=class vB0 extends iA1{constructor(X,Y={}){let G=ln5(X),Q={...Y,host:dn5(Y.host),personalApiKey:mn5(Y.personalApiKey)};if(super(G,Q),this._memoryStorage=new kB0,this.options=Q,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof Q.featureFlagsPollingInterval=="number"?Math.max(Q.featureFlagsPollingInterval,yn5):L04,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 CB0({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 OH(this,Q,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=Q.maxCacheSize||xn5}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??gn5,Q=Y>=G;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(Q)return void this.resolveWaitUntilFlush();let J=this.options.waitUntilDebounceMs??hn5;this._waitUntilCycle.timer=Kw(()=>{this.resolveWaitUntilFlush()},J)}_consumeWaitUntilCycle(){let X=this._waitUntilCycle;if(X)clearTimeout(X.timer),this._waitUntilCycle=void 0;return X?.resolve}async resolveWaitUntilFlush(){let X=this._consumeWaitUntilCycle();try{await super.flush()}catch{}finally{X?.()}}getPersistedProperty(X){return this._memoryStorage.getProperty(X)}setPersistedProperty(X,Y){return this._memoryStorage.setProperty(X,Y)}fetch(X,Y){return this.options.fetch?this.options.fetch(X,Y):fetch(X,Y)}getLibraryVersion(){return W04}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(X=!0){super.debug(X),this.featureFlagsPoller?.debug(X)}capture(X){if(typeof X=="string")this._logger.warn("Called capture() with a string as the first argument when an object was expected.");if(X.event==="$exception"&&!X._originatedFromCaptureException)this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically.");this.addPendingPromise(this.prepareEventMessage(X).then(({distinctId:Y,event:G,properties:Q,options:J})=>super.captureStateless(Y,G,Q,{timestamp:J.timestamp,disableGeoip:J.disableGeoip,uuid:J.uuid})).catch((Y)=>{if(Y)console.error(Y)}))}async captureImmediate(X){if(typeof X=="string")this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected.");if(X.event==="$exception"&&!X._originatedFromCaptureException)this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default.");return this.addPendingPromise(this.prepareEventMessage(X).then(({distinctId:Y,event:G,properties:Q,options:J})=>super.captureStatelessImmediate(Y,G,Q,{timestamp:J.timestamp,disableGeoip:J.disableGeoip,uuid:J.uuid})).catch((Y)=>{if(Y)console.error(Y)}))}identify({distinctId:X,properties:Y={},disableGeoip:G}){let{$set:Q,$set_once:J,$anon_distinct_id:W,...Z}=Y,H={$set:Q||Z,$set_once:J||{},$anon_distinct_id:W??void 0};super.identifyStateless(X,H,{disableGeoip:G})}async identifyImmediate({distinctId:X,properties:Y={},disableGeoip:G}){let{$set:Q,$set_once:J,$anon_distinct_id:W,...Z}=Y,H={$set:Q||Z,$set_once:J||{},$anon_distinct_id:W??void 0};super.identifyStatelessImmediate(X,H,{disableGeoip:G})}alias(X){super.aliasStateless(X.alias,X.distinctId,void 0,{disableGeoip:X.disableGeoip})}async aliasImmediate(X){await super.aliasStatelessImmediate(X.alias,X.distinctId,void 0,{disableGeoip:X.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(X=L04){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((Y)=>{let G=setTimeout(()=>{Q(),Y(!1)},X),Q=this._events.on("localEvaluationFlagsLoaded",(J)=>{clearTimeout(G),Q(),Y(J>0)})})}_resolveDistinctId(X,Y){if(typeof X=="string")return{distinctId:X,options:Y};return{distinctId:this.context?.get()?.distinctId,options:X}}async _getFeatureFlagResult(X,Y,G={},Q){let J=G.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&X in this._flagOverrides){let V=this._flagOverrides[X];if(V===void 0)return;let R=this._payloadOverrides?.[X];return{key:X,enabled:V!==!1,variant:typeof V=="string"?V:void 0,payload:R}}let{groups:W,disableGeoip:Z}=G,{onlyEvaluateLocally:$,personProperties:K,groupProperties:H}=G,U=this.addLocalPersonAndGroupProperties(Y,W,K,H);K=U.allPersonProperties,H=U.allGroupProperties;let N=this.createFeatureFlagEvaluationContext(Y,W,K,H);if($==null)$=this.options.strictLocalEvaluation??!1;let B,z=!1,O,w,E,P,q,j;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let V=this.featureFlagsPoller?.featureFlagsByKey[X];if(V)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(V,N,{matchValue:Q});if(R){z=!0;let k=R.value;P=V.id,j="Evaluated locally",B={key:X,enabled:k!==!1,variant:typeof k=="string"?k:void 0,payload:R.payload??void 0}}}catch(R){if(R instanceof Gz||R instanceof d5)this._logger?.info(`${R.name} when computing flag locally: ${X}: ${R.message}`);else throw R}}if(!z&&!$){let V=await super.getFeatureFlagDetailsStateless(N.distinctId,N.groups,N.personProperties,N.groupProperties,Z,[X]);if(V===void 0)E=gX1.UNKNOWN_ERROR;else{O=V.requestId,w=V.evaluatedAt;let R=[];if(V.errorsWhileComputingFlags)R.push(gX1.ERRORS_WHILE_COMPUTING);if(V.quotaLimited?.includes("feature_flags"))R.push(gX1.QUOTA_LIMITED);let k=V.flags[X];if(k===void 0)R.push(gX1.FLAG_MISSING);else{P=k.metadata?.id,q=k.metadata?.version,j=k.reason?.description??k.reason?.code;let _;if(k.metadata?.payload!==void 0)try{_=JSON.parse(k.metadata.payload)}catch{_=k.metadata.payload}B={key:X,enabled:k.enabled,variant:k.variant,payload:_}}if(R.length>0)E=R.join(",")}}if(J){let V=B===void 0?void 0:B.enabled===!1?!1:B.variant??!0,R=`${X}_${V}`;if(!(Y in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[Y].includes(R)){if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(Array.isArray(this.distinctIdHasSentFlagCalls[Y]))this.distinctIdHasSentFlagCalls[Y].push(R);else this.distinctIdHasSentFlagCalls[Y]=[R];let k={$feature_flag:X,$feature_flag_response:V,$feature_flag_id:P,$feature_flag_version:q,$feature_flag_reason:j,locally_evaluated:z,[`$feature/${X}`]:V,$feature_flag_request_id:O,$feature_flag_evaluated_at:z?Date.now():w};if(z&&this.featureFlagsPoller){let _=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(_!==void 0)k.$feature_flag_definitions_loaded_at=_}if(E)k.$feature_flag_error=E;this.capture({distinctId:Y,event:"$feature_flag_called",properties:k,groups:W,disableGeoip:Z})}}if(B!==void 0&&this._payloadOverrides!==void 0&&X in this._payloadOverrides)B={...B,payload:this._payloadOverrides[X]};return B}async getFeatureFlag(X,Y,G){let Q=await this._getFeatureFlagResult(X,Y,{...G,sendFeatureFlagEvents:G?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(Q===void 0)return;if(Q.enabled===!1)return!1;return Q.variant??!0}async getFeatureFlagPayload(X,Y,G,Q){if(this._payloadOverrides!==void 0&&X in this._payloadOverrides)return this._payloadOverrides[X];let J=await this._getFeatureFlagResult(X,Y,{...Q,sendFeatureFlagEvents:!1},G);if(J===void 0)return;return J.payload??null}async getFeatureFlagResult(X,Y,G){let{distinctId:Q,options:J}=this._resolveDistinctId(Y,G);if(!Q)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(X,Q,{...J,sendFeatureFlagEvents:J?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(X){if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let Y=await this._requestRemoteConfigPayload(X);if(!Y)return;let G=await Y.json();if(typeof G=="string")try{return JSON.parse(G)}catch(Q){}return G}async isFeatureEnabled(X,Y,G){let Q=await this.getFeatureFlag(X,Y,G);if(Q===void 0)return;return!!Q||!1}async getAllFlags(X,Y){let{distinctId:G,options:Q}=this._resolveDistinctId(X,Y);if(!G)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(G,Q)).featureFlags||{}}async getAllFlagsAndPayloads(X,Y){let{distinctId:G,options:Q}=this._resolveDistinctId(X,Y);if(!G)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};let{groups:J,disableGeoip:W,flagKeys:Z}=Q||{},{onlyEvaluateLocally:$,personProperties:K,groupProperties:H}=Q||{},U=this.addLocalPersonAndGroupProperties(G,J,K,H);K=U.allPersonProperties,H=U.allGroupProperties;let N=this.createFeatureFlagEvaluationContext(G,J,K,H);if($==null)$=this.options.strictLocalEvaluation??!1;let B=await this.featureFlagsPoller?.getAllFlagsAndPayloads(N,Z),z={},O={},w=!0;if(B)z=B.response,O=B.payloads,w=B.fallbackToFlags;if(w&&!$){let E=await super.getFeatureFlagsAndPayloadsStateless(N.distinctId,N.groups,N.personProperties,N.groupProperties,W,Z);z={...z,...E.flags||{}},O={...O,...E.payloads||{}}}if(this._flagOverrides!==void 0)z={...z,...this._flagOverrides};if(this._payloadOverrides!==void 0)O={...O,...this._payloadOverrides};return{featureFlags:z,featureFlagPayloads:O}}groupIdentify({groupType:X,groupKey:Y,properties:G,distinctId:Q,disableGeoip:J}){super.groupIdentifyStateless(X,Y,G,{disableGeoip:J},Q)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(X){let Y=(G)=>Object.fromEntries(G.map((Q)=>[Q,!0]));if(X===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(X)){this._flagOverrides=Y(X);return}if(this._isFeatureFlagOverrideOptions(X)){if("flags"in X){if(X.flags===!1)this._flagOverrides=void 0;else if(Array.isArray(X.flags))this._flagOverrides=Y(X.flags);else if(X.flags!==void 0)this._flagOverrides={...X.flags}}if("payloads"in X){if(X.payloads===!1)this._payloadOverrides=void 0;else if(X.payloads!==void 0)this._payloadOverrides={...X.payloads}}return}this._flagOverrides={...X}}_isFeatureFlagOverrideOptions(X){if(typeof X!="object"||X===null||Array.isArray(X))return!1;let Y=X;if("flags"in Y){let G=Y.flags;if(G===!1||Array.isArray(G)||typeof G=="object"&&G!==null)return!0}if("payloads"in Y){let G=Y.payloads;if(G===!1||typeof G=="object"&&G!==null)return!0}return!1}withContext(X,Y,G){if(!this.context)return Y();return this.context.run(X,Y,G)}getContext(){return this.context?.get()}enterContext(X,Y){this.context?.enter(X,Y)}async _shutdown(X){let Y=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(X),this.errorTracking.shutdown();try{return await super._shutdown(X)}finally{Y?.()}}async _requestRemoteConfigPayload(X){if(!this.options.personalApiKey)return;let Y=`${this.host}/api/projects/@current/feature_flags/${X}/remote_config?token=${encodeURIComponent(this.apiKey)}`,G={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},Q=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let J=new AbortController;Q=Kw(()=>{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(ke6(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(!OH.isPreviouslyCapturedError(X)){let J=Error("PostHog syntheticException");this.addPendingPromise(OH.buildEventMessage(X,{syntheticException:J},Y,G).then((W)=>this.capture({...W,uuid:Q})))}}async captureExceptionImmediate(X,Y,G){if(!OH.isPreviouslyCapturedError(X)){let Q=Error("PostHog syntheticException");return this.addPendingPromise(OH.buildEventMessage(X,{syntheticException:Q},Y,G).then((J)=>this.captureImmediate(J)))}}async prepareEventMessage(X){let{distinctId:Y,event:G,properties:Q,groups:J,sendFeatureFlags:W,timestamp:Z,disableGeoip:$,uuid:K}=X,H=this.context?.get(),U=Y||H?.distinctId,N={...this.props,...H?.properties||{},...Q||{}};if(!U)U=Aq(),N.$process_person_profile=!1;if(H?.sessionId&&!N.$session_id)N.$session_id=H.sessionId;let B=this._runBeforeSend({distinctId:U,event:G,properties:N,groups:J,sendFeatureFlags:W,timestamp:Z,disableGeoip:$,uuid:K});if(!B)return Promise.reject(null);let z=await Promise.resolve().then(async()=>{if(W){let O=typeof W=="object"?W:void 0;return await this.getFeatureFlagsForEvent(B.distinctId,J,$,O)}return B.event,{}}).then((O)=>{let w={};if(O)for(let[P,q]of Object.entries(O))w[`$feature/${P}`]=q;let E=Object.keys(O||{}).filter((P)=>O?.[P]!==!1).sort();if(E.length>0)w.$active_feature_flags=E;return w}).catch(()=>({})).then((O)=>{return{...O,...B.properties||{},$groups:B.groups||J}});if(B.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof z.$raw_user_agent=="string"){if(je6(z.$raw_user_agent,this.options.custom_blocked_useragents||[]))B.event="$bot_pageview",z.$browser_type="bot"}return{distinctId:B.distinctId,event:B.event,properties:z,options:{timestamp:B.timestamp,disableGeoip:B.disableGeoip,uuid:B.uuid}}}_runBeforeSend(X){let Y=this.options.before_send;if(!Y)return X;let G=Array.isArray(Y)?Y:[Y],Q=X;for(let J of G){if(Q=J(Q),!Q)return this._logger.info(`Event '${X.event}' was rejected in beforeSend function`),null;if(!Q.properties||Object.keys(Q.properties).length===0){let W=`Event '${Q.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(W)}}return Q}}});import{AsyncLocalStorage as cn5}from"async_hooks";class _B0{constructor(){this.storage=new cn5}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 P04=()=>{};function in5(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[q04.POSTHOG_ID_TAG];if(K===void 0)return Z;let H=X.options.host??"https://us.i.posthog.com",U=new URL(`/project/${X.apiKey}/person/${K}`,H).toString();Z.tags["PostHog Person URL"]=U;let N=Z.exception?.values||[],B=N.map((O)=>({...O,stacktrace:O.stacktrace?{...O.stacktrace,type:"raw",frames:(O.stacktrace.frames||[]).map((w)=>({...w,platform:"node:javascript"}))}:void 0})),z={$exception_message:N[0]?.value||Z.message,$exception_type:N[0]?.type,$exception_level:Z.level,$exception_list:B,$sentry_event_id:Z.event_id,$sentry_exception:Z.exception,$sentry_exception_message:N[0]?.value||Z.message,$sentry_exception_type:N[0]?.type,$sentry_tags:Z.tags};if(Y&&G)z.$sentry_url=(Q||"https://sentry.io/organizations/")+Y+"/issues/?project="+G+"&query="+Z.event_id;if(W)X.capture({event:"$exception",distinctId:K,properties:z});return Z}}var q04;var A04=D(()=>{q04=class q04{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(in5(X,{organization:Y,projectId:$,prefix:G,severityAllowList:Q,sendExceptionsToPostHog:J??!0}))}}}});var T04=D(()=>{sA1()});var I04=D(()=>{jj();A04();T04();SB0()});var fB0;var V04=D(()=>{Ae6();X04();G04();sA1();E04();jj();P04();I04();OH.errorPropertiesBuilder=new PW.ErrorPropertiesBuilder([new PW.EventCoercer,new PW.ErrorCoercer,new PW.ObjectCoercer,new PW.StringCoercer,new PW.PrimitiveCoercer],PW.createStackParser("node:javascript",PW.nodeStackLineParser),[qe6(),o14,Y04()]);fB0=class fB0 extends vB0{getLibraryId(){return"posthog-node"}initializeContext(){return new _B0}}});function pn5(){return{capture:()=>{},identify:()=>{},captureException:()=>{},groupIdentify:()=>{},shutdown:async()=>{}}}var bB0,j04,j4;var RX=D(()=>{V04();bB0=process.env.POSTHOG_KEY,j04=process.env.POSTHOG_HOST;j4=bB0?new fB0(bB0,{...j04?{host:j04}:{},enableExceptionAutocapture:!0,flushAt:1,flushInterval:0}):pn5();if(bB0){let X=()=>{j4.shutdown().catch(()=>{})};process.on("SIGTERM",X),process.on("SIGINT",X)}});function g$(){let X=v6();if(X.baseUrl)return X.baseUrl;return`http://localhost:${X.port??3000}`}function uX1(){return`http://localhost:${v6().port??3000}`}var Hw=D(()=>{m9()});var M04=D(()=>{RV()});function R04(X){return{organizationId:X.organization_id,domain:X.domain,autoJoinEnabled:X.auto_join_enabled,createdAt:X.created_at,updatedAt:X.updated_at}}class Fw{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?R04(Y):null}async getByOrganizationId(X){let Y=await this.db.selectFrom("organization_domains").selectAll().where("organization_id","=",X).executeTakeFirst();return Y?R04(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 yB0{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 xB0{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 Mj(X){let Y=tn5[X.provider];if(!Y)throw Error(`Unknown email provider: ${X.provider}`);return Y(X)}function Rj(X,Y){return X.find((G)=>G.id===Y)}var nn5=(X)=>{let Y=new yB0(X.config.apiKey);return async({to:G,subject:Q,html:J})=>{await Y.sendEmail({to:G,from:X.config.fromEmail,subject:Q,html:J})}},an5=(X)=>{let Y=new xB0(X.config.apiKey);return async({to:G,subject:Q,html:J})=>{await Y.sendEmail({to:G,from:X.config.fromEmail,subject:Q,html:J})}},tn5;var eA1=D(()=>{tn5={resend:nn5,sendgrid:an5}});function Sj({preheader:X="",heading:Y,subheading:G,body:Q,footnote:J}){return`<!DOCTYPE html>
|
|
1641
1641
|
<html lang="en">
|
|
1642
1642
|
<head>
|