decocms 3.4.0 → 3.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (230) hide show
  1. package/dist/client/assets/{AlertCircle-C2xmuErv.js → AlertCircle-Bc3r3AGq.js} +1 -1
  2. package/dist/client/assets/{ArrowUpRight-DY3nGAjH.js → ArrowUpRight-DfEIENBd.js} +1 -1
  3. package/dist/client/assets/{Check-Bl0EnB2J.js → Check--VLhXi5l.js} +1 -1
  4. package/dist/client/assets/{CheckCircle-Bt38xVIy.js → CheckCircle-7xc6-R3M.js} +1 -1
  5. package/dist/client/assets/{ChevronDown-BYvseX6e.js → ChevronDown-66ErjaPf.js} +1 -1
  6. package/dist/client/assets/{ChevronLeft-DoUOCEbQ.js → ChevronLeft-DyW6EtsM.js} +1 -1
  7. package/dist/client/assets/{ChevronRight-CJPo14Wd.js → ChevronRight-C87PRbBa.js} +1 -1
  8. package/dist/client/assets/{ChevronUp-CoYKSGM9.js → ChevronUp-BuPeXu8C.js} +1 -1
  9. package/dist/client/assets/{Container-Bgm498uR.js → Container-cZo3l6OX.js} +1 -1
  10. package/dist/client/assets/{DotsVertical-DdI4UlQo.js → DotsVertical-CQgc8nSx.js} +1 -1
  11. package/dist/client/assets/{Eye-D-FtEtW8.js → Eye-DHHjYDbX.js} +1 -1
  12. package/dist/client/assets/{FilterLines-Bn2_q3W3.js → FilterLines-CWR_eJ7z.js} +1 -1
  13. package/dist/client/assets/{Globe01-5KEfDt4K.js → Globe01-B10jCcNH.js} +1 -1
  14. package/dist/client/assets/{HardDrive-Bq_J68ys.js → HardDrive-7KMC69UH.js} +1 -1
  15. package/dist/client/assets/{Key01-C484g3YO.js → Key01-CTKRB2Cd.js} +1 -1
  16. package/dist/client/assets/{LayoutLeft-CnXQOO58.js → LayoutLeft-SQH1HcmI.js} +1 -1
  17. package/dist/client/assets/{LinkExternal01-DSXCOuPf.js → LinkExternal01-CjT-4hM8.js} +1 -1
  18. package/dist/client/assets/{Monitor01-DxGBVT7-.js → Monitor01-svtG00ql.js} +1 -1
  19. package/dist/client/assets/{Palette-BL7llRL5.js → Palette-CA_16qMN.js} +1 -1
  20. package/dist/client/assets/{Play-COr2_UEr.js → Play-CrdarOgl.js} +1 -1
  21. package/dist/client/assets/{Plus-DyGCHsAC.js → Plus-C9icoBmX.js} +1 -1
  22. package/dist/client/assets/{RefreshCcw01-DwuEW87g.js → RefreshCcw01-D1tvoH2_.js} +1 -1
  23. package/dist/client/assets/{SearchMd-BvLcLD4O.js → SearchMd-Di6_vvQ1.js} +1 -1
  24. package/dist/client/assets/{Settings02-DdSNGnuW.js → Settings02-BylJiOHK.js} +1 -1
  25. package/dist/client/assets/{Shield01-B-jBzvZJ.js → Shield01-CDSs18-B.js} +1 -1
  26. package/dist/client/assets/{Star01-BWl4O-UT.js → Star01-D1DEXGAi.js} +1 -1
  27. package/dist/client/assets/{Stars01-cmM0sb2I.js → Stars01-UWs0NZ30.js} +1 -1
  28. package/dist/client/assets/{Stars02-BDvnLwBo.js → Stars02-CXAcgX2g.js} +1 -1
  29. package/dist/client/assets/{Sun-BumCYr1L.js → Sun-CCiXRotp.js} +1 -1
  30. package/dist/client/assets/{SwitchHorizontal01-DL7oI9Hg.js → SwitchHorizontal01-BU3C5ze8.js} +1 -1
  31. package/dist/client/assets/{Tool01-Cgf_tMbK.js → Tool01-BMk00CcA.js} +1 -1
  32. package/dist/client/assets/{Trash01-BWWRskAa.js → Trash01-MTKniuxn.js} +1 -1
  33. package/dist/client/assets/{Upload01-CufDtzzB.js → Upload01-DsrMMWgf.js} +1 -1
  34. package/dist/client/assets/{User01-CL8jgZE5.js → User01-DShN8gQ-.js} +1 -1
  35. package/dist/client/assets/{Users01-DVvuBAcj.js → Users01-Bvh39Ydu.js} +1 -1
  36. package/dist/client/assets/{Users03-DuD0whJZ.js → Users03--pQkY_Pm.js} +1 -1
  37. package/dist/client/assets/{X-Dnhh57X7.js → X-D-FyhysP.js} +1 -1
  38. package/dist/client/assets/{XCircle-M_oWnCac.js → XCircle-Pgrh_mFJ.js} +1 -1
  39. package/dist/client/assets/{XClose-tPJB8Sgg.js → XClose-CXixB7oH.js} +1 -1
  40. package/dist/client/assets/{Zap-C7nJc6zh.js → Zap-BcF-Iz_3.js} +1 -1
  41. package/dist/client/assets/{ZapSquare-D8HT6_jN.js → ZapSquare-BH297b52.js} +1 -1
  42. package/dist/client/assets/{ZoomOut-DvI5OdTo.js → ZoomOut-qupe1GUj.js} +1 -1
  43. package/dist/client/assets/{access-gate-DImJJoEr.js → access-gate-b8qBeVwB.js} +1 -1
  44. package/dist/client/assets/{accordion-7MLP1JmO.js → accordion-bX483Ztz.js} +1 -1
  45. package/dist/client/assets/{add-section-modal--OZiIc-7.js → add-section-modal-wMptfoHV.js} +1 -1
  46. package/dist/client/assets/{agent-capabilities-BPRMoWbD.js → agent-capabilities-ADaK_qqp.js} +1 -1
  47. package/dist/client/assets/{agent-icon-WacEkBrp.js → agent-icon-6l7Nwe2K.js} +1 -1
  48. package/dist/client/assets/{agent-icons-DSxNh1vt.js → agent-icons-BDS9BBHh.js} +1 -1
  49. package/dist/client/assets/{agents-list-C2v-b0Uw.js → agents-list-BdFiPs3r.js} +1 -1
  50. package/dist/client/assets/{ai-providers-BwZCii8q.js → ai-providers-lM-GGoBl.js} +1 -1
  51. package/dist/client/assets/{alert-B3xreeC3.js → alert-Ta86Z4_L.js} +1 -1
  52. package/dist/client/assets/{alert-dialog-DXWvjPm6.js → alert-dialog-_2G9ccD7.js} +1 -1
  53. package/dist/client/assets/app-editor-BJ_HJXFs.js +1 -0
  54. package/dist/client/assets/{auth-catchall-DkH2zPkq.js → auth-catchall-BdHpJwKo.js} +1 -1
  55. package/dist/client/assets/{auth-split-layout-a7pkbs3d.js → auth-split-layout-DVUC3dWq.js} +1 -1
  56. package/dist/client/assets/{automation-list-row-Co4RY6C0.js → automation-list-row-BNHDxEG_.js} +1 -1
  57. package/dist/client/assets/{automation-runs-89AdbVbs.js → automation-runs-BbNb5m5Z.js} +1 -1
  58. package/dist/client/assets/{automations-CpHR-q7K.js → automations-ChMgB7Hm.js} +1 -1
  59. package/dist/client/assets/{avatar-MwlGDSa1.js → avatar-KTqg6Pir.js} +1 -1
  60. package/dist/client/assets/{badge-CDV4_k2B.js → badge-jK5_JNPO.js} +1 -1
  61. package/dist/client/assets/{brand-context-CEbbgDr_.js → brand-context-D1YLW65X.js} +1 -1
  62. package/dist/client/assets/{buckets-B-c_g1Bu.js → buckets-CZodJDYe.js} +1 -1
  63. package/dist/client/assets/{calendar-_Z1zwZng.js → calendar-DFy-BKZq.js} +1 -1
  64. package/dist/client/assets/{capability-load-error-U6Dy8kIL.js → capability-load-error-DUP-Lw9V.js} +1 -1
  65. package/dist/client/assets/{card-BrXXg9xg.js → card-Ce7y-Nqu.js} +1 -1
  66. package/dist/client/assets/{chat-context-DKFtpKPJ.js → chat-context-CpKbwwmM.js} +1 -1
  67. package/dist/client/assets/{checkbox-COoWVOED.js → checkbox-MO2_GITU.js} +1 -1
  68. package/dist/client/assets/{cli-auth-success-CgA40pPN.js → cli-auth-success-XZzsr92m.js} +1 -1
  69. package/dist/client/assets/{collection-detail-BZkXi3bA.js → collection-detail-Bv6I7A_k.js} +1 -1
  70. package/dist/client/assets/{collection-display-button-BkPkMS-1.js → collection-display-button-DzXqmtbd.js} +1 -1
  71. package/dist/client/assets/{collection-search-HZ4Ln7Q2.js → collection-search-CPYfTi84.js} +1 -1
  72. package/dist/client/assets/{collection-table-wrapper-Bos1aSX0.js → collection-table-wrapper-DgzLrzuP.js} +1 -1
  73. package/dist/client/assets/{collection-tabs-Bt-TX4Xo.js → collection-tabs-CIsqNrxU.js} +1 -1
  74. package/dist/client/assets/{collections-DltZgEAo.js → collections-B-PXiD2Y.js} +1 -1
  75. package/dist/client/assets/{command-DScV9t-B.js → command-BHmAxNRB.js} +1 -1
  76. package/dist/client/assets/{connect-desktop-dialog-CLGlbMya.js → connect-desktop-dialog-BQZD1I8n.js} +1 -1
  77. package/dist/client/assets/{connection-card-BXL7SVUL.js → connection-card-BHzG8ppu.js} +1 -1
  78. package/dist/client/assets/{connection-detail-ZBj-b2U9.js → connection-detail-BlmixFGl.js} +1 -1
  79. package/dist/client/assets/{connection-form-helpers-ZyPV2_OX.js → connection-form-helpers-CgKn2eM9.js} +1 -1
  80. package/dist/client/assets/{connections-kRTrf7Rr.js → connections-D5zy3mYf.js} +1 -1
  81. package/dist/client/assets/{constants-7h1Iherr.js → constants-DI_u-hVk.js} +1 -1
  82. package/dist/client/assets/{decopilot-sse-pool-DENZDpL-.js → decopilot-sse-pool-DPWhf2bX.js} +1 -1
  83. package/dist/client/assets/{dialog-DrWcnTZj.js → dialog-Bt3zXcK6.js} +1 -1
  84. package/dist/client/assets/{domain-settings-ShrDeEq2.js → domain-settings-CZnFXOwr.js} +1 -1
  85. package/dist/client/assets/{drawer-Bfik0Ru5.js → drawer-DeHC5s3g.js} +1 -1
  86. package/dist/client/assets/{dropdown-menu-CZNwXuzY.js → dropdown-menu-SwrAlbwN.js} +1 -1
  87. package/dist/client/assets/{dynamic-plugin-layout-BP4187XS.js → dynamic-plugin-layout-WDrQTfck.js} +1 -1
  88. package/dist/client/assets/{empty-state-DKLTVUZK.js → empty-state-BJFB-AwN.js} +1 -1
  89. package/dist/client/assets/{empty-state-D3IZdm2e.js → empty-state-DlCayRAK.js} +1 -1
  90. package/dist/client/assets/{extract-connection-data-nTPi-bUk.js → extract-connection-data-CrMYEI5i.js} +1 -1
  91. package/dist/client/assets/{features-BLxt6ZXO.js → features-BgkDxOlu.js} +1 -1
  92. package/dist/client/assets/{file-explorer-qXYPqBrE.js → file-explorer-DrueRu5k.js} +1 -1
  93. package/dist/client/assets/{file-type-icon-CNGWzVav.js → file-type-icon-BHF_Ovux.js} +1 -1
  94. package/dist/client/assets/{files-DxicSOqn.js → files-BCcd3t2S.js} +1 -1
  95. package/dist/client/assets/{form-DZneHGBX.js → form-8jBGaVW7.js} +1 -1
  96. package/dist/client/assets/{general-BNlVKTyv.js → general-BJkPBrz3.js} +1 -1
  97. package/dist/client/assets/{generate-id-BKVk8ACt.js → generate-id-Bfx7nOJH.js} +1 -1
  98. package/dist/client/assets/{github-repo-picker-DhCzx3JE.js → github-repo-picker-F4vLHgJ-.js} +1 -1
  99. package/dist/client/assets/{header-tab-button-FYT24Mc0.js → header-tab-button-DCSg63Wl.js} +1 -1
  100. package/dist/client/assets/{hover-card-C3fFUxNZ.js → hover-card-DcJvwauT.js} +1 -1
  101. package/dist/client/assets/{image-field-BPpyMlFF.js → image-field-cind3dwC.js} +1 -1
  102. package/dist/client/assets/{index-D8CIGkco.js → index-BIANv7ur.js} +1 -1
  103. package/dist/client/assets/{index-BYABqu1-.js → index-Bac2tQWh.js} +1 -1
  104. package/dist/client/assets/{index-BGTvYbRH.js → index-BrIVZCzt.js} +1 -1
  105. package/dist/client/assets/{index-nja5uOPv.js → index-BzoFvbIH.js} +1 -1
  106. package/dist/client/assets/{index-BzQy6K9H.js → index-C0t_9xyr.js} +1 -1
  107. package/dist/client/assets/{index-CrU7PEoz.js → index-C1kxS2Io.js} +1 -1
  108. package/dist/client/assets/{index-CE8bhCJ-.js → index-C3tcbzRj.js} +1 -1
  109. package/dist/client/assets/{index-CHxlbuKY.js → index-C_oSBqFD.js} +3 -3
  110. package/dist/client/assets/{index-CO19ITRz.js → index-CfGIr4vM.js} +4 -4
  111. package/dist/client/assets/{index-DnL9bwru.js → index-ChzbgMa2.js} +1 -1
  112. package/dist/client/assets/{index-C7bMF1Zw.js → index-DEWYXjIf.js} +1 -1
  113. package/dist/client/assets/{index-DBPwWvUg.js → index-DML39Lt-.js} +1 -1
  114. package/dist/client/assets/{index-h-7ASBRq.js → index-DQj7btfC.js} +1 -1
  115. package/dist/client/assets/{index-1DdOMz-0.js → index-DlcvFOU2.js} +1 -1
  116. package/dist/client/assets/{index-fTzwyCrX.js → index-d7-A3CDs.js} +1 -1
  117. package/dist/client/assets/{index-redirect--DRbdQvu.js → index-redirect-KnAJlqvx.js} +1 -1
  118. package/dist/client/assets/{infiniteQueryObserver-ClvxtPxd.js → infiniteQueryObserver-w8EJyyrI.js} +1 -1
  119. package/dist/client/assets/{input-BqbhwOOI.js → input-Ct22kLSY.js} +1 -1
  120. package/dist/client/assets/{integration-icon-DsdPiq0I.js → integration-icon-CNf7sZ5b.js} +1 -1
  121. package/dist/client/assets/{label-DylEtHs-.js → label-CvDTa89d.js} +1 -1
  122. package/dist/client/assets/{layout-BNJzmBuH.js → layout-Dkxj2bFg.js} +1 -1
  123. package/dist/client/assets/{login-BqdS0wu4.js → login-Dv6Rz1bY.js} +1 -1
  124. package/dist/client/assets/{members-N8gPc_Ma.js → members-BQXsk1m4.js} +1 -1
  125. package/dist/client/assets/{monaco-editor-CJckn8Zg.js → monaco-editor-DR4yoUjc.js} +1 -1
  126. package/dist/client/assets/{monitoring-stats-row-C5BKUj6s.js → monitoring-stats-row-Co70p3-n.js} +1 -1
  127. package/dist/client/assets/{oauth-callback-DpOZwh96.js → oauth-callback-CQPHoHy-.js} +1 -1
  128. package/dist/client/assets/{oauth-callback-ai-provider-Bey7NKbP.js → oauth-callback-ai-provider-BJeYyFlX.js} +1 -1
  129. package/dist/client/assets/{onboarding-DX1TA4nG.js → onboarding-CzNreyu4.js} +1 -1
  130. package/dist/client/assets/{org-install-Dw27kVYm.js → org-install-aZxuYxoI.js} +1 -1
  131. package/dist/client/assets/{org-layout-BoYrXW7O.js → org-layout-CR6iFjC9.js} +1 -1
  132. package/dist/client/assets/{org-plugin-layout-BZ7QEYUH.js → org-plugin-layout-Ah6P36_M.js} +1 -1
  133. package/dist/client/assets/{page-seo-form-DBEtnmLl.js → page-seo-form-BzX1ts5p.js} +1 -1
  134. package/dist/client/assets/page-seo-sheet-v7xZnlYi.js +1 -0
  135. package/dist/client/assets/{pair-KHOH6ev_.js → pair--AN1yq4g.js} +1 -1
  136. package/dist/client/assets/{plugin-empty-state-z6EfkGXR.js → plugin-empty-state-CIZ1bBrP.js} +1 -1
  137. package/dist/client/assets/{plugin-header-CvmTO3qC.js → plugin-header-CExvgCKI.js} +1 -1
  138. package/dist/client/assets/{plugin-layout-d2cyKIK_.js → plugin-layout-DS-orBC-.js} +1 -1
  139. package/dist/client/assets/{popover-CThu0-ID.js → popover-DXn7orE4.js} +1 -1
  140. package/dist/client/assets/{post-editor-HwjfiT82.js → post-editor-bszZQHpg.js} +1 -1
  141. package/dist/client/assets/{primitives-DOyYgRDx.js → primitives-CIXky-Gt.js} +1 -1
  142. package/dist/client/assets/{profile-DoWLwgvz.js → profile-CZWeJMEP.js} +1 -1
  143. package/dist/client/assets/project-app-view-DJMvDwFa.js +1 -0
  144. package/dist/client/assets/record-editor-C5KWfSLg.js +1 -0
  145. package/dist/client/assets/registry-CX2hi2E3.js +2 -0
  146. package/dist/client/assets/{registry-layout-B_UkD5S0.js → registry-layout-DjFUi3yC.js} +1 -1
  147. package/dist/client/assets/{require-capability-BvInsc8R.js → require-capability-DDbNSPG5.js} +1 -1
  148. package/dist/client/assets/{required-auth-layout-LJYVUIeV.js → required-auth-layout-Bpv6G5uE.js} +1 -1
  149. package/dist/client/assets/{reset-password-DtCxXZ93.js → reset-password-D1T0PiTj.js} +1 -1
  150. package/dist/client/assets/{resizable-YbTIAmC6.js → resizable-Bi3jkg9o.js} +1 -1
  151. package/dist/client/assets/{roles-deRJzwzx.js → roles-BBWw8puD.js} +1 -1
  152. package/dist/client/assets/{save-status-CznZaqbg.js → save-status-PzXq6KUK.js} +1 -1
  153. package/dist/client/assets/{schema-form-Bz-Y2xaP.js → schema-form-CM7pfylQ.js} +1 -1
  154. package/dist/client/assets/{scroll-area-iVX_9hOT.js → scroll-area-BNzrPnq5.js} +1 -1
  155. package/dist/client/assets/{search-input-BV9iWpXU.js → search-input-C76EA-t6.js} +1 -1
  156. package/dist/client/assets/{secrets-DKrtTjxD.js → secrets-DMEa7GIW.js} +1 -1
  157. package/dist/client/assets/{sections-editor-wlO4Df3c.js → sections-editor--GuZPQzC.js} +1 -1
  158. package/dist/client/assets/{select-Ci_D4qpL.js → select-D_4UU9rK.js} +1 -1
  159. package/dist/client/assets/{select-model-B4DZz0S9.js → select-model-cV_VUU8G.js} +1 -1
  160. package/dist/client/assets/{seo-editor-03fUsq4w.js → seo-editor-fhccoPNR.js} +1 -1
  161. package/dist/client/assets/{settings-layout-DWP_Rn9K.js → settings-layout-DH37q17x.js} +1 -1
  162. package/dist/client/assets/{settings-section-DKmxECct.js → settings-section-DsXtuKDY.js} +1 -1
  163. package/dist/client/assets/{sheet-B9dMT6Ki.js → sheet-D01YX9h0.js} +1 -1
  164. package/dist/client/assets/{shell-controls-CCA2MPHn.js → shell-controls-CNVI6ZJJ.js} +1 -1
  165. package/dist/client/assets/{shell-layout-BNtK431X.js → shell-layout-xPMsY5hC.js} +1 -1
  166. package/dist/client/assets/{shell-route-loading-CaBu7gGK.js → shell-route-loading-jPQ9XajT.js} +1 -1
  167. package/dist/client/assets/{sidebar-rRN-0AxT.js → sidebar-CJNdWlwy.js} +1 -1
  168. package/dist/client/assets/{skeleton-IAM_o0Ys.js → skeleton-DEf5lpEA.js} +1 -1
  169. package/dist/client/assets/{sortable.esm-DRxiermK.js → sortable.esm-KhkNVCRe.js} +1 -1
  170. package/dist/client/assets/{spinner-ZLpPHnSU.js → spinner-srK7FwNe.js} +1 -1
  171. package/dist/client/assets/{sso-CdsNChqa.js → sso-BLXKmxlD.js} +1 -1
  172. package/dist/client/assets/{store-BgRTI4Rv.js → store-DydXTg6V.js} +1 -1
  173. package/dist/client/assets/store-registry-BJqdtxTv.js +2 -0
  174. package/dist/client/assets/{switch-B1bl8sNA.js → switch-Cbu6JSI9.js} +1 -1
  175. package/dist/client/assets/{tab-id-C5NSex1c.js → tab-id-CbYpEVAZ.js} +1 -1
  176. package/dist/client/assets/{table-DB1Kd-ou.js → table-dr9K2jWM.js} +1 -1
  177. package/dist/client/assets/{tabs-B3X9vNsm.js → tabs-CJU0nxr6.js} +1 -1
  178. package/dist/client/assets/{task-status-ClueOciL.js → task-status-Dyf8qaxz.js} +1 -1
  179. package/dist/client/assets/{textarea-DywxeOH3.js → textarea-BquesfD_.js} +1 -1
  180. package/dist/client/assets/{toggle-group-7kzOZFuJ.js → toggle-group-m3q7pubc.js} +1 -1
  181. package/dist/client/assets/{toolbar-l4lsSaSH.js → toolbar-Bkxu3n7s.js} +1 -1
  182. package/dist/client/assets/{tools-list-Dm1utA0x.js → tools-list-CG_BLK1j.js} +1 -1
  183. package/dist/client/assets/{tooltip-BFGyTrfa.js → tooltip-Bm-whGHF.js} +1 -1
  184. package/dist/client/assets/{types-ksHhVabW.js → types-Bkz2p_os.js} +1 -1
  185. package/dist/client/assets/{use-ai-providers-JirMLy_w.js → use-ai-providers-B82V9Np8.js} +1 -1
  186. package/dist/client/assets/{use-automations-3R13ZeSL.js → use-automations-B5qTxkL8.js} +1 -1
  187. package/dist/client/assets/{use-capability-CQt0iOwa.js → use-capability-DpFGw1TU.js} +1 -1
  188. package/dist/client/assets/{use-collections-hMeHX3z9.js → use-collections-iUV-5kFm.js} +1 -1
  189. package/dist/client/assets/{use-connection-_VO3kzZS.js → use-connection-DTKE65yR.js} +1 -1
  190. package/dist/client/assets/{use-copy-BNAf-Qgh.js → use-copy-Dr7XRETN.js} +1 -1
  191. package/dist/client/assets/{use-create-virtual-mcp-DpiN_bgM.js → use-create-virtual-mcp-DlMteKXP.js} +1 -1
  192. package/dist/client/assets/{use-debounced-autosave-kr27xY5y.js → use-debounced-autosave-DFapff8c.js} +1 -1
  193. package/dist/client/assets/{use-delete-connection-DFb9AulP.js → use-delete-connection-CU96IyMZ.js} +1 -1
  194. package/dist/client/assets/{use-file-configs-DrA_HE6r.js → use-file-configs-C8ipJXZL.js} +1 -1
  195. package/dist/client/assets/{use-infinite-scroll-DRY2R8kb.js → use-infinite-scroll-KU0QCoEE.js} +1 -1
  196. package/dist/client/assets/{use-list-state-CGdA9sk-.js → use-list-state-DtwRJx6R.js} +1 -1
  197. package/dist/client/assets/{use-mcp-prompts-BIC4osYX.js → use-mcp-prompts-aLA3FcF_.js} +1 -1
  198. package/dist/client/assets/{use-mcp-tools-BZZ0dcgP.js → use-mcp-tools-CK1DUQVb.js} +1 -1
  199. package/dist/client/assets/{use-members-DnfZ8tEp.js → use-members-C9apz-8a.js} +1 -1
  200. package/dist/client/assets/{use-navigate-to-agent-DWh1SzWc.js → use-navigate-to-agent-DRRtr51U.js} +1 -1
  201. package/dist/client/assets/{use-org-auth-client-CwWZc3xb.js → use-org-auth-client-CI8XyYuM.js} +1 -1
  202. package/dist/client/assets/{use-org-sso-BnGud85s.js → use-org-sso-CYBgAyDV.js} +1 -1
  203. package/dist/client/assets/{use-organization-roles-BIe6gEN_.js → use-organization-roles-C5ABG30J.js} +1 -1
  204. package/dist/client/assets/{use-organization-settings-Dy_wvkUU.js → use-organization-settings-B4ywx3QZ.js} +1 -1
  205. package/dist/client/assets/{use-registry-connections-DnATENDO.js → use-registry-connections-B-c9LId-.js} +1 -1
  206. package/dist/client/assets/{use-secrets-C4Hg3-p8.js → use-secrets-D3irvtLI.js} +1 -1
  207. package/dist/client/assets/{use-status-sounds-CCM_GgH8.js → use-status-sounds-BEbMXd3N.js} +1 -1
  208. package/dist/client/assets/{use-view-mode-DZhMkEJ1.js → use-view-mode-Jd_CE1Mx.js} +1 -1
  209. package/dist/client/assets/{use-virtual-mcp-BaoT8VIh.js → use-virtual-mcp-DsdNWb58.js} +1 -1
  210. package/dist/client/assets/useInfiniteQuery-DrZL_IGs.js +1 -0
  211. package/dist/client/assets/{useRouterState-DEBHW9gr.js → useRouterState-CU2GqlKv.js} +1 -1
  212. package/dist/client/assets/useSuspenseInfiniteQuery-CN1mQR7i.js +1 -0
  213. package/dist/client/assets/{user-CmhADXs_.js → user-sLZtiN2i.js} +1 -1
  214. package/dist/client/assets/{view-mode-toggle--g2MGXro.js → view-mode-toggle-DSmCr2tD.js} +1 -1
  215. package/dist/client/assets/{workflow-DuDgvcXi.js → workflow-BK9KKo6T.js} +1 -1
  216. package/dist/client/assets/workflow-detail-DzASvQVR.js +1 -0
  217. package/dist/client/index.html +1 -1
  218. package/dist/server/cli.js +2 -2
  219. package/dist/server/migrate.js +1 -1
  220. package/dist/server/server.js +1 -1
  221. package/package.json +1 -1
  222. package/dist/client/assets/app-editor-DaKe0gcW.js +0 -1
  223. package/dist/client/assets/page-seo-sheet-B66TXIq6.js +0 -1
  224. package/dist/client/assets/project-app-view-BA3JXk-V.js +0 -1
  225. package/dist/client/assets/record-editor-B09SHssY.js +0 -1
  226. package/dist/client/assets/registry-CVaj-aEQ.js +0 -2
  227. package/dist/client/assets/store-registry-CxNFeZZm.js +0 -2
  228. package/dist/client/assets/useInfiniteQuery-BdYHzHZ3.js +0 -1
  229. package/dist/client/assets/useSuspenseInfiniteQuery-KU_h5oCb.js +0 -1
  230. package/dist/client/assets/workflow-detail-C8cBg_ad.js +0 -1
@@ -82,7 +82,7 @@ You are running the brand-context onboarding for the user's organization. Your o
82
82
 
83
83
  If the tool returns an error, surface the error message to the user and ask whether they want to try a different URL.
84
84
  `.trim();Oz0=Zq1("site-diagnostics_"),UZ8=Oz0.is,FZ8=Oz0.get,dX={AGENT_MANAGER:($)=>`studio-agent-manager_${$}`,AUTOMATION_MANAGER:($)=>`studio-automation-manager_${$}`,CONNECTION_MANAGER:($)=>`studio-connection-manager_${$}`,STORE_MANAGER:($)=>`studio-store-manager_${$}`,BRAND_MANAGER:($)=>`studio-brand-manager_${$}`,USAGE_MANAGER:($)=>`studio-usage-manager_${$}`}});var Dz0=D(()=>{RI1();Or();ia();pa()});var Lz0=D(()=>{eF()});var Ez0=D(()=>{Q9();eF()});var wz0=D(()=>{Q9();eF()});var zz0=D(()=>{TI1();Or();ia();pa();eF()});var jz0=D(()=>{Or();Dz0();ia();Lz0();Ez0();wz0();zz0()});import{z as M$}from"zod";function _3($){return $!==null&&$!==void 0&&"command"in $}function SB($){if(!$||!$.startsWith("virtual://"))return null;return $.replace("virtual://","")}function CB($){return`virtual://${$}`}var uZ8,Pz0,cZ8,lZ8,dZ8,BG,ig,ng;var Az0=D(()=>{Q9();uZ8=M$.object({authorizationEndpoint:M$.string().url(),tokenEndpoint:M$.string().url(),introspectionEndpoint:M$.string().url().optional(),clientId:M$.string(),clientSecret:M$.string().optional(),scopes:M$.array(M$.string()),grantType:M$.enum(["authorization_code","client_credentials"])}),Pz0=M$.object({type:M$.literal("object"),properties:M$.record(M$.string(),M$.unknown()).optional(),required:M$.array(M$.string()).optional()}).catchall(M$.unknown()),cZ8=Cr.extend({inputSchema:Pz0,outputSchema:Pz0.optional()}),lZ8=M$.object({headers:M$.record(M$.string(),M$.string()).optional()}),dZ8=M$.object({command:M$.string().describe("Command to run (e.g., 'npx', 'node')"),args:M$.array(M$.string()).optional().describe("Command arguments"),cwd:M$.string().optional().describe("Working directory"),envVars:M$.record(M$.string(),M$.string()).optional().describe("Environment variables (encrypted in storage)")}),BG=M$.object({id:M$.string().describe("Unique identifier for the connection"),title:M$.string().describe("Human-readable name for the connection"),created_at:M$.string().describe("When the connection was created"),updated_at:M$.string().describe("When the connection was last updated"),created_by:M$.string().describe("User ID who created the connection"),updated_by:M$.string().optional().describe("User ID who last updated the connection"),organization_id:M$.string().describe("Organization ID this connection belongs to"),description:M$.string().nullable().describe("Description of the connection"),icon:M$.string().nullable().describe("Icon URL for the connection"),app_name:M$.string().nullable().describe("Associated app name"),app_id:M$.string().nullable().describe("Associated app ID"),slug:M$.string().nullable().optional().describe("URL-safe slug derived from app_name, connection_url, or title"),connection_type:M$.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:M$.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:M$.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:M$.union([dZ8,lZ8]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:uZ8.nullable().describe("OAuth configuration"),configuration_state:M$.record(M$.string(),M$.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:M$.array(M$.string()).nullable().optional().describe("Configuration scopes"),metadata:M$.record(M$.string(),M$.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:M$.array(cZ8).nullable().describe("Discovered tools from MCP"),bindings:M$.array(M$.string()).nullable().describe("Detected bindings"),status:M$.enum(["active","inactive","error"]).describe("Current status")}),ig=BG.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}).extend({icon:M$.string().nullish()}),ng=BG.partial()});import{z as s1}from"zod";function ta($){let Z=$?.homeTiles;if(Array.isArray(Z)&&Z.length>0)return Z;let G=$?.homeTile;return G?[G]:[]}function oa($){return $==="cluster"?"agent-sandbox":$}function Dq1($){let Z=tZ8.parse($);return ra.parse({...Z,sandboxProviderKind:Z.sandboxProviderKind?oa(Z.sandboxProviderKind):void 0})}function uK($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z=$,G={};for(let[X,Q]of Object.entries(Z)){if(!Q||typeof Q!=="object")continue;if(X!=="cluster"&&X!=="agent-sandbox"&&X!=="user-desktop")continue;let Y=oa(X);try{if(X==="cluster"&&G[Y])continue;G[Y]=Dq1(Q)}catch{}}return G}function aa($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z={};for(let[G,X]of Object.entries($)){if(!X||typeof X!=="object"||Array.isArray(X))continue;let Q={};for(let[Y,J]of Object.entries(X)){let W=uK(J);if(Object.keys(W).length>0)Q[Y]=W}if(Object.keys(Q).length>0)Z[G]=Q}return Z}var pg,Tz0,mZ8,Fq1,Hq1,Rz0,Nq1,tg,Iz0,iZ8,Oq1,Bq1,nZ8,pZ8,qz0,ra,tZ8,og,DG,rg,ag;var Mz0=D(()=>{pg=s1.object({connection_id:s1.string().describe("Connection ID"),selected_tools:s1.array(s1.string()).nullable().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:s1.array(s1.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. null = all resources included, array = only these resources included"),selected_prompts:s1.array(s1.string()).nullable().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),Tz0=pg.extend({selected_tools:pg.shape.selected_tools.optional(),selected_resources:pg.shape.selected_resources.optional(),selected_prompts:pg.shape.selected_prompts.optional()}),mZ8=s1.object({connectionId:s1.string(),toolName:s1.string(),label:s1.string(),icon:s1.string().nullable().optional()}),Fq1=s1.object({id:s1.string().describe("Stable id; used as React key and ?tab= value"),title:s1.string().describe("Tab label"),icon:s1.string().optional().describe("Optional lucide icon name"),view:s1.object({type:s1.literal("ext-app"),appId:s1.string(),args:s1.record(s1.string(),s1.unknown()).optional()})}),Hq1=s1.object({defaultMainView:s1.object({type:s1.string(),id:s1.string().optional(),toolName:s1.string().optional()}).nullable().optional(),chatDefaultOpen:s1.boolean().nullable().optional(),tabs:s1.array(Fq1).optional()}),Rz0=s1.object({connectionId:s1.string().optional().describe("Connection that owns the resource \u2014 the host opens a direct MCP client to this connection so the iframe can call tools by their bare names."),resourceUri:s1.string().describe("ui:// resource URI exposed by `connectionId`. Read on the home page and rendered via MCPAppRenderer."),minHeight:s1.number().int().positive().optional(),maxHeight:s1.number().int().positive().optional()}),Nq1=s1.object({banner:s1.string().nullable().optional(),bannerColor:s1.string().nullable().optional(),icon:s1.string().nullable().optional(),themeColor:s1.string().nullable().optional(),pinnedViews:s1.array(mZ8).nullable().optional(),layout:Hq1.nullable().optional(),homeTile:Rz0.nullable().optional(),homeTiles:s1.array(Rz0).nullable().optional(),homePrompts:s1.array(s1.string()).nullable().optional()});tg=/^[A-Za-z_][A-Za-z0-9_]*$/,Iz0=s1.string().min(1).regex(tg,{message:"Env var key must start with a letter or underscore and contain only letters, digits, and underscores."}),iZ8=s1.discriminatedUnion("kind",[s1.object({key:Iz0,kind:s1.literal("literal"),value:s1.string()}),s1.object({key:Iz0,kind:s1.literal("secret"),secretId:s1.string().min(1)})]),Oq1=s1.object({selected:s1.string().nullable().optional().describe("User-selected package manager (npm | pnpm | yarn | bun | deno). Null/absent means autodetect on next SANDBOX_START."),port:s1.string().nullable().optional().describe("User-selected dev server port as a string (allows '' / null for unset). Null/absent means autodetect."),path:s1.string().nullable().optional().describe("Optional path (relative to repo root) to the directory containing package.json. Null/absent means repo root. Forwarded as `application.packageManager.path` to the daemon config."),env:s1.array(iZ8).nullable().optional().describe("Env vars injected on every SANDBOX_START. Literal entries inline their value; secret entries store a secretId that mesh resolves via the credential vault before posting /_sandbox/config.")}),Bq1=s1.object({url:s1.string().describe("GitHub repository URL"),owner:s1.string().describe("Repository owner"),name:s1.string().describe("Repository name"),installationId:s1.number().optional().describe("GitHub App installation ID. Absent when the repo was linked without a GitHub connection (public-clone mode)."),connectionId:s1.string().optional().describe("ID of the mcp-github connection used for authentication. Absent for public repos cloned without credentials.")}),nZ8=s1.enum(["agent-sandbox","user-desktop"]),pZ8=s1.enum(["agent-sandbox","user-desktop","cluster"]);qz0={sandboxHandle:s1.string().describe("Provider-specific handle"),previewUrl:s1.string().nullable().describe("URL where the sandbox's iframe-proxied UI is served, or null when the sandbox has no dev server (blank / tool sandboxes)."),sandboxApiUrl:s1.string().nullable().optional().describe("Daemon's public URL \u2014 what cluster\u2192daemon RPCs target. Equal to previewUrl for user-desktop; null/absent for the agent-sandbox provider (routes through hosted ingress)."),sandboxProviderKind:nZ8.optional(),createdAt:s1.number().optional().describe("Epoch ms the entry was first written by SANDBOX_START. Used by the booting overlay to show a stable elapsed timer that survives browser reloads. Optional for backward compatibility with entries written before this field existed."),startedWith:s1.object({packageManager:s1.string().nullable().optional().describe("metadata.runtime.selected at the time of SANDBOX_START"),port:s1.string().nullable().optional().describe("metadata.runtime.port at the time of SANDBOX_START"),path:s1.string().nullable().optional().describe("metadata.runtime.path at the time of SANDBOX_START")}).optional().describe("Snapshot of metadata.runtime fields (selected/port/path) used at SANDBOX_START. The Preview tab compares the live metadata.runtime against this to decide if a restart is required to apply changes.")},ra=s1.object(qz0),tZ8=s1.object({...qz0,sandboxProviderKind:pZ8.optional()});og=s1.record(s1.string().describe("userId"),s1.record(s1.string().describe("branch"),s1.record(s1.string().describe("sandboxProviderKind"),ra)));DG=s1.object({id:s1.string().describe("Unique identifier"),title:s1.string().describe("Human-readable name"),description:s1.string().nullable().describe("Description"),icon:s1.string().nullable().describe("Icon URL"),created_at:s1.string().describe("Creation timestamp"),updated_at:s1.string().describe("Last update timestamp"),created_by:s1.string().describe("User ID who created this item"),updated_by:s1.string().optional().describe("User ID who last updated this item"),organization_id:s1.string().describe("Organization ID this item belongs to"),status:s1.enum(["active","inactive"]).describe("Current status"),pinned:s1.boolean().describe("Whether this space is pinned to the sidebar"),metadata:s1.object({instructions:s1.string().nullable().describe("Instructions also used as system prompt"),enabled_plugins:s1.array(s1.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:s1.array(s1.string()).nullable().optional().describe("Allowlist of Virtual MCP (agent) IDs this agent may delegate to via subtask. null/absent = all active org agents; empty array = itself only (no cross-agent delegation)."),ui:Nq1.nullable().optional().describe("UI customization settings"),githubRepo:Bq1.nullable().optional().describe("Linked GitHub repository"),runtime:Oq1.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:og.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }")}).loose().describe("Metadata"),connections:s1.array(pg).describe("Connections with their selected tools, resources, and prompts")}),rg=s1.object({title:s1.string().min(1).max(255).describe("Name for the virtual MCP"),description:s1.string().nullable().optional().describe("Optional description"),icon:s1.string().nullish().describe("Optional icon URL"),status:s1.enum(["active","inactive"]).optional().default("active").describe("Initial status"),pinned:s1.boolean().optional().default(!1).describe("Pin to sidebar"),metadata:s1.object({instructions:s1.string().nullable().optional().describe("MCP server instructions"),enabled_plugins:s1.array(s1.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:s1.array(s1.string()).nullable().optional().describe("Allowlist of Virtual MCP (agent) IDs this agent may delegate to via subtask. null/absent = all active org agents; empty array = itself only (no cross-agent delegation)."),ui:Nq1.nullable().optional().describe("UI customization settings"),githubRepo:Bq1.nullable().optional().describe("Linked GitHub repository"),runtime:Oq1.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:og.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }")}).loose().nullable().optional().describe("Additional metadata including MCP server instructions"),connections:s1.array(Tz0).describe("Connections to include/exclude (can be empty for exclusion mode)")}),ag=s1.object({title:s1.string().min(1).max(255).optional().describe("New name"),description:s1.string().nullable().optional().describe("New description (null to clear)"),icon:s1.string().nullish().describe("New icon URL"),status:s1.enum(["active","inactive"]).optional().describe("New status"),pinned:s1.boolean().optional().describe("Pin/unpin from sidebar"),metadata:s1.object({instructions:s1.string().nullable().optional().describe("MCP server instructions"),enabled_plugins:s1.array(s1.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:s1.array(s1.string()).nullable().optional().describe("Allowlist of Virtual MCP (agent) IDs this agent may delegate to via subtask. null/absent = all active org agents; empty array = itself only (no cross-agent delegation)."),ui:Nq1.nullable().optional().describe("UI customization settings"),githubRepo:Bq1.nullable().optional().describe("Linked GitHub repository"),runtime:Oq1.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:og.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }")}).loose().nullable().optional().describe("Additional metadata including MCP server instructions"),connections:s1.array(Tz0).optional().describe("New connections (replaces existing)")})});var rZ;var kz0=D(()=>{rZ=["deco","anthropic","openrouter","google","claude-code","codex","openai-compatible"]});function sa($,Z){return{id:crypto.randomUUID(),type:bC.STEP,source:"decopilot",subject:$,data:{stepCount:Z},time:new Date().toISOString()}}function wH($,Z){return{id:crypto.randomUUID(),type:bC.FINISH,source:"decopilot",subject:$,data:{status:Z},time:new Date().toISOString()}}function sQ($,Z,G){return{id:crypto.randomUUID(),type:bC.THREAD_STATUS,source:"decopilot",subject:$,data:{status:Z,...G?.virtualMcpId!==void 0&&{virtual_mcp_id:G.virtualMcpId},...G?.createdBy!==void 0&&{created_by:G.createdBy},...G?.triggerId!==void 0&&{trigger_id:G.triggerId},...G?.title!==void 0&&{title:G.title},...G?.branch!==void 0&&{branch:G.branch},...G?.createdAt!==void 0&&{created_at:G.createdAt},...G?.updatedAt!==void 0&&{updated_at:G.updatedAt},...G?.metadata!==void 0&&{metadata:G.metadata}},time:new Date().toISOString()}}var _C,Vz0,bC,Sz0;var Cz0=D(()=>{_C=["in_progress","requires_action","failed","completed"],Vz0=[..._C,"expired"],bC={STEP:"decopilot.step",FINISH:"decopilot.finish",THREAD_STATUS:"decopilot.thread.status"},Sz0=Object.values(bC)});var ea=D(()=>{Az0();Mz0();kz0();Cz0()});function rZ8(){let $=new _z0.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return bz0.default($),$}class vz0{#$=rZ8();#Z=new Map;getValidator($){let Z=aZ8($),G=this.#Z.get(Z);if(!G)G=this.#$.compile($),this.#Z.set(Z,G);let X=G;return(Q)=>{if(X(Q))return{valid:!0,data:Q,errorMessage:void 0};return{valid:!1,data:void 0,errorMessage:this.#$.errorsText(X.errors)}}}}function aZ8($){return JSON.stringify($,(Z,G)=>{if(G&&typeof G==="object"&&!Array.isArray(G))return Object.fromEntries(Object.keys(G).sort().map((X)=>[X,G[X]]));return G})}var _z0,bz0,g9;var Lq1=D(()=>{_z0=f(Ta(),1),bz0=f(_21(),1);g9=new vz0});class vC{innerTransport;constructor($){this.innerTransport=$}get sessionId(){return this.innerTransport.sessionId}async start(){return this.innerTransport.onmessage=($)=>{this.handleIncomingMessage($)},this.innerTransport.onerror=($)=>{this.onerror?.($)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send($){return this.handleOutgoingMessage($)}async close(){return this.innerTransport.close()}async handleOutgoingMessage($){return this.innerTransport.send($)}handleIncomingMessage($){this.onmessage?.($)}isRequest($){return"method"in $&&$.method!==void 0}isResponse($){return"result"in $||"error"in $&&!("method"in $)}onmessage;onerror;onclose}function fC($,...Z){return Z.reduce((G,X)=>X(G),$)}class Eq1{constructor($){this._server=$}requestStream($,Z,G){return this._server.requestStream($,Z,G)}createMessageStream($,Z){let G=this._server.getClientCapabilities();if(($.tools||$.toolChoice)&&!G?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if($.messages.length>0){let X=$.messages[$.messages.length-1],Q=Array.isArray(X.content)?X.content:[X.content],Y=Q.some((U)=>U.type==="tool_result"),J=$.messages.length>1?$.messages[$.messages.length-2]:void 0,W=J?Array.isArray(J.content)?J.content:[J.content]:[],K=W.some((U)=>U.type==="tool_use");if(Y){if(Q.some((U)=>U.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!K)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(K){let U=new Set(W.filter((H)=>H.type==="tool_use").map((H)=>H.id)),F=new Set(Q.filter((H)=>H.type==="tool_result").map((H)=>H.toolUseId));if(U.size!==F.size||![...U].every((H)=>F.has(H)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:$},jB,Z)}elicitInputStream($,Z){let G=this._server.getClientCapabilities(),X=$.mode??"form";switch(X){case"url":{if(!G?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!G?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let Q=X==="form"&&$.mode===void 0?{...$,mode:"form"}:$;return this.requestStream({method:"elicitation/create",params:Q},WH,Z)}async getTask($,Z){return this._server.getTask({taskId:$},Z)}async getTaskResult($,Z,G){return this._server.getTaskResult({taskId:$},Z,G)}async listTasks($,Z){return this._server.listTasks($?{cursor:$}:void 0,Z)}async cancelTask($,Z){return this._server.cancelTask({taskId:$},Z)}}var fz0=D(()=>{Q9()});var wq1;var xz0=D(()=>{VT1();Q9();b21();WC();fz0();wq1=class wq1 extends zg{constructor($,Z){super(Z);if(this._serverInfo=$,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Dg.options.map((G,X)=>[G,X])),this.isMessageIgnored=(G,X)=>{let Q=this._loggingLevels.get(X);return Q?this.LOG_LEVEL_SEVERITY.get(G)<this.LOG_LEVEL_SEVERITY.get(Q):!1},this._capabilities=Z?.capabilities??{},this._instructions=Z?.instructions,this._jsonSchemaValidator=Z?.jsonSchemaValidator??new dg,this.setRequestHandler(Pr,(G)=>this._oninitialize(G)),this.setNotificationHandler(Ar,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(nI1,async(G,X)=>{let Q=X.sessionId||X.requestInfo?.headers["mcp-session-id"]||void 0,{level:Y}=G.params,J=Dg.safeParse(Y);if(J.success)this._loggingLevels.set(Q,J.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new Eq1(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=lr(this._capabilities,$)}setRequestHandler($,Z){let X=I3($)?.method;if(!X)throw Error("Schema is missing a method literal");let Q;if(iG(X)){let J=X;Q=J._zod?.def?.value??J.value}else{let J=X;Q=J._def?.value??J.value}if(typeof Q!=="string")throw Error("Schema method literal must be a string");if(Q==="tools/call"){let J=async(W,K)=>{let U=FG(JH,W);if(!U.success){let O=U.error instanceof Error?U.error.message:String(U.error);throw new V0(y0.InvalidParams,`Invalid tools/call request: ${O}`)}let{params:F}=U.data,H=await Promise.resolve(Z(W,K));if(F.task){let O=FG(vK,H);if(!O.success){let B=O.error instanceof Error?O.error.message:String(O.error);throw new V0(y0.InvalidParams,`Invalid task creation result: ${B}`)}return O.data}let N=FG(q3,H);if(!N.success){let O=N.error instanceof Error?N.error.message:String(N.error);throw new V0(y0.InvalidParams,`Invalid tools/call result: ${O}`)}return N.data};return super.setRequestHandler($,J)}return super.setRequestHandler($,Z)}assertCapabilityForMethod($){switch($){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${$})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${$})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${$})`);break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${$})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${$})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${$})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${$})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){if(!this._capabilities)return;switch($){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${$})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${$})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${$})`);break;case"ping":case"initialize":break}}assertTaskCapability($){ka(this._clientCapabilities?.tasks?.requests,$,"Client")}assertTaskHandlerCapability($){if(!this._capabilities)return;Ma(this._capabilities.tasks?.requests,$,"Server")}async _oninitialize($){let Z=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:ZH.includes(Z)?Z:$H,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},bK)}async createMessage($,Z){if($.tools||$.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if($.messages.length>0){let G=$.messages[$.messages.length-1],X=Array.isArray(G.content)?G.content:[G.content],Q=X.some((K)=>K.type==="tool_result"),Y=$.messages.length>1?$.messages[$.messages.length-2]:void 0,J=Y?Array.isArray(Y.content)?Y.content:[Y.content]:[],W=J.some((K)=>K.type==="tool_use");if(Q){if(X.some((K)=>K.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!W)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(W){let K=new Set(J.filter((F)=>F.type==="tool_use").map((F)=>F.id)),U=new Set(X.filter((F)=>F.type==="tool_result").map((F)=>F.toolUseId));if(K.size!==U.size||![...K].every((F)=>U.has(F)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if($.tools)return this.request({method:"sampling/createMessage",params:$},Lg,Z);return this.request({method:"sampling/createMessage",params:$},jB,Z)}async elicitInput($,Z){switch($.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let X=$;return this.request({method:"elicitation/create",params:X},WH,Z)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let X=$.mode==="form"?$:{...$,mode:"form"},Q=await this.request({method:"elicitation/create",params:X},WH,Z);if(Q.action==="accept"&&Q.content&&X.requestedSchema)try{let J=this._jsonSchemaValidator.getValidator(X.requestedSchema)(Q.content);if(!J.valid)throw new V0(y0.InvalidParams,`Elicitation response content does not match requested schema: ${J.errorMessage}`)}catch(Y){if(Y instanceof V0)throw Y;throw new V0(y0.InternalError,`Error validating elicitation response: ${Y instanceof Error?Y.message:String(Y)}`)}return Q}}}createElicitationCompletionNotifier($,Z){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:$}},Z)}async listRoots($,Z){return this.request({method:"roots/list",params:$},rI1,Z)}async sendLoggingMessage($,Z){if(this._capabilities.logging){if(!this.isMessageIgnored($.level,Z))return this.notification({method:"notifications/message",params:$})}}async sendResourceUpdated($){return this.notification({method:"notifications/resources/updated",params:$})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function zq1($){return!!$&&typeof $==="object"&&gz0 in $}function hz0($){return $[gz0]?.complete}var gz0,yz0;var uz0=D(()=>{gz0=Symbol.for("mcp.completable");(function($){$.Completable="McpCompletable"})(yz0||(yz0={}))});function eZ8($){let Z=[];if($.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if($.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${$.length})`]};if($.includes(" "))Z.push("Tool name contains spaces, which may cause parsing issues");if($.includes(","))Z.push("Tool name contains commas, which may cause parsing issues");if($.startsWith("-")||$.endsWith("-"))Z.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if($.startsWith(".")||$.endsWith("."))Z.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!sZ8.test($)){let G=$.split("").filter((X)=>!/[A-Za-z0-9._-]/.test(X)).filter((X,Q,Y)=>Y.indexOf(X)===Q);return Z.push(`Tool name contains invalid characters: ${G.map((X)=>`"${X}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:Z}}return{isValid:!0,warnings:Z}}function $78($,Z){if(Z.length>0){console.warn(`Tool name validation warning for "${$}":`);for(let G of Z)console.warn(` - ${G}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function jq1($){let Z=eZ8($);return $78($,Z.warnings),Z.isValid}var sZ8;var cz0=D(()=>{sZ8=/^[A-Za-z0-9._-]{1,128}$/});class Pq1{constructor($){this._mcpServer=$}registerToolTask($,Z,G){let X={taskSupport:"required",...Z.execution};if(X.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${$}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool($,Z.title,Z.description,Z.inputSchema,Z.outputSchema,Z.annotations,X,Z._meta,G)}}import{ZodOptional as Z78}from"zod";class cK{constructor($,Z){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new wq1($,Z)}get experimental(){if(!this._experimental)this._experimental={tasks:new Pq1(this)};return this._experimental}async connect($){return await this.server.connect($)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(zH(OC)),this.server.assertCanSetRequestHandler(zH(JH)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(OC,()=>({tools:Object.entries(this._registeredTools).filter(([,$])=>$.enabled).map(([$,Z])=>{let G={name:$,title:Z.title,description:Z.description,inputSchema:(()=>{let X=JC(Z.inputSchema);return X?TT1(X,{strictUnions:!0,pipeStrategy:"input"}):G78})(),annotations:Z.annotations,execution:Z.execution,_meta:Z._meta};if(Z.outputSchema){let X=JC(Z.outputSchema);if(X)G.outputSchema=TT1(X,{strictUnions:!0,pipeStrategy:"output"})}return G})})),this.server.setRequestHandler(JH,async($,Z)=>{try{let G=this._registeredTools[$.params.name];if(!G)throw new V0(y0.InvalidParams,`Tool ${$.params.name} not found`);if(!G.enabled)throw new V0(y0.InvalidParams,`Tool ${$.params.name} disabled`);let X=!!$.params.task,Q=G.execution?.taskSupport,Y="createTask"in G.handler;if((Q==="required"||Q==="optional")&&!Y)throw new V0(y0.InternalError,`Tool ${$.params.name} has taskSupport '${Q}' but was not registered with registerToolTask`);if(Q==="required"&&!X)throw new V0(y0.MethodNotFound,`Tool ${$.params.name} requires task augmentation (taskSupport: 'required')`);if(Q==="optional"&&!X&&Y)return await this.handleAutomaticTaskPolling(G,$,Z);let J=await this.validateToolInput(G,$.params.arguments,$.params.name),W=await this.executeToolHandler(G,J,Z);if(X)return W;return await this.validateToolOutput(G,W,$.params.name),W}catch(G){if(G instanceof V0){if(G.code===y0.UrlElicitationRequired)throw G}return this.createToolError(G instanceof Error?G.message:String(G))}}),this._toolHandlersInitialized=!0}createToolError($){return{content:[{type:"text",text:$}],isError:!0}}async validateToolInput($,Z,G){if(!$.inputSchema)return;let Q=JC($.inputSchema)??$.inputSchema,Y=await Br(Q,Z);if(!Y.success){let J="error"in Y?Y.error:"Unknown error",W=Dr(J);throw new V0(y0.InvalidParams,`Input validation error: Invalid arguments for tool ${G}: ${W}`)}return Y.data}async validateToolOutput($,Z,G){if(!$.outputSchema)return;if(!("content"in Z))return;if(Z.isError)return;if(!Z.structuredContent)throw new V0(y0.InvalidParams,`Output validation error: Tool ${G} has an output schema but no structured content was provided`);let X=JC($.outputSchema),Q=await Br(X,Z.structuredContent);if(!Q.success){let Y="error"in Q?Q.error:"Unknown error",J=Dr(Y);throw new V0(y0.InvalidParams,`Output validation error: Invalid structured content for tool ${G}: ${J}`)}}async executeToolHandler($,Z,G){let X=$.handler;if("createTask"in X){if(!G.taskStore)throw Error("No task store provided.");let Y={...G,taskStore:G.taskStore};if($.inputSchema)return await Promise.resolve(X.createTask(Z,Y));else return await Promise.resolve(X.createTask(Y))}if($.inputSchema)return await Promise.resolve(X(Z,G));else return await Promise.resolve(X(G))}async handleAutomaticTaskPolling($,Z,G){if(!G.taskStore)throw Error("No task store provided for task-capable tool.");let X=await this.validateToolInput($,Z.params.arguments,Z.params.name),Q=$.handler,Y={...G,taskStore:G.taskStore},J=X?await Promise.resolve(Q.createTask(X,Y)):await Promise.resolve(Q.createTask(Y)),W=J.task.taskId,K=J.task,U=K.pollInterval??5000;while(K.status!=="completed"&&K.status!=="failed"&&K.status!=="cancelled"){await new Promise((H)=>setTimeout(H,U));let F=await G.taskStore.getTask(W);if(!F)throw new V0(y0.InternalError,`Task ${W} not found during polling`);K=F}return await G.taskStore.getTaskResult(W)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(zH(_r)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(_r,async($)=>{switch($.params.ref.type){case"ref/prompt":return VO0($),this.handlePromptCompletion($,$.params.ref);case"ref/resource":return SO0($),this.handleResourceCompletion($,$.params.ref);default:throw new V0(y0.InvalidParams,`Invalid completion reference: ${$.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion($,Z){let G=this._registeredPrompts[Z.name];if(!G)throw new V0(y0.InvalidParams,`Prompt ${Z.name} not found`);if(!G.enabled)throw new V0(y0.InvalidParams,`Prompt ${Z.name} disabled`);if(!G.argsSchema)return sg;let Q=I3(G.argsSchema)?.[$.params.argument.name];if(!zq1(Q))return sg;let Y=hz0(Q);if(!Y)return sg;let J=await Y($.params.argument.value,$.params.context);return dz0(J)}async handleResourceCompletion($,Z){let G=Object.values(this._registeredResourceTemplates).find((Y)=>Y.resourceTemplate.uriTemplate.toString()===Z.uri);if(!G){if(this._registeredResources[Z.uri])return sg;throw new V0(y0.InvalidParams,`Resource template ${$.params.ref.uri} not found`)}let X=G.resourceTemplate.completeCallback($.params.argument.name);if(!X)return sg;let Q=await X($.params.argument.value,$.params.context);return dz0(Q)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(zH(XH)),this.server.assertCanSetRequestHandler(zH(QH)),this.server.assertCanSetRequestHandler(zH(HC)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(XH,async($,Z)=>{let G=Object.entries(this._registeredResources).filter(([Q,Y])=>Y.enabled).map(([Q,Y])=>({uri:Q,name:Y.name,...Y.metadata})),X=[];for(let Q of Object.values(this._registeredResourceTemplates)){if(!Q.resourceTemplate.listCallback)continue;let Y=await Q.resourceTemplate.listCallback(Z);for(let J of Y.resources)X.push({...Q.metadata,...J})}return{resources:[...G,...X]}}),this.server.setRequestHandler(QH,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([Z,G])=>({name:Z,uriTemplate:G.resourceTemplate.uriTemplate.toString(),...G.metadata}))}}),this.server.setRequestHandler(HC,async($,Z)=>{let G=new URL($.params.uri),X=this._registeredResources[G.toString()];if(X){if(!X.enabled)throw new V0(y0.InvalidParams,`Resource ${G} disabled`);return X.readCallback(G,Z)}for(let Q of Object.values(this._registeredResourceTemplates)){let Y=Q.resourceTemplate.uriTemplate.match(G.toString());if(Y)return Q.readCallback(G,Y,Z)}throw new V0(y0.InvalidParams,`Resource ${G} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(zH(YH)),this.server.assertCanSetRequestHandler(zH(NC)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(YH,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,$])=>$.enabled).map(([$,Z])=>{return{name:$,title:Z.title,description:Z.description,arguments:Z.argsSchema?X78(Z.argsSchema):void 0}})})),this.server.setRequestHandler(NC,async($,Z)=>{let G=this._registeredPrompts[$.params.name];if(!G)throw new V0(y0.InvalidParams,`Prompt ${$.params.name} not found`);if(!G.enabled)throw new V0(y0.InvalidParams,`Prompt ${$.params.name} disabled`);if(G.argsSchema){let X=JC(G.argsSchema),Q=await Br(X,$.params.arguments);if(!Q.success){let W="error"in Q?Q.error:"Unknown error",K=Dr(W);throw new V0(y0.InvalidParams,`Invalid arguments for prompt ${$.params.name}: ${K}`)}let Y=Q.data,J=G.callback;return await Promise.resolve(J(Y,Z))}else{let X=G.callback;return await Promise.resolve(X(Z))}}),this._promptHandlersInitialized=!0}resource($,Z,...G){let X;if(typeof G[0]==="object")X=G.shift();let Q=G[0];if(typeof Z==="string"){if(this._registeredResources[Z])throw Error(`Resource ${Z} is already registered`);let Y=this._createRegisteredResource($,void 0,Z,X,Q);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),Y}else{if(this._registeredResourceTemplates[$])throw Error(`Resource template ${$} is already registered`);let Y=this._createRegisteredResourceTemplate($,void 0,Z,X,Q);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),Y}}registerResource($,Z,G,X){if(typeof Z==="string"){if(this._registeredResources[Z])throw Error(`Resource ${Z} is already registered`);let Q=this._createRegisteredResource($,G.title,Z,G,X);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),Q}else{if(this._registeredResourceTemplates[$])throw Error(`Resource template ${$} is already registered`);let Q=this._createRegisteredResourceTemplate($,G.title,Z,G,X);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),Q}}_createRegisteredResource($,Z,G,X,Q){let Y={name:$,title:Z,metadata:X,readCallback:Q,enabled:!0,disable:()=>Y.update({enabled:!1}),enable:()=>Y.update({enabled:!0}),remove:()=>Y.update({uri:null}),update:(J)=>{if(typeof J.uri<"u"&&J.uri!==G){if(delete this._registeredResources[G],J.uri)this._registeredResources[J.uri]=Y}if(typeof J.name<"u")Y.name=J.name;if(typeof J.title<"u")Y.title=J.title;if(typeof J.metadata<"u")Y.metadata=J.metadata;if(typeof J.callback<"u")Y.readCallback=J.callback;if(typeof J.enabled<"u")Y.enabled=J.enabled;this.sendResourceListChanged()}};return this._registeredResources[G]=Y,Y}_createRegisteredResourceTemplate($,Z,G,X,Q){let Y={resourceTemplate:G,title:Z,metadata:X,readCallback:Q,enabled:!0,disable:()=>Y.update({enabled:!1}),enable:()=>Y.update({enabled:!0}),remove:()=>Y.update({name:null}),update:(K)=>{if(typeof K.name<"u"&&K.name!==$){if(delete this._registeredResourceTemplates[$],K.name)this._registeredResourceTemplates[K.name]=Y}if(typeof K.title<"u")Y.title=K.title;if(typeof K.template<"u")Y.resourceTemplate=K.template;if(typeof K.metadata<"u")Y.metadata=K.metadata;if(typeof K.callback<"u")Y.readCallback=K.callback;if(typeof K.enabled<"u")Y.enabled=K.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[$]=Y;let J=G.uriTemplate.variableNames;if(Array.isArray(J)&&J.some((K)=>!!G.completeCallback(K)))this.setCompletionRequestHandler();return Y}_createRegisteredPrompt($,Z,G,X,Q){let Y={title:Z,description:G,argsSchema:X===void 0?void 0:zB(X),callback:Q,enabled:!0,disable:()=>Y.update({enabled:!1}),enable:()=>Y.update({enabled:!0}),remove:()=>Y.update({name:null}),update:(J)=>{if(typeof J.name<"u"&&J.name!==$){if(delete this._registeredPrompts[$],J.name)this._registeredPrompts[J.name]=Y}if(typeof J.title<"u")Y.title=J.title;if(typeof J.description<"u")Y.description=J.description;if(typeof J.argsSchema<"u")Y.argsSchema=zB(J.argsSchema);if(typeof J.callback<"u")Y.callback=J.callback;if(typeof J.enabled<"u")Y.enabled=J.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[$]=Y,X){if(Object.values(X).some((W)=>{let K=W instanceof Z78?W._def?.innerType:W;return zq1(K)}))this.setCompletionRequestHandler()}return Y}_createRegisteredTool($,Z,G,X,Q,Y,J,W,K){jq1($);let U={title:Z,description:G,inputSchema:lz0(X),outputSchema:lz0(Q),annotations:Y,execution:J,_meta:W,handler:K,enabled:!0,disable:()=>U.update({enabled:!1}),enable:()=>U.update({enabled:!0}),remove:()=>U.update({name:null}),update:(F)=>{if(typeof F.name<"u"&&F.name!==$){if(typeof F.name==="string")jq1(F.name);if(delete this._registeredTools[$],F.name)this._registeredTools[F.name]=U}if(typeof F.title<"u")U.title=F.title;if(typeof F.description<"u")U.description=F.description;if(typeof F.paramsSchema<"u")U.inputSchema=zB(F.paramsSchema);if(typeof F.outputSchema<"u")U.outputSchema=zB(F.outputSchema);if(typeof F.callback<"u")U.handler=F.callback;if(typeof F.annotations<"u")U.annotations=F.annotations;if(typeof F._meta<"u")U._meta=F._meta;if(typeof F.enabled<"u")U.enabled=F.enabled;this.sendToolListChanged()}};return this._registeredTools[$]=U,this.setToolRequestHandlers(),this.sendToolListChanged(),U}tool($,...Z){if(this._registeredTools[$])throw Error(`Tool ${$} is already registered`);let G,X,Q,Y;if(typeof Z[0]==="string")G=Z.shift();if(Z.length>1){let W=Z[0];if(Aq1(W)){if(X=Z.shift(),Z.length>1&&typeof Z[0]==="object"&&Z[0]!==null&&!Aq1(Z[0]))Y=Z.shift()}else if(typeof W==="object"&&W!==null){if(Object.values(W).some((K)=>typeof K==="object"&&K!==null))throw Error(`Tool ${$} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);Y=Z.shift()}}let J=Z[0];return this._createRegisteredTool($,void 0,G,X,Q,Y,{taskSupport:"forbidden"},void 0,J)}registerTool($,Z,G){if(this._registeredTools[$])throw Error(`Tool ${$} is already registered`);let{title:X,description:Q,inputSchema:Y,outputSchema:J,annotations:W,_meta:K}=Z;return this._createRegisteredTool($,X,Q,Y,J,W,{taskSupport:"forbidden"},K,G)}prompt($,...Z){if(this._registeredPrompts[$])throw Error(`Prompt ${$} is already registered`);let G;if(typeof Z[0]==="string")G=Z.shift();let X;if(Z.length>1)X=Z.shift();let Q=Z[0],Y=this._createRegisteredPrompt($,void 0,G,X,Q);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),Y}registerPrompt($,Z,G){if(this._registeredPrompts[$])throw Error(`Prompt ${$} is already registered`);let{title:X,description:Q,argsSchema:Y}=Z,J=this._createRegisteredPrompt($,X,Q,Y,G);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),J}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage($,Z){return this.server.sendLoggingMessage($,Z)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}function mz0($){return $!==null&&typeof $==="object"&&"parse"in $&&typeof $.parse==="function"&&"safeParse"in $&&typeof $.safeParse==="function"}function iz0($){return"_def"in $||"_zod"in $||mz0($)}function Aq1($){if(typeof $!=="object"||$===null)return!1;if(iz0($))return!1;if(Object.keys($).length===0)return!0;return Object.values($).some(mz0)}function lz0($){if(!$)return;if(Aq1($))return zB($);if(!iz0($))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return $}function X78($){let Z=I3($);if(!Z)return[];return Object.entries(Z).map(([G,X])=>{let Q=NO0(X),Y=OO0(X);return{name:G,description:Q,required:!Y}})}function zH($){let G=I3($)?.method;if(!G)throw Error("Schema is missing a method literal");let X=Lr(G);if(typeof X==="string")return X;throw Error("Schema method literal must be a string")}function dz0($){return{completion:{values:$.slice(0,100),total:$.length,hasMore:$.length>100}}}var G78,sg;var eg=D(()=>{xz0();WC();kT1();Q9();uz0();cz0();G78={type:"object",properties:{}};sg={completion:{values:[],hasMore:!1}}});function lK($,Z,G){let X=G?.capabilities??$.getServerCapabilities(),Q=G?.instructions??$.getInstructions(),Y=new cK(Z,{capabilities:X,instructions:Q,jsonSchemaValidator:g9});if(Y.server.setRequestHandler(OC,async(J)=>{let W=await $.listTools(J.params);return{...W,tools:W.tools.map(({outputSchema:K,...U})=>U)}}),Y.server.setRequestHandler(JH,(J)=>$.callTool(J.params,void 0,G?.toolCallTimeoutMs?{timeout:G.toolCallTimeoutMs}:void 0)),X?.resources)Y.server.setRequestHandler(XH,(J)=>$.listResources(J.params)),Y.server.setRequestHandler(HC,(J)=>$.readResource(J.params)),Y.server.setRequestHandler(QH,(J)=>$.listResourceTemplates(J.params));if(X?.prompts)Y.server.setRequestHandler(YH,(J)=>$.listPrompts(J.params)),Y.server.setRequestHandler(NC,(J)=>$.getPrompt({...J.params,arguments:J.params.arguments??{}}));return Y}var nz0=D(()=>{eg();Lq1();Q9()});class pz0{clientQueue=[];serverQueue=[];clientClosed=!1;serverClosed=!1;clientFlushScheduled=!1;serverFlushScheduled=!1;clientTransport;serverTransport;registerTransports($,Z){this.clientTransport=$,this.serverTransport=Z,$.setOppositeTransport(Z),Z.setOppositeTransport($)}getQueue($){return $==="client"?this.clientQueue:this.serverQueue}isClosed($){return $==="client"?this.clientClosed:this.serverClosed}close($){if($==="client")this.clientClosed=!0,this.clientQueue=[];else this.serverClosed=!0,this.serverQueue=[]}enqueue($,Z){if(this.isClosed($))return;let G=this.getQueue($);if(G.length>=1e4)throw Error(`BridgeTransport: ${$} queue overflow (max 10000 messages). The receiver may not be processing messages fast enough.`);if(G.push(Z),$==="client"&&!this.clientFlushScheduled)this.scheduleFlush("client");else if($==="server"&&!this.serverFlushScheduled)this.scheduleFlush("server")}scheduleFlush($){if($==="client")this.clientFlushScheduled=!0;else this.serverFlushScheduled=!0;queueMicrotask(()=>{this.flush($)})}flush($){let Z=this.getQueue($);if($==="client")this.clientFlushScheduled=!1;else this.serverFlushScheduled=!1;if(this.isClosed($)){Z.length=0;return}let G=$==="client"?this.clientTransport:this.serverTransport;if(!G)return;if(!G.started)return;let X=Z.splice(0);for(let Q of X)G.deliverMessage(Q)}closeBoth(){this.close("client"),this.close("server")}}class Rq1{channel;side;started=!1;closed=!1;_onmessage;_onerror;_onclose;constructor($,Z){this.channel=$,this.side=Z}get onmessage(){return this._onmessage}set onmessage($){if(this._onmessage=$,$&&this.started&&!this.closed)this.channel.flush(this.side)}get onerror(){return this._onerror}set onerror($){this._onerror=$}get onclose(){return this._onclose}set onclose($){this._onclose=$}async start(){if(this.started)throw Error(`${this.side==="client"?"BridgeClientTransport":"BridgeServerTransport"} already started! If using Client/Server class, note that connect() calls start() automatically.`);if(this.started=!0,this._onmessage&&!this.closed)this.channel.flush(this.side)}async send($){if(this.closed)return Promise.resolve();let Z=this.side==="client"?"server":"client";return this.channel.enqueue(Z,$),Promise.resolve()}async close(){if(!this.started||this.closed)return;this.closed=!0,this.channel.close(this.side);let $=this.getOppositeTransport();if($&&!$.closed)$._onclose?.();this._onclose?.()}deliverMessage($){if(!this.started||this.channel.isClosed(this.side))return;try{this._onmessage?.($)}catch(Z){this._onerror?.(Z)}}}function $h(){let $=new pz0,Z=new xC($),G=new yC($);return $.registerTransports(Z,G),{client:Z,server:G,channel:$}}var xC,yC;var tz0=D(()=>{xC=class xC extends Rq1{oppositeTransport;constructor($){super($,"client")}getOppositeTransport(){return this.oppositeTransport}setOppositeTransport($){if(!($ instanceof yC))throw Error("Opposite transport must be BridgeServerTransport");this.oppositeTransport=$}async start(){await super.start()}async send($){await super.send($)}};yC=class yC extends Rq1{oppositeTransport;constructor($){super($,"server")}getOppositeTransport(){return this.oppositeTransport}setOppositeTransport($){if(!($ instanceof xC))throw Error("Opposite transport must be BridgeClientTransport");this.oppositeTransport=$}async start(){await super.start()}async send($){await super.send($)}}});var mX=D(()=>{Lq1();nz0();tz0()});var oz0=D(()=>{mX()});var rz0=D(()=>{mX()});function Zh($,Z,G,X){for(let Q of G){let Y=$.find((J)=>J.modelId===Q);if(Y)return{keyId:Z,modelId:Y.modelId,title:Y.title}}for(let Q of G){let Y=$.find((J)=>J.modelId.includes(Q));if(Y)return{keyId:Z,modelId:Y.modelId,title:Y.title}}if(X){let Q=$.find(X);if(Q)return{keyId:Z,modelId:Q.modelId,title:Q.title}}return null}function Iq1($,Z){let G={chat:{fast:null,smart:null,thinking:null},image:null,webResearch:null};for(let X of $){let Q=Z[X.id]??[],Y=X.providerId;if(!G.chat.fast)G.chat.fast=Zh(Q,X.id,az0[Y]??[]);if(!G.chat.smart)G.chat.smart=Zh(Q,X.id,sz0[Y]??[]);if(!G.chat.thinking)G.chat.thinking=Zh(Q,X.id,ez0[Y]??[]);if(!G.image)G.image=Zh(Q,X.id,$j0[Y]??[],(J)=>J.capabilities?.includes("image")===!0);if(!G.webResearch)G.webResearch=Zh(Q,X.id,Zj0[Y]??[],(J)=>{let W=J.modelId.toLowerCase().replace(/[^a-z0-9]/g,"");return W.includes("sonar")||W.includes("deepresearch")})}return G}var az0,sz0,ez0,$j0,Zj0;var Gj0=D(()=>{az0={anthropic:["claude-haiku-4-5","claude-haiku"],openrouter:["qwen/qwen3.5-flash","anthropic/claude-haiku-4.5","anthropic/claude-haiku","google/gemini-3-flash"],deco:["qwen/qwen3.5-flash","anthropic/claude-haiku"],google:["gemini-2.5-flash","gemini-3-flash"],"claude-code":["claude-code:haiku","claude-code:sonnet"],codex:["codex:gpt-5.4-mini"]},sz0={anthropic:["claude-sonnet-4-6","claude-sonnet"],openrouter:["anthropic/claude-sonnet-4.6","anthropic/claude-sonnet","anthropic/claude-opus-4.8","google/gemini-3-pro"],deco:["anthropic/claude-sonnet-4.6","anthropic/claude-sonnet","anthropic/claude"],google:["gemini-3-pro","gemini-3-flash"],"claude-code":["claude-code:sonnet"],codex:["codex:gpt-5.4"]},ez0={anthropic:["claude-fable-5","claude-opus-4-8","claude-sonnet-4-6","claude-sonnet"],openrouter:["anthropic/claude-fable-5","anthropic/claude-opus-4.8","anthropic/claude-sonnet-4.6:extended","anthropic/claude-sonnet-4.6","google/gemini-3-pro"],deco:["anthropic/claude-fable","anthropic/claude-opus","anthropic/claude-sonnet-4.6","anthropic/claude-sonnet"],google:["gemini-3-pro"],"claude-code":["claude-code:fable","claude-code:sonnet"],codex:["codex:gpt-5.5"]},$j0={openrouter:["openai/gpt-image-1","google/gemini-2.0-flash-image"],deco:["openai/gpt-image-1","google/gemini-2.0-flash-image"],google:["gemini-2.0-flash-image"]},Zj0={openrouter:["perplexity/sonar","perplexity/sonar-pro","perplexity/deep-research"],deco:["perplexity/sonar","perplexity/sonar-pro","perplexity/deep-research"]}});var Xj0=D(()=>{da()});function Gh($){if(!$)return;let Z={};for(let G in $){let X=$[G];if(typeof X==="object"&&X!==null){let Q={};for(let Y of Q78)if(Y in X)Q[Y]=X[Y];Z[G]=Q}}return Object.keys(Z).length>0?Z:void 0}var Q78;var Qj0=D(()=>{Q78=["usage","cost","model"]});var _8=D(()=>{TI1();jz0();ea();r21();oz0();rz0();eF();Gj0();Xj0();Qj0();pa()});import{z as Yj0}from"zod";function NJ(){return $J()===null}function $s($,Z){return $===K4.DEV_ASSETS(Z)}function gC($,Z){let G=$q1(Z,$),X=new Date().toISOString();return{id:G.id??K4.DEV_ASSETS($),title:G.title,description:G.description??null,icon:G.icon??null,app_name:G.app_name??null,app_id:G.app_id??null,organization_id:$,created_by:"system",created_at:X,updated_at:X,connection_type:G.connection_type,connection_url:G.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:G.metadata??null,tools:Y78,bindings:["OBJECT_STORAGE"],status:"active"}}var Y78;var hC=D(()=>{ZC();Jg();_8();Y78=EB.map(($)=>({name:$.name,description:`${$.name} operation for local file storage`,inputSchema:Yj0.toJSONSchema($.inputSchema),outputSchema:Yj0.toJSONSchema($.outputSchema)}))});function Wj0($){if(!$)return!1;try{return new URL($).host==="api.decocms.com"&&$!=="https://studio.decocms.com/org/deco/registry/mcp"}catch{return!1}}var Jj0="https://studio.decocms.com/org/deco/registry/mcp";var Tq1=($,Z,G)=>{return(X,Q)=>{let Y=-1;return J(0);async function J(W){if(W<=Y)throw Error("next() called multiple times");Y=W;let K,U=!1,F;if($[W])F=$[W][0][0],X.req.routeIndex=W;else F=W===$.length&&Q||void 0;if(F)try{K=await F(X,()=>J(W+1))}catch(H){if(H instanceof Error&&Z)X.error=H,K=await Z(H,X),U=!0;else throw H}else if(X.finalized===!1&&G)K=await G(X);if(K&&(X.finalized===!1||U))X.res=K;return X}}};var Kj0=()=>{};var G8;var OJ=D(()=>{G8=class extends Error{res;status;constructor($=500,Z){super(Z?.message,{cause:Z?.cause});this.res=Z?.res,this.status=$}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 Uj0;var Fj0=D(()=>{Uj0=Symbol()});async function J78($,Z){let G=await $.formData();if(G)return W78(G,Z);return{}}function W78($,Z){let G=Object.create(null);if($.forEach((X,Q)=>{if(!(Z.all||Q.endsWith("[]")))G[Q]=X;else K78(G,Q,X)}),Z.dot)Object.entries(G).forEach(([X,Q])=>{if(X.includes("."))U78(G,X,Q),delete G[X]});return G}var Hj0=async($,Z=Object.create(null))=>{let{all:G=!1,dot:X=!1}=Z,Y=($ instanceof Zs?$.raw.headers:$.headers).get("Content-Type");if(Y?.startsWith("multipart/form-data")||Y?.startsWith("application/x-www-form-urlencoded"))return J78($,{all:G,dot:X});return{}},K78=($,Z,G)=>{if($[Z]!==void 0)if(Array.isArray($[Z]))$[Z].push(G);else $[Z]=[$[Z],G];else if(!Z.endsWith("[]"))$[Z]=G;else $[Z]=[G]},U78=($,Z,G)=>{if(/(?:^|\.)__proto__\./.test(Z))return;let X=$,Q=Z.split(".");Q.forEach((Y,J)=>{if(J===Q.length-1)X[Y]=G;else{if(!X[Y]||typeof X[Y]!=="object"||Array.isArray(X[Y])||X[Y]instanceof File)X[Y]=Object.create(null);X=X[Y]}})};var Nj0=D(()=>{qq1()});var kq1=($)=>{let Z=$.split("/");if(Z[0]==="")Z.shift();return Z},Oj0=($)=>{let{groups:Z,path:G}=F78($),X=kq1(G);return H78(X,Z)},F78=($)=>{let Z=[];return $=$.replace(/\{[^}]+\}/g,(G,X)=>{let Q=`@${X}`;return Z.push([Q,G]),Q}),{groups:Z,path:$}},H78=($,Z)=>{for(let G=Z.length-1;G>=0;G--){let[X]=Z[G];for(let Q=$.length-1;Q>=0;Q--)if($[Q].includes(X)){$[Q]=$[Q].replace(X,Z[G][1]);break}}return $},Gs,Bj0=($,Z)=>{if($==="*")return"*";let G=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(G){let X=`${$}#${Z}`;if(!Gs[X])if(G[2])Gs[X]=Z&&Z[0]!==":"&&Z[0]!=="*"?[X,G[1],new RegExp(`^${G[2]}(?=/${Z})`)]:[$,G[1],new RegExp(`^${G[2]}$`)];else Gs[X]=[$,G[1],!0];return Gs[X]}return null},uC=($,Z)=>{try{return Z($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(G)=>{try{return Z(G)}catch{return G}})}},Dj0=($)=>uC($,decodeURI),Vq1=($)=>{let Z=$.url,G=Z.indexOf("/",Z.indexOf(":")+4),X=G;for(;X<Z.length;X++){let Q=Z.charCodeAt(X);if(Q===37){let Y=Z.indexOf("?",X),J=Z.indexOf("#",X),W=Y===-1?J===-1?void 0:J:J===-1?Y:Math.min(Y,J),K=Z.slice(G,W);return Dj0(K.includes("%25")?K.replace(/%25/g,"%2525"):K)}else if(Q===63||Q===35)break}return Z.slice(G,X)},Lj0=($)=>{let Z=Vq1($);return Z.length>1&&Z.at(-1)==="/"?Z.slice(0,-1):Z},_B=($,Z,...G)=>{if(G.length)Z=_B(Z,...G);return`${$?.[0]==="/"?"":"/"}${$}${Z==="/"?"":`${$?.at(-1)==="/"?"":"/"}${Z?.[0]==="/"?Z.slice(1):Z}`}`},Xs=($)=>{if($.charCodeAt($.length-1)!==63||!$.includes(":"))return null;let Z=$.split("/"),G=[],X="";return Z.forEach((Q)=>{if(Q!==""&&!/\:/.test(Q))X+="/"+Q;else if(/\:/.test(Q))if(/\?/.test(Q)){if(G.length===0&&X==="")G.push("/");else G.push(X);let Y=Q.replace("?","");X+="/"+Y,G.push(X)}else X+="/"+Q}),G.filter((Q,Y,J)=>J.indexOf(Q)===Y)},Mq1=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?uC($,Xh):$},Ej0=($,Z,G)=>{let X;if(!G&&Z&&!/[%+]/.test(Z)){let J=$.indexOf("?",8);if(J===-1)return;if(!$.startsWith(Z,J+1))J=$.indexOf(`&${Z}`,J+1);while(J!==-1){let W=$.charCodeAt(J+Z.length+1);if(W===61){let K=J+Z.length+2,U=$.indexOf("&",K);return Mq1($.slice(K,U===-1?void 0:U))}else if(W==38||isNaN(W))return"";J=$.indexOf(`&${Z}`,J+1)}if(X=/[%+]/.test($),!X)return}let Q={};X??=/[%+]/.test($);let Y=$.indexOf("?",8);while(Y!==-1){let J=$.indexOf("&",Y+1),W=$.indexOf("=",Y);if(W>J&&J!==-1)W=-1;let K=$.slice(Y+1,W===-1?J===-1?void 0:J:W);if(X)K=Mq1(K);if(Y=J,K==="")continue;let U;if(W===-1)U="";else if(U=$.slice(W+1,J===-1?void 0:J),X)U=Mq1(U);if(G){if(!(Q[K]&&Array.isArray(Q[K])))Q[K]=[];Q[K].push(U)}else Q[K]??=U}return Z?Q[Z]:Q},wj0,zj0=($,Z)=>{return Ej0($,Z,!0)},Xh;var jH=D(()=>{Gs={},wj0=Ej0,Xh=decodeURIComponent});var jj0=($)=>uC($,Xh),Zs;var qq1=D(()=>{OJ();Fj0();Nj0();jH();Zs=class{raw;#$;#Z;routeIndex=0;path;bodyCache={};constructor($,Z="/",G=[[]]){this.raw=$,this.path=Z,this.#Z=G,this.#$={}}param($){return $?this.#G($):this.#Y()}#G($){let Z=this.#Z[0][this.routeIndex][1][$],G=this.#Q(Z);return G&&/\%/.test(G)?jj0(G):G}#Y(){let $={},Z=Object.keys(this.#Z[0][this.routeIndex][1]);for(let G of Z){let X=this.#Q(this.#Z[0][this.routeIndex][1][G]);if(X!==void 0)$[G]=/\%/.test(X)?jj0(X):X}return $}#Q($){return this.#Z[1]?this.#Z[1][$]:$}query($){return wj0(this.url,$)}queries($){return zj0(this.url,$)}header($){if($)return this.raw.headers.get($)??void 0;let Z={};return this.raw.headers.forEach((G,X)=>{Z[X]=G}),Z}async parseBody($){return Hj0(this,$)}#X=($)=>{let{bodyCache:Z,raw:G}=this,X=Z[$];if(X)return X;let Q=Object.keys(Z)[0];if(Q)return Z[Q].then((Y)=>{if(Q==="json")Y=JSON.stringify(Y);return new Response(Y)[$]()});return Z[$]=G[$]()};json(){return this.#X("text").then(($)=>JSON.parse($))}text(){return this.#X("text")}arrayBuffer(){return this.#X("arrayBuffer")}blob(){return this.#X("blob")}formData(){return this.#X("formData")}addValidatedData($,Z){this.#$[$]=Z}valid($){return this.#$[$]}get url(){return this.raw.url}get method(){return this.raw.method}get[Uj0](){return this.#Z}get matchedRoutes(){return this.#Z[0].map(([[,$]])=>$)}get routePath(){return this.#Z[0].map(([[,$]])=>$)[this.routeIndex].path}}});var Qs,Pj0=($,Z)=>{let G=new String($);return G.isEscaped=!0,G.callbacks=Z,G},Qh=async($,Z,G,X,Q)=>{if(typeof $==="object"&&!($ instanceof String)){if(!($ instanceof Promise))$=$.toString();if($ instanceof Promise)$=await $}let Y=$.callbacks;if(!Y?.length)return Promise.resolve($);if(Q)Q[0]+=$;else Q=[$];let J=Promise.all(Y.map((W)=>W({phase:Z,buffer:Q,context:X}))).then((W)=>Promise.all(W.filter(Boolean).map((K)=>Qh(K,Z,!1,X,Q))).then(()=>Q[0]));if(G)return Pj0(await J,Y);else return J};var Ys=D(()=>{Qs={Stringify:1,BeforeStream:2,Stream:3}});var Aj0="text/plain; charset=UTF-8",Sq1=($,Z)=>{return{"Content-Type":$,...Z}},Yh=($,Z)=>new Response($,Z),Rj0=class{#$;#Z;env={};#G;finalized=!1;error;#Y;#Q;#X;#J;#W;#K;#F;#H;#N;constructor($,Z){if(this.#$=$,Z)this.#Q=Z.executionCtx,this.env=Z.env,this.#K=Z.notFoundHandler,this.#N=Z.path,this.#H=Z.matchResult}get req(){return this.#Z??=new Zs(this.#$,this.#N,this.#H),this.#Z}get event(){if(this.#Q&&"respondWith"in this.#Q)return this.#Q;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#Q)return this.#Q;else throw Error("This context has no ExecutionContext")}get res(){return this.#X||=Yh(null,{headers:this.#F??=new Headers})}set res($){if(this.#X&&$){$=Yh($.body,$);for(let[Z,G]of this.#X.headers.entries()){if(Z==="content-type")continue;if(Z==="set-cookie"){let X=this.#X.headers.getSetCookie();$.headers.delete("set-cookie");for(let Q of X)$.headers.append("set-cookie",Q)}else $.headers.set(Z,G)}}this.#X=$,this.finalized=!0}render=(...$)=>{return this.#W??=(Z)=>this.html(Z),this.#W(...$)};setLayout=($)=>this.#J=$;getLayout=()=>this.#J;setRenderer=($)=>{this.#W=$};header=($,Z,G)=>{if(this.finalized)this.#X=Yh(this.#X.body,this.#X);let X=this.#X?this.#X.headers:this.#F??=new Headers;if(Z===void 0)X.delete($);else if(G?.append)X.append($,Z);else X.set($,Z)};status=($)=>{this.#Y=$};set=($,Z)=>{this.#G??=new Map,this.#G.set($,Z)};get=($)=>{return this.#G?this.#G.get($):void 0};get var(){if(!this.#G)return{};return Object.fromEntries(this.#G)}#U($,Z,G){let X=this.#X?new Headers(this.#X.headers):this.#F??new Headers;if(typeof Z==="object"&&"headers"in Z){let Y=Z.headers instanceof Headers?Z.headers:new Headers(Z.headers);for(let[J,W]of Y)if(J.toLowerCase()==="set-cookie")X.append(J,W);else X.set(J,W)}if(G)for(let[Y,J]of Object.entries(G))if(typeof J==="string")X.set(Y,J);else{X.delete(Y);for(let W of J)X.append(Y,W)}let Q=typeof Z==="number"?Z:Z?.status??this.#Y;return Yh($,{status:Q,headers:X})}newResponse=(...$)=>this.#U(...$);body=($,Z,G)=>this.#U($,Z,G);text=($,Z,G)=>{return!this.#F&&!this.#Y&&!Z&&!G&&!this.finalized?new Response($):this.#U($,Z,Sq1(Aj0,G))};json=($,Z,G)=>{return this.#U(JSON.stringify($),Z,Sq1("application/json",G))};html=($,Z,G)=>{let X=(Q)=>this.#U(Q,Z,Sq1("text/html; charset=UTF-8",G));return typeof $==="object"?Qh($,Qs.Stringify,!1,{}).then(X):X($)};redirect=($,Z)=>{let G=String($);return this.header("Location",!/[^\x00-\xFF]/.test(G)?G:encodeURI(G)),this.newResponse(null,Z??302)};notFound=()=>{return this.#K??=()=>Yh(),this.#K(this)}};var Js=D(()=>{qq1();Ys()});var i6="ALL",Ij0="all",Tj0,Ws="Can not add a route since the matcher is already built.",Ks;var PH=D(()=>{Tj0=["get","post","put","delete","options","patch"],Ks=class extends Error{}});var Cq1="__COMPOSED_HANDLER";var _q1=()=>{};var N78=($)=>{return $.text("404 Not Found",404)},qj0=($,Z)=>{if("getResponse"in $){let G=$.getResponse();return Z.newResponse(G.body,G)}return console.error($),Z.text("Internal Server Error",500)},Mj0=class ${get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor(Z={}){[...Tj0,Ij0].forEach((Y)=>{this[Y]=(J,...W)=>{if(typeof J==="string")this.#$=J;else this.#Y(Y,this.#$,J);return W.forEach((K)=>{this.#Y(Y,this.#$,K)}),this}}),this.on=(Y,J,...W)=>{for(let K of[J].flat()){this.#$=K;for(let U of[Y].flat())W.map((F)=>{this.#Y(U.toUpperCase(),this.#$,F)})}return this},this.use=(Y,...J)=>{if(typeof Y==="string")this.#$=Y;else this.#$="*",J.unshift(Y);return J.forEach((W)=>{this.#Y(i6,this.#$,W)}),this};let{strict:X,...Q}=Z;Object.assign(this,Q),this.getPath=X??!0?Z.getPath??Vq1:Lj0}#Z(){let Z=new $({router:this.router,getPath:this.getPath});return Z.errorHandler=this.errorHandler,Z.#G=this.#G,Z.routes=this.routes,Z}#G=N78;errorHandler=qj0;route(Z,G){let X=this.basePath(Z);return G.routes.map((Q)=>{let Y;if(G.errorHandler===qj0)Y=Q.handler;else Y=async(J,W)=>(await Tq1([],G.errorHandler)(J,()=>Q.handler(J,W))).res,Y[Cq1]=Q.handler;X.#Y(Q.method,Q.path,Y)}),this}basePath(Z){let G=this.#Z();return G._basePath=_B(this._basePath,Z),G}onError=(Z)=>{return this.errorHandler=Z,this};notFound=(Z)=>{return this.#G=Z,this};mount(Z,G,X){let Q,Y;if(X)if(typeof X==="function")Y=X;else if(Y=X.optionHandler,X.replaceRequest===!1)Q=(K)=>K;else Q=X.replaceRequest;let J=Y?(K)=>{let U=Y(K);return Array.isArray(U)?U:[U]}:(K)=>{let U=void 0;try{U=K.executionCtx}catch{}return[K.env,U]};Q||=(()=>{let K=_B(this._basePath,Z),U=K==="/"?0:K.length;return(F)=>{let H=new URL(F.url);return H.pathname=H.pathname.slice(U)||"/",new Request(H,F)}})();let W=async(K,U)=>{let F=await G(Q(K.req.raw),...J(K));if(F)return F;await U()};return this.#Y(i6,_B(Z,"*"),W),this}#Y(Z,G,X){Z=Z.toUpperCase(),G=_B(this._basePath,G);let Q={basePath:this._basePath,path:G,method:Z,handler:X};this.router.add(Z,G,[X,Q]),this.routes.push(Q)}#Q(Z,G){if(Z instanceof Error)return this.errorHandler(Z,G);throw Z}#X(Z,G,X,Q){if(Q==="HEAD")return(async()=>new Response(null,await this.#X(Z,G,X,"GET")))();let Y=this.getPath(Z,{env:X}),J=this.router.match(Q,Y),W=new Rj0(Z,{path:Y,matchResult:J,env:X,executionCtx:G,notFoundHandler:this.#G});if(J[0].length===1){let U;try{U=J[0][0][0][0](W,async()=>{W.res=await this.#G(W)})}catch(F){return this.#Q(F,W)}return U instanceof Promise?U.then((F)=>F||(W.finalized?W.res:this.#G(W))).catch((F)=>this.#Q(F,W)):U??this.#G(W)}let K=Tq1(J[0],this.errorHandler,this.#G);return(async()=>{try{let U=await K(W);if(!U.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return U.res}catch(U){return this.#Q(U,W)}})()}fetch=(Z,...G)=>{return this.#X(Z,G[1],G[0],Z.method)};request=(Z,G,X,Q)=>{if(Z instanceof Request)return this.fetch(G?new Request(Z,G):Z,X,Q);return Z=Z.toString(),this.fetch(new Request(/^https?:\/\//.test(Z)?Z:`http://localhost${_B("/",Z)}`,G),X,Q)};fire=()=>{addEventListener("fetch",(Z)=>{Z.respondWith(this.#X(Z.request,Z,void 0,Z.request.method))})}};var kj0=D(()=>{Kj0();Js();PH();_q1();jH()});function Us($,Z){let G=this.buildAllMatchers(),X=(Q,Y)=>{let J=G[Q]||G[i6],W=J[2][Y];if(W)return W;let K=Y.match(J[0]);if(!K)return[[],Jh];let U=K.indexOf("",1);return[J[1][U],K]};return this.match=X,X($,Z)}var Jh;var bq1=D(()=>{PH();Jh=[]});function B78($,Z){if($.length===1)return Z.length===1?$<Z?-1:1:-1;if(Z.length===1)return 1;if($===Wh||$===Kh)return 1;else if(Z===Wh||Z===Kh)return-1;if($===Fs)return 1;else if(Z===Fs)return-1;return $.length===Z.length?$<Z?-1:1:Z.length-$.length}var Fs="[^/]+",Wh=".*",Kh="(?:|/.*)",bB,O78,Vj0=class ${#$;#Z;#G=Object.create(null);insert(Z,G,X,Q,Y){if(Z.length===0){if(this.#$!==void 0)throw bB;if(Y)return;this.#$=G;return}let[J,...W]=Z,K=J==="*"?W.length===0?["","",Wh]:["","",Fs]:J==="/*"?["","",Kh]:J.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),U;if(K){let F=K[1],H=K[2]||Fs;if(F&&K[2]){if(H===".*")throw bB;if(H=H.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(H))throw bB}if(U=this.#G[H],!U){if(Object.keys(this.#G).some((N)=>N!==Wh&&N!==Kh))throw bB;if(Y)return;if(U=this.#G[H]=new $,F!=="")U.#Z=Q.varIndex++}if(!Y&&F!=="")X.push([F,U.#Z])}else if(U=this.#G[J],!U){if(Object.keys(this.#G).some((F)=>F.length>1&&F!==Wh&&F!==Kh))throw bB;if(Y)return;U=this.#G[J]=new $}U.insert(W,G,X,Q,Y)}buildRegExpStr(){let G=Object.keys(this.#G).sort(B78).map((X)=>{let Q=this.#G[X];return(typeof Q.#Z==="number"?`(${X})@${Q.#Z}`:O78.has(X)?`\\${X}`:X)+Q.buildRegExpStr()});if(typeof this.#$==="number")G.unshift(`#${this.#$}`);if(G.length===0)return"";if(G.length===1)return G[0];return"(?:"+G.join("|")+")"}};var vq1=D(()=>{bB=Symbol(),O78=new Set(".\\+*[^]$()")});var Sj0=class{#$={varIndex:0};#Z=new Vj0;insert($,Z,G){let X=[],Q=[];for(let J=0;;){let W=!1;if($=$.replace(/\{[^}]+\}/g,(K)=>{let U=`@\\${J}`;return Q[J]=[U,K],J++,W=!0,U}),!W)break}let Y=$.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let J=Q.length-1;J>=0;J--){let[W]=Q[J];for(let K=Y.length-1;K>=0;K--)if(Y[K].indexOf(W)!==-1){Y[K]=Y[K].replace(W,Q[J][1]);break}}return this.#Z.insert(Y,Z,X,this.#$,G),X}buildRegExp(){let $=this.#Z.buildRegExpStr();if($==="")return[/^$/,[],[]];let Z=0,G=[],X=[];return $=$.replace(/#(\d+)|@(\d+)|\.\*\$/g,(Q,Y,J)=>{if(Y!==void 0)return G[++Z]=Number(Y),"$()";if(J!==void 0)return X[Number(J)]=++Z,"";return""}),[new RegExp(`^${$}`),G,X]}};var Cj0=D(()=>{vq1()});function bj0($){return _j0[$]??=new RegExp($==="*"?"":`^${$.replace(/\/\*$|([.\\+*[^\]$()])/g,(Z,G)=>G?`\\${G}`:"(?:|/.*)")}$`)}function L78(){_j0=Object.create(null)}function E78($){let Z=new Sj0,G=[];if($.length===0)return D78;let X=$.map((U)=>[!/\*|\/:/.test(U[0]),...U]).sort(([U,F],[H,N])=>U?1:H?-1:F.length-N.length),Q=Object.create(null);for(let U=0,F=-1,H=X.length;U<H;U++){let[N,O,B]=X[U];if(N)Q[O]=[B.map(([w])=>[w,Object.create(null)]),Jh];else F++;let L;try{L=Z.insert(O,F,N)}catch(w){throw w===bB?new Ks(O):w}if(N)continue;G[F]=B.map(([w,z])=>{let j=Object.create(null);z-=1;for(;z>=0;z--){let[P,R]=L[z];j[P]=R}return[w,j]})}let[Y,J,W]=Z.buildRegExp();for(let U=0,F=G.length;U<F;U++)for(let H=0,N=G[U].length;H<N;H++){let O=G[U][H]?.[1];if(!O)continue;let B=Object.keys(O);for(let L=0,w=B.length;L<w;L++)O[B[L]]=W[O[B[L]]]}let K=[];for(let U in J)K[U]=G[J[U]];return[Y,K,Q]}function cC($,Z){if(!$)return;for(let G of Object.keys($).sort((X,Q)=>Q.length-X.length))if(bj0(G).test(Z))return[...$[G]];return}var D78,_j0,Hs=class{name="RegExpRouter";#$;#Z;constructor(){this.#$={[i6]:Object.create(null)},this.#Z={[i6]:Object.create(null)}}add($,Z,G){let X=this.#$,Q=this.#Z;if(!X||!Q)throw Error(Ws);if(!X[$])[X,Q].forEach((W)=>{W[$]=Object.create(null),Object.keys(W[i6]).forEach((K)=>{W[$][K]=[...W[i6][K]]})});if(Z==="/*")Z="*";let Y=(Z.match(/\/:/g)||[]).length;if(/\*$/.test(Z)){let W=bj0(Z);if($===i6)Object.keys(X).forEach((K)=>{X[K][Z]||=cC(X[K],Z)||cC(X[i6],Z)||[]});else X[$][Z]||=cC(X[$],Z)||cC(X[i6],Z)||[];Object.keys(X).forEach((K)=>{if($===i6||$===K)Object.keys(X[K]).forEach((U)=>{W.test(U)&&X[K][U].push([G,Y])})}),Object.keys(Q).forEach((K)=>{if($===i6||$===K)Object.keys(Q[K]).forEach((U)=>W.test(U)&&Q[K][U].push([G,Y]))});return}let J=Xs(Z)||[Z];for(let W=0,K=J.length;W<K;W++){let U=J[W];Object.keys(Q).forEach((F)=>{if($===i6||$===F)Q[F][U]||=[...cC(X[F],U)||cC(X[i6],U)||[]],Q[F][U].push([G,Y-K+W+1])})}}match=Us;buildAllMatchers(){let $=Object.create(null);return Object.keys(this.#Z).concat(Object.keys(this.#$)).forEach((Z)=>{$[Z]||=this.#G(Z)}),this.#$=this.#Z=void 0,L78(),$}#G($){let Z=[],G=$===i6;if([this.#$,this.#Z].forEach((X)=>{let Q=X[$]?Object.keys(X[$]).map((Y)=>[Y,X[$][Y]]):[];if(Q.length!==0)G||=!0,Z.push(...Q);else if($!==i6)Z.push(...Object.keys(X[i6]).map((Y)=>[Y,X[i6][Y]]))}),!G)return null;else return E78(Z)}};var fq1=D(()=>{PH();jH();bq1();vq1();Cj0();D78=[/^$/,[],Object.create(null)],_j0=Object.create(null)});var w78=class{name="PreparedRegExpRouter";#$;#Z;constructor($,Z){this.#$=$,this.#Z=Z}#G($,Z){let G=this.#$[$];G[1].forEach((X)=>X&&X.push(Z)),Object.values(G[2]).forEach((X)=>X[0].push(Z))}#Y($,Z,G,X,Q){let Y=this.#$[$];if(!Q)Y[2][Z][0].push([G,{}]);else X.forEach((J)=>{if(typeof J==="number")Y[1][J].push([G,Q]);else Y[2][J||Z][0].push([G,Q])})}add($,Z,G){if(!this.#$[$]){let Q=this.#$[i6],Y={};for(let J in Q[2])Y[J]=[Q[2][J][0].slice(),Jh];this.#$[$]=[Q[0],Q[1].map((J)=>Array.isArray(J)?J.slice():0),Y]}if(Z==="/*"||Z==="*"){let Q=[G,{}];if($===i6)for(let Y in this.#$)this.#G(Y,Q);else this.#G($,Q);return}let X=this.#Z[Z];if(!X)throw Error(`Path ${Z} is not registered`);for(let[Q,Y]of X)if($===i6)for(let J in this.#$)this.#Y(J,Z,G,Q,Y);else this.#Y($,Z,G,Q,Y)}buildAllMatchers(){return this.#$}match=Us};var vj0=D(()=>{PH();bq1();fq1()});var fj0=D(()=>{fq1();vj0()});var xq1=class{name="SmartRouter";#$=[];#Z=[];constructor($){this.#$=$.routers}add($,Z,G){if(!this.#Z)throw Error(Ws);this.#Z.push([$,Z,G])}match($,Z){if(!this.#Z)throw Error("Fatal error");let G=this.#$,X=this.#Z,Q=G.length,Y=0,J;for(;Y<Q;Y++){let W=G[Y];try{for(let K=0,U=X.length;K<U;K++)W.add(...X[K]);J=W.match($,Z)}catch(K){if(K instanceof Ks)continue;throw K}this.match=W.match.bind(W),this.#$=[W],this.#Z=void 0;break}if(Y===Q)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,J}get activeRouter(){if(this.#Z||this.#$.length!==1)throw Error("No active router has been determined yet.");return this.#$[0]}};var xj0=D(()=>{PH()});var yj0=D(()=>{xj0()});var Uh,z78=($)=>{for(let Z in $)return!0;return!1},gj0=class ${#$;#Z;#G;#Y=0;#Q=Uh;constructor(Z,G,X){if(this.#Z=X||Object.create(null),this.#$=[],Z&&G){let Q=Object.create(null);Q[Z]={handler:G,possibleKeys:[],score:0},this.#$=[Q]}this.#G=[]}insert(Z,G,X){this.#Y=++this.#Y;let Q=this,Y=Oj0(G),J=[];for(let W=0,K=Y.length;W<K;W++){let U=Y[W],F=Y[W+1],H=Bj0(U,F),N=Array.isArray(H)?H[0]:U;if(N in Q.#Z){if(Q=Q.#Z[N],H)J.push(H[1]);continue}if(Q.#Z[N]=new $,H)Q.#G.push(H),J.push(H[1]);Q=Q.#Z[N]}return Q.#$.push({[Z]:{handler:X,possibleKeys:J.filter((W,K,U)=>U.indexOf(W)===K),score:this.#Y}}),Q}#X(Z,G,X,Q,Y){for(let J=0,W=G.#$.length;J<W;J++){let K=G.#$[J],U=K[X]||K[i6],F={};if(U!==void 0){if(U.params=Object.create(null),Z.push(U),Q!==Uh||Y&&Y!==Uh)for(let H=0,N=U.possibleKeys.length;H<N;H++){let O=U.possibleKeys[H],B=F[U.score];U.params[O]=Y?.[O]&&!B?Y[O]:Q[O]??Y?.[O],F[U.score]=!0}}}}search(Z,G){let X=[];this.#Q=Uh;let Y=[this],J=kq1(G),W=[],K=J.length,U=null;for(let F=0;F<K;F++){let H=J[F],N=F===K-1,O=[];for(let L=0,w=Y.length;L<w;L++){let z=Y[L],j=z.#Z[H];if(j)if(j.#Q=z.#Q,N){if(j.#Z["*"])this.#X(X,j.#Z["*"],Z,z.#Q);this.#X(X,j,Z,z.#Q)}else O.push(j);for(let P=0,R=z.#G.length;P<R;P++){let A=z.#G[P],q=z.#Q===Uh?{}:{...z.#Q};if(A==="*"){let x=z.#Z["*"];if(x)this.#X(X,x,Z,z.#Q),x.#Q=q,O.push(x);continue}let[S,k,C]=A;if(!H&&!(C instanceof RegExp))continue;let u=z.#Z[S];if(C instanceof RegExp){if(U===null){U=Array(K);let s=G[0]==="/"?1:0;for(let d=0;d<K;d++)U[d]=s,s+=J[d].length+1}let x=G.substring(U[F]),y=C.exec(x);if(y){if(q[k]=y[0],this.#X(X,u,Z,z.#Q,q),z78(u.#Z)){u.#Q=q;let s=y[0].match(/\//)?.length??0;(W[s]||=[]).push(u)}continue}}if(C===!0||C.test(H))if(q[k]=H,N){if(this.#X(X,u,Z,q,z.#Q),u.#Z["*"])this.#X(X,u.#Z["*"],Z,q,z.#Q)}else u.#Q=q,O.push(u)}}let B=W.shift();Y=B?O.concat(B):O}if(X.length>1)X.sort((F,H)=>{return F.score-H.score});return[X.map(({handler:F,params:H})=>[F,H])]}};var hj0=D(()=>{PH();jH();Uh=Object.create(null)});var yq1=class{name="TrieRouter";#$;constructor(){this.#$=new gj0}add($,Z,G){let X=Xs(Z);if(X){for(let Q=0,Y=X.length;Q<Y;Q++)this.#$.insert($,X[Q],G);return}this.#$.insert($,Z,G)}match($,Z){return this.#$.search($,Z)}};var uj0=D(()=>{jH();hj0()});var cj0=D(()=>{uj0()});var v0;var gq1=D(()=>{kj0();fj0();yj0();cj0();v0=class extends Mj0{constructor($={}){super($);this.router=$.router??new xq1({routers:[new Hs,new yq1]})}}});var o4=D(()=>{gq1()});var dj0,j78,lj0=($)=>{let Z=0,G=$.length;while(Z<G){let X=$.charCodeAt(Z);if(X!==32&&X!==9)break;Z++}while(G>Z){let X=$.charCodeAt(G-1);if(X!==32&&X!==9)break;G--}return Z===0&&G===$.length?$:$.slice(Z,G)},hq1=($,Z)=>{if(Z&&$.indexOf(Z)===-1)return{};let G=$.split(";"),X={};for(let Q of G){let Y=Q.indexOf("=");if(Y===-1)continue;let J=lj0(Q.substring(0,Y));if(Z&&Z!==J||!dj0.test(J))continue;let W=lj0(Q.substring(Y+1));if(W.startsWith('"')&&W.endsWith('"'))W=W.slice(1,-1);if(j78.test(W)){if(X[J]=W.indexOf("%")!==-1?uC(W,Xh):W,Z)break}}return X},P78=($,Z,G={})=>{if(!dj0.test($))throw Error("Invalid cookie name");let X=`${$}=${Z}`;if($.startsWith("__Secure-")&&!G.secure)throw Error("__Secure- Cookie must have Secure attributes");if($.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 Q of["domain","path"])if(G[Q]&&/[;\r\n]/.test(G[Q]))throw Error(`${Q} 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.");X+=`; Max-Age=${G.maxAge|0}`}if(G.domain&&G.prefix!=="host")X+=`; Domain=${G.domain}`;if(G.path)X+=`; 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.");X+=`; Expires=${G.expires.toUTCString()}`}if(G.httpOnly)X+="; HttpOnly";if(G.secure)X+="; Secure";if(G.sameSite)X+=`; SameSite=${G.sameSite.charAt(0).toUpperCase()+G.sameSite.slice(1)}`;if(G.priority)X+=`; Priority=${G.priority.charAt(0).toUpperCase()+G.priority.slice(1)}`;if(G.partitioned){if(!G.secure)throw Error("Partitioned Cookie must have Secure attributes");X+="; Partitioned"}return X},Ns=($,Z,G)=>{return Z=encodeURIComponent(Z),P78($,Z,G)};var mj0=D(()=>{jH();dj0=/^[\w!#$%&'*.^`|~+-]+$/,j78=/^[ !#-:<-[\]-~]*$/});var Os=($,Z,G)=>{let X=$.req.raw.headers.get("Cookie");if(typeof Z==="string"){if(!X)return;let Y=Z;if(G==="secure")Y="__Secure-"+Z;else if(G==="host")Y="__Host-"+Z;return hq1(X,Y)[Y]}if(!X)return{};return hq1(X)},A78=($,Z,G)=>{let X;if(G?.prefix==="secure")X=Ns("__Secure-"+$,Z,{path:"/",...G,secure:!0});else if(G?.prefix==="host")X=Ns("__Host-"+$,Z,{...G,path:"/",secure:!0,domain:void 0});else X=Ns($,Z,{path:"/",...G});return X},uq1=($,Z,G,X)=>{let Q=A78(Z,G,X);$.header("Set-Cookie",Q,{append:!0})};var cq1=D(()=>{mj0()});var ij0=($)=>{let G={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...$},X=((Y)=>{if(typeof Y==="string")if(Y==="*"){if(G.credentials)return(J)=>J||null;return()=>Y}else return(J)=>Y===J?J:null;else if(typeof Y==="function")return Y;else return(J)=>Y.includes(J)?J:null})(G.origin),Q=((Y)=>{if(typeof Y==="function")return Y;else if(Array.isArray(Y))return()=>Y;else return()=>[]})(G.allowMethods);return async function(J,W){function K(F,H){J.res.headers.set(F,H)}let U=await X(J.req.header("origin")||"",J);if(U)K("Access-Control-Allow-Origin",U);if(G.credentials)K("Access-Control-Allow-Credentials","true");if(G.exposeHeaders?.length)K("Access-Control-Expose-Headers",G.exposeHeaders.join(","));if(J.req.method==="OPTIONS"){if(G.origin!=="*"||G.credentials)K("Vary","Origin");if(G.maxAge!=null)K("Access-Control-Max-Age",G.maxAge.toString());let F=await Q(J.req.header("origin")||"",J);if(F.length)K("Access-Control-Allow-Methods",F.join(","));let H=G.allowHeaders;if(!H?.length){let N=J.req.header("Access-Control-Request-Headers");if(N)H=N.split(/\s*,\s*/)}if(H?.length)K("Access-Control-Allow-Headers",H.join(",")),J.res.headers.append("Vary","Access-Control-Request-Headers");return J.res.headers.delete("Content-Length"),J.res.headers.delete("Content-Type"),new Response(null,{headers:J.res.headers,status:204,statusText:"No Content"})}if(await W(),G.origin!=="*"||G.credentials)J.header("Vary","Origin",{append:!0})}};var nj0=()=>{};var pj0=()=>{try{return performance.now()}catch{}return Date.now()},lq1=($)=>{let Z={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...$};return async function(X,Q){let Y=[],J=new Map;if(X.get("metric"))return await Q();if(X.set("metric",{headers:Y,timers:J}),Z.total)eQ(X,"total",Z.totalDescription);if(await Q(),Z.total)iX(X,"total");if(Z.autoEnd)J.forEach((K,U)=>iX(X,U));if(typeof Z.enabled==="function"?Z.enabled(X):Z.enabled){X.res.headers.append("Server-Timing",Y.join(","));let K=typeof Z.crossOrigin==="function"?Z.crossOrigin(X):Z.crossOrigin;if(K)X.res.headers.append("Timing-Allow-Origin",typeof K==="string"?K:"*")}}},tj0=($,Z,G,X,Q)=>{let Y=$.get("metric");if(!Y){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof G==="number"){let J=G.toFixed(Q||1),W=X?`${Z};dur=${J};desc="${X}"`:`${Z};dur=${J}`;Y.headers.push(W)}else{let J=G?`${Z};desc="${G}"`:`${Z}`;Y.headers.push(J)}},eQ=($,Z,G)=>{let X=$.get("metric");if(!X){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}X.timers.set(Z,{description:G,start:pj0()})},iX=($,Z,G)=>{let X=$.get("metric");if(!X){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let Q=X.timers.get(Z);if(!Q){console.warn(`Timer "${Z}" does not exist!`);return}let{description:Y,start:J}=Q,W=pj0()-J;tj0($,Z,W,Y,G),X.timers.delete(Z)};var oj0=D(()=>{Js()});var dq1=D(()=>{oj0()});function aj0(){let $={};for(let Z of Bs){if(Z.id==="basic-usage")continue;$[Z.id]=!0}return $}function iq1($){let Z=$,G=(J)=>{let W=Z[J];return Array.isArray(W)?W:[]},X=G("*").includes("*")||G("self").includes("*"),Q=new Set;if(!X)for(let J of Object.values(Z)){if(!Array.isArray(J))continue;for(let W of J)Q.add(W)}let Y={};for(let J of Bs){if(J.id==="basic-usage")continue;Y[J.id]=X||J.tools.every((W)=>Q.has(W))}return Y}function Fh(){let $={Organizations:[],Connections:[],"Virtual MCPs":[],Threads:[],Monitoring:[],Users:[],"API Keys":[],"Event Bus":[],Tags:[],"AI Providers":[],Automations:[],"Object Storage":[],Registry:[],GitHub:[],VM:[],Links:[],Search:[]};for(let Z of mq1)$[Z.category]?.push(Z);return $}var mq1,Bs,rj0,R78,Ds;var Hh=D(()=>{mq1=[{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:"MONITORING_THREAD_USAGE",description:"View per-thread token usage and cost",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_TRIGGER_ROTATE_TOKEN",description:"Rotate the secret token for a webhook automation trigger",category:"Automations"},{name:"AUTOMATION_RUN",description:"Manually trigger an automation run",category:"Automations"},{name:"AUTOMATION_RUN_STATS",description:"View aggregated run counts and token/cost for an automation",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:"VIRTUAL_MCP_LAST_USED_LIST",description:"Get last-used info for one or more virtual MCPs",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_KEY_UPDATE",description:"Update AI provider API key label or credential",category:"AI Providers"},{name:"AI_PROVIDER_KEY_PREVIEW",description:"Get masked preview of AI provider API key",category:"AI Providers"},{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:"SECRET_CREATE",description:"Create a secret in the credential vault",category:"Secrets"},{name:"SECRET_LIST",description:"List secrets visible to the caller (no values returned)",category:"Secrets"},{name:"FILE_CONFIG_CREATE",description:"Create an S3-compatible bucket configuration for the org",category:"File Configs"},{name:"FILE_CONFIG_LIST",description:"List S3 bucket configurations for the org (no creds returned)",category:"File Configs"},{name:"ORG_FS_PUBLIC_SETS_SYNC",description:"Re-sync the shared public skill-set volumes from their GitHub sources",category:"File Configs"},{name:"FILE_CONFIG_UPDATE",description:"Update an S3 bucket configuration, optionally rotating credentials",category:"File Configs"},{name:"FILE_CONFIG_DELETE",description:"Delete an S3 bucket configuration",category:"File Configs"},{name:"FILE_OBJECTS_LIST",description:"List existing objects in a configured bucket",category:"File Configs"},{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:"SANDBOX_START",description:"Start a sandbox VM with dev server preview",category:"VM"},{name:"SANDBOX_DELETE",description:"Stop and delete a sandbox VM",category:"VM"},{name:"GITHUB_LIST_USER_ORGS",description:"List GitHub user's personal account and organizations",category:"GitHub"},{name:"LINK_CURRENT_GET",description:"Return the calling user's current desktop link status (online/offline, capabilities)",category:"Links"},{name:"LINK_DISCONNECT",description:"Disconnect the calling user's desktop link (stops the daemon, removes the presence claim)",category:"Links"},{name:"GLOBAL_SEARCH",description:"Search across organization resources (currently threads). Returns a typed union of matches.",category:"Search"}],Bs=[{id:"basic-usage",label:"Basic Usage",description:"Tools all org members can access by default",section:"Basic Usage",tools:["COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","CONNECTION_TEST","COLLECTION_VIRTUAL_MCP_LIST","COLLECTION_VIRTUAL_MCP_GET","VIRTUAL_MCP_PLUGIN_CONFIG_GET","VIRTUAL_MCP_LAST_USED_LIST","AUTOMATION_GET","AUTOMATION_LIST","AUTOMATION_RUN_STATS","AI_PROVIDERS_LIST","AI_PROVIDERS_LIST_MODELS","AI_PROVIDERS_ACTIVE","AI_PROVIDER_KEY_LIST","AI_PROVIDER_CREDITS","AI_PROVIDER_TOPUP_URL","LIST_OBJECTS","GET_OBJECT_METADATA","GET_PRESIGNED_URL","PUT_PRESIGNED_URL","FILE_OBJECTS_LIST","SANDBOX_START","SANDBOX_DELETE","GLOBAL_SEARCH","ORGANIZATION_SETTINGS_GET","USER_GET","LINK_CURRENT_GET","LINK_DISCONNECT","BRAND_CONTEXT_LIST","COLLECTION_THREADS_CREATE","COLLECTION_THREADS_LIST","COLLECTION_THREADS_GET","COLLECTION_THREADS_UPDATE","COLLECTION_THREADS_DELETE","COLLECTION_THREAD_MESSAGES_LIST"]},{id:"org:manage",label:"Manage organization",description:"Edit organization settings, brand context, and domain configuration",section:"Organization",tools:["ORGANIZATION_GET","ORGANIZATION_LIST","ORGANIZATION_UPDATE","ORGANIZATION_SETTINGS_GET","ORGANIZATION_SETTINGS_UPDATE","BRAND_CONTEXT_LIST","BRAND_CONTEXT_GET","BRAND_CONTEXT_CREATE","BRAND_CONTEXT_UPDATE","BRAND_CONTEXT_DELETE","BRAND_CONTEXT_EXTRACT","BRAND_GET","BRAND_LIST","ORGANIZATION_DOMAIN_GET","ORGANIZATION_DOMAIN_SET","ORGANIZATION_DOMAIN_UPDATE","ORGANIZATION_DOMAIN_CLEAR"]},{id:"members:manage",label:"Manage members",description:"Invite members, remove them, and change their roles",section:"Organization",tools:["ORGANIZATION_MEMBER_LIST","ORGANIZATION_MEMBER_ADD","ORGANIZATION_MEMBER_REMOVE","ORGANIZATION_MEMBER_UPDATE_ROLE"],dangerous:!0},{id:"connections:manage",label:"Manage connections",description:"Create, update, and delete connections",section:"Connections & Agents",tools:["COLLECTION_CONNECTIONS_CREATE","COLLECTION_CONNECTIONS_UPDATE","COLLECTION_CONNECTIONS_DELETE"],dangerous:!0},{id:"agents:manage",label:"Manage agents",description:"Create, configure, and delete agents",section:"Connections & Agents",tools:["COLLECTION_VIRTUAL_MCP_CREATE","COLLECTION_VIRTUAL_MCP_UPDATE","COLLECTION_VIRTUAL_MCP_DELETE","VIRTUAL_MCP_PLUGIN_CONFIG_UPDATE","VIRTUAL_MCP_PINNED_VIEWS_UPDATE"],dangerous:!0},{id:"automations:manage",label:"Manage automations",description:"Create, update, run, and delete automations",section:"Automations",tools:["AUTOMATION_CREATE","AUTOMATION_UPDATE","AUTOMATION_DELETE","AUTOMATION_TRIGGER_ADD","AUTOMATION_TRIGGER_REMOVE","AUTOMATION_TRIGGER_ROTATE_TOKEN","AUTOMATION_RUN"],dangerous:!0},{id:"monitoring:view",label:"View monitoring",description:"Access logs and usage statistics",section:"Monitoring",tools:["MONITORING_LOG_GET","MONITORING_LOGS_LIST","MONITORING_STATS","MONITORING_THREAD_USAGE"]},{id:"secrets:manage",label:"Manage secrets",description:"Create and list secrets stored in the credential vault",section:"Organization",tools:["SECRET_CREATE","SECRET_LIST"]},{id:"file-configs:manage",label:"Manage file configs",description:"Create, list, update and delete S3 bucket configurations",section:"Organization",tools:["FILE_CONFIG_CREATE","FILE_CONFIG_LIST","FILE_CONFIG_UPDATE","FILE_CONFIG_DELETE","FILE_OBJECTS_LIST"]},{id:"ai-providers:manage",label:"Manage AI providers",description:"Add or remove API keys and provision provider credentials",section:"AI Providers",tools:["AI_PROVIDER_KEY_CREATE","AI_PROVIDER_KEY_LIST","AI_PROVIDER_KEY_DELETE","AI_PROVIDER_KEY_UPDATE","AI_PROVIDER_KEY_PREVIEW","AI_PROVIDER_OAUTH_URL","AI_PROVIDER_OAUTH_EXCHANGE","AI_PROVIDER_PROVISION_KEY","AI_PROVIDER_TOPUP_URL","AI_PROVIDER_CREDITS"]},{id:"tags:manage",label:"Manage tags",description:"Create, assign, and delete organization tags",section:"Organization",tools:["TAGS_LIST","TAGS_CREATE","TAGS_DELETE","MEMBER_TAGS_GET","MEMBER_TAGS_SET"]},{id:"registry:manage",label:"Manage registry",description:"Browse, publish, and manage items in the registry",section:"Store & Registry",tools:["COLLECTION_REGISTRY_APP_LIST","COLLECTION_REGISTRY_APP_GET","COLLECTION_REGISTRY_APP_VERSIONS","COLLECTION_REGISTRY_APP_FILTERS","REGISTRY_ITEM_LIST","REGISTRY_ITEM_SEARCH","REGISTRY_ITEM_GET","REGISTRY_ITEM_VERSIONS","REGISTRY_ITEM_FILTERS","REGISTRY_DISCOVER_TOOLS","REGISTRY_ITEM_CREATE","REGISTRY_ITEM_BULK_CREATE","REGISTRY_ITEM_UPDATE","REGISTRY_ITEM_DELETE","REGISTRY_AI_GENERATE","REGISTRY_PUBLISH_REQUEST_LIST","REGISTRY_PUBLISH_REQUEST_REVIEW","REGISTRY_PUBLISH_REQUEST_COUNT","REGISTRY_PUBLISH_REQUEST_DELETE","REGISTRY_PUBLISH_API_KEY_GENERATE","REGISTRY_PUBLISH_API_KEY_LIST","REGISTRY_PUBLISH_API_KEY_REVOKE"],dangerous:!0},{id:"registry:monitor",label:"Monitor registry health",description:"Run health checks on registry connections and view results",section:"Store & Registry",tools:["REGISTRY_MONITOR_RUN_START","REGISTRY_MONITOR_RUN_LIST","REGISTRY_MONITOR_RUN_GET","REGISTRY_MONITOR_RUN_CANCEL","REGISTRY_MONITOR_RESULT_LIST","REGISTRY_MONITOR_CONNECTION_LIST","REGISTRY_MONITOR_CONNECTION_SYNC","REGISTRY_MONITOR_CONNECTION_UPDATE_AUTH","REGISTRY_MONITOR_SCHEDULE_SET","REGISTRY_MONITOR_SCHEDULE_CANCEL"]},{id:"api-keys:manage",label:"Manage API keys",description:"Create, update, and revoke API keys",section:"Developer",tools:["API_KEY_CREATE","API_KEY_LIST","API_KEY_UPDATE","API_KEY_DELETE"]},{id:"event-bus:use",label:"Use event bus",description:"Publish events and manage subscriptions",section:"Developer",tools:["EVENT_PUBLISH","EVENT_SUBSCRIBE","EVENT_UNSUBSCRIBE","EVENT_CANCEL","EVENT_ACK","EVENT_SUBSCRIPTION_LIST","EVENT_SYNC_SUBSCRIPTIONS"]},{id:"storage:delete",label:"Delete from storage",description:"Permanently delete files from object storage",section:"Developer",tools:["DELETE_OBJECT","DELETE_OBJECTS"],dangerous:!0},{id:"connections:sql",label:"Run SQL queries",description:"Execute raw SQL against connected databases",section:"Developer",tools:["DATABASES_RUN_SQL"],dangerous:!0}],rj0=new Set([...Bs.find(($)=>$.id==="basic-usage")?.tools??[],"ORG_FS_READ","ORG_FS_WRITE"]),R78=["agents:manage","connections:manage"],Ds=new Set(Bs.filter(($)=>R78.includes($.id)).flatMap(($)=>$.tools))});import{z as n5}from"zod";function sj0(){return T78.parse(process.env)}var nq1=($)=>n5.enum(["true","false","1","0"]).optional().transform((Z)=>Z===void 0?$:Z==="true"||Z==="1"),I78=($)=>n5.string().optional().transform((Z)=>Z?Z.split(",").map((G)=>G.trim()):$),T78;var ej0=D(()=>{T78=n5.object({AUTH_EMAIL_PASSWORD_ENABLED:nq1(!0),AUTH_GOOGLE_CLIENT_ID:n5.string().optional(),AUTH_GOOGLE_CLIENT_SECRET:n5.string().optional(),AUTH_GITHUB_CLIENT_ID:n5.string().optional(),AUTH_GITHUB_CLIENT_SECRET:n5.string().optional(),AUTH_RESEND_API_KEY:n5.string().optional(),AUTH_RESEND_FROM_EMAIL:n5.string().optional(),AUTH_SENDGRID_API_KEY:n5.string().optional(),AUTH_SENDGRID_FROM_EMAIL:n5.string().optional(),AUTH_INVITE_EMAIL_PROVIDER:n5.enum(["resend","sendgrid"]).optional(),AUTH_RESET_PASSWORD_EMAIL_PROVIDER:n5.enum(["resend","sendgrid"]).optional(),AUTH_MAGIC_LINK_ENABLED:nq1(!1),AUTH_MAGIC_LINK_EMAIL_PROVIDER:n5.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_ENABLED:nq1(!1),AUTH_EMAIL_OTP_EMAIL_PROVIDER:n5.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_LENGTH:n5.coerce.number().optional(),AUTH_EMAIL_OTP_EXPIRES_IN:n5.coerce.number().optional(),AUTH_SSO_DOMAIN:n5.string().optional(),AUTH_SSO_MS_TENANT_ID:n5.string().optional(),AUTH_SSO_MS_CLIENT_ID:n5.string().optional(),AUTH_SSO_MS_CLIENT_SECRET:n5.string().optional(),AUTH_SSO_SCOPES:I78(["openid","email","profile"]),AUTH_SSO_GOOGLE_CLIENT_ID:n5.string().optional(),AUTH_SSO_GOOGLE_CLIENT_SECRET:n5.string().optional()}).transform(($)=>{let Z={};if($.AUTH_GOOGLE_CLIENT_ID)Z.google={clientId:$.AUTH_GOOGLE_CLIENT_ID,clientSecret:$.AUTH_GOOGLE_CLIENT_SECRET??""};if($.AUTH_GITHUB_CLIENT_ID)Z.github={clientId:$.AUTH_GITHUB_CLIENT_ID,clientSecret:$.AUTH_GITHUB_CLIENT_SECRET??""};let G=[];if($.AUTH_RESEND_API_KEY)G.push({id:"resend",provider:"resend",config:{apiKey:$.AUTH_RESEND_API_KEY,fromEmail:$.AUTH_RESEND_FROM_EMAIL??"noreply@example.com"}});if($.AUTH_SENDGRID_API_KEY)G.push({id:"sendgrid",provider:"sendgrid",config:{apiKey:$.AUTH_SENDGRID_API_KEY,fromEmail:$.AUTH_SENDGRID_FROM_EMAIL??"noreply@example.com"}});let X=G[0]?.id,Q;if($.AUTH_SSO_MS_CLIENT_ID&&$.AUTH_SSO_DOMAIN)Q={providerId:"microsoft",domain:$.AUTH_SSO_DOMAIN,MS_TENANT_ID:$.AUTH_SSO_MS_TENANT_ID??"",MS_CLIENT_ID:$.AUTH_SSO_MS_CLIENT_ID,MS_CLIENT_SECRET:$.AUTH_SSO_MS_CLIENT_SECRET??"",scopes:$.AUTH_SSO_SCOPES};else if($.AUTH_SSO_GOOGLE_CLIENT_ID&&$.AUTH_SSO_DOMAIN)Q={providerId:"google",domain:$.AUTH_SSO_DOMAIN,GOOGLE_CLIENT_ID:$.AUTH_SSO_GOOGLE_CLIENT_ID,GOOGLE_CLIENT_SECRET:$.AUTH_SSO_GOOGLE_CLIENT_SECRET??"",scopes:$.AUTH_SSO_SCOPES};let Y;if($.AUTH_MAGIC_LINK_ENABLED)Y={enabled:!0,emailProviderId:$.AUTH_MAGIC_LINK_EMAIL_PROVIDER??X??""};let J;if($.AUTH_EMAIL_OTP_ENABLED)J={enabled:!0,emailProviderId:$.AUTH_EMAIL_OTP_EMAIL_PROVIDER??X??"",...$.AUTH_EMAIL_OTP_LENGTH!==void 0&&{otpLength:$.AUTH_EMAIL_OTP_LENGTH},...$.AUTH_EMAIL_OTP_EXPIRES_IN!==void 0&&{expiresIn:$.AUTH_EMAIL_OTP_EXPIRES_IN}};return{emailAndPassword:{enabled:$.AUTH_EMAIL_PASSWORD_ENABLED},socialProviders:Object.keys(Z).length>0?Z:void 0,emailProviders:G.length>0?G:void 0,inviteEmailProviderId:$.AUTH_INVITE_EMAIL_PROVIDER,resetPasswordEmailProviderId:$.AUTH_RESET_PASSWORD_EMAIL_PROVIDER,ssoConfig:Q,magicLinkConfig:Y,emailOtpConfig:J}})});var Ls;var $P0=D(()=>{Ls={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"}});import{existsSync as q78,readFileSync as M78}from"fs";function k78(){let $=sj0(),Z=q0().configPath;if(!q78(Z))return{auth:$,monitoring:Ls};try{let G=JSON.parse(M78(Z,"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:$,monitoring:G.monitoring??Ls,theme:G.theme,logo:G.logo,autoCreateOrganizationOnSignup:G.autoCreateOrganizationOnSignup}}catch{return{auth:$,monitoring:Ls}}}function vB(){if(!pq1)pq1=k78();return pq1}function ZP0(){return vB().theme}var pq1=null;var tq1=D(()=>{ej0();$P0();M4()});import{dirname as V78,posix as S78,sep as C78}from"path";function XP0(){let $=_78();return async(Z)=>{for(let G of Z)G.module=$(G.filename);return Z}}function _78($=process.argv[1]?V78(process.argv[1]):process.cwd(),Z=C78==="\\"){let G=Z?GP0($):$;return(X)=>{if(!X)return;let Q=Z?GP0(X):X,{dir:Y,base:J,ext:W}=S78.parse(Q);if(W===".js"||W===".mjs"||W===".cjs")J=J.slice(0,-1*W.length);let K=decodeURIComponent(J);if(!Y)Y=".";let U=Y.lastIndexOf("/node_modules");if(U>-1)return`${Y.slice(U+14).replace(/\//g,".")}:${K}`;if(Y.startsWith(G)){let F=Y.slice(G.length+1).replace(/\//g,".");return F?`${F}:${K}`:K}return K}}function GP0($){return $.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var QP0=()=>{};function b78($,Z,G){return{key:$,enabled:typeof Z=="string"?!0:Z,variant:typeof Z=="string"?Z:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:G?JSON.stringify(G):void 0,description:void 0}}}var oq1=($)=>{if("flags"in $){let Z=YP0($.flags),G=JP0($.flags);return{...$,featureFlags:Z,featureFlagPayloads:G}}{let Z=$.featureFlags??{},G=Object.fromEntries(Object.entries($.featureFlagPayloads||{}).map(([Q,Y])=>[Q,rq1(Y)])),X=Object.fromEntries(Object.entries(Z).map(([Q,Y])=>[Q,b78(Q,Y,G[Q])]));return{...$,featureFlags:Z,featureFlagPayloads:G,flags:X}}},YP0=($)=>Object.fromEntries(Object.entries($??{}).map(([Z,G])=>[Z,Nh(G)]).filter(([,Z])=>Z!==void 0)),JP0=($)=>{let Z=$??{};return Object.fromEntries(Object.keys(Z).filter((G)=>{let X=Z[G];return X.enabled&&X.metadata&&X.metadata.payload!==void 0}).map((G)=>{let X=Z[G].metadata?.payload;return[G,X?rq1(X):void 0]}))},Nh=($)=>$===void 0?void 0:$.variant??$.enabled,rq1=($)=>{if(typeof $!="string")return $;try{return JSON.parse($)}catch{return $}};var Es=()=>{};function WP0(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}async function ws($,Z=!0,G){try{let X=new CompressionStream("gzip"),Q=X.writable.getWriter(),Y=Q.write(new TextEncoder().encode($)).then(()=>Q.close()).catch(async(K)=>{try{await Q.abort(K)}catch{}throw K}),J=new Response(X.readable).blob(),[W]=await Promise.all([J,Y]);return W}catch(X){if(G?.rethrow)throw X;if(Z)console.error("Failed to gzip compress data",X);return null}}var aq1=()=>{};var v78,KP0=function($,Z=[]){if(!$)return!1;let G=$.toLowerCase();return v78.concat(Z).some((X)=>{let Q=X.toLowerCase();return G.indexOf(Q)!==-1})};var UP0=D(()=>{v78=["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 V7;var fB=D(()=>{V7=function($){return $.AnonymousId="anonymous_id",$.DistinctId="distinct_id",$.Props="props",$.EnablePersonProcessing="enable_person_processing",$.PersonMode="person_mode",$.FeatureFlagDetails="feature_flag_details",$.FeatureFlags="feature_flags",$.FeatureFlagPayloads="feature_flag_payloads",$.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",$.BootstrapFeatureFlags="bootstrap_feature_flags",$.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",$.OverrideFeatureFlags="override_feature_flags",$.Queue="queue",$.LogsQueue="logs_queue",$.OptedOut="opted_out",$.SessionId="session_id",$.SessionStartTimestamp="session_start_timestamp",$.SessionLastTimestamp="session_timestamp",$.PersonProperties="person_properties",$.GroupProperties="group_properties",$.InstalledAppBuild="installed_app_build",$.InstalledAppVersion="installed_app_version",$.SessionReplay="session_replay",$.SurveyLastSeenDate="survey_last_seen_date",$.SurveysSeen="surveys_seen",$.Surveys="surveys",$.RemoteConfig="remote_config",$.FlagsEndpointWasHit="flags_endpoint_was_hit",$.DeviceId="device_id",$}({})});var zs=()=>{};function Ps($){return $===null||typeof $!="object"}function xB($,Z){return Object.prototype.toString.call($)===`[object ${Z}]`}function NP0($){return xB($,"ErrorEvent")}function dC($){return typeof Event<"u"&&y78($,Event)}function OP0($){return xB($,"Object")}function y78($,Z){try{return $ instanceof Z}catch{return!1}}var x78,FP0,_p4,sq1,js,Oh=($)=>$===Object($)&&!js($),lC=($)=>$===void 0,AH=($)=>sq1.call($)=="[object String]",HP0=($)=>AH($)&&$.trim().length===0,Bh=($)=>sq1.call($)=="[object Number]"&&$===$,eq1=($)=>$ instanceof Error;var Dh=D(()=>{fB();zs();x78=Array.isArray,FP0=Object.prototype,_p4=FP0.hasOwnProperty,sq1=FP0.toString,js=x78||function($){return sq1.call($)==="[object Array]"}});function Lh($,Z,G,X,Q){if(Z>G)X.warn("min cannot be greater than max."),Z=G;if(Bh($))if($>G)return X.warn(" cannot be greater than max: "+G+". Using max value instead."),G;else{if(!($<Z))return $;return X.warn(" cannot be less than min: "+Z+". Using min value instead."),Z}return X.warn(" must be a number. using max or fallback. max: "+G+", fallback: "+Q),Lh(Q||G,Z,G,X)}var $M1=D(()=>{Dh()});class ZM1{constructor($){this._buckets={},this._onBucketRateLimited=$._onBucketRateLimited,this._bucketSize=Lh($.bucketSize,0,100,$._logger),this._refillRate=Lh($.refillRate,0,this._bucketSize,$._logger),this._refillInterval=Lh($.refillInterval,0,g78,$._logger)}_applyRefill($,Z){let G=Z-$.lastAccess,X=Math.floor(G/this._refillInterval);if(X>0){let Q=X*this._refillRate;$.tokens=Math.min($.tokens+Q,this._bucketSize),$.lastAccess=$.lastAccess+X*this._refillInterval}}consumeRateLimit($){let Z=Date.now(),G=String($),X=this._buckets[G];if(X)this._applyRefill(X,Z);else X={tokens:this._bucketSize,lastAccess:Z},this._buckets[G]=X;if(X.tokens===0)return!0;if(X.tokens--,X.tokens===0)this._onBucketRateLimited?.($);return X.tokens===0}stop(){this._buckets={}}}var g78=86400000;var BP0=D(()=>{$M1()});class yB{constructor($){this.bytes=$}static ofInner($){if($.length===16)return new yB($);throw TypeError("not 128-bit length")}static fromFieldsV7($,Z,G,X){if(!Number.isInteger($)||!Number.isInteger(Z)||!Number.isInteger(G)||!Number.isInteger(X)||$<0||Z<0||G<0||X<0||$>281474976710655||Z>4095||G>1073741823||X>4294967295)throw RangeError("invalid field value");let Q=new Uint8Array(16);return Q[0]=$/1099511627776,Q[1]=$/4294967296,Q[2]=$/16777216,Q[3]=$/65536,Q[4]=$/256,Q[5]=$,Q[6]=112|Z>>>8,Q[7]=Z,Q[8]=128|G>>>24,Q[9]=G>>>16,Q[10]=G>>>8,Q[11]=G,Q[12]=X>>>24,Q[13]=X>>>16,Q[14]=X>>>8,Q[15]=X,new yB(Q)}static parse($){let Z;switch($.length){case 32:Z=/^[0-9a-f]{32}$/i.exec($)?.[0];break;case 36:Z=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec($)?.slice(1,6).join("");break;case 38:Z=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec($)?.slice(1,6).join("");break;case 45:Z=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec($)?.slice(1,6).join("");break;default:break}if(Z){let G=new Uint8Array(16);for(let X=0;X<16;X+=4){let Q=parseInt(Z.substring(2*X,2*X+8),16);G[X+0]=Q>>>24,G[X+1]=Q>>>16,G[X+2]=Q>>>8,G[X+3]=Q}return new yB(G)}throw SyntaxError("could not parse UUID string")}toString(){let $="";for(let Z=0;Z<this.bytes.length;Z++)if($+="0123456789abcdef".charAt(this.bytes[Z]>>>4),$+="0123456789abcdef".charAt(15&this.bytes[Z]),Z===3||Z===5||Z===7||Z===9)$+="-";return $}toHex(){let $="";for(let Z=0;Z<this.bytes.length;Z++)$+="0123456789abcdef".charAt(this.bytes[Z]>>>4),$+="0123456789abcdef".charAt(15&this.bytes[Z]);return $}toJSON(){return this.toString()}getVariant(){let $=this.bytes[8]>>>4;if($<0)throw Error("unreachable");if($<=7)return this.bytes.every((Z)=>Z===0)?"NIL":"VAR_0";if($<=11)return"VAR_10";if($<=13)return"VAR_110";if($<=15)return this.bytes.every((Z)=>Z===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new yB(this.bytes.slice(0))}equals($){return this.compareTo($)===0}compareTo($){for(let Z=0;Z<16;Z++){let G=this.bytes[Z]-$.bytes[Z];if(G!==0)return Math.sign(G)}return 0}}class LP0{constructor($){this.timestamp=0,this.counter=0,this.random=$??h78()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore($,Z){let G=this.generateOrAbortCore($,Z);if(G===void 0)this.timestamp=0,G=this.generateOrAbortCore($,Z);return G}generateOrAbortCore($,Z){if(!Number.isInteger($)||$<1||$>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(Z<0||Z>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if($>this.timestamp)this.timestamp=$,this.resetCounter();else{if(!($+Z>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return yB.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 $=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return $[6]=64|$[6]>>>4,$[8]=128|$[8]>>>2,yB.ofInner($)}}var h78=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),DP0,RH=()=>u78().toString(),u78=()=>(DP0||(DP0=new LP0)).generate();var Eh=D(()=>{/*! For license information please see uuidv7.mjs.LICENSE.txt */});class GM1{add($){let Z=RH();return this.promiseByIds[Z]=$,$.catch(()=>{}).finally(()=>{delete this.promiseByIds[Z]}),$}async join(){let $=Object.values(this.promiseByIds),Z=$.length;while(Z>0)await Promise.all($),$=Object.values(this.promiseByIds),Z=$.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}}var EP0=D(()=>{Eh()});function c78($=console){return{log:$.log.bind($),warn:$.warn.bind($),error:$.error.bind($),debug:$.debug.bind($)}}function zP0($,Z=l78){return wP0($,Z,c78())}var wP0=($,Z,G)=>{function X(Y,...J){Z(()=>{let W=G[Y];W($,...J)})}return{info:(...Y)=>{X("log",...Y)},warn:(...Y)=>{X("warn",...Y)},error:(...Y)=>{X("error",...Y)},critical:(...Y)=>{G.error($,...Y)},createLogger:(Y)=>wP0(`${$} ${Y}`,Z,G)}},l78=($)=>$();var jP0=()=>{};var iC="Mobile",Rs="iOS",mC="Android",PP0="Tablet",mp4,m78="Apple",ip4,AP0="Safari",Is="BlackBerry",RP0="Samsung",i78,n78,Ts="Chrome",p78,t78,IP0="Internet Explorer",o78,QM1="Opera",np4,TP0="Edge",r78,YM1="Firefox",a78,JM1="Nintendo",WM1="PlayStation",As="Xbox",s78,e78,wh="Windows",$G8,qP0="Generic",pp4,tp4,ZG8="Konqueror",LG="(\\d+(\\.\\d+)?)",XM1,op4,rp4,ap4,GG8,XG8,sp4,ep4;var MP0=D(()=>{zs();Dh();mp4=mC+" "+PP0,ip4=m78+" Watch",i78=RP0+"Browser",n78=RP0+" Internet",p78=Ts+" OS",t78=Ts+" "+Rs,o78=IP0+" "+iC,np4=QM1+" Mini",r78="Microsoft "+TP0,a78=YM1+" "+Rs,s78=mC+" "+iC,e78=iC+" "+AP0,$G8=wh+" Phone",pp4=qP0+" "+iC.toLowerCase(),tp4=qP0+" "+PP0.toLowerCase(),XM1=new RegExp("Version/"+LG),op4=new RegExp(As,"i"),rp4=new RegExp(WM1+" \\w+","i"),ap4=new RegExp(JM1+" \\w+","i"),GG8=new RegExp(Is+"|PlayBook|BB10","i"),XG8={"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"},sp4={[o78]:[new RegExp("rv:"+LG)],[r78]:[new RegExp(TP0+"?\\/"+LG)],[Ts]:[new RegExp("("+Ts+"|CrMo)\\/"+LG)],[t78]:[new RegExp("CriOS\\/"+LG)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+LG)],[AP0]:[XM1],[e78]:[XM1],[QM1]:[new RegExp("("+QM1+"|OPR)\\/"+LG)],[YM1]:[new RegExp(YM1+"\\/"+LG)],[a78]:[new RegExp("FxiOS\\/"+LG)],[ZG8]:[new RegExp("Konqueror[:/]?"+LG,"i")],[Is]:[new RegExp(Is+" "+LG),XM1],[s78]:[new RegExp("android\\s"+LG,"i")],[n78]:[new RegExp(i78+"\\/"+LG)],[IP0]:[new RegExp("(rv:|MSIE )"+LG)],Mozilla:[new RegExp("rv:"+LG)]},ep4=[[new RegExp(As+"; "+As+" (.*?)[);]","i"),($)=>[As,$&&$[1]||""]],[new RegExp(JM1,"i"),[JM1,""]],[new RegExp(WM1,"i"),[WM1,""]],[GG8,[Is,""]],[new RegExp(wh,"i"),($,Z)=>{if(/Phone/.test(Z)||/WPDesktop/.test(Z))return[$G8,""];if(new RegExp(iC).test(Z)&&!/IEMobile\b/.test(Z))return[wh+" "+iC,""];let G=/Windows NT ([0-9.]+)/i.exec(Z);if(G&&G[1]){let X=G[1],Q=XG8[X]||"";if(/arm/i.test(Z))Q="RT";return[wh,Q]}return[wh,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,($)=>{if($&&$[3]){let Z=[$[3],$[4],$[5]||"0"];return[Rs,Z.join(".")]}return[Rs,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,($)=>{let Z="";if($&&$.length>=3)Z=lC($[2])?$[3]:$[2];return["watchOS",Z]}],[new RegExp("("+mC+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+mC+")","i"),($)=>{if($&&$[2]){let Z=[$[2],$[3],$[4]||"0"];return[mC,Z.join(".")]}return[mC,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,($)=>{let Z=["Mac OS X",""];if($&&$[1]){let G=[$[1],$[2],$[3]||"0"];Z[1]=G.join(".")}return Z}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[p78,""]],[/Linux|debian/i,["Linux",""]]]});function VP0($){return $?.replace(/\/+$/,"")}async function SP0($,Z){let G=null;for(let X=0;X<Z.retryCount+1;X++){if(X>0)await new Promise((Q)=>setTimeout(Q,Z.retryDelay));try{return await $()}catch(Q){if(G=Q,!Z.retryCheck(Q))throw Q}}throw G}function qs(){return new Date().toISOString()}function dK($,Z){let G=setTimeout($,Z);return G?.unref&&G?.unref(),G}function KM1($){return Promise.all($.map((Z)=>(Z??Promise.resolve()).then((G)=>({status:"fulfilled",value:G}),(G)=>({status:"rejected",reason:G}))))}var kP0="utf8",CP0=($)=>$ instanceof Error;var EG=D(()=>{UP0();BP0();$M1();zs();Dh();EP0();jP0();MP0()});var QG8,Ot4;var UM1=D(()=>{EG();QG8={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}},Ot4=QG8.info});var _P0=D(()=>{UM1();fB()});var bP0=D(()=>{fB()});class FM1{constructor(){this.events={},this.events={}}on($,Z){if(!this.events[$])this.events[$]=[];return this.events[$].push(Z),()=>{this.events[$]=this.events[$].filter((G)=>G!==Z)}}emit($,Z){for(let G of this.events[$]||[])G(Z);for(let G of this.events["*"]||[])G($,Z)}}var vP0=()=>{};async function fP0($){if($ instanceof nC){let Z="";try{Z=await $.text}catch{}console.error(`Error while flushing PostHog: message=${$.message}, response body=${Z}`,$)}else console.error("Error while flushing PostHog",$);return Promise.resolve()}function HM1($){return typeof $=="object"&&($ instanceof nC||$ instanceof zh)}function xP0($){return typeof $=="object"&&$ instanceof nC&&$.status===413}class Ms{constructor($,Z={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new GM1,this._events=new FM1,this._isInitialized=!1;let G=typeof $=="string"?$.trim():"",X=typeof Z.host=="string"?Z.host.trim():"",Q=!G;if(this._logger=zP0("[PostHog]",this.logMsgIfDebug.bind(this)),Q)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=G,this.host=VP0(X||"https://us.i.posthog.com"),this.flushAt=Z.flushAt?Math.max(Z.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,Z.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,Z.maxQueueSize??1000),this.flushInterval=Z.flushInterval??1e4,this.preloadFeatureFlags=Z.preloadFeatureFlags??!0,this.defaultOptIn=Z.defaultOptIn??!0,this.disableSurveys=Z.disableSurveys??!1,this._retryOptions={retryCount:Z.fetchRetryCount??3,retryDelay:Z.fetchRetryDelay??3000,retryCheck:HM1},this.requestTimeout=Z.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=Z.featureFlagsRequestTimeoutMs??3000,this.remoteConfigRequestTimeoutMs=Z.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=Z.disableGeoip??!0,this.disabled=(Z.disabled??!1)||Q,this.historicalMigration=Z?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=Z?.evaluationContexts??Z?.evaluationEnvironments,Z?.evaluationEnvironments&&!Z?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!WP0()||(Z?.disableCompression??!1)}logMsgIfDebug($){if(this.isDebug)$()}wrap($){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return $();this._initPromise.then(()=>$())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(V7.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(V7.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(V7.OptedOut,!0)})}on($,Z){return this._events.on($,Z)}debug($=!0){if(this.removeDebugCallback?.(),$){let Z=this.on("*",(G,X)=>this._logger.info(G,X));this.removeDebugCallback=()=>{Z(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload($){return{distinct_id:$.distinct_id,event:$.event,properties:{...$.properties||{},...this.getCommonEventProperties()}}}addPendingPromise($){return this.promiseQueue.add($)}identifyStateless($,Z,G){this.wrap(()=>{let X={...this.buildPayload({distinct_id:$,event:"$identify",properties:Z})};this.enqueue("identify",X,G)})}async identifyStatelessImmediate($,Z,G){let X={...this.buildPayload({distinct_id:$,event:"$identify",properties:Z})};await this.sendImmediate("identify",X,G)}captureStateless($,Z,G,X){this.wrap(()=>{let Q=this.buildPayload({distinct_id:$,event:Z,properties:G});this.enqueue("capture",Q,X)})}async captureStatelessImmediate($,Z,G,X){let Q=this.buildPayload({distinct_id:$,event:Z,properties:G});await this.sendImmediate("capture",Q,X)}aliasStateless($,Z,G,X){this.wrap(()=>{let Q=this.buildPayload({event:"$create_alias",distinct_id:Z,properties:{...G||{},distinct_id:Z,alias:$}});this.enqueue("alias",Q,X)})}async aliasStatelessImmediate($,Z,G,X){let Q=this.buildPayload({event:"$create_alias",distinct_id:Z,properties:{...G||{},distinct_id:Z,alias:$}});await this.sendImmediate("alias",Q,X)}groupIdentifyStateless($,Z,G,X,Q,Y){this.wrap(()=>{let J=this.buildPayload({distinct_id:Q||`$${$}_${Z}`,event:"$groupidentify",properties:{$group_type:$,$group_key:Z,$group_set:G||{},...Y||{}}});this.enqueue("capture",J,X)})}async getRemoteConfig(){await this._initPromise;let $=this.host;if($==="https://us.i.posthog.com")$="https://us-assets.i.posthog.com";else if($==="https://eu.i.posthog.com")$="https://eu-assets.i.posthog.com";let Z=`${$}/array/${this.apiKey}/config`,G={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(Z,G,{retryCount:0},this.remoteConfigRequestTimeoutMs).then((X)=>X.json()).catch((X)=>{this._logger.error("Remote config could not be loaded",X),this._events.emit("error",X)})}async getFlags($,Z={},G={},X={},Q={},Y=!1){await this._initPromise;let J=Y?"&config=true":"",W=`${this.host}/flags/?v=2${J}`,K={token:this.apiKey,distinct_id:$,groups:Z,person_properties:G,group_properties:X,...Q};if(G.$device_id)K.$device_id=G.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)K.evaluation_contexts=this.evaluationContexts;let U={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(K)};return this._logger.info("Flags URL",W),this.fetchWithRetry(W,U,{retryCount:0},this.featureFlagsRequestTimeoutMs).then((F)=>F.json()).then((F)=>({success:!0,response:oq1(F)})).catch((F)=>{return this._events.emit("error",F),{success:!1,error:this.categorizeRequestError(F)}})}categorizeRequestError($){if($ instanceof nC)return{type:"api_error",statusCode:$.status};if($ instanceof zh){let Z=$.error;if(Z instanceof Error&&(Z.name==="AbortError"||Z.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless($,Z,G={},X={},Q={},Y){await this._initPromise;let J=await this.getFeatureFlagDetailStateless($,Z,G,X,Q,Y);if(J===void 0)return{response:void 0,requestId:void 0};let W=Nh(J.response);if(W===void 0)W=!1;return{response:W,requestId:J.requestId}}async getFeatureFlagDetailStateless($,Z,G={},X={},Q={},Y){await this._initPromise;let J=await this.getFeatureFlagDetailsStateless(Z,G,X,Q,Y,[$]);if(J===void 0)return;return{response:J.flags[$],requestId:J.requestId,evaluatedAt:J.evaluatedAt}}async getFeatureFlagPayloadStateless($,Z,G={},X={},Q={},Y){await this._initPromise;let J=await this.getFeatureFlagPayloadsStateless(Z,G,X,Q,Y,[$]);if(!J)return;let W=J[$];if(W===void 0)return null;return W}async getFeatureFlagPayloadsStateless($,Z={},G={},X={},Q,Y){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless($,Z,G,X,Q,Y)).payloads}async getFeatureFlagsStateless($,Z={},G={},X={},Q,Y){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless($,Z,G,X,Q,Y)}async getFeatureFlagsAndPayloadsStateless($,Z={},G={},X={},Q,Y){await this._initPromise;let J=await this.getFeatureFlagDetailsStateless($,Z,G,X,Q,Y);if(!J)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:J.featureFlags,payloads:J.featureFlagPayloads,requestId:J.requestId}}async getFeatureFlagDetailsStateless($,Z={},G={},X={},Q,Y){await this._initPromise;let J={};if(Q??this.disableGeoip)J.geoip_disable=!0;if(Y)J.flag_keys_to_evaluate=Y;let W=await this.getFlags($,Z,G,X,J);if(!W.success)return;let K=W.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 $=`${this.host}/api/surveys/?token=${this.apiKey}`,Z={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},X=(await this.fetchWithRetry($,Z).then((Q)=>{if(Q.status!==200||!Q.json){let Y=`Surveys API could not be loaded: ${Q.status}`,J=Error(Y);this._logger.error(J),this._events.emit("error",Error(Y));return}return Q.json()}).catch((Q)=>{this._logger.error("Surveys API could not be loaded",Q),this._events.emit("error",Q)}))?.surveys;if(X)this._logger.info("Surveys fetched from API: ",JSON.stringify(X));return X??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(V7.Props);return this._props||{}}set props($){this._props=$}async register($){this.wrap(()=>{this.props={...this.props,...$},this.setPersistedProperty(V7.Props,this.props)})}async unregister($){this.wrap(()=>{delete this.props[$],this.setPersistedProperty(V7.Props,this.props)})}processBeforeEnqueue($){return $}async flushStorage(){}enqueue($,Z,G){this.wrap(()=>{if(this.optedOut)return void this._events.emit($,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let X=this.prepareMessage($,Z,G);if(X=this.processBeforeEnqueue(X),X===null)return;let Q=this.getPersistedProperty(V7.Queue)||[];if(Q.length>=this.maxQueueSize)Q.shift(),this._logger.info("Queue is full, the oldest event is dropped.");if(Q.push({message:X}),this.setPersistedProperty(V7.Queue,Q),this._events.emit($,X),Q.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=dK(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate($,Z,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($,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let X=this.prepareMessage($,Z,G);if(X=this.processBeforeEnqueue(X),X===null)return;let Q={api_key:this.apiKey,batch:[X],sent_at:qs()};if(this.historicalMigration)Q.historical_migration=!0;let Y=JSON.stringify(Q),J=`${this.host}/batch/`,W=this.disableCompression?null:await ws(Y,this.isDebug),K={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...W!==null&&{"Content-Encoding":"gzip"}},body:W||Y};try{await this.fetchWithRetry(J,K)}catch(U){this._events.emit("error",U)}}prepareMessage($,Z,G){let X={...Z,type:$,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:G?.timestamp?G?.timestamp:qs(),uuid:G?.uuid?G.uuid:RH()};if(G?.disableGeoip??this.disableGeoip){if(!X.properties)X.properties={};X.properties.$geoip_disable=!0}if(X.distinctId)X.distinct_id=X.distinctId,delete X.distinctId;return X}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){this.flush().catch(async($)=>{await fP0($)})}async flush(){let $=KM1([this.flushPromise]).then(()=>this._flush());return this.flushPromise=$,this.addPendingPromise($),KM1([$]).then(()=>{if(this.flushPromise===$)this.flushPromise=null}),$}getCustomHeaders(){let $=this.getCustomUserAgent(),Z={};if($&&$!=="")Z["User-Agent"]=$;return Z}async _flush(){this.clearFlushTimer(),await this._initPromise;let $=this.getPersistedProperty(V7.Queue)||[];if(!$.length)return;let Z=[],G=$.length;while($.length>0&&Z.length<G){let X=$.slice(0,this.maxBatchSize),Q=X.map((N)=>N.message),Y=async()=>{let O=(this.getPersistedProperty(V7.Queue)||[]).slice(X.length);this.setPersistedProperty(V7.Queue,O),$=O,await this.flushStorage()},J={api_key:this.apiKey,batch:Q,sent_at:qs()};if(this.historicalMigration)J.historical_migration=!0;let W=JSON.stringify(J),K=`${this.host}/batch/`,U=this.disableCompression?null:await ws(W,this.isDebug),F={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...U!==null&&{"Content-Encoding":"gzip"}},body:U||W},H={retryCheck:(N)=>{if(xP0(N))return!1;return HM1(N)}};try{await this.fetchWithRetry(K,F,H)}catch(N){if(xP0(N)&&Q.length>1){this.maxBatchSize=Math.max(1,Math.floor(Q.length/2)),this._logger.warn(`Received 413 when sending batch of size ${Q.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(N instanceof zh))await Y();throw this._events.emit("error",N),N}await Y(),Z.push(...Q)}this._events.emit("flush",Z)}async fetchWithRetry($,Z,G,X){let Q=Z.body?Z.body:"",Y=-1;try{Y=Q instanceof Blob?Q.size:Buffer.byteLength(Q,kP0)}catch{if(Q instanceof Blob)Y=Q.size;else Y=new TextEncoder().encode(Q).length}return await SP0(async()=>{let J=new AbortController,W=X??this.requestTimeout,K=dK(()=>J.abort(),W),U=null;try{U=await this.fetch($,{signal:J.signal,...Z})}catch(H){throw new zh(H)}finally{clearTimeout(K)}if(Z.mode!=="no-cors"&&(U.status<200||U.status>=400))throw new nC(U,Y);return U},{...this._retryOptions,...G})}async _shutdown($=30000){await this._initPromise;let Z=!1;this.clearFlushTimer();let G=async()=>{try{await this.promiseQueue.join();while(!0){if((this.getPersistedProperty(V7.Queue)||[]).length===0)break;if(await this.flush(),Z)break}}catch(Q){if(!HM1(Q))throw Q;await fP0(Q)}},X;try{return await Promise.race([new Promise((Q,Y)=>{X=dK(()=>{this._logger.error("Timed out while shutting down PostHog"),Z=!0,Y("Timeout while shutting down PostHog. Some events may not have been sent.")},$)}),G()])}finally{clearTimeout(X)}}async shutdown($=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($).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var nC,zh;var NM1=D(()=>{vP0();Es();aq1();fB();EG();Eh();nC=class nC extends Error{constructor($,Z){super("HTTP error while fetching PostHog: status="+$.status+", reqByteLength="+Z),this.response=$,this.reqByteLength=Z,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}};zh=class zh extends Error{constructor($){super("Network error while fetching PostHog",$ instanceof Error?{cause:$}:{}),this.error=$,this.name="PostHogFetchNetworkError"}}});var yP0=D(()=>{Es();fB();NM1();Eh();EG()});var gP0=D(()=>{Dh()});function uP0($){let Z=globalThis._posthogChunkIds;if(!Z)return;let G=Object.keys(Z);if(Vs&&G.length===hP0)return Vs;return hP0=G.length,Vs=G.reduce((X,Q)=>{if(!ks)ks={};let Y=ks[Q];if(Y)X[Y[0]]=Y[1];else{let J=$(Q);for(let W=J.length-1;W>=0;W--){let U=J[W]?.filename,F=Z[Q];if(U&&F){X[U]=F,ks[Q]=[U,F];break}}}return X},{}),Vs}var ks,hP0,Vs;var cP0=()=>{};class lP0{constructor($,Z,G=[]){this.coercers=$,this.stackParser=Z,this.modifiers=G}buildFromUnknown($,Z={}){let X=Z&&Z.mechanism||{handled:!0,type:"generic"},Y=this.buildCoercingContext(X,Z,0).apply($),J=this.buildParsingContext(Z),W=this.parseStacktrace(Y,J);return{$exception_list:this.convertToExceptionList(W,X),$exception_level:"error"}}async modifyFrames($){for(let Z of $)if(Z.stacktrace&&Z.stacktrace.frames&&js(Z.stacktrace.frames))Z.stacktrace.frames=await this.applyModifiers(Z.stacktrace.frames);return $}coerceFallback($){return{type:"Error",value:"Unknown error",stack:$.syntheticException?.stack,synthetic:!0}}parseStacktrace($,Z){let G;if($.cause!=null)G=this.parseStacktrace($.cause,Z);let X;if($.stack!=""&&$.stack!=null)X=this.applyChunkIds(this.stackParser($.stack,$.synthetic?Z.skipFirstLines:0),Z.chunkIdMap);return{...$,cause:G,stack:X}}applyChunkIds($,Z){return $.map((G)=>{if(G.filename&&Z)G.chunk_id=Z[G.filename];return G})}applyCoercers($,Z){for(let G of this.coercers)if(G.match($))return G.coerce($,Z);return this.coerceFallback(Z)}async applyModifiers($){let Z=$;for(let G of this.modifiers)Z=await G(Z);return Z}convertToExceptionList($,Z){let G={type:$.type,value:$.value,mechanism:{type:Z.type??"generic",handled:Z.handled??!0,synthetic:$.synthetic??!1}};if($.stack)G.stacktrace={type:"raw",frames:$.stack};let X=[G];if($.cause!=null)X.push(...this.convertToExceptionList($.cause,{...Z,handled:!0}));return X}buildParsingContext($){return{chunkIdMap:uP0(this.stackParser),skipFirstLines:$.skipFirstLines??1}}buildCoercingContext($,Z,G=0){let X=(Y,J)=>{if(!(J<=WG8))return;{let W=this.buildCoercingContext($,Z,J);return this.applyCoercers(Y,W)}};return{...Z,syntheticException:G==0?Z.syntheticException:void 0,mechanism:$,apply:(Y)=>X(Y,G),next:(Y)=>X(Y,G+1)}}}var WG8=4;var dP0=D(()=>{EG();cP0()});function b3($,Z,G,X,Q){let Y={platform:$,filename:Z,function:G==="<anonymous>"?aZ:G,in_app:!0};if(!lC(X))Y.lineno=X;if(!lC(Q))Y.colno=Q;return Y}var aZ="?";var IH=D(()=>{EG()});var Ss=($,Z)=>{let G=$.indexOf("safari-extension")!==-1,X=$.indexOf("safari-web-extension")!==-1;return G||X?[$.indexOf("@")!==-1?$.split("@")[0]:aZ,G?`safari-extension:${Z}`:`safari-web-extension:${Z}`]:[$,Z]};var OM1=D(()=>{IH()});var KG8,UG8,FG8,BM1=($,Z)=>{let G=KG8.exec($);if(G){let[,Q,Y,J]=G;return b3(Z,Q,aZ,+Y,+J)}let X=UG8.exec($);if(X){if(X[2]&&X[2].indexOf("eval")===0){let W=FG8.exec(X[2]);if(W)X[2]=W[1],X[3]=W[2],X[4]=W[3]}let[Y,J]=Ss(X[1]||aZ,X[2]);return b3(Z,J,Y,X[3]?+X[3]:void 0,X[4]?+X[4]:void 0)}};var mP0=D(()=>{IH();OM1();KG8=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,UG8=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,FG8=/\((\S*)(?::(\d+))(?::(\d+))\)/});var HG8,NG8,DM1=($,Z)=>{let G=HG8.exec($);if(G){if(G[3]&&G[3].indexOf(" > eval")>-1){let J=NG8.exec(G[3]);if(J)G[1]=G[1]||"eval",G[3]=J[1],G[4]=J[2],G[5]=""}let Q=G[3],Y=G[1]||aZ;return[Y,Q]=Ss(Y,Q),b3(Z,Q,Y,G[4]?+G[4]:void 0,G[5]?+G[5]:void 0)}};var iP0=D(()=>{IH();OM1();HG8=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,NG8=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i});var OG8,nP0=($,Z)=>{let G=OG8.exec($);return G?b3(Z,G[2],G[1]||aZ,+G[3],G[4]?+G[4]:void 0):void 0};var pP0=D(()=>{IH();OG8=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i});var BG8,tP0=($,Z)=>{let G=BG8.exec($);return G?b3(Z,G[2],G[3]||aZ,+G[1]):void 0},DG8,oP0=($,Z)=>{let G=DG8.exec($);return G?b3(Z,G[5],G[3]||G[4]||aZ,+G[1],+G[2]):void 0};var rP0=D(()=>{IH();BG8=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,DG8=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i});function wG8($,Z=!1){return!(Z||$&&!$.startsWith("/")&&!$.match(/^[A-Z]:/)&&!$.startsWith(".")&&!$.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&$!==void 0&&!$.includes("node_modules/")}function aP0($){return parseInt($||"",10)||void 0}var LG8,EG8,sP0=($,Z)=>{let G=$.match(EG8);if(G){let X,Q,Y,J,W;if(G[1]){Y=G[1];let F=Y.lastIndexOf(".");if(Y[F-1]===".")F--;if(F>0){X=Y.slice(0,F),Q=Y.slice(F+1);let H=X.indexOf(".Module");if(H>0)Y=Y.slice(H+1),X=X.slice(0,H)}J=void 0}if(Q)J=X,W=Q;if(Q==="<anonymous>")W=void 0,Y=void 0;if(Y===void 0)W=W||aZ,Y=J?`${J}.${W}`:W;let K=G[2]?.startsWith("file://")?G[2].slice(7):G[2],U=G[5]==="native";if(K?.match(/\/[A-Z]:/))K=K.slice(1);if(!K&&G[5]&&!U)K=G[5];return{filename:K?decodeURI(K):void 0,module:void 0,function:Y,lineno:aP0(G[3]),colno:aP0(G[4]),in_app:wG8(K||"",U),platform:Z}}if($.match(LG8))return{filename:$,platform:Z}};var eP0=D(()=>{IH();LG8=/^\s*[-]{4,}$/,EG8=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/});function GA0($){if(!$.length)return[];let Z=Array.from($);return Z.reverse(),Z.slice(0,ZA0).map((G)=>({...G,filename:G.filename||zG8(Z).filename,function:G.function||aZ}))}function zG8($){return $[$.length-1]||{}}function jG8(){return XA0("web:javascript",BM1,DM1)}function XA0($,...Z){return(G,X=0)=>{let Q=[],Y=G.split(`
85
- `);for(let J=X;J<Y.length;J++){let W=Y[J];if(W.length>1024)continue;let K=$A0.test(W)?W.replace($A0,"$1"):W;if(!K.match(/\S*Error: /)){for(let U of Z){let F=U(K,$);if(F){Q.push(F);break}}if(Q.length>=ZA0)break}}return GA0(Q)}}var $A0,ZA0=50;var QA0=D(()=>{IH();mP0();iP0();pP0();rP0();eP0();$A0=/\(error: (.*)\)/});class YA0{match($){return this.isDOMException($)||this.isDOMError($)}coerce($,Z){let G=AH($.stack);return{type:this.getType($),value:this.getValue($),stack:G?$.stack:void 0,cause:$.cause?Z.next($.cause):void 0,synthetic:!1}}getType($){return this.isDOMError($)?"DOMError":"DOMException"}getValue($){let Z=$.name||(this.isDOMError($)?"DOMError":"DOMException");return $.message?`${Z}: ${$.message}`:Z}isDOMException($){return xB($,"DOMException")}isDOMError($){return xB($,"DOMError")}}var JA0=D(()=>{EG()});class WA0{match($){return eq1($)}coerce($,Z){return{type:this.getType($),value:this.getMessage($,Z),stack:this.getStack($),cause:$.cause?Z.next($.cause):void 0,synthetic:!1}}getType($){return $.name||$.constructor.name}getMessage($,Z){let G=$.message;if(G.error&&typeof G.error.message=="string")return String(G.error.message);return String(G)}getStack($){return $.stacktrace||$.stack||void 0}}var KA0=D(()=>{EG()});class UA0{constructor(){}match($){return NP0($)&&$.error!=null}coerce($,Z){let G=Z.apply($.error);if(!G)return{type:"ErrorEvent",value:$.message,stack:Z.syntheticException?.stack,synthetic:!0};return G}}var FA0=D(()=>{EG()});class HA0{match($){return typeof $=="string"}coerce($,Z){let[G,X]=this.getInfos($);return{type:G??"Error",value:X??$,stack:Z.syntheticException?.stack,synthetic:!0}}getInfos($){let Z="Error",G=$,X=$.match(PG8);if(X)Z=X[1],G=X[2];return[Z,G]}}var PG8;var NA0=D(()=>{PG8=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i});var OA0;var BA0=D(()=>{OA0=["fatal","error","warning","log","info","debug"]});function Cs($,Z=40){let G=Object.keys($);if(G.sort(),!G.length)return"[object has no keys]";for(let X=G.length;X>0;X--){let Q=G.slice(0,X).join(", ");if(!(Q.length>Z)){if(X===G.length)return Q;return Q.length<=Z?Q:`${Q.slice(0,Z)}...`}}return""}var LM1=()=>{};class DA0{match($){return typeof $=="object"&&$!==null}coerce($,Z){let G=this.getErrorPropertyFromObject($);if(G)return Z.apply(G);return{type:this.getType($),value:this.getValue($),stack:Z.syntheticException?.stack,level:this.isSeverityLevel($.level)?$.level:"error",synthetic:!0}}getType($){return dC($)?$.constructor.name:"Error"}getValue($){if("name"in $&&typeof $.name=="string"){let X=`'${$.name}' captured as exception`;if("message"in $&&typeof $.message=="string")X+=` with message: '${$.message}'`;return X}if("message"in $&&typeof $.message=="string")return $.message;let Z=this.getObjectClassName($),G=Cs($);return`${Z&&Z!=="Object"?`'${Z}'`:"Object"} captured as exception with keys: ${G}`}isSeverityLevel($){return AH($)&&!HP0($)&&OA0.indexOf($)>=0}getErrorPropertyFromObject($){for(let Z in $)if(Object.prototype.hasOwnProperty.call($,Z)){let G=$[Z];if(CP0(G))return G}}getObjectClassName($){try{let Z=Object.getPrototypeOf($);return Z?Z.constructor.name:void 0}catch(Z){return}}}var LA0=D(()=>{EG();BA0();LM1()});class EA0{match($){return dC($)}coerce($,Z){let G=$.constructor.name;return{type:G,value:`${G} captured as exception with keys: ${Cs($)}`,stack:Z.syntheticException?.stack,synthetic:!0}}}var wA0=D(()=>{EG();LM1()});class zA0{match($){return Ps($)}coerce($,Z){return{type:"Error",value:`Primitive value captured as exception: ${String($)}`,stack:Z.syntheticException?.stack,synthetic:!0}}}var jA0=D(()=>{EG()});class PA0{match($){return xB($,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection($)}isCustomEventWrappingRejection($){if(!dC($))return!1;try{let Z=$.detail;return Z!=null&&typeof Z=="object"&&"reason"in Z}catch{return!1}}coerce($,Z){let G=this.getUnhandledRejectionReason($);if(Ps(G))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(G)}`,stack:Z.syntheticException?.stack,synthetic:!0};return Z.apply(G)}getUnhandledRejectionReason($){try{if("reason"in $)return $.reason;if("detail"in $&&$.detail!=null&&typeof $.detail=="object"&&"reason"in $.detail)return $.detail.reason}catch{}return $}}var AA0=D(()=>{EG()});var RA0=D(()=>{JA0();KA0();FA0();NA0();LA0();wA0();jA0();AA0()});class IA0{constructor($){this._maxSize=$,this._cache=new Map}get($){let Z=this._cache.get($);if(Z===void 0)return;return this._cache.delete($),this._cache.set($,Z),Z}set($,Z){this._cache.set($,Z)}reduce(){while(this._cache.size>=this._maxSize){let $=this._cache.keys().next().value;if($)this._cache.delete($)}}}var TA0=()=>{};function EM1($){if(!$)return{..._s};return{enabled:$.enabled??_s.enabled,max_bytes:IG8($.max_bytes,_s.max_bytes)}}function RG8($){if(!$)return{sanitizedProperties:{},droppedKeys:[]};let Z=[];return{sanitizedProperties:Object.keys($).reduce((X,Q)=>{if(AG8.has(Q))return Z.push(Q),X;return X[Q]=$[Q],X},{}),droppedKeys:Z}}class qA0{constructor($){this._entries=[],this._totalBytes=0,this._config=EM1($)}setConfig($){this._config=EM1($),this._trimToMaxBytes()}add($){let Z=TG8($);if(!Z)return;let G=MA0(Z.json);if(G>this._config.max_bytes)return;this._entries.push({step:Z.step,bytes:G}),this._totalBytes+=G,this._trimToMaxBytes()}getAttachable(){return this._entries.map(($)=>$.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 $=this._entries.shift();if($)this._totalBytes-=$.bytes}}}function IG8($,Z){if(!Bh($)||$===1/0||$===-1/0)return Z;let G=Math.floor($);if(G<0)return Z;return G}function TG8($){let Z=qG8($);if(!Z)return;try{let G=JSON.parse(Z);if(!Oh(G))return;let X=G,Q=X[jh.MESSAGE],Y=X[jh.TIMESTAMP];if(!AH(Q)||Q.trim().length===0)return;if(!AH(Y)&&!Bh(Y))return;return{step:X,json:Z}}catch{return}}function qG8($){let Z=new WeakSet;try{return JSON.stringify($,(G,X)=>{if(typeof X=="bigint")return X.toString();if(typeof X=="function"||typeof X=="symbol")return;if(X instanceof Date)return X.toISOString();if(X instanceof Error)return{name:X.name,message:X.message,stack:X.stack};if(X&&typeof X=="object"){if(Z.has(X))return"[Circular]";Z.add(X)}return X})}catch{return}}function MA0($){if(typeof TextEncoder<"u")return new TextEncoder().encode($).length;let Z=encodeURIComponent($),G=0;for(let X=0;X<Z.length;X++)if(Z[X]==="%")G+=1,X+=2;else G+=1;return G}var jh,AG8,_s;var kA0=D(()=>{EG();jh={MESSAGE:"$message",TIMESTAMP:"$timestamp"},AG8=new Set([jh.MESSAGE,jh.TIMESTAMP]),_s={enabled:!0,max_bytes:32768}});var aG={};p4(aG,{winjsStackLineParser:()=>nP0,stripReservedExceptionStepFields:()=>RG8,reverseAndStripFrames:()=>GA0,resolveExceptionStepsConfig:()=>EM1,opera11StackLineParser:()=>oP0,opera10StackLineParser:()=>tP0,nodeStackLineParser:()=>sP0,getUtf8ByteLength:()=>MA0,geckoStackLineParser:()=>DM1,createStackParser:()=>XA0,createDefaultStackParser:()=>jG8,chromeStackLineParser:()=>BM1,StringCoercer:()=>HA0,ReduceableCache:()=>IA0,PromiseRejectionEventCoercer:()=>PA0,PrimitiveCoercer:()=>zA0,ObjectCoercer:()=>DA0,ExceptionStepsBuffer:()=>qA0,EventCoercer:()=>EA0,ErrorPropertiesBuilder:()=>lP0,ErrorEventCoercer:()=>UA0,ErrorCoercer:()=>WA0,EXCEPTION_STEP_INTERNAL_FIELDS:()=>jh,DOMExceptionCoercer:()=>YA0,DEFAULT_EXCEPTION_STEPS_CONFIG:()=>_s});var VA0=D(()=>{dP0();QA0();RA0();TA0();kA0()});var gB=D(()=>{Es();aq1();UM1();_P0();Eh();bP0();VA0();EG();yP0();NM1();gP0();fB()});import{createReadStream as MG8}from"fs";import{createInterface as kG8}from"readline";async function bA0($){let Z={};for(let Q=$.length-1;Q>=0;Q--){let Y=$[Q],J=Y?.filename;if(!Y||typeof J!="string"||typeof Y.lineno!="number"||vG8(J)||fG8(Y))continue;if(!Z[J])Z[J]=[];Z[J].push(Y.lineno)}let G=Object.keys(Z);if(G.length==0)return $;let X=[];for(let Q of G){if(_A0.get(Q))continue;let Y=Z[Q];if(!Y)continue;Y.sort((K,U)=>K-U);let J=yG8(Y);if(J.every((K)=>xG8(Q,K)))continue;let W=gG8(bs,Q,{});X.push(CG8(Q,J,W))}if(await Promise.all(X).catch(()=>{}),$&&$.length>0)_G8($,bs);return bs.reduce(),$}function CG8($,Z,G){return new Promise((X)=>{let Q=MG8($),Y=kG8({input:Q});function J(){Q.destroy(),X()}let W=0,K=0,U=Z[K];if(U===void 0)return void J();let F=U[0],H=U[1];function N(){_A0.set($,1),Y.close(),Y.removeAllListeners(),J()}Q.on("error",N),Y.on("error",N),Y.on("close",J),Y.on("line",(O)=>{if(W++,W<F)return;if(G[W]=hG8(O,0),W>=H){if(K===Z.length-1){Y.close(),Y.removeAllListeners();return}K++;let B=Z[K];if(B===void 0){Y.close(),Y.removeAllListeners();return}F=B[0],H=B[1]}})})}function _G8($,Z){for(let G of $)if(G.filename&&G.context_line===void 0&&typeof G.lineno=="number"){let X=Z.get(G.filename);if(X===void 0)continue;bG8(G.lineno,G,X)}}function bG8($,Z,G){if(Z.lineno===void 0||G===void 0)return;Z.pre_context=[];for(let Q=vA0($);Q<$;Q++){let Y=G[Q];if(Y===void 0)return void SA0(Z);Z.pre_context.push(Y)}if(G[$]===void 0)return void SA0(Z);Z.context_line=G[$];let X=fA0($);Z.post_context=[];for(let Q=$+1;Q<=X;Q++){let Y=G[Q];if(Y===void 0)break;Z.post_context.push(Y)}}function SA0($){delete $.pre_context,delete $.context_line,delete $.post_context}function vG8($){return $.startsWith("node:")||$.endsWith(".min.js")||$.endsWith(".min.cjs")||$.endsWith(".min.mjs")||$.startsWith("data:")}function fG8($){if($.lineno!==void 0&&$.lineno>SG8)return!0;if($.colno!==void 0&&$.colno>VG8)return!0;return!1}function xG8($,Z){let G=bs.get($);if(G===void 0)return!1;for(let X=Z[0];X<=Z[1];X++)if(G[X]===void 0)return!1;return!0}function yG8($){if(!$.length)return[];let Z=0,G=$[0];if(typeof G!="number")return[];let X=CA0(G),Q=[];while(!0){if(Z===$.length-1){Q.push(X);break}let Y=$[Z+1];if(typeof Y!="number")break;if(Y<=X[1])X[1]=Y+wM1;else Q.push(X),X=CA0(Y);Z++}return Q}function CA0($){return[vA0($),fA0($)]}function vA0($){return Math.max(1,$-wM1)}function fA0($){return $+wM1}function gG8($,Z,G){let X=$.get(Z);if(X===void 0)return $.set(Z,G),G;return X}function hG8($,Z){let G=$,X=G.length;if(X<=150)return G;if(Z>X)Z=X;let Q=Math.max(Z-60,0);if(Q<5)Q=0;let Y=Math.min(Q+140,X);if(Y>X-5)Y=X;if(Y===X)Q=Math.max(Y-140,0);if(G=G.slice(Q,Y),Q>0)G=`...${G}`;if(Y<X)G+="...";return G}var bs,_A0,wM1=7,VG8=1000,SG8=1e4;var xA0=D(()=>{gB();bs=new aG.ReduceableCache(25),_A0=new aG.ReduceableCache(20)});import{isAbsolute as uG8,relative as cG8,sep as lG8}from"path";function yA0($=process.cwd()){let Z=lG8==="\\",G=(Q)=>Z?Q.replace(/\\/g,"/"):Q,X=G($);return async(Q)=>{for(let Y of Q)if(!(!Y.filename||Y.filename.startsWith("node:")||Y.filename.startsWith("data:"))){if(uG8(Y.filename))Y.filename=G(cG8(X,G(Y.filename)))}return Q}}var gA0=()=>{};function dG8($,Z){let G=!1;return Object.assign((X)=>{let Y=global.process.listeners("uncaughtException").filter((J)=>J.name!=="domainUncaughtExceptionClear"&&J._posthogErrorHandler!==!0).length===0;if($(X,{mechanism:{type:"onuncaughtexception",handled:!1}}),!G&&Y)G=!0,Z(X)},{_posthogErrorHandler:!0})}function hA0($,Z){globalThis.process?.on("uncaughtException",dG8($,Z))}function uA0($){globalThis.process?.on("unhandledRejection",(Z)=>$(Z,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var cA0=()=>{};class $Y{constructor($,Z,G){this.client=$,this._exceptionAutocaptureEnabled=Z.enableExceptionAutocapture||!1,this._logger=G,this._rateLimiter=new ZM1({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError($){return Oh($)&&"__posthog_previously_captured_error"in $&&$.__posthog_previously_captured_error===!0}static async buildEventMessage($,Z,G,X){let Q={...X},Y=this.errorPropertiesBuilder.buildFromUnknown($,Z);return Y.$exception_list=await this.errorPropertiesBuilder.modifyFrames(Y.$exception_list),{event:"$exception",distinctId:G,properties:{...Y,...Q},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())hA0(this.onException.bind(this),this.onFatalError.bind(this)),uA0(this.onException.bind(this))}onException($,Z){this.client.addPendingPromise((async()=>{if(!$Y.isPreviouslyCapturedError($)){let G=await $Y.buildEventMessage($,Z),Q=G.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(Q))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:Q});return this.client.capture(G)}})())}async onFatalError($){console.error($),await this.client.shutdown(mG8),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}var mG8=2000;var vs=D(()=>{cA0();gB()});var lA0="5.30.6";var dA0=()=>{};var Ph;var zM1=D(()=>{Ph={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"}});async function mA0($){let Z=globalThis.crypto?.subtle;if(!Z)throw Error("SubtleCrypto API not available");let G=await Z.digest("SHA-1",new TextEncoder().encode($));return Array.from(new Uint8Array(G)).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}var iA0=()=>{};class jM1{constructor({pollingInterval:$,personalApiKey:Z,projectApiKey:G,timeout:X,host:Q,customHeaders:Y,...J}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=$,this.personalApiKey=Z,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=X,this.projectApiKey=G,this.host=Q,this.poller=void 0,this.fetch=J.fetch||fetch,this.onError=J.onError,this.customHeaders=Y,this.onLoad=J.onLoad,this.cacheProvider=J.cacheProvider,this.strictLocalEvaluation=J.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug($=!0){this.debugMode=$}logMsgIfDebug($){if(this.debugMode)$()}createEvaluationContext($,Z={},G={},X={},Q={}){return{distinctId:$,groups:Z,personProperties:G,groupProperties:X,evaluationCache:Q}}async getFeatureFlag($,Z,G={},X={},Q={}){await this.loadFeatureFlags();let Y,J;if(!this.loadedSuccessfullyOnce)return Y;if(J=this.featureFlagsByKey[$],J!==void 0){let W=this.createEvaluationContext(Z,G,X,Q);try{Y=(await this.computeFlagAndPayloadLocally(J,W)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${$} -> ${Y}`))}catch(K){if(K instanceof v3||K instanceof g4)this.logMsgIfDebug(()=>console.debug(`${K.name} when computing flag locally: ${$}: ${K.message}`));else if(K instanceof Error)this.onError?.(Error(`Error computing flag locally: ${$}: ${K}`))}}return Y}async getAllFlagsAndPayloads($,Z){await this.loadFeatureFlags();let G={},X={},Q=this.featureFlags.length==0,Y=Z?Z.map((W)=>this.featureFlagsByKey[W]).filter(Boolean):this.featureFlags,J={...$,evaluationCache:$.evaluationCache??{}};return await Promise.all(Y.map(async(W)=>{try{let{value:K,payload:U}=await this.computeFlagAndPayloadLocally(W,J);if(G[W.key]=K,U)X[W.key]=U}catch(K){if(K instanceof v3||K instanceof g4)this.logMsgIfDebug(()=>console.debug(`${K.name} when computing flag locally: ${W.key}: ${K.message}`));else if(K instanceof Error)this.onError?.(Error(`Error computing flag locally: ${W.key}: ${K}`));Q=!0}})),{response:G,payloads:X,fallbackToFlags:Q}}async computeFlagAndPayloadLocally($,Z,G={}){let{matchValue:X,skipLoadCheck:Q=!1}=G;if(!Q)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let Y;Y=X!==void 0?X:await this.computeFlagValueLocally($,Z);let J=this.getFeatureFlagPayload($.key,Y);return{value:Y,payload:J}}async computeFlagValueLocally($,Z){let{distinctId:G,groups:X,personProperties:Q,groupProperties:Y}=Z;if($.ensure_experience_continuity)throw new g4("Flag has experience continuity enabled");if(!$.active)return!1;let W=($.filters||{}).aggregation_group_type_index;if(W!=null){let K=this.groupTypeMapping[String(W)];if(!K)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${W} for feature flag ${$.key}`)),new g4("Flag has unknown group type index");if(!(K in X))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${$.key} without group names passed in`)),!1;if($.bucketing_identifier==="device_id"&&(Q?.$device_id===void 0||Q?.$device_id===null||Q?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${$.key}`));let U=Y[K];return await this.matchFeatureFlagProperties($,X[K],U,Z)}{let K=this.getBucketingValueForFlag($,G,Q);if(K===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${$.key} without $device_id, falling back to server evaluation`)),new g4(`Can't compute feature flag: ${$.key} without $device_id`);return await this.matchFeatureFlagProperties($,K,Q,Z)}}getBucketingValueForFlag($,Z,G){if($.filters?.aggregation_group_type_index!=null)return Z;if($.bucketing_identifier==="device_id"){let X=G?.$device_id;if(X==null||X==="")return;return X}return Z}getFeatureFlagPayload($,Z){let G=null;if(Z!==!1&&Z!=null){if(typeof Z=="boolean")G=this.featureFlagsByKey?.[$]?.filters?.payloads?.[Z.toString()]||null;else if(typeof Z=="string")G=this.featureFlagsByKey?.[$]?.filters?.payloads?.[Z]||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($,Z,G){let{evaluationCache:X}=G,Q=$.key;if(!this.featureFlagsByKey)throw new g4("Feature flags not available for dependency evaluation");if(!("dependency_chain"in $))throw new g4(`Flag dependency property for '${Q}' is missing required 'dependency_chain' field`);let Y=$.dependency_chain;if(!Array.isArray(Y))throw new g4(`Flag dependency property for '${Q}' has an invalid 'dependency_chain' (expected array, got ${typeof Y})`);if(Y.length===0)throw new g4(`Circular dependency detected for flag '${Q}' (empty dependency chain)`);for(let W of Y){if(!(W in X)){let U=this.featureFlagsByKey[W];if(U)if(U.active)try{let F=await this.computeFlagValueLocally(U,G);X[W]=F}catch(F){throw new g4(`Error evaluating flag dependency '${W}' for flag '${Q}': ${F}`)}else X[W]=!1;else throw new g4(`Missing flag dependency '${W}' for flag '${Q}'`)}if(X[W]==null)throw new g4(`Dependency '${W}' could not be evaluated`)}let J=X[Q];return this.flagEvaluatesToExpectedValue($.value,J)}flagEvaluatesToExpectedValue($,Z){if(typeof $=="boolean")return $===Z||typeof Z=="string"&&Z!==""&&$===!0;if(typeof $=="string")return Z===$;return!1}async matchFeatureFlagProperties($,Z,G,X){let Q=$.filters||{},Y=Q.groups||[],J=!1,W;for(let K of Y)try{if(await this.isConditionMatch($,Z,K,G,X)){let U=K.variant,F=Q.multivariate?.variants||[];W=U&&F.some((H)=>H.key===U)?U:await this.getMatchingVariant($,Z)||!0;break}}catch(U){if(U instanceof v3)throw U;if(U instanceof g4)J=!0;else throw U}if(W!==void 0)return W;if(J)throw new g4("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch($,Z,G,X,Q){let Y=G.rollout_percentage,J=(W)=>{this.logMsgIfDebug(()=>console.warn(W))};if((G.properties||[]).length>0){for(let W of G.properties){let K=W.type,U=!1;if(U=K==="cohort"?rA0(W,X,this.cohorts,this.debugMode):K==="flag"?await this.evaluateFlagDependency(W,X,Q):oA0(W,X,J),!U)return!1}if(Y==null)return!0}if(Y!=null&&await nA0($.key,Z)>Y/100)return!1;return!0}async getMatchingVariant($,Z){let G=await nA0($.key,Z,"variant"),X=this.variantLookupTable($).find((Q)=>G>=Q.valueMin&&G<Q.valueMax);if(X)return X.key}variantLookupTable($){let Z=[],G=0,X=0;return(($.filters||{}).multivariate?.variants||[]).forEach((J)=>{X=G+J.rollout_percentage/100,Z.push({valueMin:G,valueMax:X,key:J.key}),G=X}),Z}updateFlagState($){this.featureFlags=$.flags,this.featureFlagsByKey=$.flags.reduce((Z,G)=>(Z[G.key]=G,Z),{}),this.groupTypeMapping=$.groupTypeMapping,this.cohorts=$.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags($){if(this.strictLocalEvaluation)return;let Z=$.filter((G)=>G.ensure_experience_continuity);if(Z.length>0)console.warn(`[PostHog] You are using local evaluation but ${Z.length} flag(s) have experience continuity enabled: ${Z.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($){if(!this.cacheProvider)return!1;try{let Z=await this.cacheProvider.getFlagDefinitions();if(Z)return this.updateFlagState(Z),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${$} (${Z.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(Z.flags),!0;return!1}catch(Z){return this.onError?.(Error(`Failed to load from cache: ${Z}`)),!1}}async loadFeatureFlags($=!1){if(this.loadedSuccessfullyOnce&&!$)return;if(!$&&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((Z)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${Z}`))).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(iG8,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 $=!0;if(this.cacheProvider)try{$=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(G){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${G}`))}if(!$){if(await this.loadFromCache("Loaded flags from cache (skipped fetch)"))return;if(this.loadedSuccessfullyOnce)return}let Z=await this._requestFeatureFlagDefinitions();if(!Z)return;switch(Z.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=Z.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new pC(`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 pC(`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 pC(`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 Z.json()??{};if(!("flags"in G))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(G)}`));this.flagsEtag=Z.headers?.get("ETag")??void 0;let X={flags:G.flags??[],groupTypeMapping:G.group_type_mapping||{},cohorts:G.cohorts||{}};if(this.updateFlagState(X),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&$)try{await this.cacheProvider.onFlagDefinitionsReceived(X)}catch(Q){this.onError?.(Error(`Failed to store in cache: ${Q}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(X.flags);break}default:return}}catch($){if($ instanceof pC)this.onError?.($)}}getPersonalApiKeyRequestOptions($="GET",Z){let G={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(Z)G["If-None-Match"]=Z;return{method:$,headers:G}}_requestFeatureFlagDefinitions(){let $=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,Z=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),G=null;if(this.timeout&&typeof this.timeout=="number"){let X=new AbortController;G=dK(()=>{X.abort()},this.timeout),Z.signal=X.signal}try{let X=this.fetch;return X($,Z)}finally{clearTimeout(G)}}async stopPoller($=30000){if(clearTimeout(this.poller),this.cacheProvider)try{let Z=this.cacheProvider.shutdown();if(Z instanceof Promise)await Promise.race([Z,new Promise((G,X)=>setTimeout(()=>X(Error(`Cache shutdown timeout after ${$}ms`)),$))])}catch(Z){this.onError?.(Error(`Error during cache shutdown: ${Z}`))}}}async function nA0($,Z,G=""){let X=await mA0(`${$}.${Z}${G}`);return parseInt(X.slice(0,15),16)/nG8}function oA0($,Z,G){let{key:X,value:Q}=$,Y=$.operator||"exact";if(X in Z){if(Y==="is_not_set")throw new g4("Operator is_not_set is not supported")}else throw new g4(`Property ${X} not found in propertyValues`);let J=Z[X];if(J==null&&!pG8.includes(Y)){if(G)G(`Property ${X} cannot have a value of null/undefined with the ${Y} operator`);return!1}function W(U,F){if(Array.isArray(U))return U.map((H)=>String(H).toLowerCase()).includes(String(F).toLowerCase());return String(U).toLowerCase()===String(F).toLowerCase()}function K(U,F,H){if(H==="gt")return U>F;if(H==="gte")return U>=F;if(H==="lt")return U<F;if(H==="lte")return U<=F;throw Error(`Invalid operator: ${H}`)}switch(Y){case"exact":return W(Q,J);case"is_not":return!W(Q,J);case"is_set":return X in Z;case"icontains":return String(J).toLowerCase().includes(String(Q).toLowerCase());case"not_icontains":return!String(J).toLowerCase().includes(String(Q).toLowerCase());case"regex":return pA0(String(Q))&&String(J).match(String(Q))!==null;case"not_regex":return pA0(String(Q))&&String(J).match(String(Q))===null;case"gt":case"gte":case"lt":case"lte":{let U=typeof Q=="number"?Q:null;if(typeof Q=="string")try{U=parseFloat(Q)}catch(F){}if(U==null||J==null)return K(String(J),String(Q),Y);if(typeof J=="string")return K(J,String(Q),Y);return K(J,U,Y)}case"is_date_after":case"is_date_before":{if(typeof Q=="boolean")throw new g4("Date operations cannot be performed on boolean values");let U=sG8(String(Q));if(U==null)U=tA0(Q);if(U==null)throw new g4(`Invalid date: ${Q}`);let F=tA0(J);if(["is_date_before"].includes(Y))return F<U;return F>U}case"semver_eq":return ZY(sZ(String(J)),sZ(String(Q)))===0;case"semver_neq":return ZY(sZ(String(J)),sZ(String(Q)))!==0;case"semver_gt":return ZY(sZ(String(J)),sZ(String(Q)))>0;case"semver_gte":return ZY(sZ(String(J)),sZ(String(Q)))>=0;case"semver_lt":return ZY(sZ(String(J)),sZ(String(Q)))<0;case"semver_lte":return ZY(sZ(String(J)),sZ(String(Q)))<=0;case"semver_tilde":{let U=sZ(String(J)),{lower:F,upper:H}=oG8(String(Q));return ZY(U,F)>=0&&ZY(U,H)<0}case"semver_caret":{let U=sZ(String(J)),{lower:F,upper:H}=rG8(String(Q));return ZY(U,F)>=0&&ZY(U,H)<0}case"semver_wildcard":{let U=sZ(String(J)),{lower:F,upper:H}=aG8(String(Q));return ZY(U,F)>=0&&ZY(U,H)<0}default:throw new g4(`Unknown operator: ${Y}`)}}function tG8($,Z){if(!($ in Z))throw new v3(`cohort ${$} not found in local cohorts - likely a static cohort that requires server evaluation`)}function rA0($,Z,G,X=!1){let Q=String($.value);tG8(Q,G);let Y=G[Q];return aA0(Y,Z,G,X)}function aA0($,Z,G,X=!1){if(!$)return!0;let{type:Q,values:Y}=$;if(!Y||Y.length===0)return!0;let J=!1;if("values"in Y[0]){for(let W of Y)try{let K=aA0(W,Z,G,X);if(Q==="AND"){if(!K)return!1}else if(K)return!0}catch(K){if(K instanceof v3)throw K;if(K instanceof g4){if(X)console.debug(`Failed to compute property ${W} locally: ${K}`);J=!0}else throw K}if(J)throw new g4("Can't match cohort without a given cohort property value");return Q==="AND"}for(let W of Y)try{let K;if(W.type==="cohort")K=rA0(W,Z,G,X);else if(W.type==="flag"){if(X)console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${W.key||"unknown"}'`);continue}else K=oA0(W,Z);let U=W.negation||!1;if(Q==="AND"){if(!K&&!U)return!1;if(K&&U)return!1}else{if(K&&!U)return!0;if(!K&&U)return!0}}catch(K){if(K instanceof v3)throw K;if(K instanceof g4){if(X)console.debug(`Failed to compute property ${W} locally: ${K}`);J=!0}else throw K}if(J)throw new g4("can't match cohort without a given cohort property value");return Q==="AND"}function pA0($){try{return new RegExp($),!0}catch(Z){return!1}}function sZ($){let G=String($).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!G||G.startsWith("."))throw new g4(`Invalid semver: ${$}`);let X=G.split("."),Q=(K)=>{if(K===void 0||K==="")return 0;if(!/^\d+$/.test(K))throw new g4(`Invalid semver: ${$}`);return parseInt(K,10)},Y=Q(X[0]),J=Q(X[1]),W=Q(X[2]);return[Y,J,W]}function ZY($,Z){for(let G=0;G<3;G++){if($[G]<Z[G])return-1;if($[G]>Z[G])return 1}return 0}function oG8($){let Z=sZ($),G=[Z[0],Z[1],Z[2]],X=[Z[0],Z[1]+1,0];return{lower:G,upper:X}}function rG8($){let Z=sZ($),[G,X,Q]=Z,Y=[G,X,Q],J;return J=G>0?[G+1,0,0]:X>0?[0,X+1,0]:[0,0,Q+1],{lower:Y,upper:J}}function aG8($){let G=String($).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!G)throw new g4(`Invalid wildcard semver: ${$}`);let X=G.split("."),Q=parseInt(X[0],10);if(isNaN(Q))throw new g4(`Invalid wildcard semver: ${$}`);let Y,J;if(X.length===1)Y=[Q,0,0],J=[Q+1,0,0];else{let W=parseInt(X[1],10);if(isNaN(W))throw new g4(`Invalid wildcard semver: ${$}`);Y=[Q,W,0],J=[Q,W+1,0]}return{lower:Y,upper:J}}function tA0($){if($ instanceof Date)return $;if(typeof $=="string"||typeof $=="number"){let Z=new Date($);if(!isNaN(Z.valueOf()))return Z;throw new g4(`${$} is in an invalid date format`)}throw new g4(`The date provided ${$} must be a string, number, or date object`)}function sG8($){let Z=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,G=$.match(Z),X=new Date(new Date().toISOString());if(!G)return null;{if(!G.groups)return null;let Q=parseInt(G.groups.number);if(Q>=1e4)return null;let Y=G.groups.interval;if(Y=="h")X.setUTCHours(X.getUTCHours()-Q);else if(Y=="d")X.setUTCDate(X.getUTCDate()-Q);else if(Y=="w")X.setUTCDate(X.getUTCDate()-7*Q);else if(Y=="m")X.setUTCMonth(X.getUTCMonth()-Q);else{if(Y!="y")return null;X.setUTCFullYear(X.getUTCFullYear()-Q)}return X}}var iG8=60000,nG8=1152921504606847000,pG8,pC,g4,v3;var sA0=D(()=>{gB();iA0();pG8=["is_not"];pC=class pC extends Error{constructor($){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=$,Object.setPrototypeOf(this,pC.prototype)}};g4=class g4 extends Error{constructor($){super($);this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,g4.prototype)}};v3=class v3 extends Error{constructor($){super($);this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,v3.prototype)}}});class PM1{getProperty($){return this._memoryStorage[$]}setProperty($,Z){this._memoryStorage[$]=Z!==null?Z:void 0}constructor(){this._memoryStorage={}}}var eA0=()=>{};function QX8($){return typeof $=="string"?$.trim():""}function YX8($){return(typeof $=="string"?$.trim():"")||void 0}function JX8($){return(typeof $=="string"?$.trim():"")||XX8}var eG8=100,$R0=30000,$X8=50000,ZX8=50,GX8=500,XX8="https://us.i.posthog.com",AM1;var ZR0=D(()=>{dA0();gB();zM1();sA0();vs();eA0();AM1=class AM1 extends Ms{constructor($,Z={}){let G=QX8($),X={...Z,host:JX8(Z.host),personalApiKey:YX8(Z.personalApiKey)};if(super(G,X),this._memoryStorage=new PM1,this.options=X,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof X.featureFlagsPollingInterval=="number"?Math.max(X.featureFlagsPollingInterval,eG8):$R0,typeof X.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(X.waitUntilDebounceMs,0);if(typeof X.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(X.waitUntilMaxWaitMs,0);if(X.personalApiKey){if(X.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(X.enableLocalEvaluation!==!1)this.featureFlagsPoller=new jM1({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:X.personalApiKey,projectApiKey:G,timeout:X.requestTimeout??1e4,host:this.host,fetch:X.fetch,onError:(Y)=>{this._events.emit("error",Y)},onLoad:(Y)=>{this._events.emit("localEvaluationFlagsLoaded",Y)},customHeaders:this.getCustomHeaders(),cacheProvider:X.flagDefinitionCacheProvider,strictLocalEvaluation:X.strictLocalEvaluation})}this.errorTracking=new $Y(this,X,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=X.maxCacheSize||$X8}enqueue($,Z,G){super.enqueue($,Z,G),this.scheduleDebouncedFlush()}async flush(){let $=super.flush(),Z=this.options.waitUntil;if(Z&&!this._waitUntilCycle)try{Z($.catch(()=>{}))}catch{}return $}scheduleDebouncedFlush(){let $=this.options.waitUntil;if(!$)return;if(this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let Y,J=new Promise((W)=>{Y=W});try{$(J)}catch{return}this._waitUntilCycle={resolve:Y,startedAt:Date.now(),timer:void 0}}let Z=Date.now()-this._waitUntilCycle.startedAt,G=this.options.waitUntilMaxWaitMs??GX8,X=Z>=G;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(X)return void this.resolveWaitUntilFlush();let Q=this.options.waitUntilDebounceMs??ZX8;this._waitUntilCycle.timer=dK(()=>{this.resolveWaitUntilFlush()},Q)}_consumeWaitUntilCycle(){let $=this._waitUntilCycle;if($)clearTimeout($.timer),this._waitUntilCycle=void 0;return $?.resolve}async resolveWaitUntilFlush(){let $=this._consumeWaitUntilCycle();try{await super.flush()}catch{}finally{$?.()}}getPersistedProperty($){return this._memoryStorage.getProperty($)}setPersistedProperty($,Z){return this._memoryStorage.setProperty($,Z)}fetch($,Z){return this.options.fetch?this.options.fetch($,Z):fetch($,Z)}getLibraryVersion(){return lA0}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug($=!0){super.debug($),this.featureFlagsPoller?.debug($)}capture($){if(typeof $=="string")this._logger.warn("Called capture() with a string as the first argument when an object was expected.");if($.event==="$exception"&&!$._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($).then(({distinctId:Z,event:G,properties:X,options:Q})=>super.captureStateless(Z,G,X,{timestamp:Q.timestamp,disableGeoip:Q.disableGeoip,uuid:Q.uuid})).catch((Z)=>{if(Z)console.error(Z)}))}async captureImmediate($){if(typeof $=="string")this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected.");if($.event==="$exception"&&!$._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($).then(({distinctId:Z,event:G,properties:X,options:Q})=>super.captureStatelessImmediate(Z,G,X,{timestamp:Q.timestamp,disableGeoip:Q.disableGeoip,uuid:Q.uuid})).catch((Z)=>{if(Z)console.error(Z)}))}identify({distinctId:$,properties:Z={},disableGeoip:G}){let{$set:X,$set_once:Q,$anon_distinct_id:Y,...J}=Z,U={$set:X||J,$set_once:Q||{},$anon_distinct_id:Y??void 0};super.identifyStateless($,U,{disableGeoip:G})}async identifyImmediate({distinctId:$,properties:Z={},disableGeoip:G}){let{$set:X,$set_once:Q,$anon_distinct_id:Y,...J}=Z,U={$set:X||J,$set_once:Q||{},$anon_distinct_id:Y??void 0};super.identifyStatelessImmediate($,U,{disableGeoip:G})}alias($){super.aliasStateless($.alias,$.distinctId,void 0,{disableGeoip:$.disableGeoip})}async aliasImmediate($){await super.aliasStatelessImmediate($.alias,$.distinctId,void 0,{disableGeoip:$.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady($=$R0){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((Z)=>{let G=setTimeout(()=>{X(),Z(!1)},$),X=this._events.on("localEvaluationFlagsLoaded",(Q)=>{clearTimeout(G),X(),Z(Q>0)})})}_resolveDistinctId($,Z){if(typeof $=="string")return{distinctId:$,options:Z};return{distinctId:this.context?.get()?.distinctId,options:$}}async _getFeatureFlagResult($,Z,G={},X){let Q=G.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&$ in this._flagOverrides){let A=this._flagOverrides[$];if(A===void 0)return;let q=this._payloadOverrides?.[$];return{key:$,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:q}}let{groups:Y,disableGeoip:J}=G,{onlyEvaluateLocally:W,personProperties:K,groupProperties:U}=G,F=this.addLocalPersonAndGroupProperties(Z,Y,K,U);K=F.allPersonProperties,U=F.allGroupProperties;let H=this.createFeatureFlagEvaluationContext(Z,Y,K,U);if(W==null)W=this.options.strictLocalEvaluation??!1;let N,O=!1,B,L,w,z,j,P;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let A=this.featureFlagsPoller?.featureFlagsByKey[$];if(A)try{let q=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(A,H,{matchValue:X});if(q){O=!0;let S=q.value;z=A.id,P="Evaluated locally",N={key:$,enabled:S!==!1,variant:typeof S=="string"?S:void 0,payload:q.payload??void 0}}}catch(q){if(q instanceof v3||q instanceof g4)this._logger?.info(`${q.name} when computing flag locally: ${$}: ${q.message}`);else throw q}}if(!O&&!W){let A=await super.getFeatureFlagDetailsStateless(H.distinctId,H.groups,H.personProperties,H.groupProperties,J,[$]);if(A===void 0)w=Ph.UNKNOWN_ERROR;else{B=A.requestId,L=A.evaluatedAt;let q=[];if(A.errorsWhileComputingFlags)q.push(Ph.ERRORS_WHILE_COMPUTING);if(A.quotaLimited?.includes("feature_flags"))q.push(Ph.QUOTA_LIMITED);let S=A.flags[$];if(S===void 0)q.push(Ph.FLAG_MISSING);else{z=S.metadata?.id,j=S.metadata?.version,P=S.reason?.description??S.reason?.code;let k;if(S.metadata?.payload!==void 0)try{k=JSON.parse(S.metadata.payload)}catch{k=S.metadata.payload}N={key:$,enabled:S.enabled,variant:S.variant,payload:k}}if(q.length>0)w=q.join(",")}}if(Q){let A=N===void 0?void 0:N.enabled===!1?!1:N.variant??!0,q=`${$}_${A}`;if(!(Z in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[Z].includes(q)){if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(Array.isArray(this.distinctIdHasSentFlagCalls[Z]))this.distinctIdHasSentFlagCalls[Z].push(q);else this.distinctIdHasSentFlagCalls[Z]=[q];let S={$feature_flag:$,$feature_flag_response:A,$feature_flag_id:z,$feature_flag_version:j,$feature_flag_reason:P,locally_evaluated:O,[`$feature/${$}`]:A,$feature_flag_request_id:B,$feature_flag_evaluated_at:O?Date.now():L};if(O&&this.featureFlagsPoller){let k=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(k!==void 0)S.$feature_flag_definitions_loaded_at=k}if(w)S.$feature_flag_error=w;this.capture({distinctId:Z,event:"$feature_flag_called",properties:S,groups:Y,disableGeoip:J})}}if(N!==void 0&&this._payloadOverrides!==void 0&&$ in this._payloadOverrides)N={...N,payload:this._payloadOverrides[$]};return N}async getFeatureFlag($,Z,G){let X=await this._getFeatureFlagResult($,Z,{...G,sendFeatureFlagEvents:G?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(X===void 0)return;if(X.enabled===!1)return!1;return X.variant??!0}async getFeatureFlagPayload($,Z,G,X){if(this._payloadOverrides!==void 0&&$ in this._payloadOverrides)return this._payloadOverrides[$];let Q=await this._getFeatureFlagResult($,Z,{...X,sendFeatureFlagEvents:!1},G);if(Q===void 0)return;return Q.payload??null}async getFeatureFlagResult($,Z,G){let{distinctId:X,options:Q}=this._resolveDistinctId(Z,G);if(!X)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult($,X,{...Q,sendFeatureFlagEvents:Q?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload($){if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let Z=await this._requestRemoteConfigPayload($);if(!Z)return;let G=await Z.json();if(typeof G=="string")try{return JSON.parse(G)}catch(X){}return G}async isFeatureEnabled($,Z,G){let X=await this.getFeatureFlag($,Z,G);if(X===void 0)return;return!!X||!1}async getAllFlags($,Z){let{distinctId:G,options:X}=this._resolveDistinctId($,Z);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,X)).featureFlags||{}}async getAllFlagsAndPayloads($,Z){let{distinctId:G,options:X}=this._resolveDistinctId($,Z);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:Q,disableGeoip:Y,flagKeys:J}=X||{},{onlyEvaluateLocally:W,personProperties:K,groupProperties:U}=X||{},F=this.addLocalPersonAndGroupProperties(G,Q,K,U);K=F.allPersonProperties,U=F.allGroupProperties;let H=this.createFeatureFlagEvaluationContext(G,Q,K,U);if(W==null)W=this.options.strictLocalEvaluation??!1;let N=await this.featureFlagsPoller?.getAllFlagsAndPayloads(H,J),O={},B={},L=!0;if(N)O=N.response,B=N.payloads,L=N.fallbackToFlags;if(L&&!W){let w=await super.getFeatureFlagsAndPayloadsStateless(H.distinctId,H.groups,H.personProperties,H.groupProperties,Y,J);O={...O,...w.flags||{}},B={...B,...w.payloads||{}}}if(this._flagOverrides!==void 0)O={...O,...this._flagOverrides};if(this._payloadOverrides!==void 0)B={...B,...this._payloadOverrides};return{featureFlags:O,featureFlagPayloads:B}}groupIdentify({groupType:$,groupKey:Z,properties:G,distinctId:X,disableGeoip:Q}){super.groupIdentifyStateless($,Z,G,{disableGeoip:Q},X)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags($){let Z=(G)=>Object.fromEntries(G.map((X)=>[X,!0]));if($===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray($)){this._flagOverrides=Z($);return}if(this._isFeatureFlagOverrideOptions($)){if("flags"in $){if($.flags===!1)this._flagOverrides=void 0;else if(Array.isArray($.flags))this._flagOverrides=Z($.flags);else if($.flags!==void 0)this._flagOverrides={...$.flags}}if("payloads"in $){if($.payloads===!1)this._payloadOverrides=void 0;else if($.payloads!==void 0)this._payloadOverrides={...$.payloads}}return}this._flagOverrides={...$}}_isFeatureFlagOverrideOptions($){if(typeof $!="object"||$===null||Array.isArray($))return!1;let Z=$;if("flags"in Z){let G=Z.flags;if(G===!1||Array.isArray(G)||typeof G=="object"&&G!==null)return!0}if("payloads"in Z){let G=Z.payloads;if(G===!1||typeof G=="object"&&G!==null)return!0}return!1}withContext($,Z,G){if(!this.context)return Z();return this.context.run($,Z,G)}getContext(){return this.context?.get()}enterContext($,Z){this.context?.enter($,Z)}async _shutdown($){let Z=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller($),this.errorTracking.shutdown();try{return await super._shutdown($)}finally{Z?.()}}async _requestRemoteConfigPayload($){if(!this.options.personalApiKey)return;let Z=`${this.host}/api/projects/@current/feature_flags/${$}/remote_config?token=${encodeURIComponent(this.apiKey)}`,G={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},X=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let Q=new AbortController;X=dK(()=>{Q.abort()},this.options.requestTimeout),G.signal=Q.signal}try{return await this.fetch(Z,G)}catch(Q){this._events.emit("error",Q);return}finally{if(X)clearTimeout(X)}}extractPropertiesFromEvent($,Z){if(!$)return{personProperties:{},groupProperties:{}};let G={},X={};for(let[Q,Y]of Object.entries($))if(OP0(Y)&&Z&&Q in Z){let J={};for(let[W,K]of Object.entries(Y))J[String(W)]=String(K);X[String(Q)]=J}else G[String(Q)]=String(Y);return{personProperties:G,groupProperties:X}}async getFeatureFlagsForEvent($,Z,G,X){let Q=X?.personProperties||{},Y=X?.groupProperties||{},J=X?.flagKeys;if(X?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let K={};for(let[U,F]of Object.entries(Z||{}))K[U]=String(F);return await this.getAllFlags($,{groups:K,personProperties:Q,groupProperties:Y,disableGeoip:G,onlyEvaluateLocally:!0,flagKeys:J})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let K={};for(let[U,F]of Object.entries(Z||{}))K[U]=String(F);return await this.getAllFlags($,{groups:K,personProperties:Q,groupProperties:Y,disableGeoip:G,onlyEvaluateLocally:!0,flagKeys:J})}return(await super.getFeatureFlagsStateless($,Z,Q,Y,G)).flags}addLocalPersonAndGroupProperties($,Z,G,X){let Q={distinct_id:$,...G||{}},Y={};if(Z)for(let J of Object.keys(Z))Y[J]={$group_key:Z[J],...X?.[J]||{}};return{allPersonProperties:Q,allGroupProperties:Y}}createFeatureFlagEvaluationContext($,Z,G,X){return{distinctId:$,groups:Z||{},personProperties:G||{},groupProperties:X||{},evaluationCache:{}}}captureException($,Z,G,X){if(!$Y.isPreviouslyCapturedError($)){let Q=Error("PostHog syntheticException");this.addPendingPromise($Y.buildEventMessage($,{syntheticException:Q},Z,G).then((Y)=>this.capture({...Y,uuid:X})))}}async captureExceptionImmediate($,Z,G){if(!$Y.isPreviouslyCapturedError($)){let X=Error("PostHog syntheticException");return this.addPendingPromise($Y.buildEventMessage($,{syntheticException:X},Z,G).then((Q)=>this.captureImmediate(Q)))}}async prepareEventMessage($){let{distinctId:Z,event:G,properties:X,groups:Q,sendFeatureFlags:Y,timestamp:J,disableGeoip:W,uuid:K}=$,U=this.context?.get(),F=Z||U?.distinctId,H={...this.props,...U?.properties||{},...X||{}};if(!F)F=RH(),H.$process_person_profile=!1;if(U?.sessionId&&!H.$session_id)H.$session_id=U.sessionId;let N=this._runBeforeSend({distinctId:F,event:G,properties:H,groups:Q,sendFeatureFlags:Y,timestamp:J,disableGeoip:W,uuid:K});if(!N)return Promise.reject(null);let O=await Promise.resolve().then(async()=>{if(Y){let B=typeof Y=="object"?Y:void 0;return await this.getFeatureFlagsForEvent(N.distinctId,Q,W,B)}return N.event,{}}).then((B)=>{let L={};if(B)for(let[z,j]of Object.entries(B))L[`$feature/${z}`]=j;let w=Object.keys(B||{}).filter((z)=>B?.[z]!==!1).sort();if(w.length>0)L.$active_feature_flags=w;return L}).catch(()=>({})).then((B)=>{return{...B,...N.properties||{},$groups:N.groups||Q}});if(N.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof O.$raw_user_agent=="string"){if(KP0(O.$raw_user_agent,this.options.custom_blocked_useragents||[]))N.event="$bot_pageview",O.$browser_type="bot"}return{distinctId:N.distinctId,event:N.event,properties:O,options:{timestamp:N.timestamp,disableGeoip:N.disableGeoip,uuid:N.uuid}}}_runBeforeSend($){let Z=this.options.before_send;if(!Z)return $;let G=Array.isArray(Z)?Z:[Z],X=$;for(let Q of G){if(X=Q(X),!X)return this._logger.info(`Event '${$.event}' was rejected in beforeSend function`),null;if(!X.properties||Object.keys(X.properties).length===0){let Y=`Event '${X.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(Y)}}return X}}});import{AsyncLocalStorage as WX8}from"async_hooks";class RM1{constructor(){this.storage=new WX8}get(){return this.storage.getStore()}run($,Z,G){return this.storage.run(this.resolve($,G),Z)}enter($,Z){this.storage.enterWith(this.resolve($,Z))}resolve($,Z){if(Z?.fresh===!0)return $;let G=this.get()||{};return{distinctId:$.distinctId??G.distinctId,sessionId:$.sessionId??G.sessionId,properties:{...G.properties||{},...$.properties||{}}}}}var GR0=()=>{};function KX8($,{organization:Z,projectId:G,prefix:X,severityAllowList:Q=["error"],sendExceptionsToPostHog:Y=!0}={}){return(J)=>{if(!(Q==="*"||Q.includes(J.level)))return J;if(!J.tags)J.tags={};let K=J.tags[XR0.POSTHOG_ID_TAG];if(K===void 0)return J;let U=$.options.host??"https://us.i.posthog.com",F=new URL(`/project/${$.apiKey}/person/${K}`,U).toString();J.tags["PostHog Person URL"]=F;let H=J.exception?.values||[],N=H.map((B)=>({...B,stacktrace:B.stacktrace?{...B.stacktrace,type:"raw",frames:(B.stacktrace.frames||[]).map((L)=>({...L,platform:"node:javascript"}))}:void 0})),O={$exception_message:H[0]?.value||J.message,$exception_type:H[0]?.type,$exception_level:J.level,$exception_list:N,$sentry_event_id:J.event_id,$sentry_exception:J.exception,$sentry_exception_message:H[0]?.value||J.message,$sentry_exception_type:H[0]?.type,$sentry_tags:J.tags};if(Z&&G)O.$sentry_url=(X||"https://sentry.io/organizations/")+Z+"/issues/?project="+G+"&query="+J.event_id;if(Y)$.capture({event:"$exception",distinctId:K,properties:O});return J}}var XR0;var QR0=D(()=>{XR0=class XR0{static#$=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor($,Z,G,X,Q){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(Y,J){let W=J()?.getClient()?.getDsn()?.projectId;Y(KX8($,{organization:Z,projectId:W,prefix:G,severityAllowList:X,sendExceptionsToPostHog:Q??!0}))}}}});var YR0=D(()=>{vs()});var JR0=D(()=>{gB();QR0();YR0();zM1()});var IM1;var WR0=D(()=>{QP0();xA0();gA0();vs();ZR0();gB();GR0();JR0();$Y.errorPropertiesBuilder=new aG.ErrorPropertiesBuilder([new aG.EventCoercer,new aG.ErrorCoercer,new aG.ObjectCoercer,new aG.StringCoercer,new aG.PrimitiveCoercer],aG.createStackParser("node:javascript",aG.nodeStackLineParser),[XP0(),bA0,yA0()]);IM1=class IM1 extends AM1{getLibraryId(){return"posthog-node"}initializeContext(){return new RM1}}});function UX8(){return{capture:()=>{},identify:()=>{},captureException:()=>{},groupIdentify:()=>{},shutdown:async()=>{}}}var TM1,KR0,z$;var H5=D(()=>{WR0();TM1=process.env.POSTHOG_KEY,KR0=process.env.POSTHOG_HOST;z$=TM1?new IM1(TM1,{...KR0?{host:KR0}:{},enableExceptionAutocapture:!0,flushAt:1,flushInterval:0}):UX8();if(TM1){let $=()=>{z$.shutdown().catch(()=>{})};process.on("SIGTERM",$),process.on("SIGINT",$)}});import{Kysely as FX8,PostgresDialect as HR0}from"kysely";import{Pool as NR0}from"pg";function BX8($){let Z=$.connect.bind($);return $.connect=(G)=>{if(typeof G==="function")return Z(G);let X=performance.now(),Q=fs(),Y=$.idleCount===0&&$.totalCount>=Q,J=$.idleCount;return Z().then((W)=>{let K=performance.now()-X;if(UR0().record(K,{"db.pool.outcome":Y?"contended":"available"}),K>NX8)if(Y)console.error("Slow pool acquire \u2014 pool saturated:",{waitMs:K,total:$.totalCount,idle:$.idleCount,waiting:$.waitingCount,max:Q});else console.warn("Slow pool acquire \u2014 event-loop lag (not pool):",{waitMs:K,idleAtStart:J,total:$.totalCount,max:Q});return W},(W)=>{throw UR0().record(performance.now()-X,{"db.pool.outcome":"error"}),W})},$}function BR0(){try{return q0().databasePgSsl}catch{return!1}}function fs(){try{return q0().databasePoolMax}catch{return 10}}function DX8($){let Z=BX8(new NR0({connectionString:$,max:fs(),ssl:BR0(),...OR0})),G=new HR0({pool:Z});return{type:"postgres",db:new FX8({dialect:G,log:OX8(Z)}),pool:Z}}function Rh(){return q0().databaseUrl}function DR0($){let Z=$||Rh();return new HR0({pool:new NR0({connectionString:Z,max:fs(),ssl:BR0(),...OR0})})}function LX8($){let Z=$||Rh();return DX8(Z)}async function LR0($){if(await $.db.destroy(),!$.pool.ended)await $.pool.end();if($===Ah)Ah=null}function n6(){if(!Ah)Ah=LX8(Rh());return Ah}var HX8=()=>V5.createHistogram("db.query.duration",{description:"Database query execution duration in milliseconds",unit:"ms"}),UR0=()=>V5.createHistogram("db.pool.acquire.duration",{description:"Time spent waiting to acquire a connection from the pool",unit:"ms"}),FR0=400,NX8=100,OX8=($)=>(Z)=>{let G={"db.statement":Z.query.sql,"db.status":Z.level==="error"?"error":"success"};if(Z.queryDurationMillis>FR0){let X=jo1(),Q=X>FR0/2;console.error(Q?"Slow query measurement \u2014 likely event-loop lag, not slow SQL:":"Slow query detected:",{durationMs:Z.queryDurationMillis,eventLoopLagMs:Math.round(X),sql:Z.query.sql,pool:{total:$.totalCount,idle:$.idleCount,waiting:$.waitingCount,max:fs()}})}if(HX8().record(Z.queryDurationMillis,G),Z.level==="error")console.error("Query failed:",{durationMs:Z.queryDurationMillis,error:Z.error,sql:Z.query.sql})},OR0,Ah=null;var f3=D(()=>{M4();s9();NB1();OR0={keepAlive:!0,keepAliveInitialDelayMillis:1e4,idleTimeoutMillis:300000,connectionTimeoutMillis:30000,allowExitOnIdle:!0}});class qM1{apiKey;constructor($){this.apiKey=$}async sendEmail({to:$,from:Z,subject:G,html:X}){let Q=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:$,from:Z,subject:G,html:X})});if(!Q.ok)throw Error(`Failed to send email: ${Q.statusText}`)}}class MM1{apiKey;constructor($){this.apiKey=$}async sendEmail({to:$,from:Z,subject:G,html:X}){let Q=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:$}]}],from:{email:Z},subject:G,content:[{type:"text/html",value:X}]})});if(!Q.ok){let Y=await Q.text();throw Error(`Failed to send email via SendGrid: ${Q.statusText} - ${Y}`)}}}function hB($){let Z=zX8[$.provider];if(!Z)throw Error(`Unknown email provider: ${$.provider}`);return Z($)}function uB($,Z){return $.find((G)=>G.id===Z)}var EX8=($)=>{let Z=new qM1($.config.apiKey);return async({to:G,subject:X,html:Q})=>{await Z.sendEmail({to:G,from:$.config.fromEmail,subject:X,html:Q})}},wX8=($)=>{let Z=new MM1($.config.apiKey);return async({to:G,subject:X,html:Q})=>{await Z.sendEmail({to:G,from:$.config.fromEmail,subject:X,html:Q})}},zX8;var xs=D(()=>{zX8={resend:EX8,sendgrid:wX8}});function cB({preheader:$="",heading:Z,subheading:G,body:X,footnote:Q}){return`<!DOCTYPE html>
85
+ `);for(let J=X;J<Y.length;J++){let W=Y[J];if(W.length>1024)continue;let K=$A0.test(W)?W.replace($A0,"$1"):W;if(!K.match(/\S*Error: /)){for(let U of Z){let F=U(K,$);if(F){Q.push(F);break}}if(Q.length>=ZA0)break}}return GA0(Q)}}var $A0,ZA0=50;var QA0=D(()=>{IH();mP0();iP0();pP0();rP0();eP0();$A0=/\(error: (.*)\)/});class YA0{match($){return this.isDOMException($)||this.isDOMError($)}coerce($,Z){let G=AH($.stack);return{type:this.getType($),value:this.getValue($),stack:G?$.stack:void 0,cause:$.cause?Z.next($.cause):void 0,synthetic:!1}}getType($){return this.isDOMError($)?"DOMError":"DOMException"}getValue($){let Z=$.name||(this.isDOMError($)?"DOMError":"DOMException");return $.message?`${Z}: ${$.message}`:Z}isDOMException($){return xB($,"DOMException")}isDOMError($){return xB($,"DOMError")}}var JA0=D(()=>{EG()});class WA0{match($){return eq1($)}coerce($,Z){return{type:this.getType($),value:this.getMessage($,Z),stack:this.getStack($),cause:$.cause?Z.next($.cause):void 0,synthetic:!1}}getType($){return $.name||$.constructor.name}getMessage($,Z){let G=$.message;if(G.error&&typeof G.error.message=="string")return String(G.error.message);return String(G)}getStack($){return $.stacktrace||$.stack||void 0}}var KA0=D(()=>{EG()});class UA0{constructor(){}match($){return NP0($)&&$.error!=null}coerce($,Z){let G=Z.apply($.error);if(!G)return{type:"ErrorEvent",value:$.message,stack:Z.syntheticException?.stack,synthetic:!0};return G}}var FA0=D(()=>{EG()});class HA0{match($){return typeof $=="string"}coerce($,Z){let[G,X]=this.getInfos($);return{type:G??"Error",value:X??$,stack:Z.syntheticException?.stack,synthetic:!0}}getInfos($){let Z="Error",G=$,X=$.match(PG8);if(X)Z=X[1],G=X[2];return[Z,G]}}var PG8;var NA0=D(()=>{PG8=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i});var OA0;var BA0=D(()=>{OA0=["fatal","error","warning","log","info","debug"]});function Cs($,Z=40){let G=Object.keys($);if(G.sort(),!G.length)return"[object has no keys]";for(let X=G.length;X>0;X--){let Q=G.slice(0,X).join(", ");if(!(Q.length>Z)){if(X===G.length)return Q;return Q.length<=Z?Q:`${Q.slice(0,Z)}...`}}return""}var LM1=()=>{};class DA0{match($){return typeof $=="object"&&$!==null}coerce($,Z){let G=this.getErrorPropertyFromObject($);if(G)return Z.apply(G);return{type:this.getType($),value:this.getValue($),stack:Z.syntheticException?.stack,level:this.isSeverityLevel($.level)?$.level:"error",synthetic:!0}}getType($){return dC($)?$.constructor.name:"Error"}getValue($){if("name"in $&&typeof $.name=="string"){let X=`'${$.name}' captured as exception`;if("message"in $&&typeof $.message=="string")X+=` with message: '${$.message}'`;return X}if("message"in $&&typeof $.message=="string")return $.message;let Z=this.getObjectClassName($),G=Cs($);return`${Z&&Z!=="Object"?`'${Z}'`:"Object"} captured as exception with keys: ${G}`}isSeverityLevel($){return AH($)&&!HP0($)&&OA0.indexOf($)>=0}getErrorPropertyFromObject($){for(let Z in $)if(Object.prototype.hasOwnProperty.call($,Z)){let G=$[Z];if(CP0(G))return G}}getObjectClassName($){try{let Z=Object.getPrototypeOf($);return Z?Z.constructor.name:void 0}catch(Z){return}}}var LA0=D(()=>{EG();BA0();LM1()});class EA0{match($){return dC($)}coerce($,Z){let G=$.constructor.name;return{type:G,value:`${G} captured as exception with keys: ${Cs($)}`,stack:Z.syntheticException?.stack,synthetic:!0}}}var wA0=D(()=>{EG();LM1()});class zA0{match($){return Ps($)}coerce($,Z){return{type:"Error",value:`Primitive value captured as exception: ${String($)}`,stack:Z.syntheticException?.stack,synthetic:!0}}}var jA0=D(()=>{EG()});class PA0{match($){return xB($,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection($)}isCustomEventWrappingRejection($){if(!dC($))return!1;try{let Z=$.detail;return Z!=null&&typeof Z=="object"&&"reason"in Z}catch{return!1}}coerce($,Z){let G=this.getUnhandledRejectionReason($);if(Ps(G))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(G)}`,stack:Z.syntheticException?.stack,synthetic:!0};return Z.apply(G)}getUnhandledRejectionReason($){try{if("reason"in $)return $.reason;if("detail"in $&&$.detail!=null&&typeof $.detail=="object"&&"reason"in $.detail)return $.detail.reason}catch{}return $}}var AA0=D(()=>{EG()});var RA0=D(()=>{JA0();KA0();FA0();NA0();LA0();wA0();jA0();AA0()});class IA0{constructor($){this._maxSize=$,this._cache=new Map}get($){let Z=this._cache.get($);if(Z===void 0)return;return this._cache.delete($),this._cache.set($,Z),Z}set($,Z){this._cache.set($,Z)}reduce(){while(this._cache.size>=this._maxSize){let $=this._cache.keys().next().value;if($)this._cache.delete($)}}}var TA0=()=>{};function EM1($){if(!$)return{..._s};return{enabled:$.enabled??_s.enabled,max_bytes:IG8($.max_bytes,_s.max_bytes)}}function RG8($){if(!$)return{sanitizedProperties:{},droppedKeys:[]};let Z=[];return{sanitizedProperties:Object.keys($).reduce((X,Q)=>{if(AG8.has(Q))return Z.push(Q),X;return X[Q]=$[Q],X},{}),droppedKeys:Z}}class qA0{constructor($){this._entries=[],this._totalBytes=0,this._config=EM1($)}setConfig($){this._config=EM1($),this._trimToMaxBytes()}add($){let Z=TG8($);if(!Z)return;let G=MA0(Z.json);if(G>this._config.max_bytes)return;this._entries.push({step:Z.step,bytes:G}),this._totalBytes+=G,this._trimToMaxBytes()}getAttachable(){return this._entries.map(($)=>$.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 $=this._entries.shift();if($)this._totalBytes-=$.bytes}}}function IG8($,Z){if(!Bh($)||$===1/0||$===-1/0)return Z;let G=Math.floor($);if(G<0)return Z;return G}function TG8($){let Z=qG8($);if(!Z)return;try{let G=JSON.parse(Z);if(!Oh(G))return;let X=G,Q=X[jh.MESSAGE],Y=X[jh.TIMESTAMP];if(!AH(Q)||Q.trim().length===0)return;if(!AH(Y)&&!Bh(Y))return;return{step:X,json:Z}}catch{return}}function qG8($){let Z=new WeakSet;try{return JSON.stringify($,(G,X)=>{if(typeof X=="bigint")return X.toString();if(typeof X=="function"||typeof X=="symbol")return;if(X instanceof Date)return X.toISOString();if(X instanceof Error)return{name:X.name,message:X.message,stack:X.stack};if(X&&typeof X=="object"){if(Z.has(X))return"[Circular]";Z.add(X)}return X})}catch{return}}function MA0($){if(typeof TextEncoder<"u")return new TextEncoder().encode($).length;let Z=encodeURIComponent($),G=0;for(let X=0;X<Z.length;X++)if(Z[X]==="%")G+=1,X+=2;else G+=1;return G}var jh,AG8,_s;var kA0=D(()=>{EG();jh={MESSAGE:"$message",TIMESTAMP:"$timestamp"},AG8=new Set([jh.MESSAGE,jh.TIMESTAMP]),_s={enabled:!0,max_bytes:32768}});var aG={};p4(aG,{winjsStackLineParser:()=>nP0,stripReservedExceptionStepFields:()=>RG8,reverseAndStripFrames:()=>GA0,resolveExceptionStepsConfig:()=>EM1,opera11StackLineParser:()=>oP0,opera10StackLineParser:()=>tP0,nodeStackLineParser:()=>sP0,getUtf8ByteLength:()=>MA0,geckoStackLineParser:()=>DM1,createStackParser:()=>XA0,createDefaultStackParser:()=>jG8,chromeStackLineParser:()=>BM1,StringCoercer:()=>HA0,ReduceableCache:()=>IA0,PromiseRejectionEventCoercer:()=>PA0,PrimitiveCoercer:()=>zA0,ObjectCoercer:()=>DA0,ExceptionStepsBuffer:()=>qA0,EventCoercer:()=>EA0,ErrorPropertiesBuilder:()=>lP0,ErrorEventCoercer:()=>UA0,ErrorCoercer:()=>WA0,EXCEPTION_STEP_INTERNAL_FIELDS:()=>jh,DOMExceptionCoercer:()=>YA0,DEFAULT_EXCEPTION_STEPS_CONFIG:()=>_s});var VA0=D(()=>{dP0();QA0();RA0();TA0();kA0()});var gB=D(()=>{Es();aq1();UM1();_P0();Eh();bP0();VA0();EG();yP0();NM1();gP0();fB()});import{createReadStream as MG8}from"fs";import{createInterface as kG8}from"readline";async function bA0($){let Z={};for(let Q=$.length-1;Q>=0;Q--){let Y=$[Q],J=Y?.filename;if(!Y||typeof J!="string"||typeof Y.lineno!="number"||vG8(J)||fG8(Y))continue;if(!Z[J])Z[J]=[];Z[J].push(Y.lineno)}let G=Object.keys(Z);if(G.length==0)return $;let X=[];for(let Q of G){if(_A0.get(Q))continue;let Y=Z[Q];if(!Y)continue;Y.sort((K,U)=>K-U);let J=yG8(Y);if(J.every((K)=>xG8(Q,K)))continue;let W=gG8(bs,Q,{});X.push(CG8(Q,J,W))}if(await Promise.all(X).catch(()=>{}),$&&$.length>0)_G8($,bs);return bs.reduce(),$}function CG8($,Z,G){return new Promise((X)=>{let Q=MG8($),Y=kG8({input:Q});function J(){Q.destroy(),X()}let W=0,K=0,U=Z[K];if(U===void 0)return void J();let F=U[0],H=U[1];function N(){_A0.set($,1),Y.close(),Y.removeAllListeners(),J()}Q.on("error",N),Y.on("error",N),Y.on("close",J),Y.on("line",(O)=>{if(W++,W<F)return;if(G[W]=hG8(O,0),W>=H){if(K===Z.length-1){Y.close(),Y.removeAllListeners();return}K++;let B=Z[K];if(B===void 0){Y.close(),Y.removeAllListeners();return}F=B[0],H=B[1]}})})}function _G8($,Z){for(let G of $)if(G.filename&&G.context_line===void 0&&typeof G.lineno=="number"){let X=Z.get(G.filename);if(X===void 0)continue;bG8(G.lineno,G,X)}}function bG8($,Z,G){if(Z.lineno===void 0||G===void 0)return;Z.pre_context=[];for(let Q=vA0($);Q<$;Q++){let Y=G[Q];if(Y===void 0)return void SA0(Z);Z.pre_context.push(Y)}if(G[$]===void 0)return void SA0(Z);Z.context_line=G[$];let X=fA0($);Z.post_context=[];for(let Q=$+1;Q<=X;Q++){let Y=G[Q];if(Y===void 0)break;Z.post_context.push(Y)}}function SA0($){delete $.pre_context,delete $.context_line,delete $.post_context}function vG8($){return $.startsWith("node:")||$.endsWith(".min.js")||$.endsWith(".min.cjs")||$.endsWith(".min.mjs")||$.startsWith("data:")}function fG8($){if($.lineno!==void 0&&$.lineno>SG8)return!0;if($.colno!==void 0&&$.colno>VG8)return!0;return!1}function xG8($,Z){let G=bs.get($);if(G===void 0)return!1;for(let X=Z[0];X<=Z[1];X++)if(G[X]===void 0)return!1;return!0}function yG8($){if(!$.length)return[];let Z=0,G=$[0];if(typeof G!="number")return[];let X=CA0(G),Q=[];while(!0){if(Z===$.length-1){Q.push(X);break}let Y=$[Z+1];if(typeof Y!="number")break;if(Y<=X[1])X[1]=Y+wM1;else Q.push(X),X=CA0(Y);Z++}return Q}function CA0($){return[vA0($),fA0($)]}function vA0($){return Math.max(1,$-wM1)}function fA0($){return $+wM1}function gG8($,Z,G){let X=$.get(Z);if(X===void 0)return $.set(Z,G),G;return X}function hG8($,Z){let G=$,X=G.length;if(X<=150)return G;if(Z>X)Z=X;let Q=Math.max(Z-60,0);if(Q<5)Q=0;let Y=Math.min(Q+140,X);if(Y>X-5)Y=X;if(Y===X)Q=Math.max(Y-140,0);if(G=G.slice(Q,Y),Q>0)G=`...${G}`;if(Y<X)G+="...";return G}var bs,_A0,wM1=7,VG8=1000,SG8=1e4;var xA0=D(()=>{gB();bs=new aG.ReduceableCache(25),_A0=new aG.ReduceableCache(20)});import{isAbsolute as uG8,relative as cG8,sep as lG8}from"path";function yA0($=process.cwd()){let Z=lG8==="\\",G=(Q)=>Z?Q.replace(/\\/g,"/"):Q,X=G($);return async(Q)=>{for(let Y of Q)if(!(!Y.filename||Y.filename.startsWith("node:")||Y.filename.startsWith("data:"))){if(uG8(Y.filename))Y.filename=G(cG8(X,G(Y.filename)))}return Q}}var gA0=()=>{};function dG8($,Z){let G=!1;return Object.assign((X)=>{let Y=global.process.listeners("uncaughtException").filter((J)=>J.name!=="domainUncaughtExceptionClear"&&J._posthogErrorHandler!==!0).length===0;if($(X,{mechanism:{type:"onuncaughtexception",handled:!1}}),!G&&Y)G=!0,Z(X)},{_posthogErrorHandler:!0})}function hA0($,Z){globalThis.process?.on("uncaughtException",dG8($,Z))}function uA0($){globalThis.process?.on("unhandledRejection",(Z)=>$(Z,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var cA0=()=>{};class $Y{constructor($,Z,G){this.client=$,this._exceptionAutocaptureEnabled=Z.enableExceptionAutocapture||!1,this._logger=G,this._rateLimiter=new ZM1({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError($){return Oh($)&&"__posthog_previously_captured_error"in $&&$.__posthog_previously_captured_error===!0}static async buildEventMessage($,Z,G,X){let Q={...X},Y=this.errorPropertiesBuilder.buildFromUnknown($,Z);return Y.$exception_list=await this.errorPropertiesBuilder.modifyFrames(Y.$exception_list),{event:"$exception",distinctId:G,properties:{...Y,...Q},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())hA0(this.onException.bind(this),this.onFatalError.bind(this)),uA0(this.onException.bind(this))}onException($,Z){this.client.addPendingPromise((async()=>{if(!$Y.isPreviouslyCapturedError($)){let G=await $Y.buildEventMessage($,Z),Q=G.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(Q))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:Q});return this.client.capture(G)}})())}async onFatalError($){console.error($),await this.client.shutdown(mG8),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}var mG8=2000;var vs=D(()=>{cA0();gB()});var lA0="5.30.6";var dA0=()=>{};var Ph;var zM1=D(()=>{Ph={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"}});async function mA0($){let Z=globalThis.crypto?.subtle;if(!Z)throw Error("SubtleCrypto API not available");let G=await Z.digest("SHA-1",new TextEncoder().encode($));return Array.from(new Uint8Array(G)).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}var iA0=()=>{};class jM1{constructor({pollingInterval:$,personalApiKey:Z,projectApiKey:G,timeout:X,host:Q,customHeaders:Y,...J}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=$,this.personalApiKey=Z,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=X,this.projectApiKey=G,this.host=Q,this.poller=void 0,this.fetch=J.fetch||fetch,this.onError=J.onError,this.customHeaders=Y,this.onLoad=J.onLoad,this.cacheProvider=J.cacheProvider,this.strictLocalEvaluation=J.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug($=!0){this.debugMode=$}logMsgIfDebug($){if(this.debugMode)$()}createEvaluationContext($,Z={},G={},X={},Q={}){return{distinctId:$,groups:Z,personProperties:G,groupProperties:X,evaluationCache:Q}}async getFeatureFlag($,Z,G={},X={},Q={}){await this.loadFeatureFlags();let Y,J;if(!this.loadedSuccessfullyOnce)return Y;if(J=this.featureFlagsByKey[$],J!==void 0){let W=this.createEvaluationContext(Z,G,X,Q);try{Y=(await this.computeFlagAndPayloadLocally(J,W)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${$} -> ${Y}`))}catch(K){if(K instanceof v3||K instanceof g4)this.logMsgIfDebug(()=>console.debug(`${K.name} when computing flag locally: ${$}: ${K.message}`));else if(K instanceof Error)this.onError?.(Error(`Error computing flag locally: ${$}: ${K}`))}}return Y}async getAllFlagsAndPayloads($,Z){await this.loadFeatureFlags();let G={},X={},Q=this.featureFlags.length==0,Y=Z?Z.map((W)=>this.featureFlagsByKey[W]).filter(Boolean):this.featureFlags,J={...$,evaluationCache:$.evaluationCache??{}};return await Promise.all(Y.map(async(W)=>{try{let{value:K,payload:U}=await this.computeFlagAndPayloadLocally(W,J);if(G[W.key]=K,U)X[W.key]=U}catch(K){if(K instanceof v3||K instanceof g4)this.logMsgIfDebug(()=>console.debug(`${K.name} when computing flag locally: ${W.key}: ${K.message}`));else if(K instanceof Error)this.onError?.(Error(`Error computing flag locally: ${W.key}: ${K}`));Q=!0}})),{response:G,payloads:X,fallbackToFlags:Q}}async computeFlagAndPayloadLocally($,Z,G={}){let{matchValue:X,skipLoadCheck:Q=!1}=G;if(!Q)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let Y;Y=X!==void 0?X:await this.computeFlagValueLocally($,Z);let J=this.getFeatureFlagPayload($.key,Y);return{value:Y,payload:J}}async computeFlagValueLocally($,Z){let{distinctId:G,groups:X,personProperties:Q,groupProperties:Y}=Z;if($.ensure_experience_continuity)throw new g4("Flag has experience continuity enabled");if(!$.active)return!1;let W=($.filters||{}).aggregation_group_type_index;if(W!=null){let K=this.groupTypeMapping[String(W)];if(!K)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${W} for feature flag ${$.key}`)),new g4("Flag has unknown group type index");if(!(K in X))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${$.key} without group names passed in`)),!1;if($.bucketing_identifier==="device_id"&&(Q?.$device_id===void 0||Q?.$device_id===null||Q?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${$.key}`));let U=Y[K];return await this.matchFeatureFlagProperties($,X[K],U,Z)}{let K=this.getBucketingValueForFlag($,G,Q);if(K===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${$.key} without $device_id, falling back to server evaluation`)),new g4(`Can't compute feature flag: ${$.key} without $device_id`);return await this.matchFeatureFlagProperties($,K,Q,Z)}}getBucketingValueForFlag($,Z,G){if($.filters?.aggregation_group_type_index!=null)return Z;if($.bucketing_identifier==="device_id"){let X=G?.$device_id;if(X==null||X==="")return;return X}return Z}getFeatureFlagPayload($,Z){let G=null;if(Z!==!1&&Z!=null){if(typeof Z=="boolean")G=this.featureFlagsByKey?.[$]?.filters?.payloads?.[Z.toString()]||null;else if(typeof Z=="string")G=this.featureFlagsByKey?.[$]?.filters?.payloads?.[Z]||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($,Z,G){let{evaluationCache:X}=G,Q=$.key;if(!this.featureFlagsByKey)throw new g4("Feature flags not available for dependency evaluation");if(!("dependency_chain"in $))throw new g4(`Flag dependency property for '${Q}' is missing required 'dependency_chain' field`);let Y=$.dependency_chain;if(!Array.isArray(Y))throw new g4(`Flag dependency property for '${Q}' has an invalid 'dependency_chain' (expected array, got ${typeof Y})`);if(Y.length===0)throw new g4(`Circular dependency detected for flag '${Q}' (empty dependency chain)`);for(let W of Y){if(!(W in X)){let U=this.featureFlagsByKey[W];if(U)if(U.active)try{let F=await this.computeFlagValueLocally(U,G);X[W]=F}catch(F){throw new g4(`Error evaluating flag dependency '${W}' for flag '${Q}': ${F}`)}else X[W]=!1;else throw new g4(`Missing flag dependency '${W}' for flag '${Q}'`)}if(X[W]==null)throw new g4(`Dependency '${W}' could not be evaluated`)}let J=X[Q];return this.flagEvaluatesToExpectedValue($.value,J)}flagEvaluatesToExpectedValue($,Z){if(typeof $=="boolean")return $===Z||typeof Z=="string"&&Z!==""&&$===!0;if(typeof $=="string")return Z===$;return!1}async matchFeatureFlagProperties($,Z,G,X){let Q=$.filters||{},Y=Q.groups||[],J=!1,W;for(let K of Y)try{if(await this.isConditionMatch($,Z,K,G,X)){let U=K.variant,F=Q.multivariate?.variants||[];W=U&&F.some((H)=>H.key===U)?U:await this.getMatchingVariant($,Z)||!0;break}}catch(U){if(U instanceof v3)throw U;if(U instanceof g4)J=!0;else throw U}if(W!==void 0)return W;if(J)throw new g4("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch($,Z,G,X,Q){let Y=G.rollout_percentage,J=(W)=>{this.logMsgIfDebug(()=>console.warn(W))};if((G.properties||[]).length>0){for(let W of G.properties){let K=W.type,U=!1;if(U=K==="cohort"?rA0(W,X,this.cohorts,this.debugMode):K==="flag"?await this.evaluateFlagDependency(W,X,Q):oA0(W,X,J),!U)return!1}if(Y==null)return!0}if(Y!=null&&await nA0($.key,Z)>Y/100)return!1;return!0}async getMatchingVariant($,Z){let G=await nA0($.key,Z,"variant"),X=this.variantLookupTable($).find((Q)=>G>=Q.valueMin&&G<Q.valueMax);if(X)return X.key}variantLookupTable($){let Z=[],G=0,X=0;return(($.filters||{}).multivariate?.variants||[]).forEach((J)=>{X=G+J.rollout_percentage/100,Z.push({valueMin:G,valueMax:X,key:J.key}),G=X}),Z}updateFlagState($){this.featureFlags=$.flags,this.featureFlagsByKey=$.flags.reduce((Z,G)=>(Z[G.key]=G,Z),{}),this.groupTypeMapping=$.groupTypeMapping,this.cohorts=$.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags($){if(this.strictLocalEvaluation)return;let Z=$.filter((G)=>G.ensure_experience_continuity);if(Z.length>0)console.warn(`[PostHog] You are using local evaluation but ${Z.length} flag(s) have experience continuity enabled: ${Z.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($){if(!this.cacheProvider)return!1;try{let Z=await this.cacheProvider.getFlagDefinitions();if(Z)return this.updateFlagState(Z),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${$} (${Z.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(Z.flags),!0;return!1}catch(Z){return this.onError?.(Error(`Failed to load from cache: ${Z}`)),!1}}async loadFeatureFlags($=!1){if(this.loadedSuccessfullyOnce&&!$)return;if(!$&&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((Z)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${Z}`))).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(iG8,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 $=!0;if(this.cacheProvider)try{$=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(G){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${G}`))}if(!$){if(await this.loadFromCache("Loaded flags from cache (skipped fetch)"))return;if(this.loadedSuccessfullyOnce)return}let Z=await this._requestFeatureFlagDefinitions();if(!Z)return;switch(Z.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=Z.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new pC(`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 pC(`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 pC(`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 Z.json()??{};if(!("flags"in G))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(G)}`));this.flagsEtag=Z.headers?.get("ETag")??void 0;let X={flags:G.flags??[],groupTypeMapping:G.group_type_mapping||{},cohorts:G.cohorts||{}};if(this.updateFlagState(X),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&$)try{await this.cacheProvider.onFlagDefinitionsReceived(X)}catch(Q){this.onError?.(Error(`Failed to store in cache: ${Q}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(X.flags);break}default:return}}catch($){if($ instanceof pC)this.onError?.($)}}getPersonalApiKeyRequestOptions($="GET",Z){let G={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(Z)G["If-None-Match"]=Z;return{method:$,headers:G}}_requestFeatureFlagDefinitions(){let $=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,Z=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),G=null;if(this.timeout&&typeof this.timeout=="number"){let X=new AbortController;G=dK(()=>{X.abort()},this.timeout),Z.signal=X.signal}try{let X=this.fetch;return X($,Z)}finally{clearTimeout(G)}}async stopPoller($=30000){if(clearTimeout(this.poller),this.cacheProvider)try{let Z=this.cacheProvider.shutdown();if(Z instanceof Promise)await Promise.race([Z,new Promise((G,X)=>setTimeout(()=>X(Error(`Cache shutdown timeout after ${$}ms`)),$))])}catch(Z){this.onError?.(Error(`Error during cache shutdown: ${Z}`))}}}async function nA0($,Z,G=""){let X=await mA0(`${$}.${Z}${G}`);return parseInt(X.slice(0,15),16)/nG8}function oA0($,Z,G){let{key:X,value:Q}=$,Y=$.operator||"exact";if(X in Z){if(Y==="is_not_set")throw new g4("Operator is_not_set is not supported")}else throw new g4(`Property ${X} not found in propertyValues`);let J=Z[X];if(J==null&&!pG8.includes(Y)){if(G)G(`Property ${X} cannot have a value of null/undefined with the ${Y} operator`);return!1}function W(U,F){if(Array.isArray(U))return U.map((H)=>String(H).toLowerCase()).includes(String(F).toLowerCase());return String(U).toLowerCase()===String(F).toLowerCase()}function K(U,F,H){if(H==="gt")return U>F;if(H==="gte")return U>=F;if(H==="lt")return U<F;if(H==="lte")return U<=F;throw Error(`Invalid operator: ${H}`)}switch(Y){case"exact":return W(Q,J);case"is_not":return!W(Q,J);case"is_set":return X in Z;case"icontains":return String(J).toLowerCase().includes(String(Q).toLowerCase());case"not_icontains":return!String(J).toLowerCase().includes(String(Q).toLowerCase());case"regex":return pA0(String(Q))&&String(J).match(String(Q))!==null;case"not_regex":return pA0(String(Q))&&String(J).match(String(Q))===null;case"gt":case"gte":case"lt":case"lte":{let U=typeof Q=="number"?Q:null;if(typeof Q=="string")try{U=parseFloat(Q)}catch(F){}if(U==null||J==null)return K(String(J),String(Q),Y);if(typeof J=="string")return K(J,String(Q),Y);return K(J,U,Y)}case"is_date_after":case"is_date_before":{if(typeof Q=="boolean")throw new g4("Date operations cannot be performed on boolean values");let U=sG8(String(Q));if(U==null)U=tA0(Q);if(U==null)throw new g4(`Invalid date: ${Q}`);let F=tA0(J);if(["is_date_before"].includes(Y))return F<U;return F>U}case"semver_eq":return ZY(sZ(String(J)),sZ(String(Q)))===0;case"semver_neq":return ZY(sZ(String(J)),sZ(String(Q)))!==0;case"semver_gt":return ZY(sZ(String(J)),sZ(String(Q)))>0;case"semver_gte":return ZY(sZ(String(J)),sZ(String(Q)))>=0;case"semver_lt":return ZY(sZ(String(J)),sZ(String(Q)))<0;case"semver_lte":return ZY(sZ(String(J)),sZ(String(Q)))<=0;case"semver_tilde":{let U=sZ(String(J)),{lower:F,upper:H}=oG8(String(Q));return ZY(U,F)>=0&&ZY(U,H)<0}case"semver_caret":{let U=sZ(String(J)),{lower:F,upper:H}=rG8(String(Q));return ZY(U,F)>=0&&ZY(U,H)<0}case"semver_wildcard":{let U=sZ(String(J)),{lower:F,upper:H}=aG8(String(Q));return ZY(U,F)>=0&&ZY(U,H)<0}default:throw new g4(`Unknown operator: ${Y}`)}}function tG8($,Z){if(!($ in Z))throw new v3(`cohort ${$} not found in local cohorts - likely a static cohort that requires server evaluation`)}function rA0($,Z,G,X=!1){let Q=String($.value);tG8(Q,G);let Y=G[Q];return aA0(Y,Z,G,X)}function aA0($,Z,G,X=!1){if(!$)return!0;let{type:Q,values:Y}=$;if(!Y||Y.length===0)return!0;let J=!1;if("values"in Y[0]){for(let W of Y)try{let K=aA0(W,Z,G,X);if(Q==="AND"){if(!K)return!1}else if(K)return!0}catch(K){if(K instanceof v3)throw K;if(K instanceof g4){if(X)console.debug(`Failed to compute property ${W} locally: ${K}`);J=!0}else throw K}if(J)throw new g4("Can't match cohort without a given cohort property value");return Q==="AND"}for(let W of Y)try{let K;if(W.type==="cohort")K=rA0(W,Z,G,X);else if(W.type==="flag"){if(X)console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${W.key||"unknown"}'`);continue}else K=oA0(W,Z);let U=W.negation||!1;if(Q==="AND"){if(!K&&!U)return!1;if(K&&U)return!1}else{if(K&&!U)return!0;if(!K&&U)return!0}}catch(K){if(K instanceof v3)throw K;if(K instanceof g4){if(X)console.debug(`Failed to compute property ${W} locally: ${K}`);J=!0}else throw K}if(J)throw new g4("can't match cohort without a given cohort property value");return Q==="AND"}function pA0($){try{return new RegExp($),!0}catch(Z){return!1}}function sZ($){let G=String($).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!G||G.startsWith("."))throw new g4(`Invalid semver: ${$}`);let X=G.split("."),Q=(K)=>{if(K===void 0||K==="")return 0;if(!/^\d+$/.test(K))throw new g4(`Invalid semver: ${$}`);return parseInt(K,10)},Y=Q(X[0]),J=Q(X[1]),W=Q(X[2]);return[Y,J,W]}function ZY($,Z){for(let G=0;G<3;G++){if($[G]<Z[G])return-1;if($[G]>Z[G])return 1}return 0}function oG8($){let Z=sZ($),G=[Z[0],Z[1],Z[2]],X=[Z[0],Z[1]+1,0];return{lower:G,upper:X}}function rG8($){let Z=sZ($),[G,X,Q]=Z,Y=[G,X,Q],J;return J=G>0?[G+1,0,0]:X>0?[0,X+1,0]:[0,0,Q+1],{lower:Y,upper:J}}function aG8($){let G=String($).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!G)throw new g4(`Invalid wildcard semver: ${$}`);let X=G.split("."),Q=parseInt(X[0],10);if(isNaN(Q))throw new g4(`Invalid wildcard semver: ${$}`);let Y,J;if(X.length===1)Y=[Q,0,0],J=[Q+1,0,0];else{let W=parseInt(X[1],10);if(isNaN(W))throw new g4(`Invalid wildcard semver: ${$}`);Y=[Q,W,0],J=[Q,W+1,0]}return{lower:Y,upper:J}}function tA0($){if($ instanceof Date)return $;if(typeof $=="string"||typeof $=="number"){let Z=new Date($);if(!isNaN(Z.valueOf()))return Z;throw new g4(`${$} is in an invalid date format`)}throw new g4(`The date provided ${$} must be a string, number, or date object`)}function sG8($){let Z=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,G=$.match(Z),X=new Date(new Date().toISOString());if(!G)return null;{if(!G.groups)return null;let Q=parseInt(G.groups.number);if(Q>=1e4)return null;let Y=G.groups.interval;if(Y=="h")X.setUTCHours(X.getUTCHours()-Q);else if(Y=="d")X.setUTCDate(X.getUTCDate()-Q);else if(Y=="w")X.setUTCDate(X.getUTCDate()-7*Q);else if(Y=="m")X.setUTCMonth(X.getUTCMonth()-Q);else{if(Y!="y")return null;X.setUTCFullYear(X.getUTCFullYear()-Q)}return X}}var iG8=60000,nG8=1152921504606847000,pG8,pC,g4,v3;var sA0=D(()=>{gB();iA0();pG8=["is_not"];pC=class pC extends Error{constructor($){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=$,Object.setPrototypeOf(this,pC.prototype)}};g4=class g4 extends Error{constructor($){super($);this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,g4.prototype)}};v3=class v3 extends Error{constructor($){super($);this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,v3.prototype)}}});class PM1{getProperty($){return this._memoryStorage[$]}setProperty($,Z){this._memoryStorage[$]=Z!==null?Z:void 0}constructor(){this._memoryStorage={}}}var eA0=()=>{};function QX8($){return typeof $=="string"?$.trim():""}function YX8($){return(typeof $=="string"?$.trim():"")||void 0}function JX8($){return(typeof $=="string"?$.trim():"")||XX8}var eG8=100,$R0=30000,$X8=50000,ZX8=50,GX8=500,XX8="https://us.i.posthog.com",AM1;var ZR0=D(()=>{dA0();gB();zM1();sA0();vs();eA0();AM1=class AM1 extends Ms{constructor($,Z={}){let G=QX8($),X={...Z,host:JX8(Z.host),personalApiKey:YX8(Z.personalApiKey)};if(super(G,X),this._memoryStorage=new PM1,this.options=X,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof X.featureFlagsPollingInterval=="number"?Math.max(X.featureFlagsPollingInterval,eG8):$R0,typeof X.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(X.waitUntilDebounceMs,0);if(typeof X.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(X.waitUntilMaxWaitMs,0);if(X.personalApiKey){if(X.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(X.enableLocalEvaluation!==!1)this.featureFlagsPoller=new jM1({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:X.personalApiKey,projectApiKey:G,timeout:X.requestTimeout??1e4,host:this.host,fetch:X.fetch,onError:(Y)=>{this._events.emit("error",Y)},onLoad:(Y)=>{this._events.emit("localEvaluationFlagsLoaded",Y)},customHeaders:this.getCustomHeaders(),cacheProvider:X.flagDefinitionCacheProvider,strictLocalEvaluation:X.strictLocalEvaluation})}this.errorTracking=new $Y(this,X,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=X.maxCacheSize||$X8}enqueue($,Z,G){super.enqueue($,Z,G),this.scheduleDebouncedFlush()}async flush(){let $=super.flush(),Z=this.options.waitUntil;if(Z&&!this._waitUntilCycle)try{Z($.catch(()=>{}))}catch{}return $}scheduleDebouncedFlush(){let $=this.options.waitUntil;if(!$)return;if(this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let Y,J=new Promise((W)=>{Y=W});try{$(J)}catch{return}this._waitUntilCycle={resolve:Y,startedAt:Date.now(),timer:void 0}}let Z=Date.now()-this._waitUntilCycle.startedAt,G=this.options.waitUntilMaxWaitMs??GX8,X=Z>=G;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(X)return void this.resolveWaitUntilFlush();let Q=this.options.waitUntilDebounceMs??ZX8;this._waitUntilCycle.timer=dK(()=>{this.resolveWaitUntilFlush()},Q)}_consumeWaitUntilCycle(){let $=this._waitUntilCycle;if($)clearTimeout($.timer),this._waitUntilCycle=void 0;return $?.resolve}async resolveWaitUntilFlush(){let $=this._consumeWaitUntilCycle();try{await super.flush()}catch{}finally{$?.()}}getPersistedProperty($){return this._memoryStorage.getProperty($)}setPersistedProperty($,Z){return this._memoryStorage.setProperty($,Z)}fetch($,Z){return this.options.fetch?this.options.fetch($,Z):fetch($,Z)}getLibraryVersion(){return lA0}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug($=!0){super.debug($),this.featureFlagsPoller?.debug($)}capture($){if(typeof $=="string")this._logger.warn("Called capture() with a string as the first argument when an object was expected.");if($.event==="$exception"&&!$._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($).then(({distinctId:Z,event:G,properties:X,options:Q})=>super.captureStateless(Z,G,X,{timestamp:Q.timestamp,disableGeoip:Q.disableGeoip,uuid:Q.uuid})).catch((Z)=>{if(Z)console.error(Z)}))}async captureImmediate($){if(typeof $=="string")this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected.");if($.event==="$exception"&&!$._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($).then(({distinctId:Z,event:G,properties:X,options:Q})=>super.captureStatelessImmediate(Z,G,X,{timestamp:Q.timestamp,disableGeoip:Q.disableGeoip,uuid:Q.uuid})).catch((Z)=>{if(Z)console.error(Z)}))}identify({distinctId:$,properties:Z={},disableGeoip:G}){let{$set:X,$set_once:Q,$anon_distinct_id:Y,...J}=Z,U={$set:X||J,$set_once:Q||{},$anon_distinct_id:Y??void 0};super.identifyStateless($,U,{disableGeoip:G})}async identifyImmediate({distinctId:$,properties:Z={},disableGeoip:G}){let{$set:X,$set_once:Q,$anon_distinct_id:Y,...J}=Z,U={$set:X||J,$set_once:Q||{},$anon_distinct_id:Y??void 0};super.identifyStatelessImmediate($,U,{disableGeoip:G})}alias($){super.aliasStateless($.alias,$.distinctId,void 0,{disableGeoip:$.disableGeoip})}async aliasImmediate($){await super.aliasStatelessImmediate($.alias,$.distinctId,void 0,{disableGeoip:$.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady($=$R0){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((Z)=>{let G=setTimeout(()=>{X(),Z(!1)},$),X=this._events.on("localEvaluationFlagsLoaded",(Q)=>{clearTimeout(G),X(),Z(Q>0)})})}_resolveDistinctId($,Z){if(typeof $=="string")return{distinctId:$,options:Z};return{distinctId:this.context?.get()?.distinctId,options:$}}async _getFeatureFlagResult($,Z,G={},X){let Q=G.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&$ in this._flagOverrides){let A=this._flagOverrides[$];if(A===void 0)return;let q=this._payloadOverrides?.[$];return{key:$,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:q}}let{groups:Y,disableGeoip:J}=G,{onlyEvaluateLocally:W,personProperties:K,groupProperties:U}=G,F=this.addLocalPersonAndGroupProperties(Z,Y,K,U);K=F.allPersonProperties,U=F.allGroupProperties;let H=this.createFeatureFlagEvaluationContext(Z,Y,K,U);if(W==null)W=this.options.strictLocalEvaluation??!1;let N,O=!1,B,L,w,z,j,P;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let A=this.featureFlagsPoller?.featureFlagsByKey[$];if(A)try{let q=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(A,H,{matchValue:X});if(q){O=!0;let S=q.value;z=A.id,P="Evaluated locally",N={key:$,enabled:S!==!1,variant:typeof S=="string"?S:void 0,payload:q.payload??void 0}}}catch(q){if(q instanceof v3||q instanceof g4)this._logger?.info(`${q.name} when computing flag locally: ${$}: ${q.message}`);else throw q}}if(!O&&!W){let A=await super.getFeatureFlagDetailsStateless(H.distinctId,H.groups,H.personProperties,H.groupProperties,J,[$]);if(A===void 0)w=Ph.UNKNOWN_ERROR;else{B=A.requestId,L=A.evaluatedAt;let q=[];if(A.errorsWhileComputingFlags)q.push(Ph.ERRORS_WHILE_COMPUTING);if(A.quotaLimited?.includes("feature_flags"))q.push(Ph.QUOTA_LIMITED);let S=A.flags[$];if(S===void 0)q.push(Ph.FLAG_MISSING);else{z=S.metadata?.id,j=S.metadata?.version,P=S.reason?.description??S.reason?.code;let k;if(S.metadata?.payload!==void 0)try{k=JSON.parse(S.metadata.payload)}catch{k=S.metadata.payload}N={key:$,enabled:S.enabled,variant:S.variant,payload:k}}if(q.length>0)w=q.join(",")}}if(Q){let A=N===void 0?void 0:N.enabled===!1?!1:N.variant??!0,q=`${$}_${A}`;if(!(Z in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[Z].includes(q)){if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(Array.isArray(this.distinctIdHasSentFlagCalls[Z]))this.distinctIdHasSentFlagCalls[Z].push(q);else this.distinctIdHasSentFlagCalls[Z]=[q];let S={$feature_flag:$,$feature_flag_response:A,$feature_flag_id:z,$feature_flag_version:j,$feature_flag_reason:P,locally_evaluated:O,[`$feature/${$}`]:A,$feature_flag_request_id:B,$feature_flag_evaluated_at:O?Date.now():L};if(O&&this.featureFlagsPoller){let k=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(k!==void 0)S.$feature_flag_definitions_loaded_at=k}if(w)S.$feature_flag_error=w;this.capture({distinctId:Z,event:"$feature_flag_called",properties:S,groups:Y,disableGeoip:J})}}if(N!==void 0&&this._payloadOverrides!==void 0&&$ in this._payloadOverrides)N={...N,payload:this._payloadOverrides[$]};return N}async getFeatureFlag($,Z,G){let X=await this._getFeatureFlagResult($,Z,{...G,sendFeatureFlagEvents:G?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(X===void 0)return;if(X.enabled===!1)return!1;return X.variant??!0}async getFeatureFlagPayload($,Z,G,X){if(this._payloadOverrides!==void 0&&$ in this._payloadOverrides)return this._payloadOverrides[$];let Q=await this._getFeatureFlagResult($,Z,{...X,sendFeatureFlagEvents:!1},G);if(Q===void 0)return;return Q.payload??null}async getFeatureFlagResult($,Z,G){let{distinctId:X,options:Q}=this._resolveDistinctId(Z,G);if(!X)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult($,X,{...Q,sendFeatureFlagEvents:Q?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload($){if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let Z=await this._requestRemoteConfigPayload($);if(!Z)return;let G=await Z.json();if(typeof G=="string")try{return JSON.parse(G)}catch(X){}return G}async isFeatureEnabled($,Z,G){let X=await this.getFeatureFlag($,Z,G);if(X===void 0)return;return!!X||!1}async getAllFlags($,Z){let{distinctId:G,options:X}=this._resolveDistinctId($,Z);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,X)).featureFlags||{}}async getAllFlagsAndPayloads($,Z){let{distinctId:G,options:X}=this._resolveDistinctId($,Z);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:Q,disableGeoip:Y,flagKeys:J}=X||{},{onlyEvaluateLocally:W,personProperties:K,groupProperties:U}=X||{},F=this.addLocalPersonAndGroupProperties(G,Q,K,U);K=F.allPersonProperties,U=F.allGroupProperties;let H=this.createFeatureFlagEvaluationContext(G,Q,K,U);if(W==null)W=this.options.strictLocalEvaluation??!1;let N=await this.featureFlagsPoller?.getAllFlagsAndPayloads(H,J),O={},B={},L=!0;if(N)O=N.response,B=N.payloads,L=N.fallbackToFlags;if(L&&!W){let w=await super.getFeatureFlagsAndPayloadsStateless(H.distinctId,H.groups,H.personProperties,H.groupProperties,Y,J);O={...O,...w.flags||{}},B={...B,...w.payloads||{}}}if(this._flagOverrides!==void 0)O={...O,...this._flagOverrides};if(this._payloadOverrides!==void 0)B={...B,...this._payloadOverrides};return{featureFlags:O,featureFlagPayloads:B}}groupIdentify({groupType:$,groupKey:Z,properties:G,distinctId:X,disableGeoip:Q}){super.groupIdentifyStateless($,Z,G,{disableGeoip:Q},X)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags($){let Z=(G)=>Object.fromEntries(G.map((X)=>[X,!0]));if($===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray($)){this._flagOverrides=Z($);return}if(this._isFeatureFlagOverrideOptions($)){if("flags"in $){if($.flags===!1)this._flagOverrides=void 0;else if(Array.isArray($.flags))this._flagOverrides=Z($.flags);else if($.flags!==void 0)this._flagOverrides={...$.flags}}if("payloads"in $){if($.payloads===!1)this._payloadOverrides=void 0;else if($.payloads!==void 0)this._payloadOverrides={...$.payloads}}return}this._flagOverrides={...$}}_isFeatureFlagOverrideOptions($){if(typeof $!="object"||$===null||Array.isArray($))return!1;let Z=$;if("flags"in Z){let G=Z.flags;if(G===!1||Array.isArray(G)||typeof G=="object"&&G!==null)return!0}if("payloads"in Z){let G=Z.payloads;if(G===!1||typeof G=="object"&&G!==null)return!0}return!1}withContext($,Z,G){if(!this.context)return Z();return this.context.run($,Z,G)}getContext(){return this.context?.get()}enterContext($,Z){this.context?.enter($,Z)}async _shutdown($){let Z=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller($),this.errorTracking.shutdown();try{return await super._shutdown($)}finally{Z?.()}}async _requestRemoteConfigPayload($){if(!this.options.personalApiKey)return;let Z=`${this.host}/api/projects/@current/feature_flags/${$}/remote_config?token=${encodeURIComponent(this.apiKey)}`,G={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},X=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let Q=new AbortController;X=dK(()=>{Q.abort()},this.options.requestTimeout),G.signal=Q.signal}try{return await this.fetch(Z,G)}catch(Q){this._events.emit("error",Q);return}finally{if(X)clearTimeout(X)}}extractPropertiesFromEvent($,Z){if(!$)return{personProperties:{},groupProperties:{}};let G={},X={};for(let[Q,Y]of Object.entries($))if(OP0(Y)&&Z&&Q in Z){let J={};for(let[W,K]of Object.entries(Y))J[String(W)]=String(K);X[String(Q)]=J}else G[String(Q)]=String(Y);return{personProperties:G,groupProperties:X}}async getFeatureFlagsForEvent($,Z,G,X){let Q=X?.personProperties||{},Y=X?.groupProperties||{},J=X?.flagKeys;if(X?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let K={};for(let[U,F]of Object.entries(Z||{}))K[U]=String(F);return await this.getAllFlags($,{groups:K,personProperties:Q,groupProperties:Y,disableGeoip:G,onlyEvaluateLocally:!0,flagKeys:J})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let K={};for(let[U,F]of Object.entries(Z||{}))K[U]=String(F);return await this.getAllFlags($,{groups:K,personProperties:Q,groupProperties:Y,disableGeoip:G,onlyEvaluateLocally:!0,flagKeys:J})}return(await super.getFeatureFlagsStateless($,Z,Q,Y,G)).flags}addLocalPersonAndGroupProperties($,Z,G,X){let Q={distinct_id:$,...G||{}},Y={};if(Z)for(let J of Object.keys(Z))Y[J]={$group_key:Z[J],...X?.[J]||{}};return{allPersonProperties:Q,allGroupProperties:Y}}createFeatureFlagEvaluationContext($,Z,G,X){return{distinctId:$,groups:Z||{},personProperties:G||{},groupProperties:X||{},evaluationCache:{}}}captureException($,Z,G,X){if(!$Y.isPreviouslyCapturedError($)){let Q=Error("PostHog syntheticException");this.addPendingPromise($Y.buildEventMessage($,{syntheticException:Q},Z,G).then((Y)=>this.capture({...Y,uuid:X})))}}async captureExceptionImmediate($,Z,G){if(!$Y.isPreviouslyCapturedError($)){let X=Error("PostHog syntheticException");return this.addPendingPromise($Y.buildEventMessage($,{syntheticException:X},Z,G).then((Q)=>this.captureImmediate(Q)))}}async prepareEventMessage($){let{distinctId:Z,event:G,properties:X,groups:Q,sendFeatureFlags:Y,timestamp:J,disableGeoip:W,uuid:K}=$,U=this.context?.get(),F=Z||U?.distinctId,H={...this.props,...U?.properties||{},...X||{}};if(!F)F=RH(),H.$process_person_profile=!1;if(U?.sessionId&&!H.$session_id)H.$session_id=U.sessionId;let N=this._runBeforeSend({distinctId:F,event:G,properties:H,groups:Q,sendFeatureFlags:Y,timestamp:J,disableGeoip:W,uuid:K});if(!N)return Promise.reject(null);let O=await Promise.resolve().then(async()=>{if(Y){let B=typeof Y=="object"?Y:void 0;return await this.getFeatureFlagsForEvent(N.distinctId,Q,W,B)}return N.event,{}}).then((B)=>{let L={};if(B)for(let[z,j]of Object.entries(B))L[`$feature/${z}`]=j;let w=Object.keys(B||{}).filter((z)=>B?.[z]!==!1).sort();if(w.length>0)L.$active_feature_flags=w;return L}).catch(()=>({})).then((B)=>{return{...B,...N.properties||{},$groups:N.groups||Q}});if(N.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof O.$raw_user_agent=="string"){if(KP0(O.$raw_user_agent,this.options.custom_blocked_useragents||[]))N.event="$bot_pageview",O.$browser_type="bot"}return{distinctId:N.distinctId,event:N.event,properties:O,options:{timestamp:N.timestamp,disableGeoip:N.disableGeoip,uuid:N.uuid}}}_runBeforeSend($){let Z=this.options.before_send;if(!Z)return $;let G=Array.isArray(Z)?Z:[Z],X=$;for(let Q of G){if(X=Q(X),!X)return this._logger.info(`Event '${$.event}' was rejected in beforeSend function`),null;if(!X.properties||Object.keys(X.properties).length===0){let Y=`Event '${X.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(Y)}}return X}}});import{AsyncLocalStorage as WX8}from"async_hooks";class RM1{constructor(){this.storage=new WX8}get(){return this.storage.getStore()}run($,Z,G){return this.storage.run(this.resolve($,G),Z)}enter($,Z){this.storage.enterWith(this.resolve($,Z))}resolve($,Z){if(Z?.fresh===!0)return $;let G=this.get()||{};return{distinctId:$.distinctId??G.distinctId,sessionId:$.sessionId??G.sessionId,properties:{...G.properties||{},...$.properties||{}}}}}var GR0=()=>{};function KX8($,{organization:Z,projectId:G,prefix:X,severityAllowList:Q=["error"],sendExceptionsToPostHog:Y=!0}={}){return(J)=>{if(!(Q==="*"||Q.includes(J.level)))return J;if(!J.tags)J.tags={};let K=J.tags[XR0.POSTHOG_ID_TAG];if(K===void 0)return J;let U=$.options.host??"https://us.i.posthog.com",F=new URL(`/project/${$.apiKey}/person/${K}`,U).toString();J.tags["PostHog Person URL"]=F;let H=J.exception?.values||[],N=H.map((B)=>({...B,stacktrace:B.stacktrace?{...B.stacktrace,type:"raw",frames:(B.stacktrace.frames||[]).map((L)=>({...L,platform:"node:javascript"}))}:void 0})),O={$exception_message:H[0]?.value||J.message,$exception_type:H[0]?.type,$exception_level:J.level,$exception_list:N,$sentry_event_id:J.event_id,$sentry_exception:J.exception,$sentry_exception_message:H[0]?.value||J.message,$sentry_exception_type:H[0]?.type,$sentry_tags:J.tags};if(Z&&G)O.$sentry_url=(X||"https://sentry.io/organizations/")+Z+"/issues/?project="+G+"&query="+J.event_id;if(Y)$.capture({event:"$exception",distinctId:K,properties:O});return J}}var XR0;var QR0=D(()=>{XR0=class XR0{static#$=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor($,Z,G,X,Q){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(Y,J){let W=J()?.getClient()?.getDsn()?.projectId;Y(KX8($,{organization:Z,projectId:W,prefix:G,severityAllowList:X,sendExceptionsToPostHog:Q??!0}))}}}});var YR0=D(()=>{vs()});var JR0=D(()=>{gB();QR0();YR0();zM1()});var IM1;var WR0=D(()=>{QP0();xA0();gA0();vs();ZR0();gB();GR0();JR0();$Y.errorPropertiesBuilder=new aG.ErrorPropertiesBuilder([new aG.EventCoercer,new aG.ErrorCoercer,new aG.ObjectCoercer,new aG.StringCoercer,new aG.PrimitiveCoercer],aG.createStackParser("node:javascript",aG.nodeStackLineParser),[XP0(),bA0,yA0()]);IM1=class IM1 extends AM1{getLibraryId(){return"posthog-node"}initializeContext(){return new RM1}}});function UX8(){return{capture:()=>{},identify:()=>{},captureException:()=>{},groupIdentify:()=>{},shutdown:async()=>{}}}var TM1,KR0,z$;var H5=D(()=>{WR0();TM1=process.env.POSTHOG_KEY,KR0=process.env.POSTHOG_HOST;z$=TM1?new IM1(TM1,{...KR0?{host:KR0}:{},enableExceptionAutocapture:!0,flushAt:1,flushInterval:0}):UX8();if(TM1){let $=()=>{z$.shutdown().catch(()=>{})};process.on("SIGTERM",$),process.on("SIGINT",$)}});import{Kysely as FX8,PostgresDialect as HR0}from"kysely";import{Pool as NR0}from"pg";function BX8($){let Z=$.connect.bind($);return $.connect=(G)=>{if(typeof G==="function")return Z(G);let X=performance.now(),Q=fs(),Y=$.idleCount===0&&$.totalCount>=Q,J=$.idleCount;return Z().then((W)=>{let K=performance.now()-X;if(UR0().record(K,{"db.pool.outcome":Y?"contended":"available"}),K>NX8)if(Y)console.error("Slow db pool acquire \u2014 pool saturated:",{waitMs:K,total:$.totalCount,idle:$.idleCount,waiting:$.waitingCount,max:Q});else console.warn("Slow db pool acquire \u2014 event-loop lag (not pool):",{waitMs:K,idleAtStart:J,total:$.totalCount,max:Q});return W},(W)=>{throw UR0().record(performance.now()-X,{"db.pool.outcome":"error"}),W})},$}function BR0(){try{return q0().databasePgSsl}catch{return!1}}function fs(){try{return q0().databasePoolMax}catch{return 10}}function DX8($){let Z=BX8(new NR0({connectionString:$,max:fs(),ssl:BR0(),...OR0})),G=new HR0({pool:Z});return{type:"postgres",db:new FX8({dialect:G,log:OX8(Z)}),pool:Z}}function Rh(){return q0().databaseUrl}function DR0($){let Z=$||Rh();return new HR0({pool:new NR0({connectionString:Z,max:fs(),ssl:BR0(),...OR0})})}function LX8($){let Z=$||Rh();return DX8(Z)}async function LR0($){if(await $.db.destroy(),!$.pool.ended)await $.pool.end();if($===Ah)Ah=null}function n6(){if(!Ah)Ah=LX8(Rh());return Ah}var HX8=()=>V5.createHistogram("db.query.duration",{description:"Database query execution duration in milliseconds",unit:"ms"}),UR0=()=>V5.createHistogram("db.pool.acquire.duration",{description:"Time spent waiting to acquire a connection from the pool",unit:"ms"}),FR0=400,NX8=100,OX8=($)=>(Z)=>{let G={"db.statement":Z.query.sql,"db.status":Z.level==="error"?"error":"success"};if(Z.queryDurationMillis>FR0){let X=jo1(),Q=X>FR0/2;console.error(Q?"Slow query measurement \u2014 likely event-loop lag, not slow SQL:":"Slow query detected:",{durationMs:Z.queryDurationMillis,eventLoopLagMs:Math.round(X),sql:Z.query.sql,pool:{total:$.totalCount,idle:$.idleCount,waiting:$.waitingCount,max:fs()}})}if(HX8().record(Z.queryDurationMillis,G),Z.level==="error")console.error("Query failed:",{durationMs:Z.queryDurationMillis,error:Z.error,sql:Z.query.sql})},OR0,Ah=null;var f3=D(()=>{M4();s9();NB1();OR0={keepAlive:!0,keepAliveInitialDelayMillis:1e4,idleTimeoutMillis:300000,connectionTimeoutMillis:30000,allowExitOnIdle:!0}});class qM1{apiKey;constructor($){this.apiKey=$}async sendEmail({to:$,from:Z,subject:G,html:X}){let Q=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:$,from:Z,subject:G,html:X})});if(!Q.ok)throw Error(`Failed to send email: ${Q.statusText}`)}}class MM1{apiKey;constructor($){this.apiKey=$}async sendEmail({to:$,from:Z,subject:G,html:X}){let Q=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:$}]}],from:{email:Z},subject:G,content:[{type:"text/html",value:X}]})});if(!Q.ok){let Y=await Q.text();throw Error(`Failed to send email via SendGrid: ${Q.statusText} - ${Y}`)}}}function hB($){let Z=zX8[$.provider];if(!Z)throw Error(`Unknown email provider: ${$.provider}`);return Z($)}function uB($,Z){return $.find((G)=>G.id===Z)}var EX8=($)=>{let Z=new qM1($.config.apiKey);return async({to:G,subject:X,html:Q})=>{await Z.sendEmail({to:G,from:$.config.fromEmail,subject:X,html:Q})}},wX8=($)=>{let Z=new MM1($.config.apiKey);return async({to:G,subject:X,html:Q})=>{await Z.sendEmail({to:G,from:$.config.fromEmail,subject:X,html:Q})}},zX8;var xs=D(()=>{zX8={resend:EX8,sendgrid:wX8}});function cB({preheader:$="",heading:Z,subheading:G,body:X,footnote:Q}){return`<!DOCTYPE html>
86
86
  <html lang="en">
87
87
  <head>
88
88
  <meta charset="utf-8" />