@decocms/mesh 1.10.0 → 1.11.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 (153) hide show
  1. package/dist/client/assets/{AlertCircle-DxJIdkjA.js → AlertCircle-fQ1a-Kye.js} +1 -1
  2. package/dist/client/assets/{ArrowLeft-CrgZDDUZ.js → ArrowLeft-BiKe-UDJ.js} +1 -1
  3. package/dist/client/assets/{ChevronDown-B2VaHCqC.js → ChevronDown-B3ly4A-X.js} +1 -1
  4. package/dist/client/assets/ChevronRight-CXZWZETT.js +1 -0
  5. package/dist/client/assets/{Copy01-DfnjsOeR.js → Copy01-CYicndkm.js} +1 -1
  6. package/dist/client/assets/DotsHorizontal-By0WO0xT.js +1 -0
  7. package/dist/client/assets/{DotsVertical-DIWcHGKr.js → DotsVertical-D6iehcQW.js} +1 -1
  8. package/dist/client/assets/{File06-DSeIH9xM.js → File06-BJJWTDds.js} +1 -1
  9. package/dist/client/assets/FilterLines-Bl9i76YX.js +1 -0
  10. package/dist/client/assets/{FlipBackward-s0RSv_vj.js → FlipBackward-h1suVrc9.js} +1 -1
  11. package/dist/client/assets/{GitBranch01-CeFBxnqq.js → GitBranch01-McK6f_RW.js} +1 -1
  12. package/dist/client/assets/{Grid01-Ch9rI6P9.js → Grid01-nuISl4Jo.js} +1 -1
  13. package/dist/client/assets/{Inbox01-7z9hTUsw.js → Inbox01-BXcb_6qt.js} +1 -1
  14. package/dist/client/assets/{InfoCircle-DQaxWpv9.js → InfoCircle-D8RiAWfe.js} +1 -1
  15. package/dist/client/assets/{Key01-CH9qCC00.js → Key01-BQ_2OE0w.js} +1 -1
  16. package/dist/client/assets/{LinkExternal01-DZDUBWQO.js → LinkExternal01-42UxL9hq.js} +1 -1
  17. package/dist/client/assets/{Loading01-B0dLQInZ.js → Loading01-BJF4I2Ad.js} +1 -1
  18. package/dist/client/assets/{Lock01-wpG8qO-9.js → Lock01-BrzFrmRw.js} +1 -1
  19. package/dist/client/assets/Play-MQJiRz2-.js +1 -0
  20. package/dist/client/assets/{Plus-D_XbrIfI.js → Plus-DMj-o9Gi.js} +1 -1
  21. package/dist/client/assets/{Terminal-BSL9-A7C.js → Terminal-CW45jfl-.js} +1 -1
  22. package/dist/client/assets/{Trash01-aTCf1hVv.js → Trash01-BmyJcEM6.js} +1 -1
  23. package/dist/client/assets/{X-BgwVwwIy.js → X-3dUB6f8T.js} +1 -1
  24. package/dist/client/assets/XClose-CCiTTWan.js +1 -0
  25. package/dist/client/assets/{alert-dialog-DIexFXOj.js → alert-dialog-B5AngVSr.js} +3 -3
  26. package/dist/client/assets/auth-bKqgeTR4.js +1 -0
  27. package/dist/client/assets/{auth-catchall-Cp5vKmTi.js → auth-catchall-nRP-qv3i.js} +1 -1
  28. package/dist/client/assets/{avatar-Bf0qQU4w.js → avatar-B3qfE1qj.js} +1 -1
  29. package/dist/client/assets/{badge-CgEtLuTw.js → badge-DnxI94Ef.js} +1 -1
  30. package/dist/client/assets/button-P1l4UZMh.js +1 -0
  31. package/dist/client/assets/{card-ciO_SNWh.js → card-DlmzE0V_.js} +1 -1
  32. package/dist/client/assets/checkbox-Da1a0gnC.js +1 -0
  33. package/dist/client/assets/{collection-detail-msiVYwQa.js → collection-detail-C-lRKJ6c.js} +4 -4
  34. package/dist/client/assets/collection-display-button-DEihXWWS.js +1 -0
  35. package/dist/client/assets/{collection-header-BkZGWAxm.js → collection-header-DldCjJ2b.js} +1 -1
  36. package/dist/client/assets/{collection-page-CREYFoHa.js → collection-page-DUqbzyRz.js} +1 -1
  37. package/dist/client/assets/collection-search-078Tk8ke.js +1 -0
  38. package/dist/client/assets/collection-tab-D9t_zdu8.js +1 -0
  39. package/dist/client/assets/{collection-table-wrapper-Dnmr37nE.js → collection-table-wrapper-s0V0lVte.js} +1 -1
  40. package/dist/client/assets/{connection-card-Dcrw1pJ1.js → connection-card-Bq4SPs9k.js} +1 -1
  41. package/dist/client/assets/connection-detail-G_uQHX56.js +1 -0
  42. package/dist/client/assets/connections-CjllWosN.js +1 -0
  43. package/dist/client/assets/constants--AQKkMmO.js +1 -0
  44. package/dist/client/assets/{create-organization-dialog-CYQoklT3.js → create-organization-dialog-BjXNKLri.js} +1 -1
  45. package/dist/client/assets/{dialog-D4dy2US8.js → dialog-DskfmP3S.js} +1 -1
  46. package/dist/client/assets/dropdown-menu-C_0icbcC.js +1 -0
  47. package/dist/client/assets/{empty-state-CA7indKP.js → empty-state-DGPTU48f.js} +1 -1
  48. package/dist/client/assets/env-vars-editor-DHPvpktS.js +1 -0
  49. package/dist/client/assets/{error-boundary-Ba_T3BIS.js → error-boundary-DVR3TWt5.js} +1 -1
  50. package/dist/client/assets/extract-connection-data-sl_xi-NX.js +1 -0
  51. package/dist/client/assets/{form-rbCVC2Lc.js → form-Dt7KStxI.js} +1 -1
  52. package/dist/client/assets/{formatDistanceToNow-Bsssu-td.js → formatDistanceToNow-CxdFFLDu.js} +1 -1
  53. package/dist/client/assets/gateway-detail-CQ2HJebN.js +1 -0
  54. package/dist/client/assets/gateway-selector-C50wFrLo.js +1 -0
  55. package/dist/client/assets/gateways-Brw5ylzi.js +1 -0
  56. package/dist/client/assets/github-icon-BrF3LMLL.js +1 -0
  57. package/dist/client/assets/{home-0xYKq0nN.js → home-DT_gtVKG.js} +1 -1
  58. package/dist/client/assets/index-BjKus4OW.css +1 -0
  59. package/dist/client/assets/{index-BGmLHZvN.js → index-CQ5PpV5-.js} +5 -5
  60. package/dist/client/assets/index-DB3jkZVV.js +1 -0
  61. package/dist/client/assets/{index-B9fZ40p9.js → index-JM_K-0vS.js} +21 -21
  62. package/dist/client/assets/{input-C3lfdgit.js → input-lEjyv7_t.js} +1 -1
  63. package/dist/client/assets/{layout-BgUF9JkX.js → layout-Mi4JIpR6.js} +1 -1
  64. package/dist/client/assets/{lazy-highlighter-Buv6v3mS.js → lazy-highlighter-6XYxZAuO.js} +1 -1
  65. package/dist/client/assets/{localstorage-keys-BGRuWcRT.js → localstorage-keys-DmEm8_Oa.js} +1 -1
  66. package/dist/client/assets/{login-fFNSXfGP.js → login-DaHhOJbN.js} +1 -1
  67. package/dist/client/assets/{mcp-oauth-DacADfyW.js → mcp-oauth-CK__gbJ2.js} +1 -1
  68. package/dist/client/assets/mcp-server-detail-DERmLIXK.js +1 -0
  69. package/dist/client/assets/members-DzWV9w7S.js +3 -0
  70. package/dist/client/assets/{monaco-editor-uZe9l_bJ.js → monaco-editor-B-DMAUS8.js} +4 -4
  71. package/dist/client/assets/monitoring-Bw9ECV_3.js +49 -0
  72. package/dist/client/assets/{oauth-callback-zUOuo71p.js → oauth-callback-ChEIlyyo.js} +1 -1
  73. package/dist/client/assets/page-DNqUgOCd.js +1 -0
  74. package/dist/client/assets/page-DieG1pN7.js +35 -0
  75. package/dist/client/assets/pin-to-sidebar-button-CbQe-lRF.js +1 -0
  76. package/dist/client/assets/popover-D51HT9Xp.js +1 -0
  77. package/dist/client/assets/project-context-provider-DxPsvg7o.js +1 -0
  78. package/dist/client/assets/resizable-uj7Ud0Nv.js +1 -0
  79. package/dist/client/assets/{resource-tabs-ltvgVmlK.js → resource-tabs-mvYm33c6.js} +1 -1
  80. package/dist/client/assets/select-DDRl1Qvs.js +1 -0
  81. package/dist/client/assets/settings-BFSp8ZnH.js +1 -0
  82. package/dist/client/assets/shell-layout-DsOoA3nx.js +19 -0
  83. package/dist/client/assets/{spinner-CDnZnQfr.js → spinner-pX_8yHq8.js} +1 -1
  84. package/dist/client/assets/switch-6o4pER7R.js +1 -0
  85. package/dist/client/assets/{textarea-CvmD-TCl.js → textarea-BIJ4bnK1.js} +1 -1
  86. package/dist/client/assets/{thread-history-popover-BQKKEP-v.js → thread-history-popover-BLJ6aCqn.js} +37 -37
  87. package/dist/client/assets/tools-list-K2fXAvZZ.js +1 -0
  88. package/dist/client/assets/{use-binding-BWHEOuVA.js → use-binding-DODEZIVG.js} +1 -1
  89. package/dist/client/assets/use-connection-BLmwBfcI.js +2 -0
  90. package/dist/client/assets/{use-connection-resources-DbXXhKLF.js → use-connection-resources-CFssgYId.js} +1 -1
  91. package/dist/client/assets/use-gateway-C8PgG30I.js +1 -0
  92. package/dist/client/assets/{use-list-state-vrSW0egR.js → use-list-state-CNyb0sVm.js} +1 -1
  93. package/dist/client/assets/{use-mcp-BXJqKT0W.js → use-mcp-askdlkSn.js} +1 -1
  94. package/dist/client/assets/use-members-MyMMikAQ.js +1 -0
  95. package/dist/client/assets/{use-mobile-CG0P5-tt.js → use-mobile-aroC6xLW.js} +1 -1
  96. package/dist/client/assets/{use-organization-settings-jxyxG3Do.js → use-organization-settings-447_kc1C.js} +1 -1
  97. package/dist/client/assets/{use-tool-call-vWU--CYB.js → use-tool-call-9WIw8dXG.js} +1 -1
  98. package/dist/client/assets/useQuery-CVizz7NG.js +1 -0
  99. package/dist/client/assets/value-DFuI_KD4.js +1 -0
  100. package/dist/client/assets/{view-mode-toggle-CTKggGXJ.js → view-mode-toggle-B2u6HchE.js} +1 -1
  101. package/dist/client/assets/{well-known-mcp-VNRT0JrW.js → well-known-mcp-D13f-8h2.js} +1 -1
  102. package/dist/client/assets/workflow-dtZDbGNi.js +1 -0
  103. package/dist/client/index.html +2 -2
  104. package/dist/server/cli.js +151 -151
  105. package/dist/server/migrate.js +1 -1
  106. package/dist/server/server.js +148 -148
  107. package/package.json +2 -3
  108. package/dist/client/assets/Clock-CafJ8d76.js +0 -1
  109. package/dist/client/assets/Code01-BHMAmoGH.js +0 -1
  110. package/dist/client/assets/CpuChip02-qVpLCR0_.js +0 -1
  111. package/dist/client/assets/Play-DSXQEflq.js +0 -1
  112. package/dist/client/assets/SearchMd-BJbLhbUT.js +0 -1
  113. package/dist/client/assets/XClose-sskkBH5X.js +0 -1
  114. package/dist/client/assets/auth-BnF0Tfz9.js +0 -1
  115. package/dist/client/assets/button-O0CudEuW.js +0 -1
  116. package/dist/client/assets/checkbox-DUc30Qpz.js +0 -1
  117. package/dist/client/assets/collection-display-button-BVgPIpv0.js +0 -1
  118. package/dist/client/assets/collection-search-s9G5Psps.js +0 -1
  119. package/dist/client/assets/collection-tab-T_hhyR7G.js +0 -1
  120. package/dist/client/assets/connection-detail-ByP6chqW.js +0 -1
  121. package/dist/client/assets/connections-DYOzkJYx.js +0 -1
  122. package/dist/client/assets/constants-BG4081pg.js +0 -1
  123. package/dist/client/assets/dropdown-menu-DjELCVXr.js +0 -1
  124. package/dist/client/assets/env-vars-editor-CFmirc3J.js +0 -1
  125. package/dist/client/assets/extract-connection-data-Bm1qZWCV.js +0 -1
  126. package/dist/client/assets/gateway-detail-JYrV5S3_.js +0 -1
  127. package/dist/client/assets/gateways--haP9jLk.js +0 -1
  128. package/dist/client/assets/index-BNguAQBW.js +0 -1
  129. package/dist/client/assets/index-C9WZdaPe.js +0 -1
  130. package/dist/client/assets/index-CmUsR6rx.css +0 -1
  131. package/dist/client/assets/members-CAufZALX.js +0 -3
  132. package/dist/client/assets/monitoring-DTJtueom.js +0 -4
  133. package/dist/client/assets/page-BP6lcPxY.js +0 -21
  134. package/dist/client/assets/pin-to-sidebar-button-DcWM6FTO.js +0 -1
  135. package/dist/client/assets/popover-BRnyFKtN.js +0 -1
  136. package/dist/client/assets/registry-utils-ulDDT0d8.js +0 -1
  137. package/dist/client/assets/resizable-Bcc9SJfZ.js +0 -1
  138. package/dist/client/assets/responsive-select-BbaQnOfE.js +0 -1
  139. package/dist/client/assets/select-Dsuiuagq.js +0 -1
  140. package/dist/client/assets/settings-Br4mx_yy.js +0 -1
  141. package/dist/client/assets/shell-layout-CM_S8ji4.js +0 -19
  142. package/dist/client/assets/store-CJqU95FV.js +0 -1
  143. package/dist/client/assets/store-app-detail-Bb4mx26e.js +0 -1
  144. package/dist/client/assets/switch-DhyQ2_hE.js +0 -1
  145. package/dist/client/assets/tools-list-zpc-T8zT.js +0 -1
  146. package/dist/client/assets/tooltip-DaImUyOX.js +0 -1
  147. package/dist/client/assets/types-BDHiECry.js +0 -46
  148. package/dist/client/assets/use-connection-9XNP6qUi.js +0 -2
  149. package/dist/client/assets/use-gateway-BU92tNo7.js +0 -1
  150. package/dist/client/assets/use-members-eTAFi1HF.js +0 -1
  151. package/dist/client/assets/useQuery-nlt5lRkW.js +0 -1
  152. package/dist/client/assets/useSuspenseInfiniteQuery-o35GYPjZ.js +0 -1
  153. package/dist/client/assets/workflow-DTYA39cO.js +0 -1
@@ -985,7 +985,7 @@ Please refer to the documentation here: https://better-auth.com/docs/plugins/org
985
985
  </script>
986
986
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference" ${Y}></script>
987
987
  </body>
988
- </html>`},P_=(X)=>{let Q=X?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:O0("/open-api/generate-schema",{method:"GET"},async(J)=>{let Y=await W60(J.context,J.context.options);return J.json(Y)}),openAPIReference:O0(Q,{method:"GET",metadata:{isAction:!1}},async(J)=>{if(X?.disableDefaultReference)throw new h("NOT_FOUND");let Y=await W60(J.context,J.context.options);return new Response(ny0(Y,X?.theme,X?.nonce),{headers:{"Content-Type":"text/html"}})})}}};PX();k9();e8();v1();d0();var rT4=P6(async()=>{return{}}),aT4=P6({use:[O8]},async(X)=>{return{session:X.context.session}}),oT4=r6({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role"});var sT4=Number.POSITIVE_INFINITY;var K60=w(),ry0=o0(["pending","accepted","rejected","canceled"]).default("pending"),tT4=b({id:w().default(Z1),name:w(),slug:w(),logo:w().nullish().optional(),metadata:v0(w(),I6()).or(w().transform((X)=>JSON.parse(X))).optional(),createdAt:E4()}),eT4=b({id:w().default(Z1),organizationId:w(),userId:j4.string(),role:K60,createdAt:E4().default(()=>new Date)}),XA4=b({id:w().default(Z1),organizationId:w(),email:w(),role:K60,status:ry0,teamId:w().nullish(),inviterId:w(),expiresAt:E4(),createdAt:E4().default(()=>new Date)}),QA4=b({id:w().default(Z1),name:w().min(1),organizationId:w(),createdAt:E4(),updatedAt:E4().optional()}),JA4=b({id:w().default(Z1),teamId:w(),userId:w(),createdAt:E4().default(()=>new Date)}),YA4=b({id:w().default(Z1),organizationId:w(),role:w(),permission:v0(w(),Z0(w())),createdAt:E4().default(()=>new Date),updatedAt:E4().optional()}),H60=["admin","member","owner"],GA4=I4([o0(H60),Z0(o0(H60))]);M8();e8();v1();var zA4=r6({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});M8();TX();e8();v1();A1();Z8();var ay0=r6({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});e8();v1();var oy0=r6({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var FK={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as Z60,readFileSync as F60}from"fs";var Ww={emailAndPassword:{enabled:!0}},V60=process.env.CONFIG_PATH||"./config.json",q60=process.env.AUTH_CONFIG_PATH||"./auth-config.json";function sy0(){if(Z60(V60))try{let X=F60(V60,"utf-8"),Q=JSON.parse(X);return{auth:Ww,monitoring:FK,...Q}}catch{return{auth:Ww,monitoring:FK}}if(Z60(q60))try{let X=F60(q60,"utf-8");return{auth:JSON.parse(X),monitoring:FK}}catch{return{auth:Ww,monitoring:FK}}return{auth:Ww,monitoring:FK}}var T_=sy0();import{existsSync as lx0,mkdirSync as dx0}from"fs";import{Kysely as _10,PostgresDialect as b10,sql as k10}from"kysely";import{BunWorkerDialect as y10}from"kysely-bun-worker";import*as f10 from"path";var uJ=WJ(Qb(),1),U24=uJ.default.Client,$b=uJ.default.Pool,z24=uJ.default.Connection,B24=uJ.default.types,L24=uJ.default.Query,D24=uJ.default.DatabaseError,j24=uJ.default.escapeIdentifier,N24=uJ.default.escapeLiteral,O24=uJ.default.Result,w24=uJ.default.TypeOverrides,M24=uJ.default.defaults;function px0(X){let Q=new $b({connectionString:X.connectionString,max:X.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1}),J=new b10({pool:Q});return{type:"postgres",db:new _10({dialect:J}),pool:Q}}function h10(X){if(X===":memory:")return":memory:";if(X.includes("://"))return new URL(X).pathname;return X}function g10(X){if(X!==":memory:"&&X!=="/"&&X){let Q=X.substring(0,X.lastIndexOf("/"));if(Q&&Q!=="/"&&!lx0(Q))try{dx0(Q,{recursive:!0})}catch{return console.warn(`Failed to create directory ${Q}, using in-memory database`),":memory:"}}return X}function cx0(X){let Q=h10(X.connectionString);Q=g10(Q);let J=new y10({url:Q||":memory:"}),Y=new _10({dialect:J});if(Q!==":memory:"&&X.options?.enableWAL!==!1)k10`PRAGMA journal_mode = WAL;`.execute(Y).catch(()=>{});if(Q!==":memory:"){let G=X.options?.busyTimeout||5000;k10`PRAGMA busy_timeout = ${G};`.execute(Y).catch(()=>{})}return{type:"sqlite",db:Y}}function x10(X){let Q=X||"file:./data/mesh.db";if(Q===":memory:")return{type:"sqlite",connectionString:":memory:"};Q=Q.startsWith("/")?`file://${Q}`:Q;let J=URL.canParse(Q)?new URL(Q):null,Y=J?.protocol.replace(":","")??Q.split("://")[0];switch(Y){case"postgres":case"postgresql":return{type:"postgres",connectionString:Q};case"sqlite":case"file":if(!J?.pathname)throw Error("Invalid database URL: "+Q);return{type:"sqlite",connectionString:J.pathname};default:throw Error(`Unsupported database protocol: ${Y}. Supported protocols: postgres://, postgresql://, sqlite://, file://`)}}function Hb(){return process.env.DATABASE_URL||`file:${f10.join(process.cwd(),"data/mesh.db")}`}function u10(X){let Q=x10(X);if(Q.type==="postgres")return new b10({pool:new $b({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1})});let J=h10(Q.connectionString);return J=g10(J),new y10({url:J||":memory:"})}function nx0(X){let Q=x10(X);if(Q.type==="postgres")return px0(Q);return cx0(Q)}async function m10(X){if(await X.db.destroy(),X.type==="postgres"&&!X.pool.ended)await X.pool.end()}var Wb=null;function Uq(){if(!Wb)Wb=nx0(Hb());return Wb}class Kb{apiKey;constructor(X){this.apiKey=X}async sendEmail({to:X,from:Q,subject:J,html:Y}){let G=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:X,from:Q,subject:J,html:Y})});if(!G.ok)throw Error(`Failed to send email: ${G.statusText}`)}}class Zb{apiKey;constructor(X){this.apiKey=X}async sendEmail({to:X,from:Q,subject:J,html:Y}){let G=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:X}]}],from:{email:Q},subject:J,content:[{type:"text/html",value:Y}]})});if(!G.ok){let $=await G.text();throw Error(`Failed to send email via SendGrid: ${G.statusText} - ${$}`)}}}var ix0=(X)=>{let Q=new Kb(X.config.apiKey);return async({to:J,subject:Y,html:G})=>{await Q.sendEmail({to:J,from:X.config.fromEmail,subject:Y,html:G})}},rx0=(X)=>{let Q=new Zb(X.config.apiKey);return async({to:J,subject:Y,html:G})=>{await Q.sendEmail({to:J,from:X.config.fromEmail,subject:Y,html:G})}},ax0={resend:ix0,sendgrid:rx0};function jw(X){let Q=ax0[X.provider];if(!Q)throw Error(`Unknown email provider: ${X.provider}`);return Q(X)}function Nw(X,Q){return X.find((J)=>J.id===Q)}var l10=(X,Q)=>{let J=Nw(Q,X.emailProviderId);if(!J)throw Error(`Email provider with id '${X.emailProviderId}' not found`);let Y=jw(J);return{sendMagicLink:async({email:G,url:$})=>{await Y({to:G,subject:"Magic Link",html:`<p>Click <a href="${$}">here</a> to login</p>`})}}};ww();import{createCipheriv as ox0,createDecipheriv as sx0,randomBytes as n10}from"crypto";var i10="aes-256-gcm",zq=16,r10=16,a10=32;class Fb{key;constructor(X){if(Buffer.from(X,"base64").length===a10)this.key=Buffer.from(X,"base64");else{let Q=G4("crypto");this.key=Q.createHash("sha256").update(X).digest()}}async encrypt(X){let Q=n10(zq),J=ox0(i10,this.key,Q),Y=J.update(X,"utf8");Y=Buffer.concat([Y,J.final()]);let G=J.getAuthTag();return Buffer.concat([Q,G,Y]).toString("base64")}async decrypt(X){let Q=Buffer.from(X,"base64"),J=Q.subarray(0,zq),Y=Q.subarray(zq,zq+r10),G=Q.subarray(zq+r10),$=sx0(i10,this.key,J);$.setAuthTag(Y);let W=$.update(G);return W=Buffer.concat([W,$.final()]),W.toString("utf8")}static generateKey(){return n10(a10).toString("base64")}}x$();import{webcrypto as e10}from"crypto";var t10="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ju0=128,gW,OK;function Yu0(X){if(!gW||gW.length<X)gW=Buffer.allocUnsafe(X*Ju0),e10.getRandomValues(gW),OK=0;else if(OK+X>gW.length)e10.getRandomValues(gW),OK=0;OK+=X}function XX0(X=21){Yu0(X|=0);let Q="";for(let J=OK-X;J<OK;J++)Q+=t10[gW[J]&63];return Q}function u$(X){return`${X}_${XX0()}`}var Gu0=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class Vb{db;vault;constructor(X,Q){this.db=X;this.vault=Q}async create(X){let Q=X.id??u$("conn"),J=new Date().toISOString(),Y=await this.findById(Q);if(Y){if(Y.organization_id!==X.organization_id)throw Error("Connection ID already exists");return this.update(Q,X)}let G=await this.serializeConnection({...X,id:X.id??Q,status:"active",created_at:J,updated_at:J});await this.db.insertInto("connections").values(G).execute();let $=await this.findById(Q);if(!$)throw Error(`Failed to create connection with id: ${Q}`);return $}async findById(X,Q){let J=this.db.selectFrom("connections").selectAll().where("id","=",X);if(Q)J=J.where("organization_id","=",Q);let Y=await J.executeTakeFirst();return Y?this.deserializeConnection(Y):null}async list(X){let Q=await this.db.selectFrom("connections").selectAll().where("organization_id","=",X).execute();return Promise.all(Q.map((J)=>this.deserializeConnection(J)))}async update(X,Q){if(Object.keys(Q).length===0){let G=await this.findById(X);if(!G)throw Error("Connection not found");return G}let J=await this.serializeConnection({...Q,updated_at:new Date().toISOString()});await this.db.updateTable("connections").set(J).where("id","=",X).execute();let Y=await this.findById(X);if(!Y)throw Error("Connection not found after update");return Y}async delete(X){await this.db.deleteFrom("connections").where("id","=",X).execute()}async testConnection(X,Q){let J=await this.findById(X);if(!J)throw Error("Connection not found");let Y=Date.now();if(J.connection_type==="STDIO")return{healthy:!0,latencyMs:Date.now()-Y};if(!J.connection_url)return{healthy:!1,latencyMs:Date.now()-Y};try{let G=J.connection_headers,$=await fetch(J.connection_url,{method:"POST",headers:{"Content-Type":"application/json",...J.connection_token&&{Authorization:`Bearer ${J.connection_token}`},...G?.headers,...Q},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:$.ok||$.status===404,latencyMs:Date.now()-Y}}catch{return{healthy:!1,latencyMs:Date.now()-Y}}}async serializeConnection(X){let Q={};for(let[J,Y]of Object.entries(X)){if(Y===void 0)continue;if(J==="connection_token"&&Y)Q[J]=await this.vault.encrypt(Y);else if(J==="configuration_state"&&Y){let G=JSON.stringify(Y);Q[J]=await this.vault.encrypt(G)}else if(J==="connection_headers"&&Y){let G=Y;if(Bq(G)&&G.envVars){let $={};for(let[W,H]of Object.entries(G.envVars))$[W]=await this.vault.encrypt(H);Q[J]=JSON.stringify({...G,envVars:$})}else Q[J]=JSON.stringify(G)}else if(Gu0.includes(J))Q[J]=Y?JSON.stringify(Y):null;else Q[J]=Y}return Q}async deserializeConnection(X){let Q=null;if(X.connection_token)try{Q=await this.vault.decrypt(X.connection_token)}catch($){console.error("Failed to decrypt connection token:",$)}let J=null;if(X.configuration_state)try{let $=await this.vault.decrypt(X.configuration_state);J=JSON.parse($)}catch($){console.error("Failed to decrypt configuration state:",$)}let Y=null;if(X.connection_headers)try{let $=JSON.parse(X.connection_headers);if(Bq($)&&$.envVars){let W={};for(let[H,K]of Object.entries($.envVars))try{W[H]=await this.vault.decrypt(K)}catch{W[H]=K}Y={...$,envVars:W}}else Y=$}catch($){console.error("Failed to parse connection_headers:",$)}let G=($)=>{if($===null)return null;if(typeof $==="string")try{return JSON.parse($)}catch{return null}return $};return{id:X.id,organization_id:X.organization_id,created_by:X.created_by,title:X.title,description:X.description,icon:X.icon,app_name:X.app_name,app_id:X.app_id,connection_type:X.connection_type,connection_url:X.connection_url,connection_token:Q,connection_headers:Y,oauth_config:G(X.oauth_config),configuration_state:J,configuration_scopes:G(X.configuration_scopes),metadata:G(X.metadata),tools:G(X.tools),bindings:G(X.bindings),status:X.status,created_at:X.created_at,updated_at:X.updated_at}}}class qb{db;constructor(X){this.db=X}async create(X,Q,J){let Y=u$("gw"),G=new Date().toISOString();if(J.isDefault)return await this.db.transaction().execute(async(W)=>{if(await W.updateTable("gateways").set({is_default:0,updated_at:G,updated_by:Q}).where("organization_id","=",X).where("is_default","=",1).execute(),await W.insertInto("gateways").values({id:Y,organization_id:X,title:J.title,description:J.description??null,tool_selection_strategy:J.toolSelectionStrategy??"passthrough",tool_selection_mode:J.toolSelectionMode??"inclusion",icon:J.icon??null,status:J.status??"active",is_default:1,created_at:G,updated_at:G,created_by:Q,updated_by:null}).execute(),J.connections.length>0)await W.insertInto("gateway_connections").values(J.connections.map((K)=>({id:u$("gwc"),gateway_id:Y,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,selected_resources:K.selectedResources?JSON.stringify(K.selectedResources):null,selected_prompts:K.selectedPrompts?JSON.stringify(K.selectedPrompts):null,created_at:G}))).execute();let H=await this.findByIdInternal(W,Y);if(!H)throw Error(`Failed to create gateway with id: ${Y}`);return H});if(await this.db.insertInto("gateways").values({id:Y,organization_id:X,title:J.title,description:J.description??null,tool_selection_strategy:J.toolSelectionStrategy??"passthrough",tool_selection_mode:J.toolSelectionMode??"inclusion",icon:J.icon??null,status:J.status??"active",is_default:0,created_at:G,updated_at:G,created_by:Q,updated_by:null}).execute(),J.connections.length>0)await this.db.insertInto("gateway_connections").values(J.connections.map((W)=>({id:u$("gwc"),gateway_id:Y,connection_id:W.connectionId,selected_tools:W.selectedTools?JSON.stringify(W.selectedTools):null,selected_resources:W.selectedResources?JSON.stringify(W.selectedResources):null,selected_prompts:W.selectedPrompts?JSON.stringify(W.selectedPrompts):null,created_at:G}))).execute();let $=await this.findById(Y);if(!$)throw Error(`Failed to create gateway with id: ${Y}`);return $}async findById(X){return this.findByIdInternal(this.db,X)}async findByIdInternal(X,Q){let J=await X.selectFrom("gateways").selectAll().where("id","=",Q).executeTakeFirst();if(!J)return null;let Y=await X.selectFrom("gateway_connections").selectAll().where("gateway_id","=",Q).execute();return this.deserializeGatewayWithConnections(J,Y)}async list(X){let Q=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",X).execute(),J=Q.map(($)=>$.id);if(J.length===0)return[];let Y=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",J).execute(),G=new Map;for(let $ of Y){let W=G.get($.gateway_id)??[];W.push($),G.set($.gateway_id,W)}return Q.map(($)=>this.deserializeGatewayWithConnections($,G.get($.id)??[]))}async listByConnectionId(X,Q){let Y=(await this.db.selectFrom("gateway_connections").select("gateway_id").where("connection_id","=",Q).execute()).map((K)=>K.gateway_id);if(Y.length===0)return[];let G=await this.db.selectFrom("gateways").selectAll().where("id","in",Y).where("organization_id","=",X).execute();if(G.length===0)return[];let $=G.map((K)=>K.id),W=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",$).execute(),H=new Map;for(let K of W){let Z=H.get(K.gateway_id)??[];Z.push(K),H.set(K.gateway_id,Z)}return G.map((K)=>this.deserializeGatewayWithConnections(K,H.get(K.id)??[]))}async update(X,Q,J){let Y=new Date().toISOString(),G={updated_at:Y,updated_by:Q};if(J.title!==void 0)G.title=J.title;if(J.description!==void 0)G.description=J.description;if(J.toolSelectionStrategy!==void 0)G.tool_selection_strategy=J.toolSelectionStrategy;if(J.toolSelectionMode!==void 0)G.tool_selection_mode=J.toolSelectionMode;if(J.icon!==void 0)G.icon=J.icon;if(J.status!==void 0)G.status=J.status;if(J.isDefault===!1)G.is_default=0;if(J.isDefault===!0)G.is_default=1;if(J.isDefault===!0){let W=await this.findById(X);if(!W)throw Error(`Gateway not found: ${X}`);await this.db.transaction().execute(async(H)=>{if(await H.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:Q}).where("organization_id","=",W.organizationId).where("is_default","=",1).execute(),await H.updateTable("gateways").set(G).where("id","=",X).execute(),J.connections!==void 0){if(await H.deleteFrom("gateway_connections").where("gateway_id","=",X).execute(),J.connections.length>0)await H.insertInto("gateway_connections").values(J.connections.map((K)=>({id:u$("gwc"),gateway_id:X,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,selected_resources:K.selectedResources?JSON.stringify(K.selectedResources):null,selected_prompts:K.selectedPrompts?JSON.stringify(K.selectedPrompts):null,created_at:Y}))).execute()}})}else if(await this.db.updateTable("gateways").set(G).where("id","=",X).execute(),J.connections!==void 0){if(await this.db.deleteFrom("gateway_connections").where("gateway_id","=",X).execute(),J.connections.length>0)await this.db.insertInto("gateway_connections").values(J.connections.map((W)=>({id:u$("gwc"),gateway_id:X,connection_id:W.connectionId,selected_tools:W.selectedTools?JSON.stringify(W.selectedTools):null,selected_resources:W.selectedResources?JSON.stringify(W.selectedResources):null,selected_prompts:W.selectedPrompts?JSON.stringify(W.selectedPrompts):null,created_at:Y}))).execute()}let $=await this.findById(X);if(!$)throw Error("Gateway not found after update");return $}async delete(X){await this.db.deleteFrom("gateways").where("id","=",X).execute()}async getDefaultByOrgId(X){let Q=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",X).where("is_default","=",1).executeTakeFirst();if(!Q)return null;let J=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","=",Q.id).execute();return this.deserializeGatewayWithConnections(Q,J)}async getDefaultByOrgSlug(X){let Q=await this.db.selectFrom("organization").select("id").where("slug","=",X).executeTakeFirst();if(!Q)return null;return this.getDefaultByOrgId(Q.id)}async setDefault(X,Q){let J=await this.findById(X);if(!J)throw Error(`Gateway not found: ${X}`);let Y=new Date().toISOString();await this.db.transaction().execute(async($)=>{await $.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:Q}).where("organization_id","=",J.organizationId).where("is_default","=",1).execute(),await $.updateTable("gateways").set({is_default:1,updated_at:Y,updated_by:Q}).where("id","=",X).execute()});let G=await this.findById(X);if(!G)throw Error("Gateway not found after setting default");return G}deserializeGatewayWithConnections(X,Q){return{...this.deserializeGateway(X),connections:Q.map((Y)=>({connectionId:Y.connection_id,selectedTools:this.parseJson(Y.selected_tools),selectedResources:this.parseJson(Y.selected_resources),selectedPrompts:this.parseJson(Y.selected_prompts)}))}}deserializeGateway(X){return{id:X.id,organizationId:X.organization_id,title:X.title,description:X.description,toolSelectionStrategy:this.parseToolSelectionStrategy(X.tool_selection_strategy),toolSelectionMode:this.parseToolSelectionMode(X.tool_selection_mode),icon:X.icon,status:X.status,isDefault:X.is_default===1,createdAt:X.created_at,updatedAt:X.updated_at,createdBy:X.created_by,updatedBy:X.updated_by}}parseToolSelectionStrategy(X){if(X==="smart_tool_selection")return"smart_tool_selection";if(X==="code_execution")return"code_execution";return"passthrough"}parseToolSelectionMode(X){if(X==="exclusion")return"exclusion";return"inclusion"}parseJson(X){if(X===null)return null;if(typeof X==="string")try{return JSON.parse(X)}catch{return null}return X}}LP();d0();function F64(X){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (FZ0(),ZZ0));return Q.map((J)=>{return{name:J.name,inputSchema:N.toJSONSchema(J.inputSchema,{unrepresentable:"any"}),outputSchema:J.outputSchema?N.toJSONSchema(J.outputSchema,{unrepresentable:"any"}):void 0,description:J.description}})},data:c10(process.env.BASE_URL||"http://localhost:3000")},{data:p10()},{data:d10(X)}]}async function VZ0(X,Q){try{let J=Uq(),Y=new Fb(process.env.ENCRYPTION_KEY||""),G=new Vb(J.db,Y),$=new qb(J.db),W=F64(X),H=[];await Promise.all(W.map(async(K)=>{let Z=null;if(K.permissions)Z=(await LZ.api.createApiKey({body:{name:`${K.data.app_name??crypto.randomUUID()}-mcp`,userId:Q,permissions:K.permissions,rateLimitEnabled:!1,metadata:{organization:{id:X},purpose:"default-org-connections"}}}))?.key;let F=await K.getTools?.()??await XZ({id:"pending",title:K.data.title,connection_type:K.data.connection_type,connection_url:K.data.connection_url,connection_token:K.data.connection_token,connection_headers:K.data.connection_headers}).catch(()=>null),V=K.data.id?`${X}_${K.data.id}`:void 0,q=await G.create({...K.data,id:V,tools:F,organization_id:X,created_by:Q,connection_token:K.data.connection_token??Z});H.push(q.id)})),await $.create(X,Q,{title:"Default Hub",description:"Auto-created Hub for organization",toolSelectionStrategy:"passthrough",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:H.map((K)=>({connectionId:K}))})}catch(J){console.error("Error creating default MCP connections:",J)}}var qZ0=["owner","admin"];var V64=(X)=>{return{defaultSSO:[{domain:X.domain,providerId:X.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:X.MS_CLIENT_ID,clientSecret:X.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:X.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},UZ0=(X)=>{if(X.providerId==="microsoft")return V64(X);throw Error(`Unsupported provider: ${X.providerId}`)};function q64(X){return X.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var zZ0=["labs","hub","studio","workspace","systems","core","cloud","works"],BZ0=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function U64(){let X=Math.floor(Math.random()*BZ0.length),Q=Math.floor(Math.random()*zZ0.length),J=BZ0[X]??"deco",Y=zZ0[Q]??"studio";return`${J}-${Y}`}var z64=Object.values(bR()).map((X)=>X.map((Q)=>Q.name)).flat(),B64={...nO,self:["*",...z64]},bP=FY(B64),L64=bP.newRole({self:["*"],...aV.statements}),D64=bP.newRole({self:["*"],...aV.statements}),j64=bP.newRole({self:["*"],...aV.statements}),LZ0=Object.values(bR()).map((X)=>X.map((Q)=>`self:${Q.name}`)).flat(),$J=T_.auth,DZ0=void 0;if($J.inviteEmailProviderId&&$J.emailProviders&&$J.emailProviders.length>0){let X=Nw($J.emailProviders,$J.inviteEmailProviderId);if(X){let Q=jw(X);DZ0=async(J)=>{let Y=J.inviter.user?.name||J.inviter.user?.email,G=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${J.invitation.id}`;await Q({to:J.email,subject:`Invitation to join ${J.organization.name}`,html:`
988
+ </html>`},P_=(X)=>{let Q=X?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:O0("/open-api/generate-schema",{method:"GET"},async(J)=>{let Y=await W60(J.context,J.context.options);return J.json(Y)}),openAPIReference:O0(Q,{method:"GET",metadata:{isAction:!1}},async(J)=>{if(X?.disableDefaultReference)throw new h("NOT_FOUND");let Y=await W60(J.context,J.context.options);return new Response(ny0(Y,X?.theme,X?.nonce),{headers:{"Content-Type":"text/html"}})})}}};PX();k9();e8();v1();d0();var rT4=P6(async()=>{return{}}),aT4=P6({use:[O8]},async(X)=>{return{session:X.context.session}}),oT4=r6({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role"});var sT4=Number.POSITIVE_INFINITY;var K60=w(),ry0=o0(["pending","accepted","rejected","canceled"]).default("pending"),tT4=b({id:w().default(Z1),name:w(),slug:w(),logo:w().nullish().optional(),metadata:v0(w(),I6()).or(w().transform((X)=>JSON.parse(X))).optional(),createdAt:E4()}),eT4=b({id:w().default(Z1),organizationId:w(),userId:j4.string(),role:K60,createdAt:E4().default(()=>new Date)}),XA4=b({id:w().default(Z1),organizationId:w(),email:w(),role:K60,status:ry0,teamId:w().nullish(),inviterId:w(),expiresAt:E4(),createdAt:E4().default(()=>new Date)}),QA4=b({id:w().default(Z1),name:w().min(1),organizationId:w(),createdAt:E4(),updatedAt:E4().optional()}),JA4=b({id:w().default(Z1),teamId:w(),userId:w(),createdAt:E4().default(()=>new Date)}),YA4=b({id:w().default(Z1),organizationId:w(),role:w(),permission:v0(w(),Z0(w())),createdAt:E4().default(()=>new Date),updatedAt:E4().optional()}),H60=["admin","member","owner"],GA4=I4([o0(H60),Z0(o0(H60))]);M8();e8();v1();var zA4=r6({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});M8();TX();e8();v1();A1();Z8();var ay0=r6({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});e8();v1();var oy0=r6({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var FK={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as Z60,readFileSync as F60}from"fs";var Ww={emailAndPassword:{enabled:!0}},V60=process.env.CONFIG_PATH||"./config.json",q60=process.env.AUTH_CONFIG_PATH||"./auth-config.json";function sy0(){if(Z60(V60))try{let X=F60(V60,"utf-8"),Q=JSON.parse(X);return{auth:Ww,monitoring:FK,...Q}}catch{return{auth:Ww,monitoring:FK}}if(Z60(q60))try{let X=F60(q60,"utf-8");return{auth:JSON.parse(X),monitoring:FK}}catch{return{auth:Ww,monitoring:FK}}return{auth:Ww,monitoring:FK}}var T_=sy0();import{existsSync as lx0,mkdirSync as dx0}from"fs";import{Kysely as _10,PostgresDialect as b10,sql as k10}from"kysely";import{BunWorkerDialect as y10}from"kysely-bun-worker";import*as f10 from"path";var uJ=WJ(Qb(),1),U24=uJ.default.Client,$b=uJ.default.Pool,z24=uJ.default.Connection,B24=uJ.default.types,L24=uJ.default.Query,D24=uJ.default.DatabaseError,j24=uJ.default.escapeIdentifier,N24=uJ.default.escapeLiteral,O24=uJ.default.Result,w24=uJ.default.TypeOverrides,M24=uJ.default.defaults;function px0(X){let Q=new $b({connectionString:X.connectionString,max:X.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1}),J=new b10({pool:Q});return{type:"postgres",db:new _10({dialect:J}),pool:Q}}function h10(X){if(X===":memory:")return":memory:";if(X.includes("://"))return new URL(X).pathname;return X}function g10(X){if(X!==":memory:"&&X!=="/"&&X){let Q=X.substring(0,X.lastIndexOf("/"));if(Q&&Q!=="/"&&!lx0(Q))try{dx0(Q,{recursive:!0})}catch{return console.warn(`Failed to create directory ${Q}, using in-memory database`),":memory:"}}return X}function cx0(X){let Q=h10(X.connectionString);Q=g10(Q);let J=new y10({url:Q||":memory:"}),Y=new _10({dialect:J});if(Q!==":memory:"&&X.options?.enableWAL!==!1)k10`PRAGMA journal_mode = WAL;`.execute(Y).catch(()=>{});if(Q!==":memory:"){let G=X.options?.busyTimeout||5000;k10`PRAGMA busy_timeout = ${G};`.execute(Y).catch(()=>{})}return{type:"sqlite",db:Y}}function x10(X){let Q=X||"file:./data/mesh.db";if(Q===":memory:")return{type:"sqlite",connectionString:":memory:"};Q=Q.startsWith("/")?`file://${Q}`:Q;let J=URL.canParse(Q)?new URL(Q):null,Y=J?.protocol.replace(":","")??Q.split("://")[0];switch(Y){case"postgres":case"postgresql":return{type:"postgres",connectionString:Q};case"sqlite":case"file":if(!J?.pathname)throw Error("Invalid database URL: "+Q);return{type:"sqlite",connectionString:J.pathname};default:throw Error(`Unsupported database protocol: ${Y}. Supported protocols: postgres://, postgresql://, sqlite://, file://`)}}function Hb(){return process.env.DATABASE_URL||`file:${f10.join(process.cwd(),"data/mesh.db")}`}function u10(X){let Q=x10(X);if(Q.type==="postgres")return new b10({pool:new $b({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1})});let J=h10(Q.connectionString);return J=g10(J),new y10({url:J||":memory:"})}function nx0(X){let Q=x10(X);if(Q.type==="postgres")return px0(Q);return cx0(Q)}async function m10(X){if(await X.db.destroy(),X.type==="postgres"&&!X.pool.ended)await X.pool.end()}var Wb=null;function Uq(){if(!Wb)Wb=nx0(Hb());return Wb}class Kb{apiKey;constructor(X){this.apiKey=X}async sendEmail({to:X,from:Q,subject:J,html:Y}){let G=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:X,from:Q,subject:J,html:Y})});if(!G.ok)throw Error(`Failed to send email: ${G.statusText}`)}}class Zb{apiKey;constructor(X){this.apiKey=X}async sendEmail({to:X,from:Q,subject:J,html:Y}){let G=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:X}]}],from:{email:Q},subject:J,content:[{type:"text/html",value:Y}]})});if(!G.ok){let $=await G.text();throw Error(`Failed to send email via SendGrid: ${G.statusText} - ${$}`)}}}var ix0=(X)=>{let Q=new Kb(X.config.apiKey);return async({to:J,subject:Y,html:G})=>{await Q.sendEmail({to:J,from:X.config.fromEmail,subject:Y,html:G})}},rx0=(X)=>{let Q=new Zb(X.config.apiKey);return async({to:J,subject:Y,html:G})=>{await Q.sendEmail({to:J,from:X.config.fromEmail,subject:Y,html:G})}},ax0={resend:ix0,sendgrid:rx0};function jw(X){let Q=ax0[X.provider];if(!Q)throw Error(`Unknown email provider: ${X.provider}`);return Q(X)}function Nw(X,Q){return X.find((J)=>J.id===Q)}var l10=(X,Q)=>{let J=Nw(Q,X.emailProviderId);if(!J)throw Error(`Email provider with id '${X.emailProviderId}' not found`);let Y=jw(J);return{sendMagicLink:async({email:G,url:$})=>{await Y({to:G,subject:"Magic Link",html:`<p>Click <a href="${$}">here</a> to login</p>`})}}};ww();import{createCipheriv as ox0,createDecipheriv as sx0,randomBytes as n10}from"crypto";var i10="aes-256-gcm",zq=16,r10=16,a10=32;class Fb{key;constructor(X){if(Buffer.from(X,"base64").length===a10)this.key=Buffer.from(X,"base64");else{let Q=G4("crypto");this.key=Q.createHash("sha256").update(X).digest()}}async encrypt(X){let Q=n10(zq),J=ox0(i10,this.key,Q),Y=J.update(X,"utf8");Y=Buffer.concat([Y,J.final()]);let G=J.getAuthTag();return Buffer.concat([Q,G,Y]).toString("base64")}async decrypt(X){let Q=Buffer.from(X,"base64"),J=Q.subarray(0,zq),Y=Q.subarray(zq,zq+r10),G=Q.subarray(zq+r10),$=sx0(i10,this.key,J);$.setAuthTag(Y);let W=$.update(G);return W=Buffer.concat([W,$.final()]),W.toString("utf8")}static generateKey(){return n10(a10).toString("base64")}}x$();import{webcrypto as e10}from"crypto";var t10="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ju0=128,gW,OK;function Yu0(X){if(!gW||gW.length<X)gW=Buffer.allocUnsafe(X*Ju0),e10.getRandomValues(gW),OK=0;else if(OK+X>gW.length)e10.getRandomValues(gW),OK=0;OK+=X}function XX0(X=21){Yu0(X|=0);let Q="";for(let J=OK-X;J<OK;J++)Q+=t10[gW[J]&63];return Q}function u$(X){return`${X}_${XX0()}`}var Gu0=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class Vb{db;vault;constructor(X,Q){this.db=X;this.vault=Q}async create(X){let Q=X.id??u$("conn"),J=new Date().toISOString(),Y=await this.findById(Q);if(Y){if(Y.organization_id!==X.organization_id)throw Error("Connection ID already exists");return this.update(Q,X)}let G=await this.serializeConnection({...X,id:X.id??Q,status:"active",created_at:J,updated_at:J});await this.db.insertInto("connections").values(G).execute();let $=await this.findById(Q);if(!$)throw Error(`Failed to create connection with id: ${Q}`);return $}async findById(X,Q){let J=this.db.selectFrom("connections").selectAll().where("id","=",X);if(Q)J=J.where("organization_id","=",Q);let Y=await J.executeTakeFirst();return Y?this.deserializeConnection(Y):null}async list(X){let Q=await this.db.selectFrom("connections").selectAll().where("organization_id","=",X).execute();return Promise.all(Q.map((J)=>this.deserializeConnection(J)))}async update(X,Q){if(Object.keys(Q).length===0){let G=await this.findById(X);if(!G)throw Error("Connection not found");return G}let J=await this.serializeConnection({...Q,updated_at:new Date().toISOString()});await this.db.updateTable("connections").set(J).where("id","=",X).execute();let Y=await this.findById(X);if(!Y)throw Error("Connection not found after update");return Y}async delete(X){await this.db.deleteFrom("connections").where("id","=",X).execute()}async testConnection(X,Q){let J=await this.findById(X);if(!J)throw Error("Connection not found");let Y=Date.now();if(J.connection_type==="STDIO")return{healthy:!0,latencyMs:Date.now()-Y};if(!J.connection_url)return{healthy:!1,latencyMs:Date.now()-Y};try{let G=J.connection_headers,$=await fetch(J.connection_url,{method:"POST",headers:{"Content-Type":"application/json",...J.connection_token&&{Authorization:`Bearer ${J.connection_token}`},...G?.headers,...Q},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:$.ok||$.status===404,latencyMs:Date.now()-Y}}catch{return{healthy:!1,latencyMs:Date.now()-Y}}}async serializeConnection(X){let Q={};for(let[J,Y]of Object.entries(X)){if(Y===void 0)continue;if(J==="connection_token"&&Y)Q[J]=await this.vault.encrypt(Y);else if(J==="configuration_state"&&Y){let G=JSON.stringify(Y);Q[J]=await this.vault.encrypt(G)}else if(J==="connection_headers"&&Y){let G=Y;if(Bq(G)&&G.envVars){let $={};for(let[W,H]of Object.entries(G.envVars))$[W]=await this.vault.encrypt(H);Q[J]=JSON.stringify({...G,envVars:$})}else Q[J]=JSON.stringify(G)}else if(Gu0.includes(J))Q[J]=Y?JSON.stringify(Y):null;else Q[J]=Y}return Q}async deserializeConnection(X){let Q=null;if(X.connection_token)try{Q=await this.vault.decrypt(X.connection_token)}catch($){console.error("Failed to decrypt connection token:",$)}let J=null;if(X.configuration_state)try{let $=await this.vault.decrypt(X.configuration_state);J=JSON.parse($)}catch($){console.error("Failed to decrypt configuration state:",$)}let Y=null;if(X.connection_headers)try{let $=JSON.parse(X.connection_headers);if(Bq($)&&$.envVars){let W={};for(let[H,K]of Object.entries($.envVars))try{W[H]=await this.vault.decrypt(K)}catch{W[H]=K}Y={...$,envVars:W}}else Y=$}catch($){console.error("Failed to parse connection_headers:",$)}let G=($)=>{if($===null)return null;if(typeof $==="string")try{return JSON.parse($)}catch{return null}return $};return{id:X.id,organization_id:X.organization_id,created_by:X.created_by,title:X.title,description:X.description,icon:X.icon,app_name:X.app_name,app_id:X.app_id,connection_type:X.connection_type,connection_url:X.connection_url,connection_token:Q,connection_headers:Y,oauth_config:G(X.oauth_config),configuration_state:J,configuration_scopes:G(X.configuration_scopes),metadata:G(X.metadata),tools:G(X.tools),bindings:G(X.bindings),status:X.status,created_at:X.created_at,updated_at:X.updated_at}}}class qb{db;constructor(X){this.db=X}async create(X,Q,J){let Y=u$("gw"),G=new Date().toISOString();if(J.isDefault)return await this.db.transaction().execute(async(W)=>{if(await W.updateTable("gateways").set({is_default:0,updated_at:G,updated_by:Q}).where("organization_id","=",X).where("is_default","=",1).execute(),await W.insertInto("gateways").values({id:Y,organization_id:X,title:J.title,description:J.description??null,tool_selection_strategy:J.toolSelectionStrategy??"passthrough",tool_selection_mode:J.toolSelectionMode??"inclusion",icon:J.icon??null,status:J.status??"active",is_default:1,created_at:G,updated_at:G,created_by:Q,updated_by:null}).execute(),J.connections.length>0)await W.insertInto("gateway_connections").values(J.connections.map((K)=>({id:u$("gwc"),gateway_id:Y,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,selected_resources:K.selectedResources?JSON.stringify(K.selectedResources):null,selected_prompts:K.selectedPrompts?JSON.stringify(K.selectedPrompts):null,created_at:G}))).execute();let H=await this.findByIdInternal(W,Y);if(!H)throw Error(`Failed to create gateway with id: ${Y}`);return H});if(await this.db.insertInto("gateways").values({id:Y,organization_id:X,title:J.title,description:J.description??null,tool_selection_strategy:J.toolSelectionStrategy??"passthrough",tool_selection_mode:J.toolSelectionMode??"inclusion",icon:J.icon??null,status:J.status??"active",is_default:0,created_at:G,updated_at:G,created_by:Q,updated_by:null}).execute(),J.connections.length>0)await this.db.insertInto("gateway_connections").values(J.connections.map((W)=>({id:u$("gwc"),gateway_id:Y,connection_id:W.connectionId,selected_tools:W.selectedTools?JSON.stringify(W.selectedTools):null,selected_resources:W.selectedResources?JSON.stringify(W.selectedResources):null,selected_prompts:W.selectedPrompts?JSON.stringify(W.selectedPrompts):null,created_at:G}))).execute();let $=await this.findById(Y);if(!$)throw Error(`Failed to create gateway with id: ${Y}`);return $}async findById(X){return this.findByIdInternal(this.db,X)}async findByIdInternal(X,Q){let J=await X.selectFrom("gateways").selectAll().where("id","=",Q).executeTakeFirst();if(!J)return null;let Y=await X.selectFrom("gateway_connections").selectAll().where("gateway_id","=",Q).execute();return this.deserializeGatewayWithConnections(J,Y)}async list(X){let Q=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",X).execute(),J=Q.map(($)=>$.id);if(J.length===0)return[];let Y=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",J).execute(),G=new Map;for(let $ of Y){let W=G.get($.gateway_id)??[];W.push($),G.set($.gateway_id,W)}return Q.map(($)=>this.deserializeGatewayWithConnections($,G.get($.id)??[]))}async listByConnectionId(X,Q){let Y=(await this.db.selectFrom("gateway_connections").select("gateway_id").where("connection_id","=",Q).execute()).map((K)=>K.gateway_id);if(Y.length===0)return[];let G=await this.db.selectFrom("gateways").selectAll().where("id","in",Y).where("organization_id","=",X).execute();if(G.length===0)return[];let $=G.map((K)=>K.id),W=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",$).execute(),H=new Map;for(let K of W){let Z=H.get(K.gateway_id)??[];Z.push(K),H.set(K.gateway_id,Z)}return G.map((K)=>this.deserializeGatewayWithConnections(K,H.get(K.id)??[]))}async update(X,Q,J){let Y=new Date().toISOString(),G={updated_at:Y,updated_by:Q};if(J.title!==void 0)G.title=J.title;if(J.description!==void 0)G.description=J.description;if(J.toolSelectionStrategy!==void 0)G.tool_selection_strategy=J.toolSelectionStrategy;if(J.toolSelectionMode!==void 0)G.tool_selection_mode=J.toolSelectionMode;if(J.icon!==void 0)G.icon=J.icon;if(J.status!==void 0)G.status=J.status;if(J.isDefault===!1)G.is_default=0;if(J.isDefault===!0)G.is_default=1;if(J.isDefault===!0){let W=await this.findById(X);if(!W)throw Error(`Gateway not found: ${X}`);await this.db.transaction().execute(async(H)=>{if(await H.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:Q}).where("organization_id","=",W.organizationId).where("is_default","=",1).execute(),await H.updateTable("gateways").set(G).where("id","=",X).execute(),J.connections!==void 0){if(await H.deleteFrom("gateway_connections").where("gateway_id","=",X).execute(),J.connections.length>0)await H.insertInto("gateway_connections").values(J.connections.map((K)=>({id:u$("gwc"),gateway_id:X,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,selected_resources:K.selectedResources?JSON.stringify(K.selectedResources):null,selected_prompts:K.selectedPrompts?JSON.stringify(K.selectedPrompts):null,created_at:Y}))).execute()}})}else if(await this.db.updateTable("gateways").set(G).where("id","=",X).execute(),J.connections!==void 0){if(await this.db.deleteFrom("gateway_connections").where("gateway_id","=",X).execute(),J.connections.length>0)await this.db.insertInto("gateway_connections").values(J.connections.map((W)=>({id:u$("gwc"),gateway_id:X,connection_id:W.connectionId,selected_tools:W.selectedTools?JSON.stringify(W.selectedTools):null,selected_resources:W.selectedResources?JSON.stringify(W.selectedResources):null,selected_prompts:W.selectedPrompts?JSON.stringify(W.selectedPrompts):null,created_at:Y}))).execute()}let $=await this.findById(X);if(!$)throw Error("Gateway not found after update");return $}async delete(X){await this.db.deleteFrom("gateways").where("id","=",X).execute()}async getDefaultByOrgId(X){let Q=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",X).where("is_default","=",1).executeTakeFirst();if(!Q)return null;let J=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","=",Q.id).execute();return this.deserializeGatewayWithConnections(Q,J)}async getDefaultByOrgSlug(X){let Q=await this.db.selectFrom("organization").select("id").where("slug","=",X).executeTakeFirst();if(!Q)return null;return this.getDefaultByOrgId(Q.id)}async setDefault(X,Q){let J=await this.findById(X);if(!J)throw Error(`Gateway not found: ${X}`);let Y=new Date().toISOString();await this.db.transaction().execute(async($)=>{await $.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:Q}).where("organization_id","=",J.organizationId).where("is_default","=",1).execute(),await $.updateTable("gateways").set({is_default:1,updated_at:Y,updated_by:Q}).where("id","=",X).execute()});let G=await this.findById(X);if(!G)throw Error("Gateway not found after setting default");return G}deserializeGatewayWithConnections(X,Q){return{...this.deserializeGateway(X),connections:Q.map((Y)=>({connectionId:Y.connection_id,selectedTools:this.parseJson(Y.selected_tools),selectedResources:this.parseJson(Y.selected_resources),selectedPrompts:this.parseJson(Y.selected_prompts)}))}}deserializeGateway(X){return{id:X.id,organizationId:X.organization_id,title:X.title,description:X.description,toolSelectionStrategy:this.parseToolSelectionStrategy(X.tool_selection_strategy),toolSelectionMode:this.parseToolSelectionMode(X.tool_selection_mode),icon:X.icon,status:X.status,isDefault:X.is_default===1,createdAt:X.created_at,updatedAt:X.updated_at,createdBy:X.created_by,updatedBy:X.updated_by}}parseToolSelectionStrategy(X){if(X==="smart_tool_selection")return"smart_tool_selection";if(X==="code_execution")return"code_execution";return"passthrough"}parseToolSelectionMode(X){if(X==="exclusion")return"exclusion";return"inclusion"}parseJson(X){if(X===null)return null;if(typeof X==="string")try{return JSON.parse(X)}catch{return null}return X}}LP();d0();function F64(X){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (FZ0(),ZZ0));return Q.map((J)=>{return{name:J.name,inputSchema:N.toJSONSchema(J.inputSchema,{unrepresentable:"any"}),outputSchema:J.outputSchema?N.toJSONSchema(J.outputSchema,{unrepresentable:"any"}):void 0,description:J.description}})},data:c10(process.env.BASE_URL||"http://localhost:3000")},{data:p10()},{data:d10(X)}]}async function VZ0(X,Q){try{let J=Uq(),Y=new Fb(process.env.ENCRYPTION_KEY||""),G=new Vb(J.db,Y),$=new qb(J.db),W=F64(X),H=[];await Promise.all(W.map(async(K)=>{let Z=null;if(K.permissions)Z=(await LZ.api.createApiKey({body:{name:`${K.data.app_name??crypto.randomUUID()}-mcp`,userId:Q,permissions:K.permissions,rateLimitEnabled:!1,metadata:{organization:{id:X},purpose:"default-org-connections"}}}))?.key;let F=await K.getTools?.()??await XZ({id:"pending",title:K.data.title,connection_type:K.data.connection_type,connection_url:K.data.connection_url,connection_token:K.data.connection_token,connection_headers:K.data.connection_headers}).catch(()=>null),V=K.data.id?K.data.id.startsWith(`${X}_`)?K.data.id:`${X}_${K.data.id}`:void 0,q=await G.create({...K.data,id:V,tools:F,organization_id:X,created_by:Q,connection_token:K.data.connection_token??Z});H.push(q.id)})),await $.create(X,Q,{title:"Default Hub",description:"Auto-created Hub for organization",toolSelectionStrategy:"passthrough",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:H.map((K)=>({connectionId:K}))})}catch(J){console.error("Error creating default MCP connections:",J)}}var qZ0=["owner","admin"];var V64=(X)=>{return{defaultSSO:[{domain:X.domain,providerId:X.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:X.MS_CLIENT_ID,clientSecret:X.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${X.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:X.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},UZ0=(X)=>{if(X.providerId==="microsoft")return V64(X);throw Error(`Unsupported provider: ${X.providerId}`)};function q64(X){return X.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var zZ0=["labs","hub","studio","workspace","systems","core","cloud","works"],BZ0=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function U64(){let X=Math.floor(Math.random()*BZ0.length),Q=Math.floor(Math.random()*zZ0.length),J=BZ0[X]??"deco",Y=zZ0[Q]??"studio";return`${J}-${Y}`}var z64=Object.values(bR()).map((X)=>X.map((Q)=>Q.name)).flat(),B64={...nO,self:["*",...z64]},bP=FY(B64),L64=bP.newRole({self:["*"],...aV.statements}),D64=bP.newRole({self:["*"],...aV.statements}),j64=bP.newRole({self:["*"],...aV.statements}),LZ0=Object.values(bR()).map((X)=>X.map((Q)=>`self:${Q.name}`)).flat(),$J=T_.auth,DZ0=void 0;if($J.inviteEmailProviderId&&$J.emailProviders&&$J.emailProviders.length>0){let X=Nw($J.emailProviders,$J.inviteEmailProviderId);if(X){let Q=jw(X);DZ0=async(J)=>{let Y=J.inviter.user?.name||J.inviter.user?.email,G=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${J.invitation.id}`;await Q({to:J.email,subject:`Invitation to join ${J.organization.name}`,html:`
989
989
  <h2>You've been invited!</h2>
990
990
  <p>${Y} has invited you to join <strong>${J.organization.name}</strong>.</p>
991
991
  <p><a href="${G}">Click here to accept the invitation</a></p>