@buildbase/sdk 0.0.51 → 0.0.53

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 (50) hide show
  1. package/AGENTS.md +18 -8
  2. package/CHANGELOG.md +56 -0
  3. package/README.md +247 -32
  4. package/dist/css/styles.css +1 -1
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.d.ts +865 -53
  7. package/dist/index.mjs +1 -1
  8. package/dist/mcp/index.cjs +1 -0
  9. package/dist/mcp/index.d.ts +1402 -0
  10. package/dist/mcp/index.mjs +1 -0
  11. package/dist/react/chunks/{SettingsDialog-uVKFxlal.mjs → SettingsDialog-BxDYsie6.mjs} +1 -1
  12. package/dist/react/chunks/{SettingsDialog-DitAiAqr.cjs → SettingsDialog-Dy8W3NA6.cjs} +1 -1
  13. package/dist/react/chunks/{SubscriptionDialog-P0GlXEyn.mjs → SubscriptionDialog-6c5dHoQd.mjs} +1 -1
  14. package/dist/react/chunks/{SubscriptionDialog-Cg-qYVKr.cjs → SubscriptionDialog-CpVnnXJg.cjs} +1 -1
  15. package/dist/react/chunks/ar-1Z1MOGAP.mjs +2 -0
  16. package/dist/react/chunks/ar-VGzBv3AZ.cjs +2 -0
  17. package/dist/react/chunks/de-BjdDg60Y.cjs +2 -0
  18. package/dist/react/chunks/de-CXUItplO.mjs +2 -0
  19. package/dist/react/chunks/es-BBPsSZUp.cjs +2 -0
  20. package/dist/react/chunks/es-BTbzVutz.mjs +2 -0
  21. package/dist/react/chunks/fr-Cax48X_S.cjs +2 -0
  22. package/dist/react/chunks/fr-DPMeOQu3.mjs +2 -0
  23. package/dist/react/chunks/hi-BJqvpG6d.cjs +2 -0
  24. package/dist/react/chunks/hi-JfJx-LV7.mjs +2 -0
  25. package/dist/react/chunks/ja-CDGtLzTk.mjs +2 -0
  26. package/dist/react/chunks/ja-DvVyj5xX.cjs +2 -0
  27. package/dist/react/chunks/react-4SlWxHdh.cjs +2 -0
  28. package/dist/react/chunks/react-OL1uSkpr.mjs +2 -0
  29. package/dist/react/chunks/zh-BAcqxkxk.cjs +2 -0
  30. package/dist/react/chunks/zh-BNZ2Ooe8.mjs +2 -0
  31. package/dist/react/index.cjs +1 -1
  32. package/dist/react/index.d.ts +39 -32
  33. package/dist/react/index.mjs +1 -1
  34. package/package.json +17 -4
  35. package/dist/react/chunks/ar-SrPOJXdL.mjs +0 -2
  36. package/dist/react/chunks/ar-a3aRbPCs.cjs +0 -2
  37. package/dist/react/chunks/de-DE3_z7r0.cjs +0 -2
  38. package/dist/react/chunks/de-xnPl61SS.mjs +0 -2
  39. package/dist/react/chunks/es-C_xcyGtp.cjs +0 -2
  40. package/dist/react/chunks/es-CyuBtosP.mjs +0 -2
  41. package/dist/react/chunks/fr-BMu7Bk4k.cjs +0 -2
  42. package/dist/react/chunks/fr-CxuDLZ27.mjs +0 -2
  43. package/dist/react/chunks/hi-CQ215yc9.cjs +0 -2
  44. package/dist/react/chunks/hi-CpuvyorS.mjs +0 -2
  45. package/dist/react/chunks/ja-DIJ_xCIi.mjs +0 -2
  46. package/dist/react/chunks/ja-DK6Buuws.cjs +0 -2
  47. package/dist/react/chunks/react-C2ikFWBG.cjs +0 -2
  48. package/dist/react/chunks/react-CCukNQ4q.mjs +0 -2
  49. package/dist/react/chunks/zh-CYQwZiBL.mjs +0 -2
  50. package/dist/react/chunks/zh-Dt-apS2s.cjs +0 -2
@@ -0,0 +1 @@
1
+ import{z as e}from"zod";const t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),n=(e,t)=>e>>>t|e<<32-t;function r(e){let r=1779033703,o=3144134277,i=1013904242,a=2773480762,s=1359893119,c=2600822924,u=528734635,d=1541459225;const p=e.length,l=p+1,m=l+(56-l%64+64)%64+8,g=new Uint8Array(m);g.set(e,0),g[p]=128;const b=8*p,h=Math.floor(b/4294967296),f=b>>>0;g[m-8]=h>>>24&255,g[m-7]=h>>>16&255,g[m-6]=h>>>8&255,g[m-5]=255&h,g[m-4]=f>>>24&255,g[m-3]=f>>>16&255,g[m-2]=f>>>8&255,g[m-1]=255&f;const w=new Uint32Array(64);for(let e=0;e<m;e+=64){for(let t=0;t<16;t++){const n=e+4*t;w[t]=g[n]<<24|g[n+1]<<16|g[n+2]<<8|g[n+3]}for(let e=16;e<64;e++){const t=n(w[e-15],7)^n(w[e-15],18)^w[e-15]>>>3,r=n(w[e-2],17)^n(w[e-2],19)^w[e-2]>>>10;w[e]=w[e-16]+t+w[e-7]+r>>>0}let p=r,l=o,m=i,b=a,h=s,f=c,y=u,k=d;for(let e=0;e<64;e++){const r=k+(n(h,6)^n(h,11)^n(h,25))+(h&f^~h&y)+t[e]+w[e]>>>0,o=p&l^p&m^l&m;k=y,y=f,f=h,h=b+r>>>0,b=m,m=l,l=p,p=r+((n(p,2)^n(p,13)^n(p,22))+o>>>0)>>>0}r=r+p>>>0,o=o+l>>>0,i=i+m>>>0,a=a+b>>>0,s=s+h>>>0,c=c+f>>>0,u=u+y>>>0,d=d+k>>>0}const y=new Uint8Array(32),k=[r,o,i,a,s,c,u,d];for(let e=0;e<8;e++)y[4*e]=k[e]>>>24&255,y[4*e+1]=k[e]>>>16&255,y[4*e+2]=k[e]>>>8&255,y[4*e+3]=255&k[e];return y}function o(e){return(new TextEncoder).encode(e)}function i(e,t){let n=e;n.length>64&&(n=r(n));const o=new Uint8Array(64),i=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<n.length?n[e]:0;o[e]=54^t,i[e]=92^t}const s=r(a(o,t));return r(a(i,s))}function a(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}class s extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function c(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4==0?"":"=".repeat(4-t.length%4),r=atob(t+n),o=new Uint8Array(r.length);for(let e=0;e<r.length;e++)o[e]=r.charCodeAt(e);return o}function u(e){return JSON.parse((new TextDecoder).decode(c(e)))}function d(e,t,n={}){const r="number"==typeof n?{clockToleranceSec:n}:n,a=r.clockToleranceSec??60,d=r.requireExp??!0;if(!e||!t)throw new s("invalid_token","Missing token or client secret");const p=e.split(".");if(3!==p.length)throw new s("invalid_token","Malformed JWT");const[l,m,g]=p,b=i(o(t),o(`${l}.${m}`));let h,f,w;try{h=c(g)}catch{throw new s("invalid_signature","Unreadable JWT signature")}if(!function(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n}(b,h))throw new s("invalid_signature","JWT signature verification failed");try{f=u(l),w=u(m)}catch{throw new s("invalid_token","Unreadable JWT segments")}if("HS256"!==f.alg)throw new s("invalid_algorithm",`Unexpected JWT alg: ${String(f.alg)}`);const y=Math.floor(Date.now()/1e3);if(d&&"number"!=typeof w.exp)throw new s("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof w.exp&&y>w.exp+a)throw new s("token_expired","JWT has expired");if("number"==typeof w.nbf&&y+a<w.nbf)throw new s("token_not_yet_valid","JWT is not yet valid");if(void 0!==r.issuer&&w.iss!==r.issuer)throw new s("invalid_issuer","JWT issuer mismatch");if(void 0!==r.audience){const e=w.aud;if(!(Array.isArray(e)?e.includes(r.audience):e===r.audience))throw new s("invalid_audience","JWT audience mismatch")}return w}function p(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function l(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function m(e){return l(o(JSON.stringify(e)))}function g(e,t,n){if(!t)throw new s("invalid_secret","Missing signing secret");const r=Math.floor(Date.now()/1e3),a={iat:r,exp:r+(n?.expiresInSec??3600),...e},c=`${m({alg:"HS256",typ:"JWT"})}.${m(a)}`;return`${c}.${l(i(o(t),o(c)))}`}function b(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}function h(e){const t=[`Bearer resource_metadata="${b(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${b(e.error)}"`),e.errorDescription&&t.push(`error_description="${b(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}const f=e.string().optional().describe("Workspace id. Omit to use the workspace bound to your token.");function w(e,t){const n=e.workspaceId??t.workspaceId;if(!n)throw new Error("workspaceId is required — call list_workspaces to find one.");return n}const y={readOnlyHint:!0},k=[{name:"list_workspaces",description:"List the authenticated user's workspaces (id, name, roles).",inputSchema:e.object({}),annotations:y,execute:(e,t)=>t.bb.workspace.list()},{name:"get_workspace",description:"Get one workspace: name, members, feature flags, quota snapshot.",inputSchema:e.object({workspaceId:f}),annotations:y,execute:(e,t)=>t.bb.workspace.get(w(e,t))},{name:"get_user_profile",description:"Get the authenticated user's profile.",inputSchema:e.object({}),annotations:y,execute:(e,t)=>t.bb.users.getProfile()},{name:"list_workspace_users",description:"List the members of a workspace with their roles.",inputSchema:e.object({workspaceId:f}),annotations:y,execute:(e,t)=>t.bb.users.list(w(e,t))},{name:"get_subscription",description:"Get a workspace's subscription: plan, status, interval, seats.",inputSchema:e.object({workspaceId:f}),annotations:y,execute:(e,t)=>t.bb.subscription.get(w(e,t))},{name:"get_plans",description:"Get the plan group available to a workspace (plans, prices, quotas).",inputSchema:e.object({workspaceId:f}),annotations:y,execute:(e,t)=>t.bb.plans.getGroup(w(e,t))},{name:"list_invoices",description:"List a workspace's invoices (newest first).",inputSchema:e.object({workspaceId:f,limit:e.number().int().min(1).max(100).optional().describe("Max invoices to return."),startingAfter:e.string().optional().describe("Invoice id to paginate after.")}),annotations:y,execute:(e,t)=>t.bb.invoices.list(w(e,t),e.limit,e.startingAfter)},{name:"get_quota_usage",description:"Get usage vs. limit for one quota in a workspace.",inputSchema:e.object({workspaceId:f,quotaSlug:e.string().describe('The quota slug, e.g. "api-calls".')}),annotations:y,execute:(e,t)=>t.bb.usage.getQuota(w(e,t),e.quotaSlug)},{name:"get_all_quota_usage",description:"Get usage vs. limit for every quota in a workspace.",inputSchema:e.object({workspaceId:f}),annotations:y,execute:(e,t)=>t.bb.usage.getAll(w(e,t))},{name:"get_credit_balance",description:"Get a workspace's prepaid credit balance.",inputSchema:e.object({workspaceId:f}),annotations:y,execute:(e,t)=>t.bb.credits.getBalance(w(e,t))},{name:"list_credit_transactions",description:"Get a workspace's credit transaction history (paginated).",inputSchema:e.object({workspaceId:f,limit:e.number().int().min(1).max(100).optional(),page:e.number().int().min(1).optional()}),annotations:y,execute:(e,t)=>t.bb.credits.getTransactions(w(e,t),{...void 0!==e.limit?{limit:e.limit}:{},...void 0!==e.page?{page:e.page}:{}})},{name:"check_feature_flag",description:"Check whether a feature flag is enabled for a workspace.",inputSchema:e.object({workspaceId:f,key:e.string().describe("The feature slug.")}),annotations:y,execute:async(e,t)=>{const n=w(e,t),r=await t.bb.workspace.get(n),o=r.features?.[e.key];if(void 0!==o)return{key:e.key,enabled:o,source:"workspace"};const i=(await t.bb.features.list()).find(t=>t.slug===e.key);if(!i)throw new Error(`Unknown feature flag: ${e.key}`);return{key:e.key,enabled:i.defaultValue,source:"default"}}},{name:"check_permission",description:"Check whether a user has permission(s) in a workspace.",inputSchema:e.object({workspaceId:f,permission:e.union([e.string(),e.array(e.string())]).describe("A permission (or list — all must hold), platform or app-defined."),userId:e.string().optional().describe("Defaults to the authenticated user.")}),annotations:y,execute:async(e,t)=>{const n=e.userId??t.auth.userId;if(!n)throw new Error("userId is required — the token carries no user identity.");const r=await t.bb.permissions.check(w(e,t),n,e.permission);return{userId:n,permission:e.permission,allowed:r}}},{name:"resolve_permissions",description:"List every permission a user holds in a workspace.",inputSchema:e.object({workspaceId:f,userId:e.string().optional().describe("Defaults to the authenticated user.")}),annotations:y,execute:async(e,t)=>{const n=e.userId??t.auth.userId;if(!n)throw new Error("userId is required — the token carries no user identity.");const r=await t.bb.permissions.resolve(w(e,t),n);return{userId:n,permissions:Array.from(r)}}},{name:"get_invoice",description:"Get one invoice by id.",inputSchema:e.object({workspaceId:f,invoiceId:e.string().describe("The invoice id.")}),annotations:y,execute:(e,t)=>t.bb.invoices.get(w(e,t),e.invoiceId)},{name:"get_plan_versions",description:"List the plan-group versions available to a workspace.",inputSchema:e.object({workspaceId:f}),annotations:y,execute:(e,t)=>t.bb.plans.getVersions(w(e,t))},{name:"get_public_plans",description:"Get a public plan group by slug (no workspace / auth needed).",inputSchema:e.object({slug:e.string().describe("The plan-group slug.")}),annotations:y,execute:(e,t)=>t.bb.plans.getPublic(e.slug)},{name:"get_plan_version",description:"Get one public plan-group version by id (no auth needed).",inputSchema:e.object({groupVersionId:e.string().describe("The plan-group version id.")}),annotations:y,execute:(e,t)=>t.bb.plans.getVersion(e.groupVersionId)},{name:"get_usage_logs",description:"Get a workspace's usage log entries (paginated, filterable).",inputSchema:e.object({workspaceId:f,quotaSlug:e.string().optional(),from:e.string().optional().describe("ISO date lower bound."),to:e.string().optional().describe("ISO date upper bound."),source:e.string().optional(),page:e.number().int().min(1).optional(),limit:e.number().int().min(1).max(100).optional()}),annotations:y,execute:(e,t)=>{const{workspaceId:n,...r}=e;return t.bb.usage.getLogs(w(e,t),r)}},{name:"get_settings",description:"Get the organization settings.",inputSchema:e.object({}),annotations:y,execute:(e,t)=>t.bb.settings.get()},{name:"get_credit_packages",description:"List the credit packages a workspace can purchase.",inputSchema:e.object({workspaceId:f}),annotations:y,execute:(e,t)=>t.bb.credits.getPackages(w(e,t))},{name:"get_credit_buckets",description:"Get a workspace's credit buckets (paginated).",inputSchema:e.object({workspaceId:f,status:e.string().optional(),source:e.string().optional(),page:e.number().int().min(1).optional(),limit:e.number().int().min(1).max(100).optional()}),annotations:y,execute:(e,t)=>{const{workspaceId:n,...r}=e;return t.bb.credits.getBuckets(w(e,t),r)}},{name:"get_expiring_credits",description:"Get credits expiring within N days (default 7).",inputSchema:e.object({workspaceId:f,days:e.number().int().min(1).optional()}),annotations:y,execute:(e,t)=>t.bb.credits.getExpiring(w(e,t),e.days)},{name:"get_public_credit_packages",description:"List credit packages publicly (no workspace / auth needed).",inputSchema:e.object({}),annotations:y,execute:(e,t)=>t.bb.credits.getPublicPackages()}],_=[{name:"record_usage",description:"Record quota usage for a workspace (metered billing).",inputSchema:e.object({workspaceId:f,quotaSlug:e.string().describe("The quota slug to record against."),quantity:e.number().positive().describe("Amount of usage to record."),idempotencyKey:e.string().optional().describe("Dedupe key for safe retries."),metadata:e.record(e.string(),e.unknown()).optional()}),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},execute:(e,t)=>t.bb.usage.record(w(e,t),{quotaSlug:e.quotaSlug,quantity:e.quantity,source:"mcp",...e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:{},...e.metadata?{metadata:e.metadata}:{}})},{name:"consume_credits",description:"Consume prepaid credits from a workspace's balance.",inputSchema:e.object({workspaceId:f,amount:e.number().positive().describe("Credits to consume."),description:e.string().optional().describe("What the credits were spent on."),idempotencyKey:e.string().optional().describe("Dedupe key for safe retries.")}),annotations:{readOnlyHint:!1,destructiveHint:!1},execute:(e,t)=>t.bb.credits.consume(w(e,t),{amount:e.amount,...e.description?{description:e.description}:{},...e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:{}})},{name:"send_notification",description:"Send a notification event to a workspace user (or all members when userId is omitted).",inputSchema:e.object({workspaceId:f,event:e.string().describe('The event slug, e.g. "comment_added".'),userId:e.string().optional().describe("Recipient. Omit to notify all members."),message:e.string().optional().describe("Message body (used for push).")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.notification.send(w(e,t),e.event,e.userId,e.message?{message:e.message}:void 0)},{name:"record_usage_batch",description:"Record multiple usage entries in one call (max 100 items).",inputSchema:e.object({workspaceId:f,items:e.array(e.object({quotaSlug:e.string(),quantity:e.number().positive(),idempotencyKey:e.string().optional(),metadata:e.record(e.string(),e.unknown()).optional()})).min(1).max(100)}),annotations:{readOnlyHint:!1,destructiveHint:!1},execute:(e,t)=>t.bb.usage.recordBatch(w(e,t),{items:e.items.map(e=>({...e,source:"mcp"}))})},{name:"create_workspace",description:"Create a new workspace.",inputSchema:e.object({name:e.string().describe("Workspace name."),image:e.string().optional().describe("Image URL.")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.workspace.create({name:e.name,...e.image?{image:e.image}:{}})},{name:"update_workspace",description:"Update a workspace's editable fields (name, image).",inputSchema:e.object({workspaceId:f,name:e.string().min(1).optional().describe("New workspace name."),image:e.string().optional().describe("New image URL.")}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const n={};return void 0!==e.name&&(n.name=e.name),void 0!==e.image&&(n.image=e.image),t.bb.workspace.update(w(e,t),n)}},{name:"delete_workspace",description:"Delete a workspace. Irreversible.",inputSchema:e.object({workspaceId:f}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.workspace.delete(w(e,t))},{name:"invite_workspace_user",description:"Invite a user to a workspace with a role.",inputSchema:e.object({workspaceId:f,email:e.string().describe("Invitee email."),role:e.string().describe("Role to grant.")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.users.invite(w(e,t),e.email,e.role)},{name:"remove_workspace_user",description:"Remove a user from a workspace. Irreversible.",inputSchema:e.object({workspaceId:f,userId:e.string().describe("The user to remove.")}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.users.remove(w(e,t),e.userId)},{name:"update_workspace_user_role",description:"Change a workspace member's role.",inputSchema:e.object({workspaceId:f,userId:e.string(),role:e.string().describe("The new role.")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.users.updateRole(w(e,t),e.userId,e.role)},{name:"update_user_profile",description:"Update the authenticated user's own profile (name, image, country, timezone, language, currency).",inputSchema:e.object({name:e.string().min(1).optional(),image:e.string().optional().describe("Profile image URL."),country:e.string().optional().describe("ISO country code."),timezone:e.string().optional().describe("IANA timezone."),language:e.string().optional().describe("Language code."),currency:e.string().optional().describe("Currency code.")}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const n={};for(const t of["name","image","country","timezone","language","currency"]){const r=e[t];void 0!==r&&(n[t]=r)}return t.bb.users.updateProfile(n)}},{name:"update_feature_flag",description:"Set a feature flag on/off for a workspace.",inputSchema:e.object({workspaceId:f,key:e.string().describe("The feature slug."),value:e.boolean().describe("Enabled?")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.features.update(w(e,t),e.key,e.value)},{name:"create_subscription_checkout",description:"Create a Stripe checkout session to subscribe a workspace to a plan.",inputSchema:e.object({workspaceId:f,planVersionId:e.string(),billingInterval:e.string().optional(),currency:e.string().optional(),successUrl:e.string().optional(),cancelUrl:e.string().optional()}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>{const{workspaceId:n,...r}=e;return t.bb.subscription.checkout(w(e,t),r)}},{name:"update_subscription",description:"Change a workspace's subscription plan.",inputSchema:e.object({workspaceId:f,planVersionId:e.string(),billingInterval:e.string().optional(),successUrl:e.string().optional(),cancelUrl:e.string().optional()}),annotations:{readOnlyHint:!1},execute:(e,t)=>{const{workspaceId:n,...r}=e;return t.bb.subscription.update(w(e,t),r)}},{name:"cancel_subscription",description:"Cancel a workspace's subscription.",inputSchema:e.object({workspaceId:f}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.subscription.cancel(w(e,t))},{name:"resume_subscription",description:"Resume a workspace's canceled subscription.",inputSchema:e.object({workspaceId:f}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.subscription.resume(w(e,t))},{name:"get_billing_portal_url",description:"Get a Stripe billing-portal URL for a workspace.",inputSchema:e.object({workspaceId:f,returnUrl:e.string().optional()}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.subscription.getBillingPortalUrl(w(e,t),e.returnUrl)},{name:"purchase_credits",description:"Create a Stripe checkout session to buy a credit package.",inputSchema:e.object({workspaceId:f,creditPackageId:e.string(),currency:e.string().optional(),successUrl:e.string().describe("Redirect URL on success."),cancelUrl:e.string().describe("Redirect URL on cancel.")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>{const{workspaceId:n,...r}=e;return t.bb.credits.purchase(w(e,t),r)}}],S=new Map([...k,..._].map(e=>[e.name,e]));function v(e){if(!1===e)return[];if("readonly"===e)return[...k];if("all"===e)return[...k,..._];const t=e.include?e.include.map(e=>{const t=S.get(e);if(!t)throw new Error(`Unknown built-in MCP tool: ${e}`);return t}):[...k],n=new Set(e.exclude??[]);return t.filter(e=>!n.has(e.name))}const I=["2025-06-18","2025-03-26","2024-11-05"],x=I[0],j="application/json",O=/^[a-zA-Z0-9_-]{1,128}$/,T=-32700,U=-32600,A=-32601,C=-32602,H=-32603;function q(e,t){const n=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===n)return e[t]}function E(e,t){return{status:e,headers:{"Content-Type":j},body:JSON.stringify(t)}}function P(e,t){return E(200,{jsonrpc:"2.0",id:e??null,result:t})}function M(e,t,n,r=200,o){return E(r,{jsonrpc:"2.0",id:e??null,error:{code:t,message:n,...void 0!==o?{data:o}:{}}})}function J(e){return"object"==typeof e&&null!==e&&"function"==typeof e.safeParse}function N(e){return e instanceof Error?e.message:"string"==typeof e?e:JSON.stringify(e)}function $(t){const n=t.serverInfo??{name:"buildbase-mcp",version:"1.0.0"},r=t.builtinTools??(!!t.buildbase&&"readonly"),o=t.maxRequestBytes??1048576;if(!1!==r&&!t.buildbase)throw new Error("builtinTools require a `buildbase` client — pass one to createMcpHandler, or set builtinTools: false.");const i=new Map;for(const e of v(r))i.set(e.name,e);const a=new Set;for(const e of t.tools??[]){if(!O.test(e.name))throw new Error(`Invalid MCP tool name: "${e.name}" (want ${String(O)})`);if(a.has(e.name))throw new Error(`Duplicate MCP tool name: "${e.name}"`);a.add(e.name),i.set(e.name,e)}const s=new Proxy({},{get(e,t){if("string"==typeof t)throw new Error(`No \`buildbase\` client configured — pass one to createMcpHandler to use bb.${t} in tools.`)}}),c=new Map;function u(t){const n=c.get(t.name);if(n)return n;let r;try{r=J(t.inputSchema)?e.toJSONSchema(t.inputSchema,{target:"draft-2020-12"}):t.inputSchema}catch(e){l(e,{method:"tools/list",tool:t.name}),r={type:"object",additionalProperties:!0}}return c.set(t.name,r),r}function d(e){const t=new Set(e?.scopes??[]);return Array.from(i.values()).filter(e=>(e.requiredScopes??[]).every(e=>t.has(e)))}function l(e,n){try{t.onError?.(e instanceof Error?e:new Error(N(e)),n)}catch{}}function m(){if(t.auth&&t.auth.resourceMetadataUrl){const e=h({resourceMetadataUrl:t.auth.resourceMetadataUrl});return{status:e.status,headers:e.headers,body:e.body}}return E(401,{error:"unauthorized"})}async function g(e){const r=function(e){if(!t.allowedOrigins)return{};const n=q(e.headers,"origin");return n&&t.allowedOrigins.includes(n)?{"Access-Control-Allow-Origin":n,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, MCP-Protocol-Version","Access-Control-Max-Age":"86400",Vary:"Origin"}:{}}(e);if("OPTIONS"===e.method.toUpperCase())return{status:204,headers:r,body:""};const i=await async function(e){const r=e.method.toUpperCase();if(t.allowedOrigins){const n=q(e.headers,"origin");if(n&&!t.allowedOrigins.includes(n))return E(403,{error:"origin_not_allowed"})}if("POST"!==r)return{status:405,headers:{"Content-Type":j,Allow:"POST, OPTIONS"},body:JSON.stringify({error:"method_not_allowed"})};if(o>0&&"string"==typeof e.body&&e.body.length>o)return E(413,{error:"payload_too_large"});let i=null;if(!1!==t.auth){const n=p(q(e.headers,"authorization"));if(!n)return m();try{i=await t.auth.verify(n,e)}catch(e){l(e,{method:"auth"}),i=null}if(!i)return m()}if(t.rateLimit){let n;try{n=await t.rateLimit(i,e)}catch(e){l(e,{method:"rateLimit"}),n=!1}if(!("boolean"==typeof n?n:n.ok)){const e="object"==typeof n?n.retryAfter:void 0;return{status:429,headers:{"Content-Type":j,...void 0!==e?{"Retry-After":String(e)}:{}},body:JSON.stringify({error:"rate_limited"})}}}let a=e.body;if("string"==typeof e.body)try{a=JSON.parse(e.body)}catch{return M(null,T,"Invalid JSON",400)}if(Array.isArray(a))return M(null,U,"Batch requests are not supported",400);if("object"!=typeof a||null===a)return M(null,U,"Expected a JSON-RPC request object",400);const c=a,g=c.id,b="string"==typeof c.method?c.method:null;if(!b)return M(g,U,"Missing method",400);if(null==g)return{status:202,headers:{"Content-Type":j},body:""};const h=c.params??{};switch(b){case"initialize":{const e=h.protocolVersion;return P(g,{protocolVersion:"string"==typeof e&&I.includes(e)?e:x,capabilities:{tools:{listChanged:!1}},serverInfo:n,...t.instructions?{instructions:t.instructions}:{}})}case"ping":return P(g,{});case"tools/list":return P(g,{tools:d(i).map(e=>({name:e.name,description:e.description,inputSchema:u(e),...e.annotations?{annotations:e.annotations}:{}}))});case"tools/call":{const n="string"==typeof h.name?h.name:"",r=d(i).find(e=>e.name===n);if(!r)return M(g,C,`Unknown tool: ${n||"(missing name)"}`);let o,a=h.arguments??{};if(J(r.inputSchema)){const e=r.inputSchema.safeParse(a);if(!e.success)return M(g,C,`Invalid arguments for ${n}`,200,{issues:e.error.issues});a=e.data}if(t.context)try{o=await t.context(i,e)}catch(e){return l(e,{method:b,tool:n}),M(g,H,"Context initialization failed")}const c={bb:t.buildbase?t.buildbase.withSession(i?.sessionId??""):s,auth:i??{sessionId:""},workspaceId:i?.workspaceId,custom:o};try{const e=await r.execute(a,c),t="object"==typeof e&&null!==e&&!Array.isArray(e);return P(g,{content:[{type:"text",text:"string"==typeof e?e:JSON.stringify(e,null,2)}],...t?{structuredContent:e}:{},isError:!1})}catch(e){l(e,{method:b,tool:n});const r=e instanceof Error?e:new Error(N(e));return P(g,{content:[{type:"text",text:t.formatToolError?t.formatToolError(r,{tool:n}):r.message}],isError:!0})}}default:return M(g,A,`Method not found: ${b}`)}}(e);return Object.keys(r).length?{...i,headers:{...i.headers,...r}}:i}return{handle:g,fetch:async function(e){const t={};if(e.headers.forEach((e,n)=>{t[n]=e}),o>0){const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>o)return new Response(JSON.stringify({error:"payload_too_large"}),{status:413,headers:{"Content-Type":j}})}const n="POST"===e.method.toUpperCase()?await e.text():void 0,r=await g({method:e.method,headers:t,body:n});return new Response(""===r.body?null:r.body,{status:r.status,headers:r.headers})},listTools:()=>Array.from(i.values()).map(e=>({name:e.name,description:e.description,...e.annotations?{annotations:e.annotations}:{}})),serverCard:e=>({name:n.name,version:n.version,endpoint:e.endpoint,transport:"streamable-http",capabilities:{tools:{listChanged:!1}},...e.description?{description:e.description}:{},...e.documentationUrl?{documentationUrl:e.documentationUrl}:{}})}}function W(e){return e}export{s as AppBridgeError,h as bearerChallenge,S as builtinMcpTools,$ as createMcpHandler,W as defineMcpTool,p as extractBearerToken,v as selectBuiltinTools,g as signClientJwt,d as verifyClientJwt};