everyapp 0.2.1 → 0.3.0-rc.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 (120) hide show
  1. package/README.md +6 -77
  2. package/bin/everyapp.js +235 -0
  3. package/dist/access-F3GKBKAW.js +1 -0
  4. package/dist/activity-4MFMH5JP.js +12 -0
  5. package/dist/apps-63K2DGVT.js +9 -0
  6. package/dist/chunk-2UFJRKEE.js +4 -0
  7. package/dist/chunk-3AAHHUJC.js +11 -0
  8. package/dist/chunk-3Z53CH4F.js +6 -0
  9. package/dist/chunk-5ZTFC6DK.js +1 -0
  10. package/dist/chunk-6O3GJS5H.js +15 -0
  11. package/dist/chunk-74EST4VW.js +2 -0
  12. package/dist/chunk-7LG3F4FF.js +10 -0
  13. package/dist/chunk-AUDGOIHE.js +1 -0
  14. package/dist/chunk-BHMRY53V.js +2 -0
  15. package/dist/chunk-DQWOXSL3.js +32 -0
  16. package/dist/chunk-E3EPK27P.js +10 -0
  17. package/dist/chunk-E7EUXUVD.js +1 -0
  18. package/dist/chunk-ECLJ5IAL.js +126 -0
  19. package/dist/chunk-EQX4GKJ2.js +4 -0
  20. package/dist/chunk-EUNGJMJ6.js +20 -0
  21. package/dist/chunk-F6IH47GT.js +4 -0
  22. package/dist/chunk-G64S77GC.js +33 -0
  23. package/dist/chunk-GD2JZMD3.js +1 -0
  24. package/dist/chunk-GRFPP4UW.js +7 -0
  25. package/dist/chunk-IA534DGW.js +10 -0
  26. package/dist/chunk-IG26HYRR.js +45 -0
  27. package/dist/chunk-IZEOAOKL.js +6 -0
  28. package/dist/chunk-JYKRUS5C.js +1 -0
  29. package/dist/chunk-KMAOZRV4.js +18 -0
  30. package/dist/chunk-MC56CUQI.js +7 -0
  31. package/dist/chunk-MDORVBPD.js +1 -0
  32. package/dist/chunk-N4E5YE4X.js +5 -0
  33. package/dist/chunk-NJFWEYX7.js +1 -0
  34. package/dist/chunk-OEOVNJAN.js +1 -0
  35. package/dist/chunk-OVKVV6MK.js +2 -0
  36. package/dist/chunk-PL6EORDJ.js +15 -0
  37. package/dist/chunk-PMPIMHKG.js +6 -0
  38. package/dist/chunk-QZWSSWMP.js +22 -0
  39. package/dist/chunk-R4CGF622.js +2 -0
  40. package/dist/chunk-RFVMR32Y.js +1 -0
  41. package/dist/chunk-RQFHVU3Y.js +25 -0
  42. package/dist/chunk-SAT3PGZU.js +57 -0
  43. package/dist/chunk-SPPR6WCI.js +1 -0
  44. package/dist/chunk-TPWSGRNT.js +30 -0
  45. package/dist/chunk-VVQRET35.js +2 -0
  46. package/dist/chunk-VXJQGJ7Y.js +2 -0
  47. package/dist/chunk-WEM3WLOC.js +1 -0
  48. package/dist/chunk-Y3VIFPN5.js +1 -0
  49. package/dist/chunk-YJBYZWSP.js +22 -0
  50. package/dist/chunk-ZYL2ZHCF.js +98 -0
  51. package/dist/configure-2KMHM22T.js +8 -0
  52. package/dist/create-ELEJMZBS.js +22 -0
  53. package/dist/db-MZIAKGBN.js +9 -0
  54. package/dist/delete-H47KPJSB.js +3 -0
  55. package/dist/deploy-HGFJLLUO.js +1 -0
  56. package/dist/dev-62VA7UEM.js +86 -0
  57. package/dist/email-NNFD3VVB.js +10 -0
  58. package/dist/events-JDY76EG6.js +15 -0
  59. package/dist/groups-NQFXDZZP.js +8 -0
  60. package/dist/index.js +92 -1
  61. package/dist/install-JTZWRZIL.js +1 -0
  62. package/dist/login-P6LYQQWP.js +1 -0
  63. package/dist/mcp-NCFWEBMD.js +1 -0
  64. package/dist/provider-WVBI2VED.js +13 -0
  65. package/dist/release-6FYSPXXA.js +1 -0
  66. package/dist/restore-XBU7DOJV.js +3 -0
  67. package/dist/secret-ML5EXS3O.js +1 -0
  68. package/dist/setup-IEXCISLP.js +1 -0
  69. package/dist/status-OPLPKJ4U.js +4 -0
  70. package/dist/teardown-3JMMLK6O.js +22 -0
  71. package/dist/update-37ZDATLR.js +1 -0
  72. package/dist/workspace-DAFZVYQ2.js +21 -0
  73. package/package.json +30 -27
  74. package/skills/build-every-app/SKILL.md +199 -0
  75. package/skills/build-every-app/patterns.md +134 -0
  76. package/skills/everyapp/SKILL.md +292 -0
  77. package/skills/everyapp/mcp.md +336 -0
  78. package/skills/everyapp/security-review.md +61 -0
  79. package/skills/everyapp/setup/README.md +263 -0
  80. package/skills/everyapp/setup/access.md +178 -0
  81. package/skills/everyapp/setup/context.md +117 -0
  82. package/skills/everyapp/setup/dataforseo.md +287 -0
  83. package/skills/everyapp/setup/email.md +366 -0
  84. package/skills/everyapp/setup/gateway.md +243 -0
  85. package/skills/everyapp/setup/google.md +360 -0
  86. package/skills/everyapp/setup/microsoft-365.md +281 -0
  87. package/skills/everyapp/setup/openai.md +318 -0
  88. package/skills/everyapp/setup/openrouter.md +309 -0
  89. package/skills/everyapp/setup/providers.md +353 -0
  90. package/skills/everyapp/setup/remote-mcp.md +199 -0
  91. package/skills/everyapp/setup/slack.md +344 -0
  92. package/skills/everyapp/setup/workers-ai.md +138 -0
  93. package/bin/__everyapp_bash_complete.js +0 -12
  94. package/dist/bash-complete.js +0 -3
  95. package/dist/chunk-3TJKOYE5.js +0 -13
  96. package/dist/chunk-4YDNA5LP.js +0 -9
  97. package/dist/chunk-7OLTQZZZ.js +0 -47
  98. package/dist/chunk-AEQXMWNU.js +0 -39
  99. package/dist/chunk-BIXKPCDH.js +0 -2
  100. package/dist/chunk-E2N6VUZY.js +0 -1
  101. package/dist/chunk-GSP5Y7U6.js +0 -7
  102. package/dist/chunk-HSYSKQ25.js +0 -8
  103. package/dist/chunk-JXZGJYRJ.js +0 -8
  104. package/dist/chunk-PMLXP26K.js +0 -1
  105. package/dist/chunk-SGRMXPI7.js +0 -4
  106. package/dist/chunk-UHLZLYQP.js +0 -6
  107. package/dist/chunk-VEYSNPDH.js +0 -3
  108. package/dist/chunk-WO3NE7ZU.js +0 -7
  109. package/dist/chunk-YJ2DKIZS.js +0 -1
  110. package/dist/chunk-YPYDHMNH.js +0 -1
  111. package/dist/create-KOQ2DWKU.js +0 -22
  112. package/dist/deploy-RFR6W22M.js +0 -55
  113. package/dist/deploy-YV2RWODJ.js +0 -7
  114. package/dist/dev-FPQWEHYM.js +0 -0
  115. package/dist/generateConfig-46Z3ERF3.js +0 -1
  116. package/dist/login-ZFFQASKS.js +0 -1
  117. package/dist/logout-AEE4AZ5D.js +0 -1
  118. package/dist/remoteD1Shell-CGFP46AW.js +0 -6
  119. package/dist/setupLocal-PC6YBN2X.js +0 -6
  120. package/gateway/every-app-gateway-build.tar.gz +0 -0
@@ -0,0 +1,57 @@
1
+ var to=Object.defineProperty;var no=(e,t,n)=>t in e?to(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var q=(e,t,n)=>(no(e,typeof t!="symbol"?t+"":t,n),n);var Bu="everyapp";var Wu="0.3.0-rc.1";var An={"@cloudflare/config":"0.24.1","@inquirer/prompts":"^8.7.3","@stricli/core":"^1.3.0",cf:"1.0.0-beta.14",chalk:"^5.6.2","cli-cursor":"^5.0.0",execa:"^9.6.0",jiti:"^2.6.1",undici:"^7.30.1",zod:"^4.2.0"};function ro(e=process.env){let t=e.npm_config_user_agent?.split("/")[0];return t?so[t]??"everyapp":"everyapp"}var so={pnpm:"pnpm everyapp",npm:"npx everyapp",yarn:"yarn everyapp"},dt=ro();function R(e=[],{terminal:t=!1,argv:n=process.argv.slice(2)}={}){let r=t?n.filter(s=>s!=="--json"):[...n];for(let s of e)r.includes(s)||r.push(s);return[dt,...r.map(oo)].join(" ")}function Fu(e,t=process.argv.slice(2)){let n=[];for(let r=0;r<t.length;r++){let s=t[r];s===e?r++:s.startsWith(`${e}=`)||n.push(s)}return R([],{argv:n})}function oo(e){return/^[\w@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var z=(e,t)=>`${e} ${t}${e===1?"":"s"}`,ve=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`,f=e=>typeof e=="string"&&e.length>0?e:void 0,Vu=e=>f(e)??null;function X(...e){return e.join(`
2
+ `).split(/\r?\n/).map(t=>t.trimEnd()).filter(t=>t.trim().length>0).slice(-20)}function pt(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}var P=e=>Array.isArray(e)?e.map(String):[];var v={openai:{mode:"ai",label:"OpenAI",description:"OpenAI's models: responses, chat, embeddings, audio, images.",auth:{kind:"bearer",secret:"OPENAI_API_KEY"},docs:"https://platform.openai.com/api-keys",api:"https://platform.openai.com/docs/api-reference",setup:"setup/openai.md",origin:"https://api.openai.com",inferenceRoutes:["/v1/responses","/v1/chat/completions","/v1/embeddings","/v1/audio/speech","/v1/audio/transcriptions","/v1/audio/translations","/v1/images/generations","/v1/images/edits","/v1/images/variations"],unstoredRoutes:["/v1/responses","/v1/chat/completions"],extraRoutes:!0,hint:"A secret key from the API keys page; the Gateway puts it on every call as a bearer token.",verified:{on:"2026-10-25",how:"live"}},openrouter:{mode:"ai",label:"OpenRouter",description:"One key for many models, through OpenAI's API shape.",auth:{kind:"bearer",secret:"OPENROUTER_API_KEY"},docs:"https://openrouter.ai/settings/keys",api:"https://openrouter.ai/docs",setup:"setup/openrouter.md",origin:"https://openrouter.ai",inferenceRoutes:["/api/v1/chat/completions","/api/v1/completions","/api/v1/responses","/api/v1/embeddings"],hint:"An API key from OpenRouter's keys page; the Gateway puts it on every call as a bearer token.",verified:{on:"2026-10-25",how:"live"}},"workers-ai":{mode:"ai",label:"Workers AI",description:"Cloudflare's models, in the Gateway's own account.",auth:{kind:"bearer",secret:"WORKERS_AI_API_TOKEN"},docs:"https://dash.cloudflare.com/profile/api-tokens",api:"https://developers.cloudflare.com/workers-ai/",setup:"setup/workers-ai.md",origin:"https://api.cloudflare.com",alsoNeeds:["CLOUDFLARE_ACCOUNT_ID"],basePath:"/client/v4/accounts/{CLOUDFLARE_ACCOUNT_ID}/ai",inferenceRoutes:["/v1/chat/completions","/v1/embeddings","/v1/responses"],normalize:"workers-ai",hint:"A Cloudflare API token with Workers AI Read (the Workers AI page's prefilled token); the account is the Gateway's own.",verified:{on:"2026-10-25",how:"live"}},dataforseo:{mode:"api_key",label:"DataForSEO",description:"SEO data: keyword metrics, live search results, domain rankings, backlinks.",auth:{kind:"basic",secret:"DATAFORSEO_API_KEY",as:"pair"},docs:"https://app.dataforseo.com/api-access",api:"https://docs.dataforseo.com/v3/",setup:"setup/dataforseo.md",hosts:["api.dataforseo.com","sandbox.dataforseo.com"],access:["read"],readMethods:["GET","POST"],accountWidePaths:[["tasks_ready"],["tasks_fixed"],["id_list"],["errors"],["appendix","user_data"],["appendix","webhook_resend"]],hint:"The API login and password from API Access, as login:password (or that pair base64-encoded); the Gateway sends them as HTTP Basic.",secrets:[{name:"DATAFORSEO_API_KEY",hint:"login:password, or its base64; never the dashboard sign-in password."}],cost:{unit:"call",responseField:"cost",note:"A Google SERP $0.002 per 10 results; a Labs task $0.012 plus $0.00012 per item."},smoke:{method:"GET",path:"/v3/appendix/user_data",expect:[200],free:!0,note:"Account-wide, so the Gateway refuses it for apps; run it from the person's terminal."},example:"find keyword ideas for a page about running shoes",verified:{on:"2026-10-25",how:"live"}},context:{mode:"api_key",label:"Context.dev",description:"Scrapes and renders web pages, JavaScript included.",auth:{kind:"bearer",secret:"CONTEXT_API_KEY"},docs:"https://context.dev/",setup:"setup/context.md",hosts:["api.context.dev"],access:["read"],readMethods:["GET","POST"],accountWidePaths:[],hint:"An API key from the Context.dev dashboard; the Gateway puts it on every call as a bearer token.",verified:{on:"2026-10-25",how:"live"}},email:{mode:"service",label:"Email",access:["write"],routes:{send:["POST"]},settings:["EMAIL_FROM","EMAIL_FROM_NAME"],optionalSettings:["EMAIL_REST_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","RESEND_API_KEY","EMAIL_PROVIDER"],setup:"setup/email.md"},members:{mode:"service",label:"Members",access:["read"],routes:{list:["GET"]},settings:[],optionalSettings:[]},linkedin:{mode:"oauth_client",label:"LinkedIn",secrets:{clientId:"LINKEDIN_CLIENT_ID",clientSecret:"LINKEDIN_CLIENT_SECRET"},token:[{host:"www.linkedin.com",path:"/oauth/v2/accessToken",methods:["POST"],inject:"form"}],access:["write"],console:"https://www.linkedin.com/developers/apps",authorize:{url:"https://www.linkedin.com/oauth/v2/authorization",scopes:["openid","profile","w_member_social","r_basicprofile","rw_organization_admin","w_organization_social","r_organization_social"]},api:["api.linkedin.com"],redirectPaths:["/integrations/social/linkedin","/integrations/social/linkedin-page"]},facebook:{mode:"oauth_client",label:"Facebook",secrets:{clientId:"FACEBOOK_APP_ID",clientSecret:"FACEBOOK_APP_SECRET"},token:[{host:"graph.facebook.com",path:/^\/v\d+\.\d+\/oauth\/access_token$/,methods:["GET","POST"],inject:"query"}],access:["write"],console:"https://developers.facebook.com/apps",authorize:{url:"https://www.facebook.com/v25.0/dialog/oauth",scopes:["pages_show_list","business_management","pages_manage_posts","pages_manage_engagement","pages_read_engagement","read_insights","instagram_basic","instagram_content_publish","instagram_manage_comments","instagram_manage_insights"]},api:["graph.facebook.com","graph.instagram.com"],redirectPaths:["/integrations/social/facebook","/integrations/social/instagram"]},instagram:{mode:"oauth_client",label:"Instagram",secrets:{clientId:"INSTAGRAM_APP_ID",clientSecret:"INSTAGRAM_APP_SECRET"},token:[{host:"api.instagram.com",path:"/oauth/access_token",methods:["POST"],inject:"form"},{host:"graph.instagram.com",path:"/access_token",methods:["GET"],inject:"query"}],access:["write"],console:"https://developers.facebook.com/apps",authorize:{url:"https://www.instagram.com/oauth/authorize",scopes:["instagram_business_basic","instagram_business_content_publish","instagram_business_manage_comments","instagram_business_manage_insights"]},api:["graph.instagram.com"],redirectPaths:["/integrations/social/instagram-standalone"]},threads:{mode:"oauth_client",label:"Threads",secrets:{clientId:"THREADS_APP_ID",clientSecret:"THREADS_APP_SECRET"},token:[{host:"graph.threads.net",path:"/oauth/access_token",methods:["GET","POST"],inject:"query"},{host:"graph.threads.net",path:"/access_token",methods:["GET"],inject:"query"}],access:["write"],console:"https://developers.facebook.com/apps",authorize:{url:"https://threads.net/oauth/authorize",scopes:["threads_basic","threads_content_publish","threads_manage_replies","threads_manage_insights"]},api:["graph.threads.net"],redirectPaths:["/integrations/social/threads"]},youtube:{mode:"oauth_client",label:"YouTube",secrets:{clientId:"YOUTUBE_CLIENT_ID",clientSecret:"YOUTUBE_CLIENT_SECRET"},token:[{host:"oauth2.googleapis.com",path:"/token",methods:["POST"],inject:"form"}],access:["write"],console:"https://console.cloud.google.com/apis/credentials",setup:"setup/google.md",authorize:{url:"https://accounts.google.com/o/oauth2/v2/auth",scopes:["https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl","https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtubepartner","https://www.googleapis.com/auth/yt-analytics.readonly","https://www.googleapis.com/auth/business.manage"]},api:["www.googleapis.com","youtubeanalytics.googleapis.com","mybusinessaccountmanagement.googleapis.com","mybusinessbusinessinformation.googleapis.com","mybusiness.googleapis.com","businessprofileperformance.googleapis.com"],redirectPaths:["/integrations/social/youtube","/integrations/social/gmb"]},tiktok:{mode:"oauth_client",label:"TikTok",secrets:{clientId:"TIKTOK_CLIENT_ID",clientSecret:"TIKTOK_CLIENT_SECRET"},token:[{host:"open.tiktokapis.com",path:"/v2/oauth/token/",methods:["POST"],inject:"form",params:{clientId:"client_key"}}],access:["write"],console:"https://developers.tiktok.com/apps",authorize:{url:"https://www.tiktok.com/v2/auth/authorize/",scopes:["video.list","user.info.basic","video.publish","video.upload","user.info.profile","user.info.stats"]},api:["open.tiktokapis.com"],redirectPaths:["/integrations/social/tiktok"]},"tiktok-business":{mode:"oauth_client",label:"TikTok Business",secrets:{clientId:"TIKTOK_BUSINESS_CLIENT_ID",clientSecret:"TIKTOK_BUSINESS_CLIENT_SECRET"},token:[{host:"business-api.tiktok.com",path:"/open_api/v1.3/tt_user/oauth2/token/",methods:["POST"],inject:"json"},{host:"business-api.tiktok.com",path:"/open_api/v1.3/tt_user/oauth2/refresh_token/",methods:["POST"],inject:"json"}],access:["write"],console:"https://business-api.tiktok.com/portal/apps",authorize:{url:"https://www.tiktok.com/v2/auth/authorize/",scopes:["user.info.basic","user.info.username","user.info.stats","video.list","video.upload","video.publish"]},api:["business-api.tiktok.com"],redirectPaths:["/integrations/social/tiktok-business/"]},reddit:{mode:"oauth_client",label:"Reddit",secrets:{clientId:"REDDIT_CLIENT_ID",clientSecret:"REDDIT_CLIENT_SECRET"},token:[{host:"www.reddit.com",path:"/api/v1/access_token",methods:["POST"],inject:"basic"}],access:["write"],console:"https://www.reddit.com/prefs/apps",authorize:{url:"https://www.reddit.com/api/v1/authorize",scopes:["read","identity","submit","flair"]},api:["oauth.reddit.com"],redirectPaths:["/integrations/social/reddit"]},pinterest:{mode:"oauth_client",label:"Pinterest",secrets:{clientId:"PINTEREST_CLIENT_ID",clientSecret:"PINTEREST_CLIENT_SECRET"},token:[{host:"api.pinterest.com",path:"/v5/oauth/token",methods:["POST"],inject:"basic"}],access:["write"],console:"https://developers.pinterest.com/apps/",authorize:{url:"https://www.pinterest.com/oauth/",scopes:["boards:read","boards:write","pins:read","pins:write","user_accounts:read"]},api:["api.pinterest.com"],redirectPaths:["/integrations/social/pinterest"]},discord:{mode:"oauth_client",label:"Discord",secrets:{clientId:"DISCORD_CLIENT_ID",clientSecret:"DISCORD_CLIENT_SECRET"},token:[{host:"discord.com",path:"/api/oauth2/token",methods:["POST"],inject:"basic"}],access:["write"],console:"https://discord.com/developers/applications",authorize:{url:"https://discord.com/oauth2/authorize",scopes:["bot","identify","guilds"]},api:["discord.com"],redirectPaths:["/integrations/social/discord"]},slack:{mode:"oauth_client",label:"Slack",secrets:{clientId:"SLACK_CLIENT_ID",clientSecret:"SLACK_CLIENT_SECRET"},token:[{host:"slack.com",path:"/api/oauth.v2.access",methods:["POST"],inject:"form"}],access:["write"],console:"https://api.slack.com/apps",setup:"setup/slack.md",authorize:{url:"https://slack.com/oauth/v2/authorize",scopes:["channels:read","groups:read","users:read","users:read.email","chat:write","chat:write.public","chat:write.customize","channels:join","channels:manage","groups:write","channels:write.invites","groups:write.invites","im:write","files:write","channels:write"]},scopePolicy:{dialect:"slack",grantTypes:[null,"refresh_token"],requestScope:"keep",alwaysRequested:[],tolerated:[],deniedSegments:[],sets:{"channels.read":{label:"Channels (read-only)",access:"read",scopes:["channels:read","groups:read"],routes:[{host:"slack.com",paths:["/api/conversations.list","/api/conversations.info","/api/conversations.members","/api/users.conversations"],posts:[/^\/api\/conversations\.(list|info|members)$/,/^\/api\/users\.conversations$/]}]},"users.read":{label:"Members (read-only)",access:"read",scopes:["users:read"],routes:[{host:"slack.com",paths:["/api/users.list","/api/users.info","/api/users.getPresence","/api/bots.info"],posts:[/^\/api\/users\.(list|info|getPresence)$/,/^\/api\/bots\.info$/]}]},"users.email":{label:"Members' email addresses (read-only)",access:"read",scopes:["users:read.email"],routes:[{host:"slack.com",paths:["/api/users.lookupByEmail"],posts:[/^\/api\/users\.lookupByEmail$/]}]},"messages.write":{label:"Messages (post as the app)",access:"write",scopes:["chat:write","chat:write.public","chat:write.customize"],routes:[{host:"slack.com",paths:["/api/chat.scheduledMessages.list"],posts:[/^\/api\/chat\.(postMessage|postEphemeral|update|delete|scheduleMessage|deleteScheduledMessage|scheduledMessages\.list)$/]}]},"channels.join":{label:"Channels (join public ones)",access:"write",scopes:["channels:join"],routes:[{host:"slack.com",paths:[],posts:[/^\/api\/conversations\.join$/]}]},"channels.manage":{label:"Channels (create, manage and invite to; open DMs)",access:"write",scopes:["channels:manage","groups:write","channels:write.invites","groups:write.invites","im:write"],routes:[{host:"slack.com",paths:[],posts:[/^\/api\/conversations\.(create|rename|archive|unarchive|invite|open|kick|leave|setTopic|setPurpose|mark)$/]}]},"files.write":{label:"Files (upload)",access:"write",scopes:["files:write"],routes:[{host:"slack.com",paths:[],posts:[/^\/api\/files\.(getUploadURLExternal|completeUploadExternal)$/]}]},"user-channels.manage":{label:"Channels (as the installing person: read, manage, invite to)",access:"write",scopes:[],userScopes:["channels:read","channels:write","groups:read","groups:write"],routes:[{host:"slack.com",paths:["/api/conversations.list","/api/conversations.info","/api/conversations.members","/api/users.conversations"],posts:[/^\/api\/conversations\.(list|info|members|create|rename|archive|unarchive|invite|kick|leave|setTopic|setPurpose|mark)$/,/^\/api\/users\.conversations$/]}]}}},api:["slack.com"],redirectPaths:["/integrations/social/slack","/integrations/slack/callback"]},mastodon:{mode:"oauth_client",label:"Mastodon",secrets:{clientId:"MASTODON_CLIENT_ID",clientSecret:"MASTODON_CLIENT_SECRET"},token:[{path:"/oauth/token",methods:["POST"],inject:"form"}],hostSetting:"MASTODON_URL",defaultOrigin:"https://mastodon.social",access:["write"],console:"/settings/applications",authorize:{url:"/oauth/authorize",scopes:["write:statuses","profile","write:media"]},api:[],redirectPaths:["/integrations/social/mastodon"]},kick:{mode:"oauth_client",label:"Kick",secrets:{clientId:"KICK_CLIENT_ID",clientSecret:"KICK_CLIENT_SECRET"},token:[{host:"id.kick.com",path:"/oauth/token",methods:["POST"],inject:"form"}],access:["write"],console:"https://kick.com/settings/developer",authorize:{url:"https://id.kick.com/oauth/authorize",scopes:["chat:write","user:read","channel:read"]},api:["api.kick.com"],redirectPaths:["/integrations/social/kick"]},twitch:{mode:"oauth_client",label:"Twitch",secrets:{clientId:"TWITCH_CLIENT_ID",clientSecret:"TWITCH_CLIENT_SECRET"},token:[{host:"id.twitch.tv",path:"/oauth2/token",methods:["POST"],inject:"form"}],access:["write"],console:"https://dev.twitch.tv/console/apps",authorize:{url:"https://id.twitch.tv/oauth2/authorize",scopes:["user:write:chat","user:read:chat","moderator:manage:announcements"]},api:["api.twitch.tv"],redirectPaths:["/integrations/social/twitch"]},tumblr:{mode:"oauth_client",label:"Tumblr",secrets:{clientId:"TUMBLR_CLIENT_ID",clientSecret:"TUMBLR_CLIENT_SECRET"},token:[{host:"api.tumblr.com",path:"/v2/oauth2/token",methods:["POST"],inject:"form"}],access:["write"],console:"https://www.tumblr.com/oauth/apps",authorize:{url:"https://www.tumblr.com/oauth2/authorize",scopes:["write","offline_access"]},api:["api.tumblr.com"],redirectPaths:["/integrations/social/tumblr"]},dribbble:{mode:"oauth_client",label:"Dribbble",secrets:{clientId:"DRIBBBLE_CLIENT_ID",clientSecret:"DRIBBBLE_CLIENT_SECRET"},token:[{host:"dribbble.com",path:"/oauth/token",methods:["POST"],inject:"query"}],access:["write"],console:"https://dribbble.com/account/applications",authorize:{url:"https://dribbble.com/oauth/authorize",scopes:["public","upload"]},api:["api.dribbble.com"],redirectPaths:["/integrations/social/dribbble"]},"google-workspace":{mode:"oauth_client",label:"Google (Gmail, Calendar, Search Console and Analytics)",secrets:{clientId:"GOOGLE_WORKSPACE_CLIENT_ID",clientSecret:"GOOGLE_WORKSPACE_CLIENT_SECRET"},token:[{host:"oauth2.googleapis.com",path:"/token",methods:["POST"],inject:"form"}],access:["write"],console:"https://console.cloud.google.com/apis/credentials",setup:"setup/google.md",authorize:{url:"https://accounts.google.com/o/oauth2/v2/auth",scopes:["openid","email","profile","https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/webmasters.readonly","https://www.googleapis.com/auth/analytics.readonly"]},scopePolicy:{dialect:"google",grantTypes:["authorization_code","refresh_token"],requestScope:"drop",alwaysRequested:[],tolerated:["openid","email","profile","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile"],deniedSegments:["batch","measurementProtocolSecrets"],sets:{identity:{label:"Google account (who you are)",access:"read",scopes:["openid","email","profile"],routes:[{host:"openidconnect.googleapis.com",paths:["/v1/userinfo"]},{host:"www.googleapis.com",paths:["/oauth2/v2/userinfo","/oauth2/v3/userinfo","/userinfo/v2/me"]}]},"gmail.read":{label:"Gmail (read-only)",access:"read",scopes:["https://www.googleapis.com/auth/gmail.readonly"],routes:[{host:"gmail.googleapis.com",paths:["/gmail/v1/users/"],posts:[/^\/gmail\/v1\/users\/[^/]+\/(watch|stop)$/]}]},"calendar.read":{label:"Google Calendar (read-only)",access:"read",scopes:["https://www.googleapis.com/auth/calendar.readonly"],routes:[{host:"www.googleapis.com",paths:["/calendar/v3/"],posts:[/^\/calendar\/v3\/freeBusy$/,/^\/calendar\/v3\/calendars\/[^/]+\/events\/watch$/,/^\/calendar\/v3\/users\/me\/calendarList\/watch$/,/^\/calendar\/v3\/channels\/stop$/]}]},"search-console.read":{label:"Search Console (read-only)",access:"read",scopes:["https://www.googleapis.com/auth/webmasters.readonly"],routes:[{host:"www.googleapis.com",paths:["/webmasters/v3/"],posts:[/^\/webmasters\/v3\/sites\/[^/]+\/searchAnalytics\/query$/]},{host:"searchconsole.googleapis.com",paths:["/webmasters/v3/"],posts:[/^\/webmasters\/v3\/sites\/[^/]+\/searchAnalytics\/query$/,/^\/v1\/urlInspection\/index:inspect$/]}]},"analytics.read":{label:"Google Analytics (read-only)",access:"read",scopes:["https://www.googleapis.com/auth/analytics.readonly"],routes:[{host:"analyticsdata.googleapis.com",paths:["/v1beta/properties/"],posts:[/^\/v1beta\/properties\/[^/]+:(runReport|batchRunReports|runPivotReport|batchRunPivotReports|runRealtimeReport|checkCompatibility)$/]},{host:"analyticsadmin.googleapis.com",paths:["/v1beta/accountSummaries","/v1beta/accounts","/v1beta/accounts/","/v1beta/properties","/v1beta/properties/","/v1alpha/properties/"]}]}}},api:["gmail.googleapis.com","www.googleapis.com","searchconsole.googleapis.com","analyticsdata.googleapis.com","analyticsadmin.googleapis.com","openidconnect.googleapis.com"],redirectPaths:["/integrations/google/callback"]},"microsoft-365":{mode:"oauth_client",label:"Microsoft 365 (Outlook mail and calendar)",secrets:{clientId:"MICROSOFT_365_CLIENT_ID",clientSecret:"MICROSOFT_365_CLIENT_SECRET"},token:[{host:"login.microsoftonline.com",path:"/common/oauth2/v2.0/token",methods:["POST"],inject:"form"}],access:["write"],console:"https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade",setup:"setup/microsoft-365.md",authorize:{url:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",scopes:["offline_access","User.Read","Mail.Read","Calendars.Read"]},scopePolicy:{dialect:"microsoft",grantTypes:["authorization_code","refresh_token"],requestScope:"replace",alwaysRequested:["offline_access"],tolerated:["openid","profile","email","offline_access","User.Read"],deniedSegments:["$batch","beta"],sets:{identity:{label:"Microsoft account (who you are)",access:"read",scopes:["User.Read"],routes:[{host:"graph.microsoft.com",paths:["/v1.0/me","/oidc/userinfo"]}]},"mail.read":{label:"Outlook mail (read-only)",access:"read",scopes:["Mail.Read"],routes:[{host:"graph.microsoft.com",paths:["/v1.0/me/messages","/v1.0/me/messages/","/v1.0/me/mailFolders","/v1.0/me/mailFolders/"]}]},"calendar.read":{label:"Outlook calendar (read-only)",access:"read",scopes:["Calendars.Read"],routes:[{host:"graph.microsoft.com",paths:["/v1.0/me/calendar","/v1.0/me/calendar/","/v1.0/me/calendars","/v1.0/me/calendars/","/v1.0/me/events","/v1.0/me/events/","/v1.0/me/calendarView","/v1.0/me/calendarView/"],posts:[/^\/v1\.0\/me\/calendar\/getSchedule$/]}]}}},api:["graph.microsoft.com"],redirectPaths:["/integrations/microsoft/callback"]}};function Z(e){let t=[e.secret];return e.kind==="basic"&&e.as==="password"&&typeof e.user=="object"&&t.push(e.user.secret),t}function C(e){switch(e.mode){case"api_key":return[...Z(e.auth),...e.hostSetting?[e.hostSetting]:[]];case"ai":return[e.auth.secret,...e.alsoNeeds??[]];case"service":return[...e.settings,...e.optionalSettings];case"oauth_client":return[e.secrets.clientId,...e.secrets.clientSecret?[e.secrets.clientSecret]:[],...e.hostSetting?[e.hostSetting]:[]]}}var D=Object.keys(v);function lt(e){return typeof e=="string"&&Object.hasOwn(v,e)}var Q={get:e=>lt(e)?v[e]:void 0,ids:()=>D};function kn(e){return e.ids().filter(t=>e.get(t)?.mode!=="ai")}function io(e,t){if(!e.hostSetting)return null;let n=t?.[e.hostSetting],r=typeof n=="string"&&n.trim()?n.trim():e.defaultOrigin;if(!r)return null;let s;try{s=new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(r)?r:`https://${r}`)}catch{return null}let o=s.pathname==="/"&&!s.search&&!s.hash&&!s.username&&!s.password;return s.protocol==="https:"&&o?s.origin:null}function Yu(e){return e.token.map(({host:t,path:n,methods:r})=>`${r.join("/")} https://${t??`<${e.hostSetting}>`}${ao(n)}`).join(", ")}function ao(e){return typeof e=="string"?e:e.source.replace(/^\^|\$$/g,"").replace(/v\\d\+\\\.\\d\+/g,"v<version>").replace(/\\(.)/g,"$1")}var co=["GATEWAY_URL","APP_BASE_DOMAIN","BETTER_AUTH_SECRET","JWT_PRIVATE_KEY","JWT_PUBLIC_KEY","GATEWAY_DEPLOYMENT_MODE","CLOUDFLARE_ACCOUNT_ID","THIRD_PARTY_DEPLOYS"],In=new Set(co);function de(e){return In.has(e)}var uo=[...new Set(D.flatMap(e=>{let t=v[e];return t.mode==="service"?[]:C(t)}))].filter(e=>!In.has(e)),po=["AI_PROXY_EXTRA_ROUTES","EMAIL_REST_API_TOKEN","RESEND_API_KEY","EMAIL_PROVIDER","EMAIL_FROM","EMAIL_FROM_NAME","MCP_OAUTH_ENABLED","MCP_DCR_ENABLED","MCP_ALLOWED_ORIGINS","MCP_AUDIT_RETENTION_DAYS","CLOUDFLARE_ACCESS_OIDC_ISSUER","CLOUDFLARE_ACCESS_OIDC_CLIENT_ID","CLOUDFLARE_ACCESS_OIDC_CLIENT_SECRET","CLOUDFLARE_ACCESS_OIDC_LABEL","CLOUDFLARE_ACCESS_TEAM_DOMAIN","CLOUDFLARE_ACCESS_AUD","CLOUDFLARE_ACCESS_APPS_AUD","CLOUDFLARE_ACCESS_AUTO_JOIN_DOMAINS","CLOUDFLARE_ACCESS_OUTER_RING_AUTO_JOIN","EMAIL_PASSWORD_SIGN_IN","HOSTED_OPEN_SIGNUP","CF_DEPLOY_TOKEN","BROWSER_APP_INSTALLS","DISPATCH_NAMESPACE","THIRD_PARTY_DOMAIN","EVENTS_ALLOW_PRIVATE_TARGETS"],lo=[...uo,...po],fo=new Set(lo),mo=/^[A-Z][A-Z0-9_]*_MCP_TOKEN$/;function pe(e){return mo.test(e)}function G(e){return fo.has(e)||pe(e)}var ho=["EMAIL_FROM","EMAIL_FROM_NAME","EMAIL_PROVIDER","EMAIL_PASSWORD_SIGN_IN","MASTODON_URL","AI_PROXY_EXTRA_ROUTES","MCP_OAUTH_ENABLED","MCP_DCR_ENABLED","MCP_ALLOWED_ORIGINS","MCP_AUDIT_RETENTION_DAYS","CLOUDFLARE_ACCESS_OIDC_ISSUER","CLOUDFLARE_ACCESS_OIDC_CLIENT_ID","CLOUDFLARE_ACCESS_OIDC_LABEL","CLOUDFLARE_ACCESS_TEAM_DOMAIN","CLOUDFLARE_ACCESS_AUD","CLOUDFLARE_ACCESS_APPS_AUD","CLOUDFLARE_ACCESS_AUTO_JOIN_DOMAINS","CLOUDFLARE_ACCESS_OUTER_RING_AUTO_JOIN","HOSTED_OPEN_SIGNUP","BROWSER_APP_INSTALLS","DISPATCH_NAMESPACE","THIRD_PARTY_DOMAIN","EVENTS_ALLOW_PRIVATE_TARGETS"],go=new Set(ho);function Zu(e){return go.has(e)}var yo=["HOSTED_OPEN_SIGNUP","DISPATCH_NAMESPACE","THIRD_PARTY_DOMAIN"],wo=new Set(yo);function Qu(e){return wo.has(e)}var Eo=["MCP_ACCESS_TOKEN_TTL","DATAFORSEO_SANDBOX"];function Tn(e){return Eo.includes(e)}var bo=new Set(["GATEWAY_URL","CF_VERSION_METADATA"]),_o=["EVERYAPP_","EVERY_APP_","APP__"],Rn="GATEWAY_URL, CF_VERSION_METADATA and the EVERYAPP_*, EVERY_APP_* and APP__* names";function Pe(e){let t=e.toUpperCase();return bo.has(t)||_o.some(n=>t.startsWith(n))}function xn(e){for(let t of D){let n=v[t];if(C(n).includes(e))return{kind:n.mode==="ai"?"provider":"capability",id:t}}return null}var nd="provider",Ce={dataforseo:{id:"dataforseo",name:"DataForSEO",description:"SEO data for your agent: keyword metrics and suggestions, live Google results, domain rankings, competitors and backlinks, through the Gateway's DataForSEO key.",capability:"dataforseo",why:"Serves DataForSEO's keyword, search-result, domain and backlink data to members' AI clients.",example:"find keyword ideas for a page about running shoes"}},rd=Object.keys(Ce).sort();function vn(e){return Object.hasOwn(Ce,e)}function sd(e){return Z(v[Ce[e].capability].auth)[0]}function od(e){let t=Ce[e];return{id:t.id,name:t.name,description:t.description,capabilities:{[t.capability]:{access:"read",why:t.why}}}}var le="/__everyapp/tools",ad=`${le}/list`,cd=`${le}/call`,So=["read","write","destructive"],ud="mcp:read",dd="mcp:write";var Pn=/^[a-z][a-z0-9_]{0,47}$/;function Cn(e){return typeof e=="string"&&So.includes(e)}function pd(e){return JSON.stringify(ft(e))}function ft(e){if(Array.isArray(e))return e.map(ft);if(!e||typeof e!="object")return e;let t={};for(let n of Object.keys(e).sort()){let r=e[n];r!==void 0&&(t[n]=ft(r))}return t}var On=["none","bearer","header","basic","oauth"],$n=["annotations","read","write"],Mn=/^[a-z]([a-z0-9-]*[a-z0-9])?$/,mt=32,Ao=["everyapp"],ko=64,Io=/^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,100}$/,To=32,jn=2048,Ro=255,xo=1e3,Nn=500,vo=256,Po=new Set(["authorization","cookie","host","content-type","content-length","accept","connection","transfer-encoding","mcp-session-id","mcp-protocol-version","mcp-method","mcp-name"]);function Co(e){return`${e.toUpperCase().replace(/-/g,"_")}_MCP_TOKEN`}function Oo(e){return typeof e!="string"||!Mn.test(e)?"the id must be kebab-case: lowercase letters, digits and hyphens, starting with a letter":e.length>mt?`the id must be at most ${mt} characters`:Ao.includes(e)?`"${e}" is reserved`:vn(e)?`"${e}" is the Gateway's built-in MCP app; a remote server can't take its id`:null}function yd(e){let t;try{t=new URL(e).hostname.toLowerCase().replace(/\.$/,"")}catch{return null}if(!t||/^[\d.]+$/.test(t)||t.includes(":"))return null;let n=t.split(".").filter(a=>a.length>0);if(n.length<2)return null;let r=new Set(["co","com","net","org","gov","edu","ac"]),s=n.length-2;s>0&&r.has(n[s])&&n[s+1].length===2&&(s-=1);let i=(n[s]??"").replace(/[^a-z0-9-]/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-").slice(0,mt).replace(/-+$/g,"");return!i||!Mn.test(i)||Oo(i)?null:i}function Dn(e,t){return e===t||e.endsWith(`.${t}`)}function $o(){let e=new Set(["api.openai.com","openrouter.ai","gateway.ai.cloudflare.com","api.cloudflare.com"]);for(let t of Object.values(v))if(t.mode==="api_key")for(let n of t.hosts)e.add(n);else if(t.mode==="oauth_client")for(let n of t.token)"host"in n&&typeof n.host=="string"&&e.add(n.host);return[...e].sort()}function wd(e,t){if(typeof e!="string"||!e.trim())return"give the server's URL";if(e.length>jn)return"the URL is too long";let n;try{n=new URL(e)}catch{return"the URL doesn't parse"}let r=t.gatewayUrl.trim().toLowerCase().startsWith("http://");if(n.username||n.password)return"the URL must not carry credentials; the Gateway sends the credential from its own setting";if(n.hash)return"the URL must not have a fragment";let s=n.hostname.toLowerCase().replace(/\.$/,""),o=s==="localhost"||s.endsWith(".localhost")||s==="127.0.0.1"||s==="[::1]"||s==="::1";if(n.protocol!=="https:"&&!(n.protocol==="http:"&&r&&o))return r?"the URL must be https://, or http:// on localhost while the Gateway runs locally":"the URL must be https://";if(!s)return"the URL has no host";if(!o&&(/^[\d.]+$/.test(s)||s.startsWith("[")))return"the URL must name a host, not an IP address";if(o&&!r)return"the URL must name a public host";let i="",a="";try{let c=new URL(t.gatewayUrl);i=c.hostname.toLowerCase().replace(/\.$/,""),a=c.origin.toLowerCase()}catch{i=""}if(i&&(r?n.origin.toLowerCase()===a:Dn(s,i)))return"the URL is this Gateway's own address";for(let c of[t.appBaseDomain,t.thirdPartyDomain]){let d=(c??"").trim().toLowerCase().replace(/\.$/,"");if(d&&Dn(s,d))return`the URL is on this Gateway's app domain (${d})`}return $o().includes(s)?`${s} is a provider this Gateway holds a key for; apps reach it through the Gateway's capabilities, not as an MCP app`:null}function ee(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function No(e){return typeof e!="string"||!e?"give the credential's setting name":e.length>ko?"the credential's name is too long":pe(e)?null:`the credential's name must end in _MCP_TOKEN (letters, digits and underscores), like ${Co("treg")}`}function Do(e){if(!ee(e)||typeof e.kind!="string")return{ok:!1,problem:"auth must name a kind"};let t=e.kind;if(!On.includes(t))return{ok:!1,problem:`auth.kind must be one of ${On.join(", ")}`};if(t==="none"||t==="oauth")return{ok:!0,auth:{kind:t}};let n=No(e.secret);if(n)return{ok:!1,problem:`auth.secret: ${n}`};let r=e.secret;if(t==="bearer"||t==="basic")return{ok:!0,auth:{kind:t,secret:r}};let s=e.header;if(typeof s!="string"||!Io.test(s))return{ok:!1,problem:"auth.header must be an HTTP header name"};if(Po.has(s.toLowerCase()))return{ok:!1,problem:`auth.header can't be ${s}; use kind "bearer" or "basic" for Authorization`};let o=e.prefix;return o!==void 0&&(typeof o!="string"||o.length>To||/[\r\n]/.test(o))?{ok:!1,problem:"auth.prefix must be a short string"}:{ok:!0,auth:{kind:"header",secret:r,header:s,...typeof o=="string"&&o?{prefix:o}:{}}}}function Lo(e){if(!ee(e))return{ok:!1,problem:"remote must be an object"};let t=e.url;if(typeof t!="string"||!t||t.length>jn)return{ok:!1,problem:"remote.url must be a URL"};let n=Do(e.auth);if(!n.ok)return n;let r=e.risk??"annotations";if(!$n.includes(r))return{ok:!1,problem:`remote.risk must be one of ${$n.join(", ")}`};let s={},o=e.tools??{};if(!ee(o))return{ok:!1,problem:"remote.tools must be an object"};let i=Object.entries(o);if(i.length>Nn)return{ok:!1,problem:`remote.tools has more than ${Nn} entries`};for(let[c,d]of i){if(!c||c.length>vo)return{ok:!1,problem:"remote.tools has a tool name that is empty or too long"};if(!ee(d))return{ok:!1,problem:`remote.tools.${c} must be an object`};let l={};if(d.risk!==void 0){if(!Cn(d.risk))return{ok:!1,problem:`remote.tools.${c}.risk must be read, write or destructive`};l.risk=d.risk}if(d.enabled!==void 0){if(typeof d.enabled!="boolean")return{ok:!1,problem:`remote.tools.${c}.enabled must be true or false`};l.enabled=d.enabled}s[c]=l}let a=e.rev??1;return typeof a!="number"||!Number.isInteger(a)||a<1?{ok:!1,problem:"remote.rev must be a positive integer"}:{ok:!0,block:{url:t,auth:n.auth,risk:r,tools:s,rev:a}}}function Un(e){if(!ee(e)||e.remote===void 0)return null;let t=Lo(e.remote);return t.ok?t.block:null}function Ed(e){return ee(e)&&e.remote!==void 0}function Kn(e){return"secret"in e?e.secret:null}function Mo(e,t){let n="";try{n=new URL(t).origin}catch{n=""}return`${e}'s MCP server${n?` at ${n}`:""}, served to your AI clients through this Gateway.`}function zn(e,t){let n=e.tools[t];if(n)return n;let r=Ln(t);if(r){for(let[s,o]of Object.entries(e.tools))if(Ln(s)===r)return o}}function bd(e){let t=(e.name??"").trim().slice(0,Ro)||e.id,n=(e.description??"").trim().slice(0,xo)||Mo(t,e.remote.url);return{id:e.id,name:t,description:n,remote:e.remote}}function _d(e,t,n){let r=zn(t,n)?.risk;return r?{risk:r,source:"override"}:t.risk==="read"||t.risk==="write"?{risk:t.risk,source:"app"}:e?.readOnlyHint===!0?{risk:"read",source:"hint"}:e?.destructiveHint===!0?{risk:"destructive",source:"hint"}:{risk:"write",source:"default"}}function Sd(e,t){return zn(e,t)?.enabled!==!1}function Ln(e){if(typeof e!="string")return null;let t=e.trim().replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase().replace(/[\s./:-]+/g,"_").replace(/[^a-z0-9_]/g,"").replace(/_{2,}/g,"_").replace(/^_+|_+$/g,"");return t?(/^[0-9]/.test(t)&&(t=`t_${t}`),t=t.slice(0,48).replace(/_+$/g,""),Pn.test(t)?t:null):null}function Gn(e){switch(e.kind){case"none":return"no credential";case"bearer":return"bearer token";case"basic":return"user and password";case"header":return`header ${e.header}`;case"oauth":return"OAuth (not supported yet)"}}function jo(e){return e?typeof e.anyOf=="string"&&e.anyOf.trim()?{kind:"anyOf",group:e.anyOf.trim()}:e.optional===!0?{kind:"optional"}:{kind:"required"}:{kind:"required"}}function gt(e){if(!e||typeof e!="object")return{};let t=e;return{...typeof t.why=="string"?{why:t.why}:{},...typeof t.docs=="string"?{docs:t.docs}:{},...typeof t.optional=="boolean"?{optional:t.optional}:{},...typeof t.setup=="string"?{setup:t.setup}:{},...typeof t.anyOf=="string"?{anyOf:t.anyOf}:{}}}function Oe(e){return(e.providers??[]).flatMap(t=>typeof t=="string"?[{id:t}]:t&&typeof t=="object"&&typeof t.id=="string"?[{id:t.id,...gt(t)}]:[])}function Rd(e){return Oe(e).map(t=>t.id)}function $e(e){return(e.secrets??[]).flatMap(t=>typeof t=="string"?[{name:t}]:t&&typeof t=="object"&&typeof t.name=="string"?[{name:t.name,...gt(t)}]:[])}function Wn(e){return $e(e).map(t=>t.name)}function Fn(e){return C(e).filter(t=>!de(t))}function Uo(e){let t=n=>n.filter(r=>G(r)&&!de(r));switch(e.mode){case"api_key":return{names:[...C(e)],alsoReads:[]};case"ai":return{names:Fn(e),alsoReads:[]};case"service":return{names:t(e.settings),alsoReads:t(e.optionalSettings)};case"oauth_client":{let n=[e.secrets.clientId,...e.secrets.clientSecret?[e.secrets.clientSecret]:[]],r=e.hostSetting?[e.hostSetting]:[];return e.defaultOrigin?{names:n,alsoReads:r}:{names:[...n,...r],alsoReads:[]}}}}function Ko(e){switch(e.mode){case"api_key":case"ai":return e.docs;case"oauth_client":return e.console.startsWith("https://")?e.console:e.defaultOrigin?`${e.defaultOrigin}${e.console}`:void 0;case"service":return}}function Bn(e,t){if(e.mode==="service"||e.mode==="oauth_client")return{};let n=e.secrets??[],r=[...e.hint?[e.hint]:[],...n.filter(s=>s.hint&&t.includes(s.name)).map(s=>t.length>1?`${s.name}: ${s.hint}`:s.hint)];return r.length>0?{hint:r.join(" ")}:{}}function ht(e,t,n={}){let r=t?.docs??n.docs,s=e.holder==="gateway"?n.setup:t?.setup;return{...e,need:jo(t),...t?.why?{why:t.why}:{},...r?{docs:r}:{},...s?{setup:s}:{},...n.hint?{hint:n.hint}:{}}}function xd(e,t=Q){let n=[];for(let s of Oe(e)){let o=t.get(s.id);if(o?.mode!=="ai")continue;let i=Fn(o);n.push(ht({kind:"provider",id:s.id,label:o.label,holder:"gateway",names:i,alsoReads:[]},s,{docs:o.docs,setup:o.setup,...Bn(o,i)}))}for(let[s,o]of Object.entries(e.capabilities??{})){let i=t.get(s);if(!i||i.mode==="ai")continue;let{names:a,alsoReads:c}=Uo(i);n.push(ht({kind:"capability",id:s,label:i.label,holder:"gateway",names:a,alsoReads:c},gt(o),{docs:Ko(i),setup:i.setup,...Bn(i,a)}))}e.ai?.routes?.length&&n.push({kind:"ai-routes",id:"ai-routes",label:"AI proxy routes",holder:"gateway",names:["AI_PROXY_EXTRA_ROUTES"],alsoReads:[],need:{kind:"required"},why:`Lets the app call ${e.ai.routes.join(", ")} through the AI proxy.`,setup:"setup/openai.md"});let r=Un(e);if(r){let s=Kn(r.auth);if(s){let o=typeof e.name=="string"&&e.name.trim()?e.name.trim():"the MCP server";n.push({kind:"remote-mcp",id:s,label:`${o} credential`,holder:"gateway",names:[s],alsoReads:[],need:{kind:"required"},why:`What ${o} expects: ${Gn(r.auth)}. The Gateway sends it to ${r.url} and nowhere else.`,setup:"setup/remote-mcp.md"})}}for(let s of $e(e))n.push(ht({kind:"secret",id:s.name,label:s.name,holder:"app",names:[s.name],alsoReads:[]},s));return n}function zo(e,t){let n=!1;for(let r of e.names){let s=t(e.holder,r);if(s===!1)return!1;s===null&&(n=!0)}return n?null:!0}function vd(e,t,n={}){let r=e.map(i=>{let a=n.readiness?.(i);return{...i,set:a===void 0?zo(i,t):a,blocking:!1}}),s=[];for(let i of r){if(i.need.kind!=="anyOf")continue;let a=i.need.group,c=s.find(d=>d.group===a);c||(c={group:a,members:[],met:!1},s.push(c)),c.members.push(i)}for(let i of s){i.met=i.members.some(c=>c.set===!0);let a=i.members.some(c=>c.set===null);if(!i.met&&!a)for(let c of i.members)c.blocking=!0}for(let i of r)i.need.kind==="required"&&i.set===!1&&(i.blocking=!0);let o=r.filter(i=>i.blocking);return{ready:o.length===0,settings:r,groups:s,unmet:o}}function Go(e,{cli:t,appId:n,provider:r=!1}){if(e.unmet.length===0)return null;if(!r)return{command:`${t} configure ${n}`};let s=[],o=i=>{for(let a of i.names)s.includes(a)||s.push(a)};for(let i of e.unmet)i.need.kind==="required"&&o(i);for(let i of e.groups){let a=i.members.find(c=>c.blocking);a&&o(a)}return{command:`${t} secret set ${s.join(" ")}`}}function Pd(e,t){let n=({alsoReads:r,...s})=>s;return{ready:e.ready,settings:e.settings.map(n),unmet:e.unmet.map(n),groups:e.groups.map(r=>({group:r.group,met:r.met,members:r.members.map(s=>s.id)})),command:t.withCommand===!1?null:Go(e,t)}}var Od=["cloudflare","resend"];var Ne={bodyBytes:5*1024*1024,recipients:50,subjectChars:998,headers:20,headerValueBytes:2048,headerNameBytes:100,headersTotalBytes:16*1024,attachments:32,senders:20,inbound:50,inboundAddressChars:90},Bo=/^(\*|[a-z0-9._+-]+)@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z][a-z0-9-]*[a-z0-9]$/,Wo=/^(\*|[a-z0-9._+-]+)@([a-z0-9-]+\.)+[a-z]{2,}$/,yt="everyapp email set";function $d(e,t){let n=[],r=e==="senders"?Ne.senders:Ne.inbound;t.length>r&&n.push(`At most ${r} ${e==="senders"?"senders":"inbound addresses"}, not ${t.length}.`);for(let s of t)e==="inbound"&&s.length>Ne.inboundAddressChars?n.push(`${s} is longer than Email Routing's ${Ne.inboundAddressChars} characters.`):(e==="senders"?Bo:Wo).test(s)||n.push(e==="senders"?`"${s}" isn't a sender: a sender is "*@<domain>" or "<local>@<domain>", in lowercase.`:`"${s}" isn't an inbound address: an inbound address is "*@<domain>" or "<local>@<domain>", in lowercase.`);for(let s of new Set(t.filter((o,i)=>t.indexOf(o)!==i)))n.push(`${s} is listed twice.`);return n}function Nd(e){return e.length===0?null:JSON.stringify(e)}function Dd(e,t){let n=e?.trim();if(!n)return null;let r=/^(.*?)\s*<([^<>]+)>$/.exec(n),s=(r?.[2]??n).trim(),o=r?.[1]?.trim().replace(/^(["'])(.*)\1$/,"$2").trim(),i=t?.trim()||o;return s&&i?{address:s,name:i}:null}function Ld(e){if(typeof e!="string"||!e.trim())return[];let t=e.trim();if(t.startsWith("["))try{let n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{return[]}return t.split(/[\s,]+/).filter(Boolean)}function jd(e){if(/[\p{Cc}\p{Cf}\u2028\u2029]/u.test(e))return null;let t=e.trim().replace(/\s+/g," ");return!t||[...t].length>64?null:t}var Et=/^[a-z][a-z0-9-]{1,39}$/,Fo=/^[A-Z][A-Z0-9_]{2,63}$/,Ho=/^(?=.{1,253}$)(?!-)[a-z0-9-]{1,63}(?<!-)(?:\.(?!-)[a-z0-9-]{1,63}(?<!-))+$/,wt=["GET","HEAD","POST","PUT","PATCH","DELETE"],Vo=/^[a-z0-9_-]{1,64}$/,Jo=/^[A-Za-z0-9-]{1,64}$/,Yo=/^[A-Za-z0-9_.-]{1,64}$/,qo=/^[A-Za-z][A-Za-z0-9-]{0,31}$/,Xo=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/,Zo=/^\d{4}-\d{2}-\d{2}$/,Qo=/^[a-z][a-z0-9-]{0,31}$/,ei=/[\p{Cc}\p{Cf}]/u,ti=new Set(["host","cookie","content-length","content-type","transfer-encoding","connection","upgrade","te","trailer","keep-alive","proxy-authorization","proxy-authenticate","forwarded","x-forwarded-for","x-forwarded-host","x-forwarded-proto"]),ni=20,Hn=50,ri=new Set(["id","mode","name","description","docs","api","hosts","hostSetting","data","auth","secrets","access","readMethods","writeMethods","accountWidePaths","hint","smoke","cost","rate","example","verified","tags"]);function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function T(e,t,n,{max:r,min:s=1}){if(e!==void 0){if(typeof e!="string"){n.push({path:t,message:"must be a string"});return}if(e.length<s||e.length>r){n.push({path:t,message:`must be ${s} to ${r} characters`});return}if(ei.test(e)){n.push({path:t,message:"holds a control character"});return}return e}}function Vn(e,t,n){let r=T(e,t,n,{max:500});if(r===void 0)return;let s;try{s=new URL(r)}catch{n.push({path:t,message:"must be an https URL"});return}if(s.protocol!=="https:"){n.push({path:t,message:"must be an https URL"});return}return r}function De(e,t,n,{max:r,each:s}){if(e===void 0)return;if(!Array.isArray(e)){n.push({path:t,message:"must be a list"});return}if(e.length>r){n.push({path:t,message:`at most ${r} entries`});return}let o=[];return e.forEach((i,a)=>{if(typeof i!="string"){n.push({path:`${t}.${a}`,message:"must be a string"});return}s(i,`${t}.${a}`),o.push(i)}),new Set(o).size!==o.length&&n.push({path:t,message:"lists an entry twice"}),o}function Jn(e,t,n){return De(e,t,n,{max:wt.length,each:(r,s)=>{wt.includes(r)||n.push({path:s,message:`must be one of ${wt.join(", ")}`})}})}function Me(e,t,n){if(typeof e!="string"||!Fo.test(e)){n.push({path:t,message:"must name a Gateway setting: upper case letters, digits and underscores, a letter first, 3 to 64 characters (STRIPE_API_KEY)"});return}return e}function si(e,t){if(!L(e)){t.push({path:"auth",message:"must be an object with a kind: bearer, header, query or basic"});return}let n=e.kind,r=Me(e.secret,"auth.secret",t),s=o=>{for(let i of Object.keys(e))o.includes(i)||t.push({path:`auth.${i}`,message:`not a field of auth.kind ${String(n)}`})};switch(n){case"bearer":{s(["kind","secret","scheme"]);let o=T(e.scheme,"auth.scheme",t,{max:32});return o!==void 0&&!qo.test(o)&&t.push({path:"auth.scheme",message:"must be a token such as Bearer, Token or Api-Key"}),r?{kind:n,secret:r,...o===void 0?{}:{scheme:o}}:void 0}case"header":{s(["kind","secret","header","prefix"]);let o=T(e.header,"auth.header",t,{max:64});o!==void 0&&(Jo.test(o)?(ti.has(o.toLowerCase())||o.toLowerCase().startsWith("x-everyapp-"))&&t.push({path:"auth.header",message:`${o} is a header the Gateway sets or strips itself`}):t.push({path:"auth.header",message:"must be a header name (letters, digits, hyphens)"}));let i=T(e.prefix,"auth.prefix",t,{max:32,min:0});return!r||o===void 0?void 0:{kind:n,secret:r,header:o,...i===void 0?{}:{prefix:i}}}case"query":{s(["kind","secret","param"]);let o=T(e.param,"auth.param",t,{max:64});return o!==void 0&&!Yo.test(o)&&t.push({path:"auth.param",message:"must be a query parameter name"}),!r||o===void 0?void 0:{kind:n,secret:r,param:o}}case"basic":{s(["kind","secret","as","user"]);let o=e.as;if(o!=="password"&&o!=="username"&&o!=="pair"){t.push({path:"auth.as",message:'must say where the key goes: "password" (beside user), "username" (with an empty password), or "pair" (the key is login:password)'});return}if(o!=="password")return e.user!==void 0&&t.push({path:"auth.user",message:`not a field of auth.as ${o}`}),r?{kind:n,secret:r,as:o}:void 0;let i=e.user,a;if(typeof i=="string"){let c=T(i,"auth.user",t,{max:128});c!==void 0&&c.includes(":")&&t.push({path:"auth.user",message:"may not hold a colon"}),a=c}else if(L(i)&&Object.keys(i).join()==="secret"){let c=Me(i.secret,"auth.user.secret",t);c!==void 0&&c===r&&t.push({path:"auth.user.secret",message:"must be another setting than auth.secret"}),a=c===void 0?void 0:{secret:c}}else t.push({path:"auth.user",message:"required with as: password: a string, or { secret: NAME }"});return!r||a===void 0?void 0:{kind:n,secret:r,as:o,user:a}}default:t.push({path:"auth.kind",message:"must be bearer, header, query or basic (an OAuth client or an AI provider is a catalog entry, not a spec this gateway takes)"});return}}function oi(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push({path:"secrets",message:"must be a list"});return}let r=[];return e.forEach((s,o)=>{let i=`secrets.${o}`;if(!L(s)){n.push({path:i,message:"must be an object"});return}for(let d of Object.keys(s))["name","hint"].includes(d)||n.push({path:`${i}.${d}`,message:"unknown field"});let a=Me(s.name,`${i}.name`,n);a!==void 0&&!t.includes(a)&&n.push({path:`${i}.name`,message:`auth names no setting ${a}`});let c=T(s.hint,`${i}.hint`,n,{max:300});a!==void 0&&r.push({name:a,...c===void 0?{}:{hint:c}})}),new Set(r.map(s=>s.name)).size!==r.length&&n.push({path:"secrets",message:"names a setting twice"}),r}function ii(e,t){if(e===void 0)return;if(!Array.isArray(e)){t.push({path:"accountWidePaths",message:'must be a list of segment runs: [["v1", "account"]]'});return}if(e.length>Hn){t.push({path:"accountWidePaths",message:`at most ${Hn} entries`});return}let n=[];return e.forEach((r,s)=>{let o=`accountWidePaths.${s}`;if(!Array.isArray(r)||r.length===0){t.push({path:o,message:"must be a non-empty list of segments"});return}let i=[];r.forEach((a,c)=>{if(typeof a!="string"||!Vo.test(a)){t.push({path:`${o}.${c}`,message:"must be a lowercase path segment (letters, digits, _ and -)"});return}i.push(a)}),i.length===r.length&&n.push(i)}),n}function ai(e,t,n){if(e===void 0)return;if(!L(e)){n.push({path:"smoke",message:"must be an object"});return}for(let l of Object.keys(e))["method","host","path","expect","free","note"].includes(l)||n.push({path:`smoke.${l}`,message:"unknown field"});let r=e.method;r!=="GET"&&r!=="HEAD"&&r!=="POST"&&n.push({path:"smoke.method",message:"must be GET, HEAD or POST"});let s=T(e.host,"smoke.host",n,{max:253});s!==void 0&&!t.includes(s)&&n.push({path:"smoke.host",message:"must be one of hosts"});let o=T(e.path,"smoke.path",n,{max:500});o!==void 0&&(!o.startsWith("/")||o.startsWith("//"))&&n.push({path:"smoke.path",message:"must start with one /"});let i=e.expect,a=Array.isArray(i)&&i.length>0&&i.every(l=>Number.isInteger(l)&&l>=100&&l<=599)?i:void 0;a||n.push({path:"smoke.expect",message:"must list the HTTP statuses that mean the key works"});let c=e.free;typeof c!="boolean"&&n.push({path:"smoke.free",message:"must be true or false"});let d=T(e.note,"smoke.note",n,{max:200});if(!(r!=="GET"&&r!=="HEAD"&&r!=="POST"||o===void 0||!a||typeof c!="boolean"))return{method:r,...s===void 0?{}:{host:s},path:o,expect:a,free:c,...d===void 0?{}:{note:d}}}function Le(e,t,n){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0){n.push({path:t,message:"must be a number, zero or more"});return}return e}}function ci(e,t){if(e===void 0)return;if(!L(e)){t.push({path:"cost",message:"must be an object"});return}for(let i of Object.keys(e))["unit","usd","note","responseField"].includes(i)||t.push({path:`cost.${i}`,message:"unknown field"});let n=e.unit;n!=="call"&&n!=="result"&&n!=="token"&&t.push({path:"cost.unit",message:"must be call, result or token"});let r=Le(e.usd,"cost.usd",t),s=T(e.note,"cost.note",t,{max:200}),o=T(e.responseField,"cost.responseField",t,{max:64});if(o!==void 0&&!Xo.test(o)&&t.push({path:"cost.responseField",message:"must be a JSON field name"}),!(n!=="call"&&n!=="result"&&n!=="token"))return{unit:n,...r===void 0?{}:{usd:r},...s===void 0?{}:{note:s},...o===void 0?{}:{responseField:o}}}function ui(e,t){if(e===void 0)return;if(!L(e)){t.push({path:"rate",message:"must be an object"});return}for(let i of Object.keys(e))["perSecond","perMinute","perDay","note"].includes(i)||t.push({path:`rate.${i}`,message:"unknown field"});let n=Le(e.perSecond,"rate.perSecond",t),r=Le(e.perMinute,"rate.perMinute",t),s=Le(e.perDay,"rate.perDay",t),o=T(e.note,"rate.note",t,{max:200});return{...n===void 0?{}:{perSecond:n},...r===void 0?{}:{perMinute:r},...s===void 0?{}:{perDay:s},...o===void 0?{}:{note:o}}}function di(e,t){if(e!==void 0){if(e===!1)return!1;if(L(e)&&typeof e.on=="string"&&Zo.test(e.on)&&(e.how==="docs"||e.how==="live")&&Object.keys(e).length===2)return{on:e.on,how:e.how};t.push({path:"verified",message:'must be false, or { "on": "YYYY-MM-DD", "how": "docs" | "live" }'})}}function bt(e){let t=[];if(!L(e))return{ok:!1,problems:[{path:"(root)",message:"must be a JSON object"}]};for(let N of Object.keys(e))ri.has(N)||t.push({path:N,message:"unknown field"});let n=e.id;(typeof n!="string"||!Et.test(n))&&t.push({path:"id",message:"must be lowercase letters, digits and hyphens, a letter first, 2 to 40 characters (stripe)"}),e.mode!==void 0&&e.mode!=="api_key"&&t.push({path:"mode",message:"this gateway registers api_key providers; an AI provider or an OAuth client is a catalog entry"});let r=T(e.name,"name",t,{max:64});e.name===void 0&&t.push({path:"name",message:"required"});let s=T(e.description,"description",t,{max:200}),o=Vn(e.docs,"docs",t);e.docs===void 0&&t.push({path:"docs",message:"required: where the person gets the key, an https URL"});let i=Vn(e.api,"api",t),a=De(e.hosts,"hosts",t,{max:ni,each:(N,ue)=>{Ho.test(N)||t.push({path:ue,message:"must be a bare lowercase host with a dot and no port, path or scheme (api.stripe.com)"})}}),c=e.hostSetting===void 0?void 0:Me(e.hostSetting,"hostSetting",t);c===void 0&&(e.hosts===void 0||a&&a.length===0)&&t.push({path:"hosts",message:"required: at least one host, or a hostSetting naming one"});let d=e.data;d!==void 0&&d!=="per-call"&&d!=="account"&&t.push({path:"data",message:"must be per-call or account"});let l=d==="per-call"||d==="account"?d:void 0,h=si(e.auth,t);e.auth===void 0&&t.push({path:"auth",message:"required"}),c!==void 0&&h&&Z(h).includes(c)&&t.push({path:"hostSetting",message:"must be another setting than the key"});let y=oi(e.secrets,[...h?Z(h):[],...c===void 0?[]:[c]],t),_=De(e.access,"access",t,{max:2,each:(N,ue)=>{N!=="read"&&N!=="write"&&t.push({path:ue,message:"must be read or write"})}});_&&_.length===0&&t.push({path:"access",message:"must list read, write or both"});let p=Jn(e.readMethods,"readMethods",t);p&&p.length===0&&t.push({path:"readMethods",message:"must list a method"});let E=Jn(e.writeMethods,"writeMethods",t),g=ii(e.accountWidePaths,t),b=T(e.hint,"hint",t,{max:500}),A=ai(e.smoke,a??[],t),K=ci(e.cost,t),En=ui(e.rate,t),bn=T(e.example,"example",t,{max:200}),_n=di(e.verified,t),Sn=De(e.tags,"tags",t,{max:10,each:(N,ue)=>{Qo.test(N)||t.push({path:ue,message:"must be a lowercase word"})}});if(t.length>0||typeof n!="string"||r===void 0||o===void 0||!a&&c===void 0||!h)return{ok:!1,problems:t};let eo={mode:"api_key",label:r,auth:h,docs:o,hosts:a??[],...c===void 0?{}:{hostSetting:c},...l===void 0?{}:{data:l},access:_??["read"],readMethods:p??["GET","HEAD"],accountWidePaths:g??[],...s===void 0?{}:{description:s},...i===void 0?{}:{api:i},...y===void 0?{}:{secrets:y},...E===void 0?{}:{writeMethods:E},...b===void 0?{}:{hint:b},...A===void 0?{}:{smoke:A},...K===void 0?{}:{cost:K},...En===void 0?{}:{rate:En},...bn===void 0?{}:{example:bn},..._n===void 0?{}:{verified:_n},...Sn===void 0?{}:{tags:Sn}};return{ok:!0,id:n,capability:eo}}function _t(e){return e.map(t=>`${t.path}: ${t.message}`).join("; ")}function Gd(e,t){return{id:e,name:t.label,...t.description===void 0?{}:{description:t.description},docs:t.docs,...t.api===void 0?{}:{api:t.api},hosts:[...t.hosts],...t.hostSetting===void 0?{}:{hostSetting:t.hostSetting},...t.data===void 0?{}:{data:t.data},auth:{...t.auth},...t.secrets===void 0?{}:{secrets:t.secrets.map(n=>({...n}))},access:[...t.access],readMethods:[...t.readMethods],...t.writeMethods===void 0?{}:{writeMethods:[...t.writeMethods]},accountWidePaths:t.accountWidePaths.map(n=>[...n]),...t.hint===void 0?{}:{hint:t.hint},...t.smoke===void 0?{}:{smoke:{...t.smoke,expect:[...t.smoke.expect]}},...t.cost===void 0?{}:{cost:{...t.cost}},...t.rate===void 0?{}:{rate:{...t.rate}},...t.example===void 0?{}:{example:t.example},...t.verified===void 0?{}:{verified:t.verified},...t.tags===void 0?{}:{tags:[...t.tags]}}}var pi=".everyapp/providers";function Fd(e){return`${pi}/${e}.json`}var B=new TextEncoder,Yn=new TextDecoder,li=new TextDecoder("utf-8",{fatal:!0}),Vd=2**32;function qn(...e){let t=e.reduce((s,{length:o})=>s+o,0),n=new Uint8Array(t),r=0;for(let s of e)n.set(s,r),r+=s.length;return n}var fi=/[^\x00-\x7f]/;function je(e){if(typeof e=="string"&&e.length>=128){if(fi.test(e))throw new TypeError("non-ASCII string encountered in encode()");return B.encode(e)}let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw new TypeError("non-ASCII string encountered in encode()");t[n]=r}return t}function St(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?"base64url":"base64",omitPadding:t});let n=32768,r=[];for(let o=0;o<e.length;o+=n)r.push(String.fromCharCode.apply(null,e.subarray(o,o+n)));let s=btoa(r.join(""));return t?s.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):s}function Ue(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw new TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return r}var W=class extends Error{code="ERR_JOSE_GENERIC";constructor(t,n){super(t,n),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};q(W,"code","ERR_JOSE_GENERIC");var x=class extends W{code="ERR_JOSE_NOT_SUPPORTED"};q(x,"code","ERR_JOSE_NOT_SUPPORTED");var O=class extends W{code="ERR_JWS_INVALID"};q(O,"code","ERR_JWS_INVALID");var fe=class extends W{code="ERR_JWT_INVALID"};q(fe,"code","ERR_JWT_INVALID");var At=class extends W{[Symbol.asyncIterator]=async function*(){};code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",n){super(t,n)}};q(At,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var mi="The input to be decoded is not correctly encoded.";function Xn(e){try{return Ue(typeof e=="string"?e:Yn.decode(e),!0)}catch(t){throw new TypeError(mi,{cause:t})}}function me(e){return St(typeof e=="string"?B.encode(e):e,!0)}function he(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function Zn(...e){let t=new Set;for(let n of e)if(n)for(let r of Object.keys(n)){if(t.has(r))return!1;t.add(r)}return!0}function Qn(e,t){if(e!==void 0)throw new TypeError(`${t} can only be called once`)}var er={__proto__:null,b64:!0};function tr(e,t){let{crit:n}=t??{};if(Array.isArray(n)&&new Set(n).size!==n.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function nr(e,t,n,r,s){if(s.crit!==void 0&&r?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o=n===void 0?t:{__proto__:null,...n,...t};for(let i of r.crit){if(!(i in o))throw new x(`Extension Header Parameter "${i}" is not recognized`);if(!Object.hasOwn(s,i)||s[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(o[i]&&(!Object.hasOwn(r,i)||r[i]===void 0))throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return r.crit}function rr(e,t){if(t.includes("b64")){let n=e.b64;if(typeof n!="boolean")throw new O('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return n}return!0}function kt(e,t){let n,r;try{n=JSON.stringify(t),r=JSON.parse(n)}catch(s){throw new e("JOSE Header is not valid JSON",{cause:s})}if(!he(r))throw new e("JOSE Header is not a JSON object");return[r,n]}var hi=e=>e[Symbol.toStringTag],gi=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let s=n==="sign"||n==="verify"?"sig":"enc";if(t.use!==s)throw new TypeError(`Invalid key for this operation, its "use" must be "${s}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw new TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let s=n==="encrypt"||n==="decrypt"?e.ops?.[n==="encrypt"?0:1]:n;if(s&&!t.key_ops.includes(s))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${s}" when present`)}};async function or(e,t,n){let{alg:r,secret:s}=e,o=n==="decrypt"||n==="sign";if(s&&t instanceof Uint8Array)return t;let i,a;if(he(t)){if(i=Ai(t),typeof i.kty!="string")throw sr(r,t,s);if(!(s?i.kty==="oct"&&typeof i.k=="string":i.kty!=="oct"&&(o?i.kty==="AKP"&&typeof i.priv=="string"||typeof i.d=="string":i.d===void 0&&i.priv===void 0)))throw new TypeError(s?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${o?"private":"public"} JWK`);if(gi(e,i,n),i.kty==="oct")return Xn(i.k);if(!Object.isFrozen(t)){let{key_ops:l}=t;Array.isArray(l)&&Object.freeze(l),Object.freeze(t)}}else{if(!wi(t))throw sr(r,t,s);let l=s?"secret":o?"private":"public";if(t.type!==l&&(s||["secret","public","private"].includes(t.type)))throw new TypeError(`${hi(t)} instances must be of type "${l}" for the ${r} algorithm`);if(Tt(t))return t;if(a=t,a.type==="secret")return a.export()}It||=new WeakMap;let c=t,d=It.get(c);if(d?.[r])return d[r];if(d||It.set(c,d={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",h=yi[a.asymmetricKeyDetails?.namedCurve],y=e.resolve?.({crv:h,asymmetricKeyType:a.asymmetricKeyType})??e.subtle;return d[r]=a.toCryptoKey(y,l,e.usages[l?0:1])}return i??=a.export({format:"jwk"}),i.alg=r,d[r]=await ki(e,i)}var It,yi={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};var Tt=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},ir=e=>e?.[Symbol.toStringTag]==="KeyObject",wi=e=>Tt(e)||ir(e);function Ei(e,t,...n){if(n.length>2){let r=n.pop();e+=`one of type ${n.join(", ")}, or ${r}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function sr(e,t,n){let r=["CryptoKey","KeyObject","JSON Web Key"];return n&&r.push("Uint8Array"),new TypeError(Ei(`Key for the ${e} algorithm must be `,t,...r))}var Ke=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function bi(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function ar(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!="number"||n<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function _i(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw Ke(t.name);if(t.hash&&r.hash?.name!==t.hash)throw Ke(t.hash,"algorithm.hash");if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw Ke(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&r.length!==t.length)throw Ke(t.length,"algorithm.length");bi(e,n)}function Si(e){return{__proto__:null,...e}}function Ai(e){let t=Si(e);if(t.ext!==void 0&&typeof t.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let n=t.key_ops,r=Array.isArray(n)?[...n]:void 0;if(!r||r.some(s=>typeof s!="string")||new Set(r).size!==r.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=r}return t}function cr(e){if(e!==void 0&&typeof e!="boolean")throw new TypeError('"extractable" option must be a boolean');return e}async function ki(e,t,n){if(!e.kty.includes(t.kty))throw new x('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,s=!!(t.d||t.priv),o={...t,ext:n??t.ext};return o.kty!=="AKP"&&delete o.alg,delete o.use,crypto.subtle.importKey("jwk",o,r,o.ext??!s,t.key_ops??e.usages[s?1:0])}async function ur(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,r,[n])),_i(e,t,n),e}function ge(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}var Ii=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Ti=[[],["deriveBits"]],Be=[[],[]];function ze(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:Ii,ops:["wrapKey","unwrapKey"]}}function Ge(e){return{kty:["EC","OKP"],mode:e,subtle:{name:"ECDH"},resolve:({kty:t,crv:n,asymmetricKeyType:r})=>{if(n==="X25519"||r==="x25519")return{name:"X25519"};if(t==="OKP")throw new x('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:n}},usages:Ti,ops:[void 0,"deriveBits"]}}function te(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:Be,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function Rt(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:Be,ops:["deriveBits","deriveBits"]}}var dr=ge({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:Be,ops:["encrypt","decrypt"]},"RSA-OAEP":ze(1),"RSA-OAEP-256":ze(256),"RSA-OAEP-384":ze(384),"RSA-OAEP-512":ze(512),"ECDH-ES":Ge("direct-key-agreement"),"ECDH-ES+A128KW":Ge("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":Ge("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":Ge("key-agreement-with-key-wrapping"),A128KW:te(128),A192KW:te(192),A256KW:te(256),A128GCMKW:te(128,!0),A192GCMKW:te(192,!0),A256GCMKW:te(256,!0),"PBES2-HS256+A128KW":Rt(),"PBES2-HS384+A192KW":Rt(),"PBES2-HS512+A256KW":Rt()}),Ri=["encrypt","decrypt"];function ne(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:Be,ops:Ri,cekBits:e,ivBits:t?128:96,cbc:t}}var cp=ge({A128GCM:ne(128),A192GCM:ne(192),A256GCM:ne(256),"A128CBC-HS256":ne(256,!0),"A192CBC-HS384":ne(384,!0),"A256CBC-HS512":ne(512,!0)});var ye=[["verify"],["sign"]];function xt(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:ye}}function re(e,t){let n={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:n,signing:t?{...n,saltLength:t}:n,usages:ye,minRsaBits:2048}}function vt(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:ye}}function pr(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:ye}}function Pt(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:ye}}var Ct=ge({HS256:xt(256),HS384:xt(384),HS512:xt(512),RS256:re(256),RS384:re(384),RS512:re(512),PS256:re(256,32),PS384:re(384,48),PS512:re(512,64),ES256:vt("P-256",256),ES384:vt("P-384",384),ES512:vt("P-521",512),EdDSA:pr(),Ed25519:pr(),"ML-DSA-44":Pt(44),"ML-DSA-65":Pt(65),"ML-DSA-87":Pt(87)});function lr(e){let t=typeof e=="string"?Ct[e]:void 0;if(!t)throw new x(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}var We=e=>Math.floor(e.getTime()/1e3),xi={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},vi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Ot(){throw new TypeError("Invalid time period format")}function fr(e){typeof e!="string"&&Ot();let t=vi.exec(e);(!t||t[4]&&t[1])&&Ot();let n=parseFloat(t[2]),r=Math.round(n*xi[t[3][0].toLowerCase()]);return Number.isFinite(r)||Ot(),t[1]==="-"||t[4]==="ago"?-r:r}function Dt(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function $t(e,t){if(typeof t!="string")throw new TypeError(`"${e}" claim must be a string`)}function Pi(e){if(typeof e!="string"&&(!Array.isArray(e)||Array.from(e).some(t=>typeof t!="string")))throw new TypeError('"aud" claim must be a string or an array of strings')}function Nt(e,t){return typeof e=="number"?Dt(t,e):e instanceof Date?Dt(t,We(e)):We(new Date)+fr(e)}var mr;function M(e){return mr.get(e)}function hr(e){let t=M(e);for(let n of["iat","nbf","exp"]){let r=t[n];if(typeof r=="number"&&!Number.isFinite(r))throw new TypeError(`"${n}" claim must be a finite number`)}return B.encode(JSON.stringify(t))}var Fe=class{constructor(t={}){if(!he(t))throw new TypeError("JWT Claims Set MUST be an object");(mr||=new WeakMap).set(this,structuredClone(t))}setIssuer(t){return $t("iss",t),M(this).iss=t,this}setSubject(t){return $t("sub",t),M(this).sub=t,this}setAudience(t){return Pi(t),M(this).aud=t,this}setJti(t){return $t("jti",t),M(this).jti=t,this}setNotBefore(t){return M(this).nbf=Nt(t,"setNotBefore"),this}setExpirationTime(t){return M(this).exp=Nt(t,"setExpirationTime"),this}setIssuedAt(t){let n=M(this);return t===void 0?n.iat=We(new Date):typeof t=="string"?n.iat=Dt("setIssuedAt",We(new Date)+fr(t)):n.iat=Nt(t,"setIssuedAt"),this}};async function Ci(e,t,n){let[r,s,o,i]=e,a="";if(s!==void 0){let b=kt(O,s);s=b[0],a=me(b[1])}if(o!==void 0&&(o=kt(O,o)[0]),!s&&!o)throw new O("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Zn(s,o))throw new O("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...s,...o};tr(O,s);let d=rr(s,nr(O,er,i,s,c));d||n?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new O('JWS "alg" (Algorithm) Header Parameter missing or invalid');let h=lr(l),y="",_=r,p;if(d){let b=e[4];b?(y=b[0]??=me(r),_=b[1]??=je(y)):(y=me(r),p=B.encode(`${a}.${y}`))}p??=qn(je(a),je("."),_);let E=await ur(await or(h,t,"sign"),h.subtle,"sign");h.minRsaBits&&ar(h.alg,E);let g={signature:me(new Uint8Array(await crypto.subtle.sign(h.signing,E,p))),payload:y};return s&&(g.protected=a),o&&(g.header=o),[g,d]}async function gr(e,t,n,r,s){let[o]=await Ci([e,t,void 0,n],r,s);return`${o.protected}.${o.payload}.${o.signature}`}var Oi=Fe,F=class extends Oi{#e;setProtectedHeader(t){return Qn(this.#e,"setProtectedHeader"),this.#e=t,this}async sign(t,n){return gr(hr(this),this.#e,n?.crit,t,()=>{throw new fe("JWTs MUST NOT use unencoded payload")})}};var Lt='"alg" (Algorithm)';function Mt(e='JWK "alg" (Algorithm) Parameter'){throw new x(`Invalid or unsupported ${e} value`)}function yr(e,t){return(typeof e=="string"?Ct[e]??dr[e]:void 0)??Mt(t)}var we=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},$i=e=>({data:e,pos:0}),jt=e=>{let t=e.data[e.pos++];if(t===void 0)throw new Error("Unexpected end of ASN.1 input");return t},Ee=e=>{let t=jt(e);if(t&128){let n=t&127,r=0;for(let s=0;s<n;s++)r=r<<8|jt(e);return r}return t};var be=(e,t,n)=>{if(jt(e)!==t)throw new Error(n)},wr=(e,t)=>{if(t<0||e.pos+t>e.data.length)throw new Error("Unexpected end of ASN.1 input");let n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},Ni=e=>{be(e,6,"Expected algorithm OID");let t=Ee(e);return wr(e,t)};function Di(e,t){if(be(e,48,`Invalid ${t==="spki"?"SPKI":"PKCS#8"} structure`),Ee(e),t==="pkcs8"){be(e,2,"Expected version field");let n=Ee(e);e.pos+=n}be(e,48,"Expected algorithm identifier"),Ee(e)}var Li=e=>{let t=Ni(e);if(we(t,[43,101,110]))return"X25519";if(!we(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");be(e,6,"Expected curve OID");let n=Ee(e),r=wr(e,n);if(we(r,[42,134,72,206,61,3,1,7]))return"P-256";if(we(r,[43,129,4,0,34]))return"P-384";if(we(r,[43,129,4,0,35]))return"P-521";throw new Error("Unsupported named curve")},Mi=async(e,t,n,r)=>{let s=cr(r?.extractable),o=yr(n,Lt);o.secret&&Mt(Lt);let i=e==="spki",a;if(o.resolve)try{let c=$i(t);Di(c,e),a=o.resolve({crv:Li(c)})}catch{throw new x("Invalid or unsupported key format")}else a=o.subtle;return crypto.subtle.importKey(e,t,a,s??i,o.usages[i?0:1])},ji=(e,t)=>Ue(e.replace(t,"")),Er=(e,t,n)=>{let r=ji(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);return Mi("pkcs8",r,t,n)};async function Ut(e,t,n){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Er(e,t,n)}var _e="RS256",Ve="everyapp-identity",Ui="everyapp-identity-dev";var Ki="x-everyapp-identity",zi="x-everyapp-public",Yp="x-everyapp-system";var br=120,Kt=60;var _r="public",Gi="system";function Bi(e,t){return{typ:"user",email:e.email,org_id:e.orgId,org_role:e.orgRole,chan:t.channel??"web",act:t.actor??{sub:e.sub},scopes:t.scopes??["*"],jti:t.jti,...t.toolCall?{tc:{id:t.toolCall.id,name:t.toolCall.name}}:{}}}function Wi(e){return{typ:"public",pub:!0,jti:e}}var He=null;async function zt(e){let t=e.replace(/\\n/g,`
3
+ `);if(He&&He.pem===t)return He.key;let n=await Ut(t,_e);return He={pem:t,key:n},n}async function qp(e,t){let n=await zt(e),r=Math.floor((t.now??Date.now())/1e3),s=t.ttlSeconds??br,o=crypto.randomUUID();return new F(Bi(t.subject,{channel:t.channel,actor:t.actor,scopes:t.scopes,toolCall:t.toolCall,jti:o})).setProtectedHeader({alg:_e,kid:t.keyId??Ve}).setIssuer(t.issuer).setSubject(t.subject.sub).setAudience(t.audience).setIssuedAt(r).setExpirationTime(r+s).sign(n)}async function Xp(e,t){let n=await zt(e),r=Math.floor((t.now??Date.now())/1e3),s=t.ttlSeconds??br;return new F(Wi(crypto.randomUUID())).setProtectedHeader({alg:_e,kid:t.keyId??Ve}).setIssuer(t.issuer).setSubject(_r).setAudience(t.audience).setIssuedAt(r).setExpirationTime(r+s).sign(n)}async function Zp(e,t){let n=t.ttlSeconds??Kt;if(n<=0||n>Kt)throw new RangeError(`system tokens live at most ${Kt}s (got ${n})`);let r=await zt(e),s=Math.floor((t.now??Date.now())/1e3),o={typ:"system",purpose:t.purpose,jti:crypto.randomUUID()};return new F(o).setProtectedHeader({alg:_e,kid:t.keyId??Ve}).setIssuer(t.issuer).setSubject(Gi).setAudience(t.audience).setIssuedAt(s).setExpirationTime(s+n).sign(r)}function Fi(e){let{basePath:t,normalize:n}=e;return{origin:e.origin,keyEnv:e.auth.secret,auth:e.auth,docs:e.docs,...e.setup===void 0?{}:{setup:e.setup},...e.alsoNeeds===void 0?{}:{alsoNeeds:e.alsoNeeds},...t===void 0?{}:{basePath:r=>Hi(t,r)??""},...n==="workers-ai"?{normalizeResponse:qi}:{}}}var Sr=Object.fromEntries(D.flatMap(e=>{let t=v[e];return t.mode==="ai"?[[e,Fi(t)]]:[]}));function tl(e){return Object.hasOwn(Sr,e)?Sr[e]:void 0}function nl(e){return[e.keyEnv,...e.alsoNeeds??[]]}function Hi(e,t){let n=!1,r=e.replace(/\{([A-Z][A-Z0-9_]*)\}/g,(s,o)=>{let i=t[o];return typeof i!="string"||!i.trim()?(n=!0,""):encodeURIComponent(i.trim())});return n?null:r}var Vi=new Set(["/v1/chat/completions"]),Ji=["content","reasoning_content","reasoning"],Yi=/"(?:content|reasoning_content|reasoning)"\s*:\s*-?\d/;function qi(e,t){if(!t.body||!Vi.has(e))return t;let n=(t.headers.get("content-type")??"").toLowerCase(),r=n.startsWith("text/event-stream")?Zi():n.startsWith("application/json")?Qi():null;if(!r)return t;let s=new Headers(t.headers);return s.delete("content-length"),new Response(t.body.pipeThrough(r),{status:t.status,statusText:t.statusText,headers:s})}function Xi(e){if(!Gt(e)||!Array.isArray(e.choices))return!1;let t=!1;for(let n of e.choices)if(Gt(n)){for(let r of[n.delta,n.message])if(Gt(r))for(let s of Ji){let o=r[s];typeof o=="number"&&(r[s]=String(o),t=!0)}}return t}function Ar(e){if(!Yi.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}return Xi(t)?JSON.stringify(t):null}function Zi(){let e=new TextDecoder,t=new TextEncoder,n="",r=s=>{let o=/^(data:[ ]?)(.*?)(\r?)$/s.exec(s);if(!o)return s;let i=Ar(o[2]);return i===null?s:`${o[1]}${i}${o[3]}`};return new TransformStream({transform(s,o){n+=e.decode(s,{stream:!0});let i=n.lastIndexOf(`
4
+ `);if(i===-1)return;let a=n.slice(0,i+1);n=n.slice(i+1),o.enqueue(t.encode(a.split(`
5
+ `).map(r).join(`
6
+ `)))},flush(s){n+=e.decode(),n&&s.enqueue(t.encode(r(n)))}})}function Qi(){let e=[];return new TransformStream({transform(t){e.push(t)},flush(t){let n=new TextDecoder,r=e.map(o=>n.decode(o,{stream:!0})).join("")+n.decode(),s=Ar(r);if(s!==null){t.enqueue(new TextEncoder().encode(s));return}for(let o of e)t.enqueue(o)}})}function Gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var il=64*1024;var w=(e,t,n,r=1)=>({type:t,version:r,description:n,group:e}),kr=[w("member","member.invited","Someone was invited to the workspace"),w("member","member.joined","Someone joined the workspace"),w("member","member.role_changed","A member's role changed"),w("member","member.deactivated","A member was deactivated"),w("member","member.reactivated","A member was reactivated"),w("member","member.removed","A member was removed"),w("member","member.password_reset","A member reset their password"),w("app","app.installed","An app was installed on the Gateway"),w("app","app.updated","An app was redeployed"),w("app","app.removed","An app was removed from the Gateway"),w("app","app.needs_setup","An app needs a setting before it opens"),w("app","app.ready","An app has every setting it needs"),w("app","app.paused_cap","An app is paused: its monthly cap is reached"),w("app","app.tools_changed","An app's AI tools changed"),w("cap","cap.warning","An app is at 80% of its monthly cap"),w("cap","cap.reached","An app reached its monthly cap"),w("cap","cap.raised","An app's monthly cap, or the workspace default, was raised or removed"),w("tool","tool.blocked","An AI client's tool call was blocked"),w("tool","tool.error","An AI client's tool call failed"),w("connection","connection.created","An AI app was connected"),w("connection","connection.revoked","An AI app connection was revoked"),w("token","token.created","A personal access token was created"),w("token","token.revoked","A personal access token was revoked"),w("access","access.changed","Cloudflare Access was turned on or off"),w("mcp_app","mcp_app.added","An MCP app was added"),w("mcp_app","mcp_app.removed","An MCP app was removed"),w("mcp_app","mcp_app.enabled","An MCP app is being served again"),w("mcp_app","mcp_app.disabled","An MCP app stopped being served"),w("provider","provider.added","An API provider was registered"),w("provider","provider.removed","An API provider was removed"),w("ping","ping","A test event, sent to one subscription on request")],Ft=new Map(kr.map(e=>[e.type,e]));function ul(e){return Ft.get(e)}var Bt="app.";var ea=64;function ta(e){return e.startsWith(Bt)&&!Ft.has(e)&&e.slice(Bt.length).includes(".")}var na=8*1024,dl=16*1024,Ir=8;var pl=25,ll=16,fl=128,ml=30,hl=2048,gl=100,ra=[6e4,3e5,18e5,72e5,288e5,864e5],yl=ra.length+1;var wl="EVENTS_ALLOW_PRIVATE_TARGETS",sa=["localhost","local","localdomain","internal","intranet","lan","corp","private","home.arpa","onion"];function El(e){return e.includes(".")?sa.some(t=>e===t||e.endsWith(`.${t}`)):!0}var bl=["owners","admins"];function oa(e,t){return e==="*"?t!=="ping":e.endsWith(".*")?t.startsWith(e.slice(0,-1)):e===t}function _l(e,t){return e.some(n=>oa(n,t))}var ia=/^(\*|[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*(\.\*)?)$/;function Sl(e){if(!ia.test(e)||e.length>ea+8)return`"${e}" isn't an event type or pattern (member.joined, member.*, app.crm.*, *)`;if(e==="*"||Ft.has(e))return null;if(e.endsWith(".*")){let t=e.slice(0,-1);return kr.some(n=>n.type.startsWith(t))||e.startsWith(Bt)?null:`"${e}" matches no event type (everyapp events types lists them)`}return ta(e)?null:`"${e}" isn't an event type (everyapp events types lists them)`}var aa=/secret|token|password|passwd|authorization|api[_-]?key|private[_-]?key|credential|cookie|session/i;function Wt(e,t){if(t>Ir)return"\0depth";if(Array.isArray(e)){for(let n of e){let r=Wt(n,t+1);if(r)return r}return null}if(e&&typeof e=="object")for(let[n,r]of Object.entries(e)){if(aa.test(n))return n;let s=Wt(r,t+1);if(s)return s}return null}function Al(e,t=na){if(e===null||typeof e!="object"||Array.isArray(e))return{ok:!1,code:"event_data_invalid",message:"data is a JSON object"};let n;try{n=JSON.stringify(e)}catch{return{ok:!1,code:"event_data_invalid",message:"data must serialize as JSON"}}if(n===void 0)return{ok:!1,code:"event_data_invalid",message:"data is a JSON object"};let r=new TextEncoder().encode(n).length;if(r>t)return{ok:!1,code:"event_data_too_large",message:`data is at most ${t.toLocaleString("en-US")} bytes as JSON (this is ${r.toLocaleString("en-US")})`,bytes:r};let s=Wt(JSON.parse(n),1);return s==="\0depth"?{ok:!1,code:"event_data_invalid",message:`data nests at most ${Ir} levels deep`}:s?{ok:!1,code:"event_data_refused",message:`data must not carry a credential: the key "${s}" reads like one (secret, token, password, authorization, api key, private key, credential, cookie, session)`,key:s}:{ok:!0,bytes:r}}function ca(e){let t=Object.fromEntries(Object.entries(e.auth).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>[n,typeof r=="object"&&r!==null?Object.fromEntries(Object.entries(r).sort(([s],[o])=>s<o?-1:s>o?1:0)):r]));return JSON.stringify({auth:t,hostSetting:e.hostSetting??null,hosts:[...e.hosts].sort()})}var ua=new Set(["everyapp"]),da=/^\d{1,3}(\.\d{1,3}){3}$/,pa=[".localhost",".local",".internal",".arpa"];function la(e){return`${e.toUpperCase().replace(/-/g,"_")}_`}function fa(e){return da.test(e)?`${e} is an IP address, not a host name`:e==="localhost"||pa.some(t=>e.endsWith(t))?`${e} is not a public host`:null}function Ht(e){let t=e?.trim().toLowerCase().replace(/\.$/,"");if(!t)return null;if(!t.includes("/"))return t;try{return new URL(t).hostname.toLowerCase()}catch{return null}}function xl(e,t){let n=Ht(t.gatewayHost);if(n&&e===n)return`${e} is this gateway's own host`;let r=Ht(t.appBaseDomain);if(r&&(e===r||e.endsWith(`.${r}`)))return`${e} is under this gateway's app domain ${r}`;let s=Ht(t.thirdPartyDomain);return s&&(e===s||e.endsWith(`.${s}`))?`${e} is under this gateway's third-party domain ${s}`:null}function ma(e,t,n){let r=la(e);return t.startsWith(r)?de(t)?`${t} is one of the Gateway's own keys`:Tn(t)?`${t} is a local-development setting`:Pe(t)?`${t} is a name everyapp sets itself`:G(t)?`${t} is a Gateway setting another provider or the Gateway reads`:n(t)?`${t} is another registered provider's`:null:`${t} doesn't start with ${r}: a provider's settings carry its own id`}function ha(e,t,n){if(ua.has(e)||D.includes(e))return{id:e,code:"PROVIDER_BUILTIN",message:`${e} is a built-in provider; a registered one can't take its id`};for(let r of C(t)){let s=ma(e,r,o=>n.rowSettings.has(o));if(s)return{id:e,code:"PROVIDER_SECRET_TAKEN",message:s}}for(let r of t.hosts){let s=fa(r)??n.refuseHost?.(r);if(s)return{id:e,code:"PROVIDER_HOST_REFUSED",message:s}}return null}function ga(e,t){let n=e.spec;if(typeof n=="string")try{n=JSON.parse(n)}catch{return{ok:!1,refusal:{id:e.id,code:"PROVIDER_SPEC_INVALID",message:"the stored spec isn't JSON"}}}let r=bt(n);if(!r.ok)return{ok:!1,refusal:{id:e.id,code:"PROVIDER_SPEC_INVALID",message:_t(r.problems)}};if(r.id!==e.id||!Et.test(e.id))return{ok:!1,refusal:{id:e.id,code:"PROVIDER_SPEC_INVALID",message:`the row is ${e.id} but its spec says ${r.id}`}};let s=ha(r.id,r.capability,t);return s?{ok:!1,refusal:s}:{ok:!0,capability:r.capability}}function ya(e=[],t={}){let n=new Map(D.map(d=>[d,v[d]])),r=new Map,s=[],o=new Set;for(let d of e){if(r.has(d.id)){s.push({id:d.id,code:"PROVIDER_SPEC_INVALID",message:"listed twice"});continue}let l=ga(d,{rowSettings:o,...t.refuseHost?{refuseHost:t.refuseHost}:{}});if(!l.ok){s.push(l.refusal);continue}r.set(d.id,{id:d.id,capability:l.capability,bound:d.boundTo===ca(l.capability),addedBy:d.addedBy??null,addedAt:d.addedAt??null});for(let h of C(l.capability))o.add(h)}let i=new Map([...n,...[...r.values()].map(d=>[d.id,d.capability])]),a,c;return{get:d=>i.get(d),ids:()=>[...i.keys()],entries:()=>[...i.entries()],sourceOf:d=>n.has(d)?"catalog":r.has(d)?"row":void 0,settingNames:()=>(a??=new Set([...i.values()].flatMap(d=>C(d))),a),bound:d=>n.has(d)||(r.get(d)?.bound??!1),unboundSettings:()=>(c??=new Set([...r.values()].filter(d=>!d.bound).flatMap(d=>C(d.capability))),c),rows:()=>[...r.values()],rejected:s}}var vl=ya();import{z as u}from"zod";var Tr=/[\x00-\x1f\x7f]/,wa=/%2f|%5c/i;function Vt(e){if(typeof e!="string"||e.length===0)return{canonical:"/",ambiguous:!0,reason:"empty path"};if(!e.startsWith("/"))return{canonical:"/",ambiguous:!0,reason:"non-absolute path"};if(Tr.test(e))return{canonical:"/",ambiguous:!0,reason:"control characters"};if(e.includes("\\"))return{canonical:"/",ambiguous:!0,reason:"backslash"};if(wa.test(e))return{canonical:"/",ambiguous:!0,reason:"encoded path separator"};let t;try{t=decodeURIComponent(e)}catch{return{canonical:"/",ambiguous:!0,reason:"invalid percent-encoding"}}if(t.includes("%"))return{canonical:"/",ambiguous:!0,reason:"double-encoded"};if(Tr.test(t)||t.includes("\\"))return{canonical:"/",ambiguous:!0,reason:"decoded to unsafe characters"};let n=[],r=!1;for(let o of t.split("/"))if(!(o===""||o===".")){if(o===".."){if(n.length===0)return{canonical:"/",ambiguous:!0,reason:"path traversal above root"};n.pop(),r=!0;continue}n.push(o)}let s="/"+n.join("/");return r&&/%2e/i.test(e)?{canonical:s,ambiguous:!0,reason:"encoded traversal"}:{canonical:s,ambiguous:!1}}function Ea(e){return e===H||e.startsWith(H+"/")}function wf(e){return Rr(Vt(e).canonical)||Rr(vr(e))}function Rr(e){let t=e.toLowerCase();return t===le||t.startsWith(`${le}/`)}var ba=["oauth-protected-resource","oauth-authorization-server","openid-configuration"],_a=ba.flatMap(e=>[`/.well-known/${e}`,`/mcp/.well-known/${e}`]);function Ef(e){return xr(Vt(e).canonical)||xr(vr(e))}function xr(e){let t=e.toLowerCase();return _a.some(n=>t===n||t.startsWith(`${n}/`))}function vr(e){let t=e;for(let r=0;r<3;r+=1){let s;try{s=decodeURIComponent(t)}catch{break}if(s===t)break;t=s}let n=[];for(let r of t.replace(/\\/g,"/").split("/"))if(!(r===""||r===".")){if(r===".."){n.pop();continue}n.push(r)}return"/"+n.join("/")}function Sa(e){let t="^",n=0;for(;n<e.length;){let r=e[n];if(r==="*")e[n+1]==="*"?(t+=".*",n+=2):(t+="[^/]*",n+=1);else if(r===":"&&e[n-1]==="/"){let s=e.slice(n+1).match(/^[A-Za-z_][A-Za-z0-9_]*/)?.[0],o=s?e[n+1+s.length]:void 0;s&&(o===void 0||o==="/")?(t+="[^/]+",n+=1+s.length):(t+="\\:",n+=1)}else t+=r.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n+=1}return t+="$",new RegExp(t)}function Pr(e,t,n){if(!e||e.length===0)return{public:!1,reason:"no public routes declared"};let{canonical:r,ambiguous:s,reason:o}=Vt(n);if(s)return{public:!1,reason:`ambiguous path: ${o}`};if(Ea(r))return{public:!1,reason:"internal namespace is never public"};let i=t.toUpperCase();for(let a of e)if((a.methods??["GET"]).map(d=>d.toUpperCase()).includes(i)&&Sa(a.path).test(r))return{public:!0,route:a,reason:`matched ${a.path}`};return{public:!1,reason:"no matching public route"}}var Nr=u.object({path:u.string(),methods:u.array(u.string()).optional()}),Je=u.object({name:u.string(),className:u.string(),worker:u.string().optional()}),Dr=u.object({name:u.string(),worker:u.string().optional(),caching:u.enum(["off","default"]).optional()}),Lr=u.object({d1:u.array(u.string()).optional(),kv:u.array(u.string()).optional(),durableObjects:u.array(Je).optional(),workflows:u.array(Je).optional(),hyperdrive:u.array(Dr).optional(),r2:u.array(u.string()).optional()}).passthrough(),Aa=u.string().regex(/^\d{4}-\d{2}-\d{2}$/,"must be YYYY-MM-DD"),ka=/^[a-z0-9][a-z0-9:_-]{0,63}$/,Jt={when:({value:e})=>typeof e=="object"&&e!==null&&!Array.isArray(e)},Mr=u.record(u.string(),u.string().min(1).max(200)).superRefine((e,t)=>{for(let n of Object.keys(e))n==="*"||n.startsWith("provider:")?t.addIssue({code:u.ZodIssueCode.custom,path:[n],message:"reserved scope id"}):ka.test(n)||t.addIssue({code:u.ZodIssueCode.custom,path:[n],message:"invalid scope id"})},Jt),Ia=Mr,Ta=u.object({engine:u.enum(["drizzle","d1-sql","prisma"]),dialect:u.enum(["sqlite","postgresql"]).optional(),dir:u.string().optional(),config:u.string().min(1).optional(),binding:u.string().min(1).optional()}).strict().superRefine((e,t)=>{if(e.engine==="prisma"&&e.dialect!=="postgresql"&&t.addIssue({code:u.ZodIssueCode.custom,path:["engine"],message:'Prisma migrations run on Postgres (dialect "postgresql"); D1 takes the generated SQL through "d1-sql"'}),e.dialect==="postgresql"&&(e.engine==="d1-sql"&&t.addIssue({code:u.ZodIssueCode.custom,path:["engine"],message:'Postgres migrations run on the "drizzle" or "prisma" engine'}),e.binding!==void 0&&t.addIssue({code:u.ZodIssueCode.custom,path:["binding"],message:"binding names a D1 database; Postgres migrations have none"})),e.config!==void 0&&!$r(e.config)&&t.addIssue({code:u.ZodIssueCode.custom,path:["config"],message:"config must be a relative path without .. segments"}),e.engine==="d1-sql"&&!e.dir?.trim()){t.addIssue({code:u.ZodIssueCode.custom,path:["dir"],message:'dir is required when migrations.engine is "d1-sql"'});return}e.dir&&!$r(e.dir)&&t.addIssue({code:u.ZodIssueCode.custom,path:["dir"],message:"dir must be a relative path without .. segments"})}),Ra=u.union([u.literal(!1),u.string().min(1)]),jr=/^[a-z][a-z0-9-]*$/,Ur="provider must start with a lowercase letter and contain only lowercase letters, digits, and hyphens",Xe=u.string().regex(jr,Ur);function Kr(e,t){return jr.test(e)?!1:(t.addIssue({code:u.ZodIssueCode.custom,path:[e],message:Ur}),!0)}var xa=u.string().url().refine(e=>e.startsWith("https://"),"must be an https URL"),Yt={why:u.string().min(1).max(200).optional(),docs:xa.optional(),optional:u.boolean().optional(),anyOf:u.string().trim().min(1).max(40).optional()},va=u.object({id:Xe}).passthrough(),Pa=u.object({id:Xe,...Yt}).strict(),zr=(e,t)=>{let n=new Set;e.forEach((r,s)=>{let o=typeof r=="string"?r:r.id;n.has(o)&&t.addIssue({code:u.ZodIssueCode.custom,path:[s],message:"duplicate provider"}),n.add(o)})},Ca=u.array(u.union([Xe,va])).superRefine(zr),Oa=u.array(u.union([Xe,Pa])).superRefine(zr),Cr=u.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"a secret's name is an identifier").max(64),Ye=u.object({scopes:u.array(u.string()).optional().catch(void 0),access:u.enum(["read","write"]),...Yt}),$a=Ye.passthrough();function Na(e,t=Q){let n=t.get(e);if(!n||n.mode==="ai")throw new Error(`capabilityEntrySchema: ${e} is not a capability`);let r=u.enum(["read","write"]).refine(c=>n.access.includes(c),`${n.label} offers ${n.access.join(" or ")} access`),s="scopePolicy"in n?n.scopePolicy:void 0;if(!s){let c=u.undefined({error:`${n.label} takes no scopes; list it as { access: ..., why }`}).optional();return Ye.extend({access:r,scopes:c}).strict()}let o=Object.keys(s.sets),i=`${n.label} needs scopes: one or more of ${o.join(", ")}`,a=u.array(u.enum(o,{error:`unknown scope set (${n.label} offers: ${o.join(", ")})`}),{error:i}).min(1,i).refine(c=>new Set(c).size===c.length,"a scope set is listed twice");return Ye.extend({access:r,scopes:a}).strict()}var Da=u.record(u.string(),$a).superRefine((e,t)=>{for(let n of Object.keys(e))Kr(n,t)},Jt),La=Ye.extend({scopes:u.undefined({error:"a provider registered on the gateway takes no scopes; list it as { access: ..., why }"}).optional()}).strict();function Gr(e,t){return u.record(u.string(),u.unknown()).superRefine((n,r)=>{for(let[s,o]of Object.entries(n)){if(Kr(s,r))continue;let i=e.get(s);if(i?.mode==="ai"){r.addIssue({code:u.ZodIssueCode.custom,path:[s],message:`${s} is an AI provider: list it under providers, not capabilities`});continue}if(!i){if(t==="refuse"){r.addIssue({code:u.ZodIssueCode.custom,path:[s],message:`unknown capability (the gateway offers: ${kn(e).join(", ")})`});continue}let c=La.safeParse(o);if(c.success)continue;for(let d of c.error.issues)r.addIssue({...d,path:[s,...d.path]});continue}if(s==="email"&&o!==null&&typeof o=="object"&&"senders"in o){r.addIssue({code:u.ZodIssueCode.custom,path:[s,"senders"],message:`senders moved out of the manifest: set them with \`${yt} --sender <pattern>\` in the app's directory after its first deploy`});continue}let a=Na(s,e).safeParse(o);if(!a.success)for(let c of a.error.issues)r.addIssue({...c,path:[s,...c.path]})}},Jt).transform(n=>n)}var Ma=Gr(Q,"refuse"),ja=`inbound is true (the Worker exports an email() handler) or left out; the addresses moved out of the manifest: set them with \`${yt} --inbound <address>\` in the app's directory after its first deploy`,Ua=u.object({inbound:u.boolean().optional().catch(void 0)}).passthrough(),Ka=u.object({inbound:u.boolean({error:ja}).optional()}).strict(),za="email.inbound: apps in a dispatch namespace don't receive mail",qe=u.object({cpuMs:u.number().int().min(1).max(3e5).optional()}).passthrough(),Br=u.object({provider:u.enum(["d1","postgres"]),region:u.string().regex(/^[a-z0-9]+:[a-z0-9-]+$/,'region must be a cloud region such as "aws:us-east-1"').optional()}).passthrough(),Ga=u.string().regex(/^[a-z]([a-z0-9]|-(?!-))*[a-z0-9]$|^[a-z]$/,"helper Worker names are kebab-case (lowercase letters, digits, single hyphens)").max(20),Wr=u.object({name:Ga,binding:u.string().optional(),limits:qe.optional()}),Ba=u.enum(["everyone","admins"]),Wa=u.string().regex(/^\/v1(\/[a-z0-9_-]+)+$/,'must be an OpenAI API path such as "/v1/files"'),Fr=u.object({models:u.array(u.string().min(1).max(200)).optional(),routes:u.array(Wa).optional()}).passthrough(),Fa=`mcp is { by: "gateway" | "app", why: "..." }: "gateway" serves the app's defineTools() at <app-host>/mcp, "app" leaves the path to the app's own MCP server; left out, the Gateway's own /mcp is the one connector`,Ha=/^[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}]*$/u,Hr=u.object({by:u.enum(["gateway","app"]),why:u.string().min(1,"say why the app needs /mcp on its own host").max(200).regex(Ha,"why is plain text: no control characters")},{error:e=>e.code==="invalid_type"?Fa:void 0}).passthrough(),Vr=u.object({id:u.string().min(1).regex(/^[a-z]([a-z0-9-]*[a-z0-9])?$/,"id must be kebab-case (lowercase, digits, hyphens)"),name:u.string().min(1).optional(),description:u.string().optional(),icon:u.string().regex(/^(\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)*\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*\.svg$/,'icon must be the path of an SVG the app serves, such as "/everyapp-icon.svg"').optional(),main:u.string().optional(),compatibilityDate:Aa.optional(),resources:Lr.optional(),workers:u.array(Wr.passthrough()).optional(),database:Br.optional(),limits:qe.optional(),public:u.array(Nr).optional(),providers:Ca.optional(),capabilities:Da.optional(),secrets:u.array(u.union([Cr,u.object({name:Cr}).passthrough()])).max(100).optional(),scopes:Mr.optional(),ai:Fr.optional(),email:Ua.optional(),access:Ba.optional(),serverFnGuard:u.boolean().optional(),serverFnBase:u.string().regex(/^(\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)+\/?$/,'must be a path such as "/app/_serverFn"').optional(),build:u.string().min(1).optional(),dev:u.string().min(1).optional(),devPort:u.number().int().positive().optional(),install:Ra.optional(),migrations:Ta.optional(),mcp:Hr.optional()}).passthrough(),Va=Nr.strict(),j=u.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"binding names must be JavaScript identifiers"),Ja=u.string().regex(/^setup\/[a-z0-9][a-z0-9-]*\.md$/,'must be a guide in the everyapp skill, such as "setup/main-secret.md"'),Ya=u.object({name:j,...Yt,setup:Ja.optional()}).strict();function qa(e,t){if(!e)return null;for(let n of e.ids()){if(lt(n))continue;let r=e.get(n);if(r&&C(r).includes(t))return{kind:"capability",id:n}}return null}function Jr(e){return u.array(u.union([j,Ya])).superRefine((t,n)=>{let r=new Set;t.forEach((s,o)=>{let i=typeof s=="string"?s:s.name,a=y=>n.addIssue({code:u.ZodIssueCode.custom,path:[o],message:y});if(r.has(i)&&a(`duplicate secret ${i}`),r.add(i),Pe(i)){a(`${i} is set by everyapp itself (${Rn})`);return}let c=i.toUpperCase(),d=G(c)?null:qa(e,c);if(!G(c)&&!d)return;if(pe(c)){a(`${i} is a remote MCP app's credential name (every name ending in _MCP_TOKEN is the Gateway's, set with \`everyapp secret set\`); give the app's secret another name`);return}let l=d??xn(c),h=l?`list \`${l.id}\` under ${l.kind==="provider"?"providers":"capabilities"} instead`:"give the app's secret another name";a(`${i} is a Gateway setting, which \`everyapp secret set ${c}\` sets on the Gateway for every app; ${h}`)})})}var Xa=Jr(),Za=Lr.extend({d1:u.array(j).optional(),kv:u.array(j).optional(),r2:u.array(j).optional(),durableObjects:u.array(Je.strict()).optional(),workflows:u.array(Je.extend({name:j}).strict()).optional(),hyperdrive:u.array(Dr.extend({name:j}).strict()).optional()}).strict();function Yr(e={}){let t=e.capabilities===void 0&&(e.unknownCapabilities??"refuse")==="refuse"?Ma:Gr(e.capabilities??Q,e.unknownCapabilities??"refuse");return Vr.extend({resources:Za.optional(),providers:Oa.optional(),workers:u.array(Wr.extend({binding:j.optional(),limits:qe.strict().optional()}).strict()).optional(),public:u.array(Va).optional(),scopes:Ia.optional(),ai:Fr.strict().optional(),capabilities:t.optional(),secrets:(e.capabilities?Jr(e.capabilities):Xa).optional(),email:Ka.optional(),database:Br.strict().optional(),limits:qe.strict().optional(),mcp:Hr.strict().optional()}).strict()}var kf=Yr(),H="/__everyapp",Qa=["everyapp"];function ec(e){return Qa.includes(e)}var S=class extends Error{constructor(t){super(t),this.name="ManifestError"}};function qr(e){return e.map(t=>`${t.path.map(String).join(".")||"(root)"}: ${t.message}`).join("; ")}function If(e){let t=Vr.safeParse(e);if(!t.success)throw new S(`Invalid manifest: ${qr(t.error.issues)}`);let n=t.data;for(let r of n.public??[])Qr(r.path);return n}function Tf(e,t={}){let n=Yr(t).safeParse(e);if(!n.success)throw new S(`Invalid everyapp.config: ${qr(n.error.issues)}`);let r=n.data,s=sc(r),o=Wn(r).find(i=>s.has(i));if(o)throw new S(`Invalid everyapp.config: secrets: ${o} is one of the app's bindings; pick another name for the secret`);if(ec(r.id))throw new S(`Invalid everyapp.config: id "${r.id}" is reserved for the platform.`);for(let i of r.public??[]){Qr(i.path);let a=i.path==="/mcp"||i.path.startsWith("/mcp/");if(a||(i.methods??["GET"]).some(d=>Pr([i],d,"/mcp").public))throw new S(`Invalid everyapp.config: public: ${i.path} can't be public${a?"":" (it covers /mcp)"}; an app that runs its own MCP server sets mcp: { by: "app", why: "..." }`)}return nc(r),rc(r),tc(r),r}function tc(e){let t=[...Oe(e).map(r=>({path:`providers: ${r.id}`,need:r})),...Object.entries(e.capabilities??{}).map(([r,s])=>({path:`capabilities.${r}`,need:s})),...$e(e).map(r=>({path:`secrets: ${r.name}`,need:r}))],n=new Map;for(let{path:r,need:s}of t){let o=s.anyOf?.trim();if(s.optional===!0&&o)throw new S(`Invalid everyapp.config: ${r} is both optional and in the any-of group "${o}"; a group's member is optional by itself, so drop one of them.`);o&&n.set(o,[...n.get(o)??[],r])}for(let[r,s]of n)if(s.length<2)throw new S(`Invalid everyapp.config: the any-of group "${r}" has one member (${s[0]}); an any-of group needs two or more. Drop anyOf, or mark it optional.`)}function nc(e){let t=new Set;for(let{name:r}of e.workers??[]){if(t.has(r))throw new S(`Invalid everyapp.config: workers lists "${r}" twice.`);t.add(r)}let n=e.resources;for(let r of[...n?.durableObjects??[],...n?.workflows??[]])if(r.worker!==void 0&&!t.has(r.worker))throw new S(`Invalid everyapp.config: ${r.name} is defined by Worker "${r.worker}", which workers doesn't declare.`);for(let r of n?.hyperdrive??[])if(r.worker!==void 0&&!t.has(r.worker))throw new S(`Invalid everyapp.config: Hyperdrive ${r.name} is bound by Worker "${r.worker}", which workers doesn't declare.`)}function rc(e){if(e.migrations?.dialect==="postgresql"&&e.database?.provider!=="postgres")throw new S('Invalid everyapp.config: Postgres migrations (migrations.dialect "postgresql") need database: { provider: "postgres" }.');let t=new Set;for(let n of[...e.resources?.d1??[],...e.resources?.kv??[],...e.resources?.r2??[],...(e.resources?.hyperdrive??[]).map(r=>r.name)]){if(t.has(n))throw new S(`Invalid everyapp.config: the binding ${n} is declared twice in resources.`);t.add(n)}}function sc(e){return new Set([...e.resources?.d1??[],...e.resources?.kv??[],...e.resources?.r2??[],...(e.resources?.durableObjects??[]).map(t=>t.name),...(e.resources?.workflows??[]).map(t=>t.name),...(e.resources?.hyperdrive??[]).map(t=>t.name),...(e.workers??[]).flatMap(t=>t.binding?[t.binding]:[]),...e.database?["DATABASE_PROVIDER"]:[],"ASSETS"])}function Rf(e,t){if(t==="service_binding")return[];if(t!=="dispatch")return[`apps on tier "${t}" can't be deployed`];let n=[];return e.resources?.hyperdrive?.length&&n.push("resources.hyperdrive: Hyperdrive isn't available to apps in a dispatch namespace (an account holds at most 25 configs)"),e.resources?.r2?.length&&n.push("resources.r2: R2 buckets aren't available to apps in a dispatch namespace yet"),e.email?.inbound===!0&&n.push(za),e.secrets?.length&&n.push("secrets: third-party apps can't have secrets of their own yet"),n}function xf(e){return e.startsWith("every-")?e:`every-${e}`}var Or="every-app-gateway",oc=63;function ic(e){let t=e.toLowerCase();return t===Or||t.startsWith(`${Or}-`)}var Xr="--";function ac({appId:e,orgKey:t}){if(!t)throw new Error("An org-scoped Worker name needs an org key.");return`every-${t}-${e}`}function vf(e){return ic(e.workerName)||e.workerName.length>oc||!e.orgKey||e.appId.includes(Xr)?!1:e.workerName===ac(e)}function Pf(e,t){return t==="DB"||t==="KV"?e:Zr(e,t)}var Cf=63;function Of(e,t){return t==="R2"?e:Zr(e,t)}function Zr(e,t){let n=t.toLowerCase().replaceAll("_","-");return`${e}${Xr}${n}`}function Qr(e){if(!e.startsWith("/"))throw new S(`Public route path must be absolute (start with "/"): ${JSON.stringify(e)}`);if(e==="/*"||e==="/**"||e==="*"||e==="/")throw new S(`Public route "${e}" exposes the entire app. A catch-all public route is not allowed.`);if(e.includes("%"))throw new S(`Public route "${e}" must not contain percent-encoding; declare the decoded path.`);if(e.includes("\\"))throw new S(`Public route "${e}" must not contain backslashes.`);let t=e.split("/");if(t.some(r=>r==="."||r===".."))throw new S(`Public route "${e}" must not contain "." or ".." segments.`);for(let r of t)if(r.startsWith(":")&&!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new S(`Public route "${e}" has an invalid named segment "${r}".`);let n="/"+(t[1]??"");if(e===H||e.startsWith(H+"/")||n===H)throw new S(`Public route "${e}" targets the reserved ${H} namespace, which can never be public.`)}function $r(e){return!e.trim()||e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)?!1:!e.split(/[\\/]+/).some(t=>t==="..")}var cc="APP__";function Nf(e){return`${cc}${e}`}var Df=Object.freeze({manifest:"manifest",stamp:"stamp",worker:"worker",modulePrefix:"module:",assetPrefix:"asset:",migrationPrefix:"migration:"});var uc={DNS_RECORD_CONFLICT:"--force-dns",DNS_UNREADABLE:"--force-dns",CAA_BLOCKS_ISSUANCE:"--force-dns",DURABLE_OBJECT_REMOVED:"--allow-delete-durable-object-data",WORKFLOW_REMOVED:"--allow-delete-workflows",EMAIL_ROUTING_DISABLED:"--enable-email-routing",CONFIRMATION_REQUIRED:"--yes"},I=class extends Error{code;retryable;fix;rerun;rerunNote;authorize;data;constructor(t,n,r={}){super(n),this.name="EveryAppError",this.code=t,this.retryable=r.retryable??!1,this.fix=r.fix;let s=uc[t];this.rerun=r.rerun??(s?R([s]):this.retryable?R():void 0),this.rerunNote=r.rerunNote,this.authorize=r.authorize??s!==void 0,this.data=r.data}},Ze=class extends Error{action;url;rerun;rerunNote;data;constructor(t,n,r,s={}){super(n),this.name="ActionRequiredError",this.action=t,this.url=r,this.rerun=s.rerun===void 0?R():s.rerun,this.rerunNote=s.rerunNote,this.data=s.data}},es=class extends I{constructor(t="Cancelled. Nothing changed."){super("CANCELLED",t),this.name="CancelledError"}},qt=new WeakMap;function zf(e,t){return t&&typeof e=="object"&&e!==null&&(qt.has(e)||qt.set(e,t)),e}function ts(e){return typeof e=="object"&&e!==null?qt.get(e):void 0}function Gf(e){return e instanceof Error?e.message:String(e)}var U=class extends Error{kind;apiCodes;exitCode;stderr;stdout;constructor(t,n){super(t.message),this.name="CfError",this.kind=t.kind,this.apiCodes=t.apiCodes,this.exitCode=n.exitCode,this.stderr=n.stderr,this.stdout=n.stdout??""}};function Se(e,t){return e instanceof U&&e.kind===t}function Ff(e){return Se(e,"r2_not_enabled")||Se(e,"access_not_enabled")}var se=class extends Error{constructor(t,n,r){super(`\`${t}\` did not finish within ${Math.round(n/1e3)}s`+(r?` (last output: ${r})`:"")),this.name="CfTimeoutError"}},V=class extends Error{constructor(t,n){super(`Unexpected output from \`${t}\`: ${n}`),this.name="CfOutputError"}},dc=/Aborting the upload operation because of conflicts/,pc=[["d1_id_rejected",e=>/Expected a D1 database ID/.test(e)],["subdomain_missing",e=>/workers\.dev subdomain|\/workers\/onboarding/.test(e)],["email_unverified",(e,t)=>t.includes(10034)],["r2_not_enabled",(e,t)=>t.includes(10042)],["access_not_enabled",e=>/access\.api\.error\.not_enabled/.test(e)],["free_plan",e=>/Workers Paid|paid plan/i.test(e)],["auth",(e,t)=>t.includes(1e4)||t.includes(9109)||/No authentication token found|Not logged in|cf auth login/.test(e)],["already_exists",(e,t)=>t.includes(7502)||t.includes(10014)||/\balready exists\b/i.test(e)],["not_found",(e,t)=>t.includes(10007)||t.includes(10009)||t.includes(7404)||t.includes(10200)||/\bnot found\b|does not exist/i.test(e)]];function ns(e,t){return/^Aborted\.$/m.test(t)?new U({message:`\`${e}\` asked for a confirmation no one could give, and did nothing (it printed "Aborted.").`,apiCodes:[],kind:"aborted"},{exitCode:0,stderr:t}):null}function rs(e,t=""){let n=lc(e)??mc(t,e),r=[...n.matchAll(/\[(?:code: )?(\d{4,})\]/g)].map(o=>Number(o[1])),s=dc.test(`${t}
7
+ ${e}`)?"strict_conflict":pc.find(([,o])=>o(n,r))?.[0]??"unknown";return{message:n,apiCodes:r,kind:s}}function lc(e){let t=e.split(/\r?\n/),n=t.findIndex(o=>/^┌\s*(API)?Error/.test(o.trim()));if(n<0)return;let r=[];for(let o of t.slice(n+1)){let i=o.trim();if(i.startsWith("\u2514"))break;r.push(i.replace(/^│ ?/,""))}let s=fc(r);return s.length>0?s:void 0}function fc(e){let t=[],n="";for(let r of e)r.trim().length===0?(n&&t.push(n),t.push(""),n=""):/^\s/.test(r)||/^\d+\./.test(r.trim())?(n&&t.push(n),n=r.trimEnd()):n=n?`${n} ${r.trim()}`:r.trim();return n&&t.push(n),t.join(`
8
+ `).replace(/\n{3,}/g,`
9
+
10
+ `).trim()}function mc(...e){return X(...e).join(`
11
+ `)||"cf failed without an error message"}var Xt=new Set;function ss(e){return Xt.add(e),()=>Xt.delete(e)}function Qe(){for(let e of Xt)e()}function os(){return!!process.stdout.isTTY&&process.env.TERM!=="dumb"&&!process.env.CI}function Vf(e,t=process.env,n=!!process.stdout.isTTY){return!e&&!t.NO_COLOR&&n&&t.TERM!=="dumb"}import{AsyncLocalStorage as wc}from"node:async_hooks";import hc from"chalk";import{spawn as gc}from"node:child_process";import{once as is}from"node:events";var J=process.platform!=="win32",yc=1e3;function as({command:e,args:t,cwd:n,env:r,shell:s=!1,hold:o}){let i=gc(e,t,{cwd:n,shell:s,env:o&&hc.level>0?{...r,FORCE_COLOR:"1"}:r,stdio:["ignore",o?"pipe":"inherit",o?"pipe":"inherit"],detached:J}),a=o?[]:null,c=o?Promise.race([Promise.all([is(i.stdout,"end"),is(i.stderr,"end")]),new Promise(l=>setTimeout(l,1e3).unref())]):Promise.resolve();if(o)for(let[l,h]of[[i.stdout,process.stdout],[i.stderr,process.stderr]])l.on("data",y=>{a?a.push({to:h,chunk:y}):h.write(y)});return{exited:new Promise((l,h)=>{i.once("error",h),i.once("exit",(y,_)=>{c.then(()=>l({code:y,signal:_}))})}),stop:l=>tt(i,J,l),releaseOutput:l=>{let h=a??[];if(a=null,l)for(let{to:y,chunk:_}of h)y.write(_)}}}function tt(e,t,n="SIGTERM"){e.pid!==void 0&&(et(e,t,n),n!=="SIGKILL"&&setTimeout(()=>et(e,t,"SIGKILL"),yc).unref())}function et(e,t,n){let r=e.pid;if(r!==void 0)try{t?process.kill(-r,n):e.kill(n)}catch{}}var Ec=3e3,bc=1e4,_c=["SIGINT","SIGTERM"],oe=new Set,st=new Set,Y=new Set,cs=new WeakSet,ls=new wc,us=!1,Ae=!1,nt;function fs(e,t){let n={child:e,group:t,exited:new Promise(r=>{e.exitCode!==null||e.signalCode!==null?r():e.once("close",()=>r())})};return Ae&&!ls.getStore()&&rt(n,"SIGKILL"),oe.add(n),ot(),()=>{oe.delete(n),ot()}}function rm(){return Ae}function sm(e){return nt=e,()=>{nt===e&&(nt=void 0)}}function ms(e){return Y.add(e),ot(),()=>{Y.delete(e),ot()}}function en(e){return st.add(e),()=>st.delete(e)}function Sc(){let e=[...new Set([...Y].flatMap(r=>r.label?[r.label]:[]))],t=[...oe.size>0&&!e.some(r=>r.startsWith("stopping "))?["stopping cf"]:[],...e];if(t.length===0)return"Stopping";let n=t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`;return ve(n)}function Ac(e){for(let t of[...e].reverse()){let n=t.closing?.();if(n!==void 0)return n}return"Stopped."}function ds(e,t){st.size===0&&process.stderr.write(t);for(let n of st)e(n)}function ot(){let e=oe.size>0||Y.size>0;if(!(e===us||Ae)){us=e;for(let t of _c)e?process.on(t,ps):process.off(t,ps)}}function ps(e){kc(e)}async function kc(e,{exit:t=n=>process.exit(n)}={}){let n=e==="SIGTERM"?143:130;if(Ae){if(e==="SIGTERM")return;for(let c of oe)rt(c,"SIGKILL");Zt(),t(n);return}Ae=!0,Qe();let r=nt,s=r===void 0?Sc():r?`Stopping ${r}`:"";s&&ds(c=>c.stopping(s),`
12
+ ${s} (Ctrl+C again to quit at once)...
13
+ `);let o=[...Y],i=[...oe];for(let c of i)rt(c,e);let a=Promise.all(i.map(c=>c.exited));if(!await Qt(a,Ec)){for(let c of i)rt(c,"SIGKILL");await Qt(a,1e3)}if(Zt(),await Qt(Ic(),bc),Zt(),r===void 0){let c=Ac(o);ds(d=>d.stopped(c),c?`${c}
14
+ `:"")}t(n)}async function Ic(){for(let e of[...Y].reverse())e.async&&await ls.run(!0,()=>e.async()).catch(()=>{})}function Zt(){for(let e of[...Y])if(!cs.has(e)){cs.add(e);try{e.sync?.()}catch{}}}function rt({child:e,group:t},n){et(e,t,n)}async function Qt(e,t){let n,r=new Promise(s=>{n=setTimeout(()=>s(!1),t)});try{return await Promise.race([e.then(()=>!0),r])}finally{clearTimeout(n)}}var ie="22.18.0",tn="--dns-result-order=ipv4first";function hs(e){let t=(e??"").trim();return t.split(/\s+/).includes(tn)?t:t?`${t} ${tn}`:tn}function nn(e){return Tc(e,ie)>=0}function cm(e=process.versions){return e.bun?new I("UNSUPPORTED_RUNTIME",`everyapp runs on Node.js, not Bun
15
+ The Cloudflare CLI can't load cloudflare.config.ts under Bun.`,{rerun:R(),rerunNote:`with Node.js ${ie} or newer`}):nn(e.node)?null:new I("UNSUPPORTED_RUNTIME",`everyapp needs Node.js ${ie} or newer; this is ${e.node}
16
+ The Cloudflare CLI loads cloudflare.config.ts with Node's built-in TypeScript support.`,{fix:"install Node 22 or 24, then run the command again"})}function Tc(e,t){let n=o=>o.replace(/^v/,"").split(/[.-]/).slice(0,3).map(i=>Number.parseInt(i,10)||0),[r,s]=[n(e),n(t)];for(let o=0;o<3;o+=1){let i=(r[o]??0)-(s[o]??0);if(i!==0)return i}return 0}import xc from"node:path";import{fileURLToPath as vc}from"node:url";import gs from"node:fs/promises";import ke from"node:path";async function ys(e,t,n){let r=ke.resolve(e);try{let s=await Rc(r,t),o=JSON.parse(await gs.readFile(s,"utf-8")),i=typeof o.bin=="string"?o.bin:o.bin?.[n];if(!i)throw new Error(`Package does not declare the "${n}" binary.`);return{version:o.version??"unknown",binPath:ke.resolve(ke.dirname(s),i)}}catch(s){throw new Error(`Could not resolve the project-local "${n}" binary from project root "${r}". Install the project's declared ${t} dependency and try again. (If the install skipped devDependencies, include them; Yarn Plug'n'Play projects are not supported \u2014 use nodeLinker: node-modules.)`,{cause:s})}}async function Rc(e,t){let n=e;for(;;){let r=ke.join(n,"node_modules",...t.split("/"),"package.json");try{return await gs.realpath(r)}catch{}let s=ke.dirname(n);if(s===n)break;n=s}throw new Error(`${t} is not installed under ${e} or any directory above it.`)}var Pc=An.cf;function Cc(){return ws(xc.dirname(vc(import.meta.url)),"cli")}async function ws(e,t){let{binPath:n,version:r}=await ys(e,"cf","cf");return{path:n,version:r,source:t}}var Oc="EVERYAPP_CF_BINARY";async function Es(e){let t=process.env[Oc];if(t)return{path:t,version:Pc,source:"cli"};if(e)try{return await ws(e,"project")}catch{}return Cc()}import Ie from"node:fs/promises";import bs from"node:path";async function $c(e,t,n={}){let r=n.exclude||[];await Ie.mkdir(t,{recursive:!0});let s=await Ie.readdir(e,{withFileTypes:!0});for(let o of s){let i=bs.join(e,o.name),a=bs.join(t,o.name);r.some(c=>o.name===c)||(o.isDirectory()?await $c(i,a,n):await Ie.copyFile(i,a))}}async function bm(e){try{return(await Ie.stat(e)).isDirectory()}catch{return!1}}async function _m(e){try{return await Ie.access(e),!0}catch{return!1}}function ae(e){return e?.code==="ENOENT"}import Ss from"node:fs/promises";import it from"node:path";import{execa as zc}from"execa";import Nc from"node:fs";import _s from"node:fs/promises";import Dc from"node:os";import rn from"node:path";import Lc from"chalk";import{execa as Mc}from"execa";async function sn(e,t,n){let r=[e,...t].join(" "),s=await Uc(n.logName??r),o=Nc.createWriteStream(s,{flags:"a",mode:384}),i=`$ ${r}
17
+ # in ${n.cwd??process.cwd()}
18
+
19
+ `;o.write(i);let a=n.echo?jc(r):null,c=_=>{o.write(_),a?.write(_)},d=Mc(e,[...t],{cwd:n.cwd,env:n.env,shell:n.shell,stdin:"ignore",stdout:"pipe",stderr:"pipe",buffer:!1,reject:!1});d.stdout?.on("data",c),d.stderr?.on("data",c);let l=await d;if(a?.end(),await new Promise(_=>o.end(_)),!l.failed)return;let h=await Kc(s,i.length),y=l.exitCode!==void 0?`${l.command} exited with code ${l.exitCode}`:l.signal?`${l.command} was stopped by ${l.signal}`:l.shortMessage;throw new I(n.code??"COMMAND_FAILED",[`${n.what} failed`,`${y}.${h.length>0?" Its last lines:":""}`,...h.map(_=>` ${_}`),`Full log: ${s}`].join(`
20
+ `),{...n.fix?{fix:n.fix}:{},data:{command:r,exitCode:l.exitCode??null,tail:h,log:s}})}function jc(e){let t=r=>process.stderr.write(`${Lc.dim(` ${r}`)}
21
+ `);t(`$ ${e}`);let n="";return{write:r=>{let s=`${n}${r.toString("utf8")}`.split(/\r?\n/);n=s.pop()??"";for(let o of s)t(o)},end:()=>{n&&t(n),n=""}}}async function Uc(e){let t=rn.join(Dc.tmpdir(),"everyapp");await _s.mkdir(t,{recursive:!0,mode:448});let n=e.split(/\s+/).slice(0,2).map(s=>rn.basename(s).replace(/[^\w.-]+/g,"")).filter(Boolean).join("-")||"command",r=new Date().toISOString().replace(/[:.]/g,"-");return rn.join(t,`${n}-${r}-${process.pid}.log`)}async function Kc(e,t){return X((await _s.readFile(e,"utf8").catch(()=>"")).slice(t))}async function Gc(){try{return await zc("pnpm",["--version"],{stdio:"pipe"}),!0}catch{return!1}}async function Mm({cwd:e,description:t,install:n,verbose:r=!1}){if(n===!1)return;let s=t.replace(/\.+$/,"");if(typeof n=="string"){await sn(n,[],{cwd:e,shell:!0,echo:r,what:s,code:"INSTALL_FAILED"});return}let o=await an(e),{command:i,args:a}=await Wc(o);await sn(i,a,{cwd:e,echo:r,what:`${s} with ${o}`,code:"INSTALL_FAILED"})}async function an(e){let t=await Bc(e);return t||(await on(it.join(e,"pnpm-lock.yaml"))?"pnpm":await on(it.join(e,"yarn.lock"))?"yarn":await on(it.join(e,"package-lock.json"))?"npm":"pnpm")}async function Bc(e){let t=it.join(e,"package.json");try{let r=JSON.parse(await Ss.readFile(t,"utf-8")).packageManager;return typeof r!="string"?null:r.startsWith("pnpm")?"pnpm":r.startsWith("yarn")?"yarn":r.startsWith("npm")?"npm":null}catch(n){if(ae(n))return null;throw n}}async function Wc(e){return e==="yarn"?{command:"yarn",args:["install"]}:e==="npm"?{command:"npm",args:["install"]}:await Gc()?{command:"pnpm",args:["install"]}:{command:"npx",args:["pnpm","install"]}}async function on(e){try{return await Ss.access(e),!0}catch(t){if(ae(t))return!1;throw t}}import{spawn as su}from"node:child_process";import ou from"node:fs/promises";import at from"node:path";import{createHash as Fc}from"node:crypto";import k from"node:fs/promises";import{rmSync as Hc}from"node:fs";import cn from"node:os";import $ from"node:path";var Vc="cloudflare.config.ts",Re=448,ks=18;async function Is(){return dn("neutral")}var Ts="files-";async function Jc(e){let t=await dn("tmp");return await qc(t),k.mkdtemp($.join(t,`${e}${process.pid}-`))}async function Rs(e){let t=await Jc(e),n=ms({sync:()=>Hc(t,{recursive:!0,force:!0})});return{dir:t,cleanup:async()=>{await k.rm(t,{recursive:!0,force:!0}),n()}}}var Yc=24*60*6e4;async function qc(e){let t=Date.now()-Yc;for(let n of await k.readdir(e).catch(()=>[])){let r=Number(/-(\d+)-[^-]+$/.exec(n)?.[1]);if(r&&Xc(r))continue;let s=$.join(e,n),o=await Ps(s).catch(()=>null);o&&o.ctimeMs<t&&await k.rm(s,{recursive:!0,force:!0}).catch(()=>{})}}function Xc(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function xs(){if(process.platform==="win32")return $.dirname(process.execPath);let e=await dn("bin"),t=$.join(e,Fc("sha256").update(process.execPath).digest("hex").slice(0,16));await un(t);let n=$.join(t,"node");if(await k.readlink(n).catch(()=>null)!==process.execPath){await k.rm(n,{force:!0});try{await k.symlink(process.execPath,n)}catch(r){if(r.code!=="EEXIST")throw r}}return t}async function dn(e){await Zc();let t=$.join(cn.homedir(),".everyapp");await Qc(t);let n=$.join(t,"cf");await un(n);let r=$.join(n,e);return await un(r),await eu(r),r}async function Zc(){let e=Number(process.env.SUDO_UID);if(process.getuid?.()!==0||!Number.isInteger(e)||e===0)return;if((await k.stat(cn.homedir()).catch(()=>null))?.uid===e)throw new I("UNSAFE_CF_DIRECTORY",`everyapp is running as root (sudo) with your HOME
22
+ It would leave ~/.everyapp in ${cn.homedir()} to root.`,{fix:"run it without sudo"})}async function Qc(e){let t;try{t=await k.stat(e)}catch(r){if(!ae(r))throw r;await k.mkdir(e,{recursive:!0,mode:Re});return}if(!t.isDirectory())throw Te(e,"isn't a directory");let n=vs(t);if(n){if(t.uid!==process.getuid?.()||!(t.mode&ks))throw Te(e,n);for(let r of await k.readdir(e))if((await k.lstat($.join(e,r))).uid!==t.uid)throw Te(e,`${n}, and ${r} in it belongs to another user`);await k.chmod(e,Re)}}async function un(e){try{let t=await Ps(e);if(t&&As(t))return;t&&await k.rm(e,{recursive:!0,force:!0});try{await k.mkdir(e,{mode:Re})}catch(r){if(r.code!=="EEXIST")throw r}if((await k.lstat(e)).isDirectory()&&await k.chmod(e,Re),!As(await k.lstat(e)))throw Te(e,"can't be made a private directory")}catch(t){throw t instanceof I?t:Te(e,`can't be made a private directory (${t.message}; was everyapp run with sudo?)`)}}function As(e){if(!e.isDirectory())return!1;let t=process.getuid?.();return t===void 0?!0:e.uid===t&&(e.mode&511)===Re}function vs(e,{uid:t=process.getuid?.(),parent:n=!1}={}){return t===void 0?null:e.uid===t||e.uid===0||n&&t===0?e.mode&ks?"is writable by other users":null:"is owned by another user"}async function eu(e){for(let t=await k.realpath(e);;t=$.dirname(t)){let n=vs(await k.lstat(t),{parent:!0});if(n)throw new I("UNSAFE_CF_DIRECTORY",`${t} ${n}, so everyapp won't run cf below it
23
+ cf runs any cloudflare.config.ts it finds in a parent of its working directory (here ${e}).`,{fix:`make it writable only by you (chmod go-w "${t}"), or run everyapp with a HOME that is`});let r=$.join(t,Vc);if(await tu(r))throw new I("UNSAFE_CF_DIRECTORY",`cf would run ${r} in every command everyapp starts
24
+ cf loads a cloudflare.config.ts from any parent of its working directory (here ${e}).`,{fix:"move that file into a project directory",rerun:R()});if($.dirname(t)===t)return}}function Te(e,t){return new I("UNSAFE_CF_DIRECTORY",`${e} ${t}
25
+ everyapp runs cf and keeps the files it hands to cf (secrets among them) there, so only you may be able to write to it.`,{fix:"fix or remove it",rerun:R()})}async function Ps(e){try{return await k.lstat(e)}catch(t){if(ae(t))return null;throw t}}async function tu(e){try{return(await k.stat(e)).isFile()}catch{return!1}}import{execa as nu}from"execa";var ru=6e4;function pn(e){return e[0]==="build"||e[0]==="dev"}async function ln(e,t){let n=["node","-p","process.versions.node"],r,s;try{r=await an(e);let o=r==="yarn"?n:r==="npm"?["exec","--",...n]:["exec",...n],{stdout:i}=await nu(r,o,{cwd:e,env:t,extendEnv:!1,stdin:"ignore",timeout:ru});s=i.trim().split(`
26
+ `).at(-1)?.trim()??""}catch{return}if(!(!/^\d+\.\d+\.\d+$/.test(s)||nn(s)))throw new I("NODE_TOO_OLD",`${r} runs this project's tools on Node.js ${s}; cf needs ${ie} or newer
27
+ everyapp runs on ${process.versions.node}, but something pins this project's (a Volta \`volta.node\` in package.json, pnpm's use-node-version). cf needs ${ie} or newer to load cloudflare.config.ts.`,{fix:"raise the pin (`volta pin node@22`, for Volta)",rerun:R()})}var iu=12e4,au=2e3;function fh(e={}){let t=e.resolveBinary??Es,n=e.env??process.env,r=e.watchdogIdleMs??au,s;async function o(i,a,c={}){let d={...n,CF_DELEGATION:"1",...a==="interactive"?{}:{NO_COLOR:"1"},...a==="json"?{CF_QUIET:"1"}:{},...e.accountId?{CLOUDFLARE_ACCOUNT_ID:e.accountId}:{},...i==="project"?{NODE_OPTIONS:hs(n.NODE_OPTIONS)}:{},...c};return s??=xs(),lu(d,await s)}return{async run(i){let a=await uu(i),c=await t(i.plane==="project"&&!i.cliCf?a:void 0),d=i.files?await du(i.files):null;try{let l=typeof i.args=="function"?i.args(d?.paths??{}):[...i.args],h=await o(i.plane,i.mode,i.env);return i.plane==="project"&&pn(l)&&await ln(a,h),await pu({binary:c,args:l,cwd:a,env:h,onOutput:i.onOutput,mode:i.mode,timeoutMs:i.timeoutMs??(i.mode==="interactive"?void 0:iu),watchdogIdleMs:i.local?r:void 0})}finally{await d?.remove()}},async start(i){let a=await t(i.cwd),c=await o("project","interactive",i.env);return pn(i.args)&&await ln(i.cwd,c),as({command:process.execPath,args:[a.path,...i.args],cwd:i.cwd,env:c,hold:i.holdOutput??!1})}}}async function cu(e,t,n){let r=await e.run({...t,mode:"json"}),s=Cs(t.args),o;try{o=JSON.parse(r.stdout)}catch{throw new V(s,"stdout is not JSON")}let i=n.safeParse(o);if(!i.success)throw new V(s,i.error.message);return i.data}async function mh(e,t,n,{perPage:r,maxPages:s}){let o=[];for(let i=1;i<=s;i+=1){let a=await cu(e,{plane:"account",args:[...t,"--per-page",String(r),"--page",String(i)]},n);if(o.push(...a),a.length<r)break}return o}async function uu(e){if(e.plane==="project"){if(!e.cwd)throw new Error("project-plane cf calls need a cwd");return e.cwd}return Is()}async function du(e){let{dir:t,cleanup:n}=await Rs(Ts),r={};try{for(let[s,o]of Object.entries(e)){let i=at.join(t,at.basename(s));await ou.writeFile(i,typeof o=="string"?o:JSON.stringify(o),{mode:384}),r[s]=i}}catch(s){throw await n(),s}return{paths:r,remove:n}}function pu(e){let t=Cs(e.args),n=e.mode==="interactive";return n&&Qe(),new Promise((r,s)=>{let o=su(process.execPath,[e.binary.path,...e.args],{cwd:e.cwd,env:e.env,stdio:n?"inherit":["ignore","pipe","pipe"],detached:!n&&J}),i=fs(o,!n&&J),a="",c="",d=!1,l,h=E=>{d||(d=!0,i(),clearTimeout(_),clearTimeout(l),E())},y=e.timeoutMs,_=y===void 0?void 0:setTimeout(()=>{tt(o,!n&&J),h(()=>s(new se(t,y,X(c).at(-1)?.trim())))},y),p=()=>{e.watchdogIdleMs===void 0||d||!l&&!fu(a)||(clearTimeout(l),l=setTimeout(()=>{tt(o,J),h(()=>r({stdout:a,stderr:c,stoppedByWatchdog:!0}))},e.watchdogIdleMs))};for(let[E,g]of[[o.stdout,b=>a+=b],[o.stderr,b=>c+=b]])E?.on("data",b=>{g(b.toString()),e.onOutput?.(b.toString()),p()});o.once("error",E=>h(()=>s(E))),o.once("close",E=>{h(()=>{if(E===0){let b=ns(t,c);b?s(b):r({stdout:a,stderr:c,stoppedByWatchdog:!1});return}let g=n?{message:`\`${t}\` exited with code ${E}`,apiCodes:[],kind:"unknown"}:rs(c,a);s(new U(g,{exitCode:E,stderr:c,stdout:a}))})})})}function lu(e,t){let n=Object.keys(e).find(s=>s.toUpperCase()==="PATH")??"PATH",r=(e[n]??"").split(at.delimiter).filter(s=>s&&s!==t);return{...e,[n]:[t,...r].join(at.delimiter)}}function fu(e){let t=e.trim();if(!t)return!1;try{return JSON.parse(t),!0}catch{return!1}}function Cs(e){return typeof e=="function"?"cf":["cf",...e].join(" ")}function Os(e){let t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:t<3600?`${Math.round(t/60)}m`:`${Math.round(t/3600)}h`}function ct(e){let t=e/1e3;if(t<10)return`${t.toFixed(1)}s`;if(t<60)return`${Math.round(t)}s`;let n=Math.round(t);return`${Math.floor(n/60)}m ${n%60}s`}function gh(e){let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`}import mu from"node:fs";var $s="EVERYAPP_EVENT_LOG",fn;function mn(){let e=process.env[$s];return e?(fn?.path!==e&&(fn={path:e,log:hu(e)}),fn.log):null}function hu(e){let t=!1;return{append(n){if(!t)try{let r=`${JSON.stringify({...n,pid:process.pid})}
28
+ `;mu.appendFileSync(e,r,{mode:384})}catch(r){t=!0;let s=r instanceof Error?r.message:String(r);process.stderr.write(`everyapp: can't write ${$s}=${e} (${s}); not logging
29
+ `)}}}}function Eh({argv:e,json:t}){mn()?.append({type:"invocation",ts:new Date().toISOString(),argv:[...e],cwd:process.cwd(),json:t,isatty:{stdin:!!process.stdin.isTTY,stdout:!!process.stdout.isTTY,stderr:!!process.stderr.isTTY},ci:!!process.env.CI})}function Ns(e,t){mn()?.append({v:1,ts:t.toISOString(),...e})}function bh(e,t){mn()?.append({type:"exit",ts:new Date().toISOString(),code:(e%256+256)%256,ms:t})}import{stripVTControlCharacters as gu}from"node:util";import Ds from"chalk";var hn=e=>gu(e).length,yu=(e,t)=>e+" ".repeat(t-hn(e));function Ls(e){let t=Math.max(...e.map(n=>n.label.length));return e.map(n=>`${Ds.dim(n.label.padEnd(t))} ${n.value}`)}function kh(e,t){let n=e.map((s,o)=>Math.max(hn(s),...t.map(i=>hn(i[o]??"")))),r=s=>s.map((o,i)=>i===s.length-1?o:yu(o,n[i])).join(" ");return[Ds.dim(r(e)),...t.map(r)]}import m from"chalk";import Us from"cli-cursor";function Th(e){return(e?.public??[]).map(t=>js(t.path,t.methods))}function Rh(e){if(typeof e!="string")return[];try{let n=JSON.parse(e)?.public;return Array.isArray(n)?n.flatMap(r=>{let s=r?.path;if(typeof s!="string")return[];let o=r.methods;return[js(s,Array.isArray(o)?o.filter(i=>typeof i=="string"):void 0)]}):[]}catch{return[]}}function xh(e){return e?.mcp?{by:e.mcp.by,why:e.mcp.why}:null}function vh(e){if(typeof e!="string")return null;try{let n=JSON.parse(e)?.mcp;if(!n||typeof n!="object")return null;let{by:r,why:s}=n;return r!=="gateway"&&r!=="app"||typeof s!="string"?null:{by:r,why:s}}catch{return null}}var Ph=e=>`MCP /mcp (${e.by})`;function Ms(e,t=6){return{shown:e.slice(0,t).map(n=>`${n.methods.join("/")} ${n.path}`).join(", "),more:Math.max(0,e.length-t)}}function js(e,t){return{path:e,methods:(t??["GET"]).map(n=>n.toUpperCase())}}function Vs(e=n=>process.stdout.write(n),t=()=>new Date){let n=Ys(r=>{let s=r.type==="done"?{...r,display:void 0}:r;e(`${JSON.stringify({v:1,ts:t().toISOString(),...s})}
30
+ `)},!1,()=>t().getTime());return en({stopping:r=>n.emit({type:"progress",step:"interrupt",message:r}),stopped:()=>{}}),n}function Js(e={}){let t=e.verbose??!1,n=e.terminal??!1,r=e.now??Date.now,s=r(),o=e.writeProblem??(p=>void process.stderr.write(p)),i=new wn(e.write??(p=>void process.stdout.write(p)),n,e.columns??(()=>process.stdout.columns??80),r);n&&ss(()=>i.handOver()),en({stopping:p=>i.interrupt(`${p} (Ctrl+C again to quit at once)`),stopped:p=>{i.finish(),p&&o(`${m.dim(p)}
31
+ `)}});let a=p=>i.aside(()=>o(`${p.join(`
32
+ `)}
33
+ `)),c=new Map,d=new Set,l=[],h=0,y=0,_=(p,E)=>{for(let g of p)if("line"in g)i.lines(g.line);else if("fact"in g)l.splice(g.lead?y++:l.length,0,g.fact);else if("done"in g){let b=g.detail??(E!==void 0&&E>=1e3?ct(E):"");i.lines([Eu(g.done,b),...(g.notes??[]).map(A=>m.dim(` ${A}`))].join(`
34
+ `))}};return Ys(p=>{switch(p.type){case"step":{for(let A of d)A!==p.step&&(i.drop(A),d.delete(A),c.delete(A));let E=bu[p.step]?.(p,A=>c.has(A)),g=E?[E].flat():[];if(p.status==="start"){c.set(p.step,r());let A=g.find(K=>"spin"in K);g.length===0&&t&&!n&&p.message&&i.lines(m.dim(p.message)),_(g),i.spin(p.step,A?A.spin:g.length>0?"":p.message??"");return}let b=c.get(p.step);c.delete(p.step),d.delete(p.step),i.stopSpinning(p.step),g.length>0?_(g,b===void 0?void 0:r()-b):t&&p.message&&i.lines(m.dim(p.message));return}case"progress":ku.has(p.step)?i.lines(m.dim(p.message)):Au[p.step]?.(p.data??{})?(c.has(p.step)||c.set(p.step,r()),n?i.spin(p.step,p.message):d.has(p.step)||i.lines(p.message),d.add(p.step)):t&&i.lines(m.dim(p.message));return;case"warning":{if(_u.has(p.code)&&!t)return;h+=1,a([...Ws(m.yellow("!"),p.message),...yn(p.data,{url:!0})]);return}case"action_required":{let[E="",...g]=p.message.split(`
35
+ `),b=[`${m.cyan("\u2192")} ${E}`,...p.data?.url?[` ${m.cyan(p.data.url)}`]:[],...p.data?.code?[` Code: ${m.bold(p.data.code)}`]:[],...g.map(A=>m.dim(` ${A}`))];if(p.data?.waiting){let A=p.step??p.action;i.lines(b.join(`
36
+ `)),c.set(A,r());let K=f(p.data.waitingFor);i.spin(A,K?`Waiting for ${K}`:"Waiting");return}i.finish(),o(`${[...b,...Tu(p.data?.choices),...yn(p.data)].join(`
37
+ `)}
38
+ `);return}case"error":{if(i.finish(),p.code==="CANCELLED"){o(`${m.dim(p.message)}
39
+ `);return}let E=t?f(p.data?.stack):void 0;o(`${[...Ws(m.red("\u2717"),p.message),...yn(p.data,{url:!0}),...E?E.split(`
40
+ `).filter(g=>/^\s+at /.test(g)).map(g=>m.dim(` ${g.trim()}`)):[],...t?[m.dim(` Error code: ${p.code}`)]:[]].join(`
41
+ `)}
42
+ `);return}case"done":{i.finish();let E=r()-s,g=[...l,...Ru(p.data?.facts)],b=Ou(p.data?.next),A=[...p.display!==void 0?p.display?[p.display]:[]:p.message?[m.green(p.message)]:[],...g.length>0?["",...Ls(g)]:[],...E>=1e4&&p.display===void 0?[m.dim(`Done in ${ct(E)}${h>0?` with ${z(h,"warning")}`:""}`)]:[],...b.length>0?["","Next:",...$u(b)]:[]];A.length>0&&i.lines(A.join(`
43
+ `));return}}},t,r)}function Hh(e,t){return{emit(n){if(n.type!=="done"){e.emit(n);return}e.emit({type:"step",step:t,status:"ok",...n.message?{message:n.message}:{},...n.data?{data:n.data}:{}})},get exitCode(){return e.exitCode},get verbose(){return e.verbose}}}function Eu(e,t){return`${e} ${m.green("\u2713")}${t?` ${m.dim(t)}`:""}`}function Ks(e,t){return n=>n.status==="ok"?{done:e,detail:t}:null}function zs(e,t){return n=>n.status==="start"?{spin:e}:n.status==="ok"?{done:t}:null}function ce(e){return e.status==="start"?{spin:e.message??""}:e.status==="ok"&&e.message?{done:e.message}:null}var bu={"setup.account":e=>{if(e.status!=="ok")return null;let t=e.data??{};if(t.gateway===!0)return null;let n=f(t.email);return{line:`Setting up Every App in ${f(t.name)??f(t.id)}${n?m.dim(` (${n})`):""}`}},"setup.gateway":e=>{let t=e.data??{},n=f(t.releaseName),r=f(t.account),s=r?`${r}'s Gateway`:"the Gateway";if(e.status==="start"){let o=f(t.gatewayUrl)?.replace(/^https:\/\//,"");switch(t.change){case"install":{let i=xu(t.expectedMinutes);return{line:`Installing the Gateway at ${o} (${n})${i?m.dim(` (usually ${i.min}\u2013${i.max} minutes, then the owner link)`):""}`}}case"resume":return{line:`Resuming the Gateway install at ${o} (${n})`};case"upgrade":return{line:`Upgrading ${s} to ${n}`};case"repair":return{line:`Repairing ${s} (${n})`};case"redeploy":return{line:`Redeploying ${s} (${n})`};default:return null}}if(e.status==="ok"&&t.repaired===!0){let o=P(t.added);if(o.length>0)return{done:`Gateway now routes ${o.join(", ")}`};let i=Number(t.apps??0),a=Number(t.was??i);return{done:`Gateway routes ${z(i,"app")}`,detail:a!==i?`was ${a}`:""}}return e.status!=="skip"?null:t.upToDate===!0?{done:`${ve(s)} is up to date with ${n}`,detail:""}:e.message?{line:e.message}:null},"setup.owner":e=>{let t=f(e.data?.email);return t?e.status==="skip"?{done:`Owner account is ${t}`,detail:""}:e.status==="ok"?{done:`Owner account created for ${t}`}:null:null},"gateway.migrations":(e,t)=>{let n=t("setup.gateway"),r=t("gateway.upgrade");if(e.status==="start")return n?null:{spin:""};if(!n&&!r&&P(e.data?.applied).length===0)return null;let s=Bs(e,n||r?"Database":"Gateway database");return r?gn(s):s},"gateway.deploy":(e,t)=>e.status==="start"?{spin:t("setup.gateway")?"Uploading...":t("app.bind")||t("app.delete")?"":"Updating the Gateway..."}:e.status!=="ok"?null:t("gateway.upgrade")?gn({done:"Uploaded"}):t("setup.gateway")?{done:"Uploaded"}:null,"gateway.reconcile":e=>e.status==="skip"&&e.message?{line:e.message}:null,"app.deploy":e=>{if(e.status!=="ok")return null;let t=e.data??{},n=f(t.version),r=f(t.organizationName),s=f(t.origin);return{line:[`Deploying ${f(t.appId)}${n?` ${n}`:""} to ${f(t.gatewayHost)}${r?m.dim(` (${r})`):""}`,...s?[m.dim(` From ${s}`)]:[]].join(`
44
+ `)}},"app.register":e=>{let t=e.data??{};if(e.status!=="ok")return null;let n=vu(t.publicRoutes),r=Pu(t.mcp),s=[...n.length>0?[{fact:{label:"Public",value:Cu(n)}}]:[],...r?[{fact:{label:"MCP",value:`Serves /mcp on its own host (${r.by}): ${r.why}`}}]:[]];if(t.firstDeploy!==!0)return s.length>0?s:null;let o=f(t.organizationName),i=m.dim(`\xB7 change it at ${f(t.gatewayUrl)}/admin/apps`),a=t.scope==="shared"?`Members of every organization ${m.dim("(shared app)")}`:t.defaultAccess===!0?`Everyone${o?` in ${o}`:""} ${i}`:t.deployerAccess===!1?`Private to owners and admins ${i}`:`Private to you, owners and admins ${i}`,c=t.hasOwner===!1?`
45
+ ${m.dim(`The Gateway has no owner yet; its first owner gets the app (${dt} setup).`)}`:"";return[{fact:{label:"Who can open",value:`${a}${c}`}},...s]},"app.hyperdrive":e=>e.status==="ok"?{done:"Connected to Postgres through Hyperdrive",notes:e.data?.caching==="off"?['Query caching is off; caching: "default" in everyapp.config.ts turns it on.']:[]}:null,"app.install":Ks("Installed dependencies"),"app.build":e=>e.status==="start"?{spin:"Building..."}:e.status!=="ok"?null:{done:e.data?.release===!0?"Release checked":"Built"},"app.schema":e=>e.status==="start"?{spin:"Checking the schema..."}:e.status==="skip"&&e.message?{line:m.dim(e.message)}:e.status==="ok"?{done:"Schema matches the migrations"}:null,"app.migrations":e=>e.status==="start"?{spin:e.data?.dialect==="postgresql"?"Migrating the Postgres database...":"Migrating the database..."}:e.status==="ok"&&e.data?.applied===void 0?{done:"Database migrated"}:Bs(e,"Database"),"app.helper":e=>{let t=f(e.data?.name);return e.status==="start"?{spin:`Uploading ${t}...`}:e.status==="ok"?{done:`Uploaded helper Worker ${t}`}:null},"app.upload":e=>e.status==="start"?{spin:"Uploading..."}:e.status==="ok"?{done:"Uploaded"}:null,"app.release":e=>{if(e.status!=="ok")return null;let t=e.data??{};return[{done:`Packed ${f(t.appId)} ${f(t.version)}`},{fact:{label:"Release",value:f(t.shown)??""}},{fact:{label:"SHA-256",value:f(t.sha256)??""}}]},"app.workflows":e=>e.status==="ok"?{done:`Deleted the Workflow ${f(e.data?.binding)}`}:null,"app.lease":Gs,"gateway.lease":Gs,"gateway.release":(e,t)=>{if(e.status!=="ok")return null;let n=e.data??{};if(n.downloaded===!0)return{done:`Downloaded Gateway ${f(n.release)}`};let r=f(n.origin?.path);return r?{done:`Loaded Gateway ${f(n.release)} from ${r}`,detail:""}:n.cached!==!1?null:t("gateway.upgrade")?gn({done:"Built"}):{done:"Built from this checkout"}},"app.email":e=>{let t=e.data??{};if(e.status==="start")return{spin:t.removing===!0?"Removing mail routes...":"Routing mail..."};if(e.status!=="ok")return null;let n=P(t.addresses),r=f(t.replyHint);return[...P(t.enabled).map(s=>({done:`Email Routing turned on for ${s}`})),n.length?{done:`Mail to ${n.join(", ")} routed`,...r?{notes:[r]}:{}}:{done:"Mail routes removed"}]},"app.access":e=>e.status==="ok"?{done:e.data?.removed===!0?`Cloudflare Access no longer lets ${f(e.data?.appId)}'s public routes through`:`Cloudflare Access lets ${f(e.data?.appId)}'s public routes through`}:null,"app.bind":e=>e.status==="start"?{spin:`Adding ${f(e.data?.appId)} to the Gateway...`}:e.status==="ok"?{done:"Added to the Gateway"}:null,"gateway.upgrade":e=>e.status==="start"?{line:m.bold(`Gateway ${f(e.data?.from)} \u2192 ${f(e.data?.to)}`)}:null,"app.live":e=>{let t=e.data??{},n=f(t.url)??`https://${f(t.hostname)}`;if(e.status==="skip")return Iu(t,n);if(e.status!=="ok")return null;let r={fact:{label:"Live",value:m.cyan(n)},lead:!0},s=f(t.waited);return s?[{done:s==="certificate"?"Certificate issued":"Live"},r]:r},"app.delete":e=>{let t=f(e.data?.appId);return e.status==="start"?{spin:`Removing ${t} from the Gateway...`}:e.status!=="ok"?null:e.data?.alreadyDeleted===!0?{line:`${t} was already removed from the Gateway`}:{done:`Removed ${t} from the Gateway`}},"app.certificate":e=>e.status==="ok"?{done:`Removed ${f(e.data?.hostname)}'s certificate`}:null,"app.purge":e=>{let t=f(e.data?.appId);if(e.status==="start")return{spin:`Deleting ${t}'s Worker and data...`};if(e.status!=="ok")return null;let n=P(e.data?.kinds);return n.length>0?{done:`Deleted ${t}'s ${pt(n)}`}:{line:m.dim(`Nothing of ${t}'s was left to delete in Cloudflare`)}},"create.copy":e=>{let t=e.data??{};return e.status==="start"?[{line:`Creating ${f(t.appId)} in ${f(t.shown)}`},...t.elsewhere===!0?[{line:m.dim("New apps go in the checkout's apps/ folder, wherever you run create.")}]:[]]:e.status==="ok"?{done:"Copied the starter template"}:null},"secrets.gateway":(e,t)=>t("access.update")||t("access.off")?null:ce(e),"setup.access":e=>{if(e.status!=="ok")return null;let t=e.data??{},n=Array.isArray(t.signInMethods)?t.signInMethods.map(o=>o.type):[],r=[...n.includes("cloudflare")?["a Cloudflare account"]:[],...n.includes("onetimepin")?["a one-time PIN"]:[]],s=P(t.signIn?.pending);return{done:"Cloudflare Access on",detail:r.length>0?`sign-in with ${r.join(" or ")}`:void 0,notes:s.length>0?[`${pt(s)} ${s.length===1?"signs":"sign"} in once with ${s.length===1?"their":"their own"} password; Access asks them to sign in first.`]:[]}},"secrets.app":ce,"secrets.provider":e=>e.status==="ok"&&e.message?{line:e.message}:null,"provider.add":e=>e.status==="start"?{spin:e.message??"Registering..."}:null,"provider.remove":e=>e.status==="start"?{spin:e.message??"Removing..."}:null,"provider.alias":e=>e.status==="ok"&&e.message?{line:m.dim(e.message)}:null,"events.deliver":ce,"create.skill":ce,"create.install":zs("Installing dependencies...","Installed dependencies"),"create.types":zs("Generating types...","Generated types"),"create.git":e=>e.status==="start"?{spin:"Starting a git repository..."}:e.status==="ok"?{done:"Started a git repository",detail:"first commit: Starter template"}:null,"create.done":e=>e.status==="ok"?{line:""}:null,"dev.types":Ks("Worker types generated",".cloudflare/types"),"dev.migrations":e=>{if(e.status==="skip")return e.data?.reason==="flag"?{line:m.dim("Skipped local migrations (--skip-migrations)")}:null;if(e.status!=="ok")return null;let t=P(e.data?.applied);return{done:t.length?`${z(t.length,"local migration")} applied`:"Local database up to date"}},"dev.app":e=>e.status==="ok"?[{done:`${f(e.data?.appId)??"The app"} is running locally`},...e.message?[{line:e.message}]:[]]:null,"dev.stop":e=>{let t=f(e.data?.appId)??"the app";return e.data?.started===!0?{done:`${t} stopped`}:{line:m.dim(`Stopped before ${t} started.`)}},"migrations.local":e=>{if(e.status==="start")return{spin:"Setting up the local database..."};if(e.status==="skip"&&e.message)return{line:e.message};if(e.status!=="ok")return null;let t=P(e.data?.applied);return{done:"Set up the local database",...t.length?{detail:z(t.length,"migration")}:{}}},"cloudflare.login":e=>{let t=e.data??{},n=f(t.email),r=n?` as ${n}`:t.token===!0?" with CLOUDFLARE_API_TOKEN":"";return e.status==="skip"?{line:`Already logged in to Cloudflare${r}`}:e.status==="ok"?{done:`Logged in to Cloudflare${r}`}:null},"db.migrate":e=>{if(e.status==="start")return{spin:"Applying migrations to the local database..."};if(e.status==="skip"&&e.message)return{line:m.dim(e.message)};if(e.status!=="ok")return null;let t=P(e.data?.applied);return t.length?{done:`${z(t.length,"migration")} applied to the local database`,detail:"",notes:t}:{done:"Local database up to date",detail:""}},"db.query":e=>e.status==="start"?{spin:`Querying the ${f(e.data?.database)} database...`}:null,"teardown.check":ce,"teardown.inventory":e=>e.status==="start"?{spin:e.message??""}:null,"teardown.plan":e=>e.status==="ok"?{done:e.message??"",notes:P(e.data?.lines)}:null,"teardown.delete":ce,"db.restore":e=>{if(e.status==="start")return{spin:"Restoring..."};if(e.status!=="ok")return null;let t=e.data??{},n=f(t.appId);return{done:`Restored ${n?`${n}'s`:"the Gateway's"} database`,detail:`before ${P(t.migrations).join(", ")}`}}},_u=new Set(["CUSTOM_DOMAIN_OWNER_UNCHECKED"]);function Gs(e){return e.status==="ok"?{done:`Other ${f(e.data?.waitedFor)??"run"} finished`}:null}var xe=()=>!0,Su=e=>e.host===void 0,Au={"app.release":xe,"app.lease":xe,"gateway.lease":xe,"db.lease":xe,"app.live":xe,"gateway.tls":Su},ku=new Set(["dev.mcp","dev.session"]);function Bs(e,t){if(e.status!=="ok")return null;let n=e.data??{},r=P(n.applied);if(r.length===0)return{done:`${t} up to date`};if(n.fresh===!0)return{done:`${t} created`,detail:z(r.length,"migration")};let s=f(n.restoreCommand);return{done:`${t} migrated`,detail:r.join(", "),notes:s?[`Restore point saved. To undo: ${s}`]:[]}}function gn(e){return!e||!("done"in e)?e:{...e,done:` ${e.done}`,...e.notes?{notes:e.notes.map(t=>` ${t}`)}:{}}}function Iu(e,t){if(e.reason==="outside-base")return[{fact:{label:"Live",value:m.yellow("Not routed")},lead:!0}];let n=e.reason==="certificate"?"Goes live on its first visit, once its certificate comes (a few minutes)":e.reason==="first-visit"?"Goes live on its first visit":void 0;return[{fact:{label:"URL",value:m.cyan(t)},lead:!0},...n?[{fact:{label:"Status",value:n},lead:!0}]:[]]}function Ws(e,t){let[n="",...r]=t.split(`
46
+ `);return[`${e} ${n}`,...r.map(s=>m.dim(` ${s}`))]}function yn(e,{url:t=!1}={}){let n=f(e?.didYouMean),r=f(e?.usage),s=f(e?.fix),o=t?f(e?.url):void 0,i=f(e?.rerun)??f(e?.help),a=f(e?.rerunNote);return[...n?[` Did you mean ${m.bold(n)}?`]:[],...r?[m.dim(` Usage: ${r}`)]:[],...s?[` Fix: ${s}`]:[],...o?[` ${m.cyan(o)}`]:[],...i?[` ${e?.authorize===!0?"To go ahead anyway":"Run"}: ${m.bold(i)}${a?` ${m.dim(a)}`:""}`]:[]]}function Tu(e){if(!Array.isArray(e))return[];let t=e.map(r=>r),n=Math.max(...t.map(r=>r.rerun.length));return t.map(r=>` ${m.bold(r.rerun.padEnd(n))}${r.label?` ${m.dim(r.label)}`:""}`)}function Ru(e){return Array.isArray(e)?e.map(t=>({label:t.label,value:`${/^https?:\/\//.test(t.value)?m.cyan(t.value):t.value}${t.note?` ${m.dim(t.note)}`:""}`})):[]}function xu(e){if(typeof e!="object"||e===null)return;let{min:t,max:n}=e;return typeof t=="number"&&typeof n=="number"?{min:t,max:n}:void 0}function vu(e){return Array.isArray(e)?e.map(t=>t):[]}function Pu(e){if(!e||typeof e!="object")return null;let{by:t,why:n}=e;return(t==="gateway"||t==="app")&&typeof n=="string"?{by:t,why:n}:null}function Cu(e){let{shown:t,more:n}=Ms(e);return`Open to the internet without sign-in: ${t}${n>0?m.dim(` \u2026 and ${n} more (everyapp.config.ts public)`):""}`}function Ou(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?{command:t}:t):[]}function $u(e){let t=r=>r.command??r.url??"",n=Math.max(...e.map(r=>t(r).length));return e.map(r=>r.note?` ${t(r).padEnd(n)} ${m.dim(r.note)}`:` ${t(r)}`)}var Fs=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Nu=80,Hs=3e4,wn=class{constructor(t,n,r,s){this.write=t;this.terminal=n;this.columns=r;this.now=s}steps=[];frame=0;timer;drawn=!1;lines(t){this.erase(),this.write(`${t}
47
+ `),this.draw()}spin(t,n){let r=this.steps.find(s=>s.step===t);if(r?r.label=n:this.steps.push({step:t,label:n,since:this.now()}),!this.terminal){this.keepAlive();return}this.timer||(Us.hide(process.stdout),this.timer=setInterval(()=>{this.frame=(this.frame+1)%Fs.length,this.draw()},Nu),this.timer.unref()),this.draw()}stopSpinning(t){let n=this.steps.findIndex(r=>r.step===t);n<0||(this.steps=this.steps.slice(0,n),this.settle())}drop(t){this.steps=this.steps.filter(n=>n.step!==t),this.settle()}aside(t){this.terminal&&this.erase(),t(),this.draw()}handOver(){this.steps=[],this.stopTimer(),this.erase()}finish(){this.handOver()}interrupt(t){this.handOver(),this.terminal?this.spin("interrupt",t):this.write(`${m.dim(t)}
48
+ `)}settle(){this.steps.length===0&&this.stopTimer(),this.draw()}stopTimer(){this.timer&&(clearInterval(this.timer),this.timer=void 0,this.terminal&&Us.show(process.stdout))}keepAlive(){this.timer||(this.timer=setInterval(()=>{let t=this.steps.findLast(s=>s.label);if(!t)return;let n=this.now()-t.since;if(n<Hs)return;let r=t.label.replace(/\.{3}$|…$/,"");this.write(`${m.dim(`still ${r.charAt(0).toLowerCase()}${r.slice(1)} \xB7 ${Os(n)}`)}
49
+ `)},Hs),this.timer.unref())}erase(){this.drawn&&(this.write("\r\x1B[2K"),this.drawn=!1)}draw(){if(!this.terminal)return;let t=this.steps.findLast(o=>o.label)??this.steps.at(-1);if(!t){this.erase();return}let n=this.now()-t.since,r=`${t.label?`${t.label} `:""}${n>=5e3?`\xB7 ${ct(n)} `:""}${Fs[this.frame]}`,s=Math.max(this.columns()-1,10);this.write(`\r\x1B[2K${m.dim(r.length>s?`\u2026${r.slice(r.length-s+1)}`:r)}`),this.drawn=!0}};function Ys(e,t,n){let r=n(),s=new Set,o=!1,i=!1,a=!1;return{emit(c){let d=c;if(d.type==="warning"){let l=`${d.code}
50
+ ${d.message}`;if(s.has(l))return;s.add(l)}else d.type==="done"&&(d={...d,data:{...d.data,durationMs:n()-r}});d.type==="error"?o=!0:d.type==="action_required"?d.data?.waiting?a=!0:i=!0:d.type==="done"&&(a=!1),e(d),Ns(d.type==="done"?{...d,display:void 0}:d,new Date(n()))},get exitCode(){return o?1:i||a?2:0},verbose:t}}var qs;function Xs(e){qs=e,process.exitCode=e}function Jh(){return qs}var Du="https://dash.cloudflare.com/?to=/:account/workers/plans",Lu="https://dash.cloudflare.com/profile",Mu=new Set(["ECONNREFUSED","ECONNRESET","ENOTFOUND","EAI_AGAIN","ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]);function Qs(e,t,n){let r=ts(t),s=h=>r?`${h}
51
+ The database stays migrated. To roll it back: ${r.restoreCommand}`:h,o=r?{rollbackCommand:r.rollbackCommand}:{},i=n?{step:n}:{},a=(h,y,_)=>e.emit({type:"action_required",action:h,message:s(y),...i,data:{..._,...o}}),c=(h,y,_,p)=>e.emit({type:"error",code:h,message:s(y),retryable:_,...i,data:{...p,...o}});if(t instanceof Ze){a(t.action,t.message,{...t.data,...t.url?{url:t.url}:{},...t.rerun?{rerun:t.rerun}:{},...t.rerunNote?{rerunNote:t.rerunNote}:{}});return}if(Se(t,"free_plan")){a("upgrade_workers_paid",`Cloudflare refused, for the Free plan: ${t.message}
52
+ Every App needs Workers Paid ($5 a month, then usage). Subscribe, then run this command again.`,{url:Du,rerun:R()});return}if(t instanceof I){c(t.code,t.message,t.retryable,{...t.data,...t.fix?{fix:t.fix}:{},...t.rerun?{rerun:t.rerun}:{},...t.rerunNote?{rerunNote:t.rerunNote}:{},...t.authorize?{authorize:!0}:{}});return}let d=ju(t);if(d){c(d.code,d.message,d.retryable,{...d.data,...d.retryable?{rerun:R()}:{}});return}let l=t instanceof Error?t:new Error(String(t));c("UNEXPECTED",`everyapp hit an unexpected error
53
+ ${l.name}: ${l.message}
54
+ This is a bug in everyapp, not something you did.`,!1,{...l.stack?{stack:l.stack}:{},...e.verbose?{}:{rerun:R(["--verbose"]),rerunNote:"for a stack trace to report"}})}function ju(e){if(!(e instanceof Error))return null;if(Se(e,"email_unverified"))return{code:"CF_EMAIL_UNVERIFIED",message:`Verify your Cloudflare account's email address first
55
+ Cloudflare refuses to create anything until the address on the account is verified. Open the message Cloudflare sent you, then run this command again.`,retryable:!0,data:{url:Lu,cloudflare:e.message}};if(e instanceof U)return{code:`CF_${e.kind.toUpperCase()}`,message:e.message,retryable:!1};if(e instanceof se)return{code:"CF_TIMEOUT",message:e.message,retryable:!0};if(e instanceof V)return{code:"CF_OUTPUT",message:e.message,retryable:!1};if(e instanceof S)return{code:"INVALID_MANIFEST",message:e.message,retryable:!1};let t=Zs(e)??Zs(e.cause);return t&&Mu.has(t)?{code:"NETWORK_ERROR",message:`The network failed (${t})
56
+ ${e.message}`,retryable:!0}:e instanceof TypeError&&e.message==="fetch failed"?{code:"NETWORK_ERROR",message:`The network failed
57
+ fetch failed`,retryable:!0}:t?{code:"SYSTEM_ERROR",message:e.message,retryable:!1}:null}function Zs(e){let t=e?.code;return typeof e=="object"&&typeof t=="string"&&/^[A-Z_]+$/.test(t)?t:void 0}function Uu(e,t){return e?Vs():Js({verbose:t,terminal:os()})}async function Ku(e,t){try{await t()}catch(n){Qs(e,n)}Xs(e.exitCode)}async function og(e,t){let n=Uu(e.json,e.verbose);await Ku(n,()=>t(n))}export{Bu as a,Wu as b,dt as c,R as d,Fu as e,z as f,ve as g,f as h,Vu as i,X as j,pt as k,P as l,Ui as m,Ki as n,zi as o,Yp as p,br as q,qp as r,Xp as s,Zp as t,ad as u,cd as v,So as w,ud as x,dd as y,Pn as z,Cn as A,pd as B,v as C,C as D,D as E,lt as F,Q as G,kn as H,io as I,Yu as J,Sr as K,tl as L,nl as M,de as N,lo as O,pe as P,G as Q,Zu as R,Qu as S,Tn as T,Rn as U,Pe as V,nd as W,Ce as X,rd as Y,vn as Z,sd as _,od as $,On as aa,$n as ba,Co as ca,Oo as da,yd as ea,wd as fa,Do as ga,Lo as ha,Un as ia,Ed as ja,Kn as ka,bd as la,_d as ma,Sd as na,Gn as oa,Rd as pa,$e as qa,Wn as ra,xd as sa,vd as ta,Pd as ua,Od as va,$d as wa,Nd as xa,Dd as ya,Ld as za,jd as Aa,kr as Ba,ul as Ca,dl as Da,pl as Ea,ll as Fa,fl as Ga,ml as Ha,hl as Ia,gl as Ja,wl as Ka,El as La,bl as Ma,_l as Na,Sl as Oa,Al as Pa,Fo as Qa,bt as Ra,_t as Sa,Gd as Ta,ca as Ua,xl as Va,ha as Wa,ya as Xa,pi as Ya,Fd as Za,wf as _a,Ef as $a,Pr as ab,Vr as bb,ec as cb,S as db,If as eb,Tf as fb,Rf as gb,xf as hb,Or as ib,oc as jb,ic as kb,Xr as lb,ac as mb,vf as nb,Pf as ob,Cf as pb,Of as qb,cc as rb,Nf as sb,I as tb,Ze as ub,es as vb,zf as wb,Gf as xb,U as yb,Se as zb,Ff as Ab,se as Bb,as as Cb,Qe as Db,Vf as Eb,rm as Fb,sm as Gb,ms as Hb,hs as Ib,cm as Jb,ys as Kb,Pc as Lb,Es as Mb,$c as Nb,bm as Ob,_m as Pb,ae as Qb,Rs as Rb,sn as Sb,Mm as Tb,fh as Ub,cu as Vb,mh as Wb,Th as Xb,Rh as Yb,xh as Zb,vh as _b,Ph as $b,Ms as ac,Os as bc,ct as cc,gh as dc,Eh as ec,bh as fc,Ls as gc,kh as hc,Hh as ic,Eu as jc,Jh as kc,Qs as lc,Uu as mc,Ku as nc,og as oc};
@@ -0,0 +1 @@
1
+ import{$ as N,B as S,W as u,X as z,Y as L,Z as E,ba as w,ca as B,cb as j,da as V,db as X,ea as K,eb as M,fa as F,ga as G,ha as H,ia as J,ja as W,jb as v,la as O,lb as T,mb as Y,nb as q,ob as Q,pb as k,qb as Z}from"./chunk-SAT3PGZU.js";function de(e){if(!e)return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.every(r=>typeof r=="string")?t:null}catch{return null}}function le(e){return JSON.stringify([...new Set(e)].sort())}var b=class extends Error{constructor(r,n){super(`App "${r}" can't be routed: ${n}`);this.appId=r;this.name="UnroutableAppError"}};var D=class{byHostname=new Map;byAppId=new Map;byOrgApp=new Map;constructor(t=[]){for(let r of t)this.add(r)}add(t){this.byHostname.set(t.hostname.toLowerCase(),t),this.byAppId.set(t.appId,t),this.byOrgApp.set(ee(t.organizationId,t.appId),t)}async findByHostname(t){return this.byHostname.get(t.toLowerCase())??null}async hasAnyActiveApp(){return Array.from(this.byAppId.values()).some(t=>t.status==="active")}async findByAppId(t){return this.byAppId.get(t)??null}async findByOrgApp(t,r){return this.byOrgApp.get(ee(t,r))??null}};function ee(e,t){return JSON.stringify([e,t])}var p="deleted",o=class extends Error{status;code;constructor({status:t,code:r,message:n}){super(n),this.name="RegistrationError",this.status=t,this.code=r}},ce=/^(?=.{1,63}$)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,re=12,ge=50;function ne(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"").slice(0,re)||"org"}function ue(e){let t=ne(e);return Array.from({length:ge},(r,n)=>{let s=n===0?"":String(n+1);return`${t.slice(0,re-s.length)}${s}`})}function te(e,t){let r=e.trim().toLowerCase();if(!ce.test(r))throw new o({status:400,code:"INVALID_APP_HOSTNAME",message:`${t} must form a valid DNS label of at most 63 characters; received "${r}".`});return r}function se(e){let{appSlug:t,orgKey:r}=e;if(j(t))throw new o({status:400,code:"RESERVED_APP_ID",message:`The app id "${t}" is reserved for the platform.`});if(t.includes(T))throw new o({status:400,code:"INVALID_APP_ID",message:`App id "${t}" can't contain "${T}": it separates an app's Worker name from its resources' names. Choose another id.`});let n=e.existingApp?.workerName??Y({appId:t,orgKey:r}),s=e.appBaseDomain.trim().toLowerCase().replace(/\.$/,""),i=e.existingApp?.hostname??`${e.isInstallOrganization?te(t,"The app id"):te(`${t}-${r}`,"The app id and organization key")}.${s}`;if(!q({appId:t,orgKey:r,workerName:n}))throw new o({status:400,code:"INVALID_WORKER_NAME",message:n.length>v?`App id "${t}" is too long: its Worker name "${n}" would exceed ${v} characters.`:`App id "${t}" can't be registered: its Worker would be "${n}", which is reserved for the gateway or isn't the app's own.`});return{workerName:n,hostname:i}}function oe(e,t){let r;try{r=M(e)}catch(n){throw new o({status:400,code:"INVALID_MANIFEST",message:n instanceof X?n.message:"Invalid manifest"})}if(r.id!==t)throw new o({status:400,code:"INVALID_MANIFEST",message:`manifest.id "${r.id}" does not match appId "${t}"`});return r}function U(e){if(!e)return null;try{return M(JSON.parse(e))}catch{return null}}function ie(e,t){let r=(n,s=Q)=>Object.fromEntries((n??[]).map(i=>[i,s(e,i)]));return{d1:r(t?.resources?.d1),kv:r(t?.resources?.kv),r2:r(t?.resources?.r2,Z)}}function me(e){return e.workerName?ie(e.workerName,U(e.manifest)):{d1:{},kv:{},r2:{}}}var Ae={d1:"D1 database",kv:"KV namespace",r2:"R2 bucket"},fe=/^[a-z0-9][a-z0-9-]*[a-z0-9]$/;function Re(e){for(let[t,r]of Object.entries(e)){let n=new Map;for(let[s,i]of Object.entries(r)){let a=n.get(i);if(a!==void 0)throw new o({status:400,code:"RESOURCE_NAME_CONFLICT",message:`Bindings ${a} and ${s} would share the ${Ae[t]} "${i}". Rename one of them in everyapp.config.ts.`});if(t==="r2"&&(i.length>k||!fe.test(i)))throw new o({status:400,code:"INVALID_MANIFEST",message:`resources.r2: ${s} would be the R2 bucket "${i}", which Cloudflare refuses (at most ${k} lowercase letters, digits and hyphens, starting and ending with a letter or digit). Rename the binding in everyapp.config.ts.`});n.set(i,s)}}}function Ie(e){return(e??"").split(",").some(t=>["owner","admin"].includes(t.trim()))}function ye(e,t,r,n){if(t==="shared")return{isDefault:!1,grants:[]};let s=r.access==="everyone";return{isDefault:s,grants:e.members.filter(i=>s||i.id===e.deployerUserId||Ie(i.role)).map(i=>({id:crypto.randomUUID(),organizationId:e.organizationId,userId:i.id,appRowId:n,grantedBy:null}))}}function we(e){let{existingApp:t}=e,r=e.scope??(t?.scope==="shared"?"shared":"org");if(t&&(t.organizationId!==e.organizationId||t.appSlug!==e.appSlug))throw new Error("existingApp is another organization's or app's row.");if(r==="shared"&&!e.isInstallOrganization)throw new o({status:403,code:"SHARED_APP_NOT_PLATFORM",message:`Only the platform organization registers shared apps; "${e.appSlug}" can't be shared from another organization.`});if(t&&t.scope!==r)throw new o({status:409,code:"APP_SCOPE_MISMATCH",message:t.scope==="shared"?`App "${e.appSlug}" is a shared app, not this organization's own. Deploy it without asking for another scope, or give the organization's own app an id of its own.`:`App "${e.appSlug}" is this organization's own app, not a shared one. Shared apps need an app id of their own.`});let n=e.tier??"service_binding";if(n==="dispatch"&&r==="shared")throw new o({status:400,code:"APP_TIER_MISMATCH",message:`A shared app is reached over a service binding; "${e.appSlug}" can't be deployed through the hosted deploy API.`});if(t&&t.tier!==n)throw new o({status:409,code:"APP_TIER_MISMATCH",message:t.tier===u?`"${e.appSlug}" is the Gateway's MCP app of that name${t.status===p?" (turned off)":""}; give this app an id of its own.`:t.tier==="dispatch"?`App "${e.appSlug}" is deployed through the hosted deploy API; deploy it the same way, or give this app an id of its own.`:`App "${e.appSlug}" is reached over a service binding, not deployed through the hosted deploy API; give the third-party app an id of its own.`});let s=se(e),i=oe(e.manifest,e.appSlug),{workerName:a,hostname:d}=s;for(let[A,_,pe]of[[e.hostnameOwner,"hostname",d],[e.workerNameOwner,"workerName",a]])if(A&&A[_]!==pe)throw new Error(`The ${_} owner passed holds another ${_}.`);let m=A=>A!==null&&(A.organizationId!==e.organizationId||A.appSlug!==e.appSlug);if(m(e.hostnameOwner))throw new o({status:409,code:"HOSTNAME_TAKEN",message:`The hostname "${d}" is already registered to another app on this gateway.`});if(m(e.workerNameOwner))throw new o({status:409,code:"WORKER_NAME_TAKEN",message:`The worker name "${a}" is already registered to another app on this gateway. Choose a different app id.`});let f=ie(a,i);Re(f);let y={organizationId:e.organizationId,name:e.name,description:e.description,hostname:d,workerName:a},l={previousManifest:U(t?.manifest??null),versionId:t?.versionId??null,resources:f};if(t&&t.status!==p)return{kind:"existing",app:{...t,...y},grants:[],...l};let R=t?.id??crypto.randomUUID(),{isDefault:c,grants:h}=ye(e,r,i,R),g={...y,manifest:JSON.stringify(i),status:"pending",isDefault:c};return t?{kind:"revived",app:{...t,...g},grants:h,...l}:{kind:"new",app:{id:R,appSlug:e.appSlug,tier:n,scope:r,versionId:null,deployedAt:null,deployedByActor:null,...g},grants:h,...l}}function he(e){if(e.status===p)throw new o({status:404,code:"APP_NOT_FOUND",message:`No app "${e.appSlug}" is registered for this organization.`});if(!e.workerName||!e.hostname&&e.tier!=="dispatch")throw new o({status:409,code:"APP_NOT_REGISTERED",message:`App "${e.appSlug}" has no Worker or hostname yet; deploy it again.`})}function Ee(e,{versionId:t,manifest:r,actor:n,now:s=Date.now()}){return he(e),{manifest:JSON.stringify(oe(r,e.appSlug)),versionId:t,deployedAt:s,deployedByActor:n,status:e.status==="pending"?"binding":e.status}}function P(e){return e.status===p?null:{status:p,isDefault:!1,emailSenders:null,emailInbound:null,secretNames:null}}function Me(e){return(e??"").split(",").some(t=>["owner","admin"].includes(t.trim()))}function I(e,t){throw new o({status:400,code:e,message:t})}function Pe(e,t){let r=t&&typeof t=="object"&&!Array.isArray(t)?t:{kind:t??"none"},n=r.kind,s=(n==="bearer"||n==="header"||n==="basic")&&r.secret===void 0?{...r,secret:B(e)}:r,i=G(s);return i.ok||I("REMOTE_MCP_INVALID",i.problem),i.auth}function C(e){if(e.tier!==u||!e.manifest)return!1;try{return W(JSON.parse(e.manifest))}catch{return!1}}function $(e){return e.tier===u}function x(e){if(e.tier!==u||!e.manifest)return null;try{return J(JSON.parse(e.manifest))}catch{return null}}function _e(e,t,r){if(r&&(r.organizationId!==e||r.appSlug!==t))throw new Error("existingApp is another organization's or app's row.")}function Se(e,t){if(C(t))return;let r=t.tier===u?"the Gateway's built-in MCP app":`an app deployed to this Gateway${t.status===p?" (deleted, its names still its organization's)":""}`;throw new o({status:409,code:"APP_TIER_MISMATCH",message:`"${e}" is ${r}; a remote MCP server can't take its id.`})}function Ne(e){let t=e.url.trim(),r=F(t,e.env);r&&I("REMOTE_MCP_URL_REFUSED",r);let n=(e.id??"").trim()||K(t);n||I("REMOTE_MCP_INVALID","no app id could be read from the URL's host; give one with --name");let s=V(n);s&&I("REMOTE_MCP_INVALID",s);let i=e.sharedApp?.(n);if(i&&i.status!==p)throw new o({status:409,code:"APP_TIER_MISMATCH",message:`"${n}" is a shared app every organization sees; a remote MCP server can't take its id.`});let a=e.existingApp(n);_e(e.organizationId,n,a);let d=(e.risk??"annotations").trim();w.includes(d)||I("REMOTE_MCP_INVALID",`risk must be one of ${w.join(", ")}`);let m=Pe(n,e.auth);if("secret"in m&&e.secretUsedAt){let g=e.secretUsedAt(m.secret),A=new URL(t).origin;if(g&&g!==A)throw new o({status:409,code:"REMOTE_MCP_SECRET_TAKEN",message:`${m.secret} is the credential of an MCP app at ${g}; a server at ${A} takes another name (--secret <NAME>_MCP_TOKEN).`})}let f=a?x(a)?.rev??0:0,y={url:t,auth:m,risk:d,tools:{},rev:f+1},l=O({id:n,name:e.name,description:e.description,remote:y});if(a&&((E(n)||!C(a))&&Se(n,a),a.status!==p))throw new o({status:409,code:"REMOTE_MCP_EXISTS",message:`"${n}" is an MCP app on this Gateway already (${a.status==="active"?"on":"off"}); remove it first, or change it in place.`});let R=a?.id??crypto.randomUUID(),c={id:R,organizationId:e.organizationId,appSlug:n,name:l.name,description:l.description,hostname:null,workerName:null,tier:u,scope:"org",manifest:JSON.stringify(l),status:"active",versionId:null,deployedAt:e.now,deployedByActor:e.actor,isDefault:!1},h=e.members.filter(g=>g.id===e.actorUserId||Me(g.role)).map(g=>({id:crypto.randomUUID(),organizationId:e.organizationId,userId:g.id,appRowId:R,grantedBy:null}));return{kind:a?"revived":"new",id:n,app:c,grants:h,remote:y}}function Oe(e,t){let r=x(e);if(!r)throw new o({status:404,code:"APP_NOT_FOUND",message:`"${e.appSlug}" is not a remote MCP app.`});if(e.status===p)throw new o({status:404,code:"APP_NOT_FOUND",message:`"${e.appSlug}" was removed.`});let n=r.risk;t.risk!==void 0&&(w.includes(t.risk)||I("REMOTE_MCP_INVALID",`risk must be one of ${w.join(", ")}`),n=t.risk);let s={...r.tools};if(t.tools&&(s={...t.tools}),t.tool){let{name:l,override:R}=t.tool;if(l.trim()||I("REMOTE_MCP_INVALID","name the tool"),R===null)delete s[l];else{let c={...s[l],...R};c.risk===void 0&&delete c.risk,(c.enabled===void 0||c.enabled===!0)&&delete c.enabled,Object.keys(c).length===0?delete s[l]:s[l]=c}}let i=S({risk:n,tools:s})!==S({risk:r.risk,tools:r.tools}),a={...r,risk:n,tools:s,rev:i?r.rev+1:r.rev},d=H(a);d.ok||I("REMOTE_MCP_INVALID",d.problem);let m=JSON.parse(e.manifest??"{}"),f=O({id:e.appSlug,name:t.name===void 0?e.name:t.name,description:t.description===void 0?e.description:t.description,remote:a}),y={...m,...f};return{manifest:JSON.stringify(y),name:f.name,description:f.description,remote:a}}function ve(e,t){if(!$(e))throw new o({status:409,code:"APP_TIER_MISMATCH",message:`"${e.appSlug}" is an app deployed to this Gateway, not an MCP app.`});if(e.status===p)throw new o({status:404,code:"APP_NOT_FOUND",message:`"${e.appSlug}" was removed; add it again.`});return e.status===t?null:{status:t}}function Te(e){return!e||!$(e)?null:P(e)}function ke(e){return(e??"").split(",").some(t=>["owner","admin"].includes(t.trim()))}function ae(e){if(E(e))return e;throw new o({status:400,code:"PROVIDER_APP_UNKNOWN",message:`"${e}" is not an MCP app. The Gateway offers: ${L.join(", ")}.`})}function be(e,t){if(t.tier!==u)throw new o({status:409,code:"APP_TIER_MISMATCH",message:`"${e}" is an app deployed to this Gateway${t.status===p?" (deleted, its names still its organization's)":""}, not the MCP app; the MCP app can't take its id.`})}function De(e){let t=ae(e.id),{existingApp:r}=e;if(r&&(r.organizationId!==e.organizationId||r.appSlug!==t))throw new Error("existingApp is another organization's or app's row.");let n=z[t];if(r&&be(t,r),r&&r.status!==p)return{kind:"existing",app:{...r,name:n.name,description:n.description,manifest:JSON.stringify(N(t)),status:"active"},grants:[]};let s=r?.id??crypto.randomUUID(),i={id:s,organizationId:e.organizationId,appSlug:t,name:n.name,description:n.description,hostname:null,workerName:null,tier:u,scope:"org",manifest:JSON.stringify(N(t)),status:"active",versionId:null,deployedAt:e.now,deployedByActor:e.actor,isDefault:!1},a=e.members.filter(d=>d.id===e.actorUserId||ke(d.role)).map(d=>({id:crypto.randomUUID(),organizationId:e.organizationId,userId:d.id,appRowId:s,grantedBy:null}));return{kind:r?"revived":"new",app:i,grants:a}}export{de as a,le as b,b as c,D as d,p as e,o as f,ue as g,se as h,me as i,we as j,Ee as k,P as l,ae as m,De as n,C as o,x as p,Ne as q,Oe as r,ve as s,Te as t};
@@ -0,0 +1,30 @@
1
+ import{c as ve,d as O,e as ke,f as Ae,g as K,h as Ee,i as Re,j as P,k as Oe,l as W,m as H,n as Me,o as Te,p as Pe,t as _e,z as Ie}from"./chunk-IG26HYRR.js";import{a as S}from"./chunk-Y3VIFPN5.js";import{B as de,W as le,X as pe,Y as me,Z as ue,_ as fe,aa as ge,ca as he,da as we,ea as ye,qa as $e,sa as be,y as ce}from"./chunk-ZYL2ZHCF.js";import{e as ae,m as se,n as re,p as ie}from"./chunk-SPPR6WCI.js";import{a as V,b as oe}from"./chunk-F6IH47GT.js";import{X as Z,_ as ee,b as Q,c as f,ca as te,ea as ne,f as z,gc as j,hc as G,ib as I,ka as D,oa as B,oc as k,tb as R}from"./chunk-SAT3PGZU.js";import{stripVTControlCharacters as Ge}from"node:util";import w from"chalk";function We(e,t,a){let{app:n}=e;if(e.kind==="existing")return[{sql:"UPDATE apps SET name = ?, description = ?, manifest = ?, status = ?, updated_at = ? WHERE id = ?",params:[n.name,n.description,n.manifest,n.status,t,n.id]}];let o=e.grants.map(s=>({sql:`INSERT INTO user_app_access (id, user_id, app_row_id, organization_id, granted_by)
2
+ VALUES (?, ?, ?, ?, NULL) ON CONFLICT DO NOTHING`,params:[s.id,s.userId,s.appRowId,s.organizationId]}));return e.kind==="new"?[{sql:`INSERT INTO apps (id, organization_id, app_slug, name, description, hostname,
3
+ worker_name, tier, manifest, status, version_id, deployed_at, deployed_by_actor,
4
+ is_default, created_at, updated_at, scope)
5
+ VALUES (?1, ?2, ?3, ?4, ?5, NULL, NULL, ?6, ?7, ?8, NULL, ?9, ?10, 0, ?11, ?11, ?12)`,params:[n.id,n.organizationId,n.appSlug,n.name,n.description,n.tier,n.manifest,n.status,n.deployedAt,n.deployedByActor,t,n.scope]},...o]:[{sql:`UPDATE apps SET name = ?, description = ?, manifest = ?, status = ?, is_default = 0,
6
+ deployed_at = ?, deployed_by_actor = ?, updated_at = ?
7
+ WHERE id = ? AND status = '${ae}'`,params:[n.name,n.description,n.manifest,n.status,n.deployedAt,n.deployedByActor,t,n.id]},...ye(n,t,a),...o]}function Se(e,t){return le(async()=>{let a=t.now??Date.now(),n=se(t.id),{organization:o,hasOwner:s}=await ge(e,t.organizationName,a),[c=[],l=[],p=[]]=await e.run([{sql:`SELECT ${await me(e)} FROM apps WHERE organization_id = ? AND app_slug = ?`,params:[o.id,n]},...he(o.id,t.deployer.email)]),i=c[0]?fe(c[0]):null,d=ue(p[0]?.id),m=re({organizationId:o.id,id:n,existingApp:i,members:we(l),actorUserId:d,actor:t.deployer.actor,now:a}),r=m.kind==="existing"?i?.status==="active"?"existing":"off":m.kind,u=r==="existing"?[]:await de(e,{organizationId:o.id,type:r==="off"?"mcp_app.enabled":"mcp_app.added",actor:ce(t.deployer),data:{app:{id:m.app.appSlug,rowId:m.app.id,name:m.app.name},kind:"builtin"},appRowId:m.app.id,onlyIf:{sql:"EXISTS (SELECT 1 FROM apps WHERE id = ? AND status = ? AND updated_at = ?)",params:[m.app.id,m.app.status,a]},now:a});await e.run([...We(m,a,{secretNames:await pe(e)}),...u]);let g=d!==null&&(m.grants.some(b=>b.userId===d)||m.kind==="existing"&&await He(e,m.app.id,d));return{plan:m,was:r,organization:o,hasOwner:s,actorGranted:g}})}async function He(e,t,a){let[n=[]]=await e.run([{sql:"SELECT 1 AS granted FROM user_app_access WHERE app_row_id = ? AND user_id = ? LIMIT 1",params:[t,a]}]);return n.length>0}var Y="2026-07-28",Ye="2025-11-25";async function Ne(e,t){let a=t.fetch??fetch,n=AbortSignal.timeout(t.timeoutMs??1e4),o={name:"everyapp-cli",version:t.version};try{let s=await Ce(a,e,n,{headers:{"mcp-protocol-version":Y,"mcp-method":"tools/list"},body:{jsonrpc:"2.0",id:1,method:"tools/list",params:{_meta:{"io.modelcontextprotocol/protocolVersion":Y,"io.modelcontextprotocol/clientInfo":o,"io.modelcontextprotocol/clientCapabilities":{}}}}});if(s.kind==="final")return s.probe;let c=s.message?xe(s.message):null;if(c&&Array.isArray(c.tools)){let i=A(c._meta),d=A(i?.["io.modelcontextprotocol/serverInfo"]);return{outcome:"reachable",era:Y,tools:c.tools.length,server:typeof d?.name=="string"?d.name:null}}let l=await Ce(a,e,n,{headers:{},body:{jsonrpc:"2.0",id:2,method:"initialize",params:{protocolVersion:Ye,capabilities:{},clientInfo:o}}});if(l.kind==="final")return l.probe;let p=l.message?xe(l.message):null;if(p&&typeof p.protocolVersion=="string"){let i=A(p.serverInfo);return{outcome:"reachable",era:p.protocolVersion,tools:null,server:typeof i?.name=="string"?i.name:null}}return{outcome:"unreachable",reason:Ze(s.status,l.status)}}catch(s){return{outcome:"unreachable",reason:tt(s,n)}}}async function Ce(e,t,a,n){let o=await e(t,{method:"POST",redirect:"manual",signal:a,headers:{"content-type":"application/json",accept:"application/json, text/event-stream",...n.headers},body:JSON.stringify(n.body)});if(o.status>=300&&o.status<400)return await o.body?.cancel().catch(()=>{}),{kind:"final",probe:{outcome:"redirected",status:o.status,location:o.headers.get("location")}};if(o.status===401||o.status===403){await o.body?.cancel().catch(()=>{});let i=o.headers.get("www-authenticate")??"";return{kind:"final",probe:{outcome:"needs-credential",status:o.status,oauth:/resource_metadata\s*=/i.test(i)}}}let s=n.body.id,c=await qe(o),p=(o.headers.get("content-type")??"").toLowerCase().includes("text/event-stream")?Qe(c,s):Je(c);return{kind:"message",status:o.status,message:p}}async function qe(e){if(!e.body)return"";let t=e.body.getReader(),a=new TextDecoder,n="",o=0;for(;;){let{done:s,value:c}=await t.read();if(s)break;if(o+=c.byteLength,n+=a.decode(c,{stream:!0}),o>=1048576){await t.cancel().catch(()=>{});break}if(/\n\n/.test(n)&&Xe(n)){await t.cancel().catch(()=>{});break}}return n+a.decode()}function Je(e){try{let t=JSON.parse(e);return Array.isArray(t)?A(t.find(a=>A(a)&&"id"in a)):A(t)}catch{return null}}function De(e){let t=[];for(let a of e.replace(/\r\n?/g,`
8
+ `).split(`
9
+
10
+ `)){let n=a.split(`
11
+ `).filter(o=>o.startsWith("data:")).map(o=>o.slice(5).replace(/^ /,"")).join(`
12
+ `);if(n)try{let o=A(JSON.parse(n));o&&t.push(o)}catch{}}return t}function Xe(e){return De(e).some(t=>"id"in t&&("result"in t||"error"in t))}function Qe(e,t){let a=De(e);return a.find(n=>n.id===t&&("result"in n||"error"in n))??a.find(n=>"result"in n||"error"in n)??null}function xe(e){return e.jsonrpc==="2.0"?A(e.result):null}function A(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function Ze(e,t){let a=n=>n>=200&&n<300;return a(e)||a(t)?"it answered, but not as an MCP server":e===t?`it answered ${e}`:`it answered ${e} to tools/list and ${t} to initialize`}var et=[[/^(ENOTFOUND|EAI_AGAIN)$/,"its host name doesn't resolve from here"],[/^ECONNREFUSED$/,"it refused the connection"],[/^(ERR_TLS|CERT_|DEPTH_ZERO|SELF_SIGNED|UNABLE_TO_VERIFY)/,"its TLS certificate wasn't accepted"]];function tt(e,t){if(t.aborted)return"it didn't answer within 10 seconds";let a=e?.cause,n=typeof a?.code=="string"?a.code:null;if(!n)return"it couldn't be reached";let o=et.find(([s])=>s.test(n));return o?o[1]:`it couldn't be reached (${n})`}async function zt(e,t){await k(e,a=>rt({flags:e,out:a},t))}async function Bt(e,t){await k(e,a=>dt({flags:e,out:a},t))}async function Vt(e,t){await k(e,a=>it({flags:e,out:a},t))}async function jt(e,t){await k(e,a=>ct({flags:e,out:a},t))}async function Kt(e){await k(e,t=>lt({flags:e,out:t}))}async function Wt(e,t){await k(e,a=>mt({flags:e,out:a},t))}async function Ht(e,t){await k(e,a=>ut({flags:e,out:a},t))}async function Yt(e,t,a){await k(e,n=>ft({flags:e,out:n},t,a))}function E({flags:e,out:t,createCf:a}){return be({gateway:$e(e.gateway),accountId:e["account-id"],interactive:V(e.json??!1),login:{json:e.json,out:t,step:"login"},createCf:a})}var C="provider.update";function M(e,t,a,n=[]){e.emit({type:"done",message:Ge(t.join(`
13
+ `)),display:[t[0],...t.slice(1).map(o=>w.dim(o)),...n].join(`
14
+ `),data:a})}function Le(e,t){return`${e?"You, the owners and the admins can use it":t?"The owners and the admins can use it":"The owner gets it when they claim the Gateway"}; an admin grants others in Admin \u2192 Apps \u2192 Manage access.`}function q(e){return{kind:e.kind,..."secret"in e?{secret:e.secret}:{},...e.kind==="header"?{header:e.header}:{}}}function L(e,t,a,n){if(!e)return null;let o=t.includes(e);if(!a)return{name:e,set:o};let s=n.get(e)?.origin??null;return{name:e,set:o,bound:s!==null&&s===H(a.url),boundOrigin:s}}function nt(e){let t=e.header?.trim(),a=e.secret?.trim(),n=e.auth??(t?"header":a?"bearer":"none");if(t&&n!=="header")throw new R("REMOTE_MCP_INVALID",`--header names the header of --auth header
15
+ With --auth ${n} the Gateway sends ${n==="none"||n==="oauth"?"no credential":"Authorization"}.`,{fix:"drop --header, or use --auth header"});if(n==="header"&&!t)throw new R("REMOTE_MCP_INVALID","--auth header needs --header <name>: the header the server reads the credential from",{fix:"add --header X-Api-Key (the name the server's docs give)"});if((a||e["from-env"])&&(n==="none"||n==="oauth")){let o=a?"--secret":"--from-env";throw new R("REMOTE_MCP_INVALID",`${o} names a credential, and --auth ${n} sends none`,{fix:`drop ${o}, or use --auth bearer, header or basic`})}return{kind:n,...a?{secret:a}:{},...t?{header:t}:{}}}function ot(e,t){switch(t.outcome){case"reachable":{let a=[t.era,...t.tools!==null?[z(t.tools,"tool")]:[],...t.server?[`server ${t.server}`]:[]];return`${e} answers MCP (${a.join(", ")})`}case"needs-credential":return`${e} asks for a credential (${t.status}${t.oauth?", OAuth":""})`;case"redirected":return`${e} redirects (${t.status}${t.location?` to ${t.location}`:""})`;case"unreachable":return`${e} didn't answer from here: ${t.reason}`}}function at(e,t,a,n,o){let s=`${f} mcp remove ${t}, then ${f} mcp add ${a} --name ${t} --auth bearer`,c={probe:o};if(o.outcome==="needs-credential"&&o.oauth){let l=D(n);e.emit({type:"warning",code:"REMOTE_MCP_WANTS_OAUTH",step:"mcp.probe",message:l?`${a} asks for OAuth
16
+ The Gateway doesn't sign in to MCP servers with OAuth yet; it sends ${l} as you set it, which works only if the server also takes an API key.`:`${a} wants OAuth
17
+ The Gateway doesn't sign in to MCP servers with OAuth yet. If the server also takes an API key, add it with --auth bearer and set the key.`,data:l?c:{...c,fix:s}});return}if(o.outcome==="needs-credential"&&n.kind==="none"){e.emit({type:"warning",code:"REMOTE_MCP_PROBE_FAILED",step:"mcp.probe",message:`${a} asks for a credential, and ${t} sends none
18
+ The Gateway's listing of its tools will fail the same way until it has one.`,data:{...c,fix:s}});return}if(o.outcome==="redirected"){e.emit({type:"warning",code:"REMOTE_MCP_PROBE_FAILED",step:"mcp.probe",message:`${a} redirects${o.location?` to ${o.location}`:""}
19
+ The Gateway follows no redirects; register the address it redirects to.`,data:{...c,fix:`${f} mcp remove ${t}, then ${f} mcp add <the address it redirects to> --name ${t}`}});return}o.outcome==="unreachable"&&e.emit({type:"warning",code:"REMOTE_MCP_PROBE_FAILED",step:"mcp.probe",message:`Couldn't reach ${a} from here: ${o.reason}
20
+ The Gateway may still reach it; ${f} mcp show ${t} says whether its tools listed.`,data:c})}async function st(e,t,a){(await ve(t.db)).tools||e.emit({type:"warning",code:"REMOTE_MCP_GATEWAY_OUTDATED",step:a,message:`This Gateway predates MCP apps by URL
21
+ It serves a remote MCP server's tools once it is updated to this checkout.`,data:{rerun:`${f} update`}})}async function rt(e,t){let{out:a,flags:n}=e,o=nt(n),s=e.readValue??(v=>_e(v,{fromEnv:n["from-env"],json:n.json})),c=n["from-env"]?await s(n.secret?.trim()||te(n.name?.trim()||ne(t.trim())||"remote")):null,l=await E(e);a.emit({type:"step",step:"mcp.add",status:"start",message:`Adding ${t}...`});let p=await Ae(l.db,{url:t,id:n.name,description:n.description,auth:o,risk:n.risk,env:{gatewayUrl:l.gatewayUrl,appBaseDomain:l.install.appBaseDomain},deployer:l.deployer,organizationName:l.accountName??"My Organization",now:e.now?.()}),{plan:i,organization:d}=p,{app:m,remote:r}=i,u=m.appSlug;a.emit({type:"step",step:"mcp.add",status:"ok",message:`${m.name} is on for ${d.name}`,data:{id:u,was:i.kind}}),await st(a,l,"mcp.add"),a.emit({type:"step",step:"mcp.probe",status:"start",message:`Looking at ${r.url}...`});let g=await Ne(r.url,{version:Q,fetch:e.fetch});a.emit({type:"step",step:"mcp.probe",status:"ok",message:ot(r.url,g),data:{probe:g}}),at(a,u,r.url,r.auth,g);let b=H(r.url),y=D(r.auth),h=null;if(y){let v=(await S(l.cf,I)).includes(y),N=c,Ke=e.interactive??V(n.json??!1);N===null&&!v&&Ke&&await(e.confirm??oe)(`Set ${y} now?`,[`${m.name}'s credential (${B(r.auth)}${r.auth.kind==="basic"?", entered as user:password":""}) is a Gateway setting.`,`The Gateway sends it to ${b} and nowhere else. Later: ${f} secret set ${y}`])&&(N=await s(y)),N!==null&&(await Ie(l,{[y]:N},{flags:n,out:a}),v=!0);let U=await P(l.db);v&&!U.has(y)&&(await Pe(l.db,[y],l.deployer.actor,e.now?.()),U=await P(l.db)),h=L(y,v?[y]:[],r,U),v?h?.boundOrigin&&!h.bound&&a.emit({type:"warning",code:"REMOTE_MCP_SECRET_BOUND_ELSEWHERE",step:"mcp.add",message:`${y} was set for ${h.boundOrigin}, not ${b}
22
+ The Gateway sends a credential only to the origin it was set for; set it again for ${m.name}.`,data:{fix:`${f} secret set ${y}`,name:y,boundOrigin:h.boundOrigin}}):a.emit({type:"warning",code:"PROVIDER_KEY_UNSET",step:"mcp.add",message:`${y} isn't set on the Gateway
23
+ ${m.name}'s tools stay out of /mcp until it is.`,data:{fix:`${f} secret set ${y}`,name:y}})}let T={url:`${l.gatewayUrl}/mcp`,toolPrefix:`${u}_`},x=r.auth.kind==="oauth"?"It serves no tools yet: the Gateway doesn't sign in to MCP servers with OAuth this week.":h?h.set?h.bound?`${h.name} is set on the Gateway and pinned to ${b}.`:`${h.name} is set, but for ${h.boundOrigin}: ${f} secret set ${h.name}`:`${h.name} isn't set: ${f} secret set ${h.name}`:"It takes no credential.",$=[`${m.name} is on for ${d.name}${i.kind==="revived"?" (added again, from scratch)":""}.`,Le(p.actorGranted,p.hasOwner),`Its tools are on ${T.url} as ${T.toolPrefix}<tool>; the Gateway lists them on first use.`,x],je=[...h&&(!h.set||!h.bound)?[{command:`${f} secret set ${h.name}`,note:`${m.name}'s credential`}]:[],{command:`${f} mcp show ${u}`,note:"its tools, once the Gateway lists them"}];M(a,$,{id:u,name:m.name,url:r.url,auth:q(r.auth),risk:r.risk,on:!0,was:i.kind,organization:{id:d.id,name:d.name},probe:g,key:h,mcp:T,granted:i.grants.map(v=>v.userId),next:je})}function F(e){if(!e.app||e.app.status==="deleted")throw ke(e);return e.app}function _(e){return e.kind==="builtin"?Z[e.id].name:e.app?.name??e.id}function J(e){if(e.kind==="builtin")return{name:ee(e.id),remote:null};let t=e.app?ie(e.app):null;return{name:t?D(t.auth):null,remote:t}}async function X(e,t){let{name:a,remote:n}=J(t);if(!a)return null;let[o,s]=await Promise.all([S(e.cf,I),n?P(e.db):Promise.resolve(new Map)]);return L(a,o,n,s)}async function it(e,t){let{out:a}=e,n=await E(e),o=await O(n.db,t);a.emit({type:"step",step:C,status:"start",message:`Turning ${t} on...`});let s,c,l=null,p=[];if(o.kind==="builtin"){let u=await Se(n.db,{id:t,deployer:n.deployer,organizationName:n.accountName??"My Organization",now:e.now?.()});s=u.was,c=u.organization,p=u.plan.grants.map(g=>g.userId),(s==="new"||s==="revived")&&(l=Le(u.actorGranted,u.hasOwner))}else{let u=F(o),{changed:g}=await K(n.db,u,"active",n.deployer,e.now?.());s=g?"off":"existing",c=o.organization}let i=_(o);a.emit({type:"step",step:C,status:"ok",message:s==="existing"?`${i} was on already`:`${i} is on for ${c.name}`,data:{id:t,was:s}});let d=await X(n,o),m={url:`${n.gatewayUrl}/mcp`,toolPrefix:`${t}_`};d&&!d.set&&a.emit({type:"warning",code:"PROVIDER_KEY_UNSET",step:C,message:`${d.name} isn't set on the Gateway
24
+ ${i}'s tools ${o.kind==="builtin"?'answer "not set up"':"stay out of /mcp"} until it is.`,data:{fix:`${f} secret set ${d.name}`,name:d.name}});let r=[`${i} is on for ${c.name}${s==="existing"?" (it was already)":s==="off"?" (it was off; everyone's access was kept)":""}.`,...l?[l]:[],`Its tools are on ${m.url} as ${m.toolPrefix}<tool>.`,...d?[d.set?`${d.name} is set on the Gateway.`:`${d.name} isn't set: ${f} secret set ${d.name}`]:[]];M(a,r,{id:t,name:i,kind:o.kind,on:!0,was:s,organization:{id:c.id,name:c.name},key:d,mcp:m,granted:p,...d&&!d.set?{next:[{command:`${f} secret set ${d.name}`,note:o.kind==="builtin"?"the provider's key":`${i}'s credential`}]}:{}})}async function ct(e,t){let{out:a}=e,n=await E(e),o=await O(n.db,t);a.emit({type:"step",step:C,status:"start",message:`Turning ${t} off...`});let s=_(o),c=o.app&&o.app.status!=="deleted"?o.app:null,l=c?(await K(n.db,c,"disabled",n.deployer,e.now?.())).changed:!1,p=o.organization?` for ${o.organization.name}`:"",i=l?`${s} is off${p}`:c?`${s} was off already${p}`:o.kind==="remote"?`${s} was removed${p}`:`${s} isn't on${p}`;a.emit({type:"step",step:C,status:"ok",message:i,data:{id:t}});let d=await X(n,o),m=[`${i}.`,l?`Its tools leave /mcp within 30 seconds. Everyone's access, its tokens and its tools snapshot are kept: ${f} mcp on ${t} serves it again at once.`:"Nothing changed.",...c?[`${f} mcp remove ${t} removes it for good.`]:[]];M(a,m,{id:t,name:s,kind:o.kind,on:!1,wasOn:l,key:d})}async function dt(e,t){let{out:a}=e,n=await E(e),o=await O(n.db,t);a.emit({type:"step",step:"mcp.remove",status:"start",message:`Removing ${t}...`});let s=_(o),{removed:c}=await Ee(n.db,o.app,n.deployer,e.now?.()),l=o.organization?` from ${o.organization.name}`:"",p=c?`${s} is removed${l}`:o.app?`${s} was removed already${l}`:`${s} isn't added${l}`;a.emit({type:"step",step:"mcp.remove",status:"ok",message:p,data:{id:t,removed:c}});let i=await X(n,o),d=J(o).remote,m=[`${p}.`,c?"Its tools left /mcp, and everyone's access to it, its tokens, its tools snapshot and its place in AI connections went with it.":"Nothing changed.",...i&&i.set?[i.boundOrigin?`${i.name} stays on the Gateway, pinned to ${i.boundOrigin}: ${f} secret unset ${i.name} removes both.`:`${i.name} stays on the Gateway${o.kind==="builtin"?" (an app may use it too)":""}: ${f} secret unset ${i.name} removes it.`]:[],...o.kind==="builtin"?[`${f} mcp on ${t} adds it again, from scratch.`]:d?[`${f} mcp add ${d.url} --name ${t} adds it again, from scratch.`]:[]];M(a,m,{id:t,name:s,kind:o.kind,removed:c,key:i})}function Fe(e){if(!e)return"not listed yet";let t=e.listedAt?` ${Ue(e.listedAt)}`:"";return e.status==="error"?`listing failed${t}${e.lastError?`: ${e.lastError}`:""}`:`${z(e.toolCount,"tool")}, listed${t}`}function Ue(e){return`${new Date(e).toISOString().slice(0,16).replace("T"," ")} UTC`}function ze(e){return e?{status:e.status,tools:e.status==="error"?null:e.toolCount,listedAt:e.listedAt===null?null:new Date(e.listedAt).toISOString(),lastError:e.lastError}:null}function Be(e,t){return e?.kind==="oauth"?w.yellow("OAuth: not supported yet"):t?t.set?t.boundOrigin&&!t.bound?`${t.name} ${w.yellow(`set for ${t.boundOrigin}`)}`:`${t.name} ${w.green("set")}`:`${t.name} ${w.yellow("not set")}`:w.dim("none")}function Ve(e){switch(e){case"on":return w.green("on");case"needs setup":return w.yellow("needs setup");default:return w.dim(e)}}async function lt(e){let{out:t}=e,a=await E(e),[n,o,s]=await Promise.all([Oe(a.db),S(a.cf,I),P(a.db)]),c=n.map(r=>{let u=W(r,o,s),g=L(r.keyName,o,r.remote,s),b=r.snapshot&&r.snapshot.status!=="error"?r.snapshot.toolCount:null;return{entry:r,state:u,key:g,tools:b}}),l=G(["APP","KIND","STATUS","TOOLS","KEY"],c.map(({entry:r,state:u,key:g})=>[`${r.id} ${w.dim(r.name)}`,r.kind==="builtin"?"built-in":"remote",Ve(u),r.snapshot?r.snapshot.status==="error"?w.yellow("listing failed"):String(r.snapshot.toolCount):w.dim("not listed yet"),Be(r.remote?.auth??null,g)])),p=c.flatMap(({entry:r,state:u,key:g})=>[...u==="not added"?[{command:`${f} mcp on ${r.id}`,note:`offer ${r.name}`}]:[],...g&&r.app&&(!g.set||g.boundOrigin&&!g.bound)?[{command:`${f} secret set ${g.name}`,note:`${r.name}'s ${r.kind==="builtin"?"key":"credential"}`}]:[]]),d=`${c.filter(r=>r.entry.app?.status==="active").length} of ${c.length} MCP ${c.length===1?"app":"apps"} on`,m=c.some(r=>r.entry.kind==="remote");t.emit({type:"done",message:d,display:[...l,"",w.dim(`Tools are on ${a.gatewayUrl}/mcp as <id>_<tool>.`),...m?[]:[w.dim(`Add any MCP server by its URL: ${f} mcp add <url>`)]].join(`
25
+ `),data:{apps:c.map(({entry:r,state:u,key:g,tools:b})=>({id:r.id,name:r.name,kind:r.kind,status:u,on:r.app?.status==="active",...r.remote?{url:r.remote.url,auth:q(r.remote.auth),supported:r.remote.auth.kind!=="oauth"}:{},tools:b,key:g,...r.snapshot?.listedAt?{lastListedAt:new Date(r.snapshot.listedAt).toISOString()}:{},...r.snapshot?.lastError?{lastError:r.snapshot.lastError}:{}})),mcp:`${a.gatewayUrl}/mcp`,...p.length>0?{next:p}:{}}})}function pt(e){switch(e){case"annotations":return"annotations (the server's hints; a tool without one is write)";case"read":return"read (every tool)";case"write":return"write (every tool)"}}async function mt(e,t){let{out:a}=e,n=await E(e),o=await O(n.db,t);o.kind==="remote"&&F(o);let s=_(o),[c,l]=await Promise.all([S(n.cf,I),P(n.db)]),{name:p,remote:i}=J(o),d=o.app&&o.app.status!=="deleted"?o.app:null,m=W({kind:o.kind,app:d,remote:i,keyName:p},c,l),r=L(p,c,i,l),u=d?await Me(n.db,{...o,app:d},i):null,g={url:`${n.gatewayUrl}/mcp`,toolPrefix:`${t}_`},b=d?.deployedAt?`${d.deployedByActor?`by ${d.deployedByActor}, `:""}${Ue(d.deployedAt)}`:null,y=[{label:"Kind",value:o.kind==="builtin"?"built-in (the Gateway's own)":"remote"},{label:"Status",value:Ve(m)},...i?[{label:"URL",value:i.url},{label:"Auth",value:B(i.auth)},{label:"Risk",value:pt(i.risk)},{label:"Revision",value:String(i.rev)}]:[],...b?[{label:"Added",value:b}]:[],...r||i?.auth.kind==="oauth"?[{label:o.kind==="builtin"?"Key":"Credential",value:Be(i?.auth??null,r)+(r?.bound?w.dim(`, pinned to ${r.boundOrigin}`):"")}]:[],...d?[{label:"Tools",value:Fe(u.snapshot)}]:[]],h=u?i?G(["NAME","SERVER NAME","RISK","ON"],u.remoteTools.map($=>[$.name??w.dim("(none)"),$.serverName,`${$.risk} ${w.dim($.source)}`,$.on?w.green("on"):w.yellow($.problem??"off")])):G(["NAME","RISK"],u.catalogTools.map($=>[$.name,$.risk])):[],T=u?i?u.remoteTools.length>0:u.catalogTools.length>0:!1,x=[`${s} (${t})`];a.emit({type:"done",message:Ge([x[0],...j(y)].join(`
26
+ `)),display:[w.bold(x[0]),...j(y),...T?["",...h]:[],...d&&!T?["",w.dim(`No tools listed yet: the Gateway lists them on the next request to ${g.url}.`)]:[]].join(`
27
+ `),data:{id:t,name:s,kind:o.kind,status:m,on:d?.status==="active",...i?{url:i.url,auth:q(i.auth),supported:i.auth.kind!=="oauth",risk:i.risk,rev:i.rev,overrides:i.tools}:{},addedBy:d?.deployedByActor??null,addedAt:d?.deployedAt?new Date(d.deployedAt).toISOString():null,key:r,snapshot:ze(u?.snapshot??null),tools:u?i?u.remoteTools:u.catalogTools.map($=>({...$,source:"registry",on:!0})):[],mcp:g,...r&&d&&(!r.set||r.boundOrigin&&!r.bound)?{next:[{command:`${f} secret set ${r.name}`,note:`${s}'s ${o.kind==="builtin"?"key":"credential"}`}]}:m==="not added"?{next:[{command:`${f} mcp on ${t}`,note:`offer ${s}`}]}:{}}})}async function ut(e,t){let{out:a}=e,n=await E(e),o=await O(n.db,t);o.kind==="remote"&&F(o);let s=_(o),c=o.app&&o.app.status!=="deleted"?o.app:null;if(!c){let i=`${s} isn't on, so it has no tools to list again`;M(a,[`${i}.`,"Nothing changed."],{id:t,name:s,kind:o.kind,refreshed:!1},[]);return}a.emit({type:"step",step:"mcp.refresh",status:"start",message:`Dropping ${s}'s tools snapshot...`});let l=await Re(n.db,c);a.emit({type:"step",step:"mcp.refresh",status:"ok",message:`Dropped ${s}'s tools snapshot`,data:{id:t}});let p=[l?`Dropped ${s}'s tools snapshot (${Fe(l)}).`:`${s} had no tools snapshot to drop.`,c.status==="active"?`The Gateway lists its tools again on the next request to ${n.gatewayUrl}/mcp, or within the hour.`:`It's off: the Gateway lists its tools again once it's on (${f} mcp on ${t}).`];M(a,p,{id:t,name:s,kind:o.kind,refreshed:!0,dropped:ze(l)})}async function ft(e,t,a){let{out:n,flags:o}=e;if(o.on&&o.off)throw new R("MCP_TOOL_CHANGE_INVALID","--on and --off say opposite things; give one",{fix:"drop one of them"});if(!o.risk&&!o.on&&!o.off)throw new R("MCP_TOOL_CHANGE_INVALID",`Nothing to change about ${a}
28
+ Give --risk read|write|destructive|annotations, --on or --off.`,{rerun:`${f} mcp show ${t}`,rerunNote:"lists its tools with their risks"});let s=await E(e),c=await O(s.db,t);if(c.kind==="builtin")throw new R("MCP_APP_BUILTIN",`${_(c)} is the Gateway's built-in MCP app
29
+ Its tools and their risks are the Gateway's own, and can't be changed here. ${f} mcp off ${t} stops serving it.`);let l=F(c);n.emit({type:"step",step:"mcp.tool",status:"start",message:`Changing ${a} on ${t}...`});let p=await Te(s.db,{...c,app:l},a,{...o.risk?{risk:o.risk}:{},...o.on?{enabled:!0}:o.off?{enabled:!1}:{}},e.now?.());n.emit({type:"step",step:"mcp.tool",status:"ok",message:`Changed ${p.serverName} on ${t}`,data:{id:t}}),p.inListing||n.emit({type:"warning",code:"REMOTE_MCP_TOOL_NOT_LISTED",step:"mcp.tool",message:`${a} isn't in ${t}'s last tool listing
30
+ The override is kept under the server's name ${p.serverName} and applies once the server lists a tool by that name.`,data:{rerun:`${f} mcp show ${t}`,rerunNote:"lists its tools by both names"}});let i=p.after??{},d=i.risk?`risk ${i.risk} (your override)`:"risk from the app's default and the server's hints",m=i.enabled===!1?"left out of the catalog":"listed",r=[`${p.serverName}${p.listedName?` (${p.listedName})`:""} on ${t}: ${d}, ${m}.`,`The Gateway lists ${t}'s tools again on first use (revision ${p.rev}).`];M(n,r,{id:t,tool:{serverName:p.serverName,name:p.listedName,inListing:p.inListing},before:p.before,override:p.after,rev:p.rev})}export{zt as a,Bt as b,Vt as c,jt as d,Kt as e,Wt as f,Ht as g,Yt as h,rt as i,it as j,ct as k,dt as l,lt as m,mt as n,ut as o,ft as p};