@buildbase/sdk 0.0.88 → 0.0.89
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +1 -1
- package/CHANGELOG.md +10 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/AGENTS.md
CHANGED
|
@@ -91,7 +91,7 @@ Config also accepts: `timeout`, `maxRetries`, `debug`, `headers`, `onError(err,
|
|
|
91
91
|
- **Factory:** `BuildBase` (also default export) → `{ auth, workspace, subscription, usage, credits, plans, invoices, users, features, settings, notification, permissions, withSession, client }`.
|
|
92
92
|
- **API classes:** `BaseApi` (extend for custom APIs), `AuthApi`, `UserApi`, `WorkspaceApi`, `SettingsApi`, `PushApi`.
|
|
93
93
|
- **Webhook verification (runtime-agnostic — Node, edge, Deno, Bun, browsers):** `verifyWebhookSignature`, `parseWebhookEvent`. Verify against the **raw** request body (`await req.text()`), not the parsed JSON. Headers: `x-buildbase-signature` (`sha256=` HMAC over `{timestamp}.{body}`), `x-buildbase-timestamp` (Unix seconds), `x-buildbase-event`.
|
|
94
|
-
- **Webhook events:** `WEBHOOK_EVENTS` (
|
|
94
|
+
- **Webhook events:** `WEBHOOK_EVENTS` (113 `domain.action` names), `WEBHOOK_EVENTS_BY_CATEGORY`, `WebhookEventName`, `isWebhookEvent(name)`, vendored from the platform catalog. A failed payment is `payment.failed`, with `workspaceId, subscriptionId, invoiceId, dunningState, amount, currency, failedAt, nextRetryAt`. Full list: https://docs.buildbase.app/webhooks/overview. Never invent an event name; narrow with `isWebhookEvent` instead.
|
|
95
95
|
- **Agent readiness (framework-agnostic, returns plain `DiscoveryDocument`):** **App owns discovery content, platform owns auth.** All content — `llms.txt`, `robots.txt`, `sitemap`, `protectedResources` (RFC 9728), API catalog, skills — is defined locally in `AgentReadyConfig` and served with no platform round-trip. The platform bundle (`fetchAgentReadiness`, fail-soft/cached) supplies ONLY `{ enabled, authorizationServer }` (the OAuth AS pointer). Functions: `resolveAgentPath` (dispatch ALL agent paths — root docs + `.well-known/*`; prefer for new wiring), `resolveWellKnown` (`.well-known/*` only), `clearAgentReadinessCache`, `buildAgentCard`, `buildA2AAgentCard` (A2A card at `/.well-known/agent-card.json`; served by DEFAULT, derived from `site`+`skills`; `a2aCard: false` disables, object overrides), `buildProtectedResourceMetadata(path, config)` (local), `buildAgentSkillsIndex`, `buildSkillMd`, `buildSecurityTxt`, `buildLlmsTxt(config)` (from `config.llmsTxt`), `buildLlmsFullTxt` (from `config.llmsFullTxt`), `buildRobotsTxt`, `buildSitemap`, `buildApiCatalog`, `buildMcpServerCard`, `buildAuthMd`, `buildWebBotAuthDirectory` (JWKS at `/.well-known/http-message-signatures-directory` from `config.webBotAuth.keys`; opt-in), `buildDnsAidRecords` (suggested `_agents` DNS records — publish at your DNS provider, can't be served over HTTP), `buildDiscoveryLinkHeader`, `wantsMarkdown`/`negotiateMarkdown`, `sha256Digest`, `AI_BOT_USER_AGENTS`, `DISCOVERY_CACHE_TIMEOUT_MS`. `config.extraPaths` serves ANY literal document by exact path (commerce discovery: x402/UCP/ACP/MPP, `/openapi.json`, future `.well-known` docs) and takes precedence over built-ins. `config.cache` (a `DiscoveryCacheStore`: string `get`/`set`, optional `delete`) shares the platform fetches across replicas instead of caching per process; the default is process memory. Types: `AgentReadyConfig`, `AgentReadinessBundle`, `AgentSkill`, `DiscoveryCacheStore`, `ApiCatalogApi`, `A2ACardConfig`, `A2ACardSkill`, `DnsAidRecord`, `McpServerCard`, `RobotsConfig`, `RobotsPolicy`, `ContentSignals`, `SitemapUrl`, `DiscoveryDocument`.
|
|
96
96
|
- **OAuth2 app-bridge:** `handleAppTokenRequest`, `handleAppRevokeRequest` (one-call handlers), `bearerChallenge` (RFC 9728/6750 401; header values are quoted-string-escaped + CR/LF-stripped), `verifyAppTokenRequest`, `verifyAppRevokeRequest`, `verifyClientJwt`, `signClientJwt` (HS256 mint — symmetric counterpart of verify), `extractBearerToken`, `appTokenSuccess`, `appTokenFailure`, `AppBridgeError`. Types: `AppTokenRequestClaims`, `AppRevokeRequestClaims`, `AppTokenResult`, `AppTokenResponseBody`, `HandlerResult`, `VerifyClientJwtOptions`. `verifyClientJwt(token, secret, opts?: VerifyClientJwtOptions)` **requires a numeric `exp` by default** (`requireExp: false` to allow non-expiring tokens); optional `clockToleranceSec` / `issuer` / `audience`. **Presets** (also in core): `mintAgentToken` (the whole mint in one call — HS256 with the app's secret, `aud` from the grant's resource, encrypted `sid`) + `buildbaseAuth` (the whole verify) + `createSessionRefCrypto`. Security invariant: the platform relays the minted token but never sees the app secret — it can neither forge nor decode app tokens, and the BuildBase session is never stored and never plaintext in a token.
|
|
97
97
|
- **Currency & pricing utils (pure):** `formatCents`, `formatOverageRate`, `formatOverageRateWithLabel`, `formatQuotaIncludedOverage`, `formatQuotaWithPrice`, `getCurrencySymbol`, `getCurrencyFlag`, `getQuotaUnitLabelFromName`, `getQuotaDisplayValue`, `CURRENCY_DISPLAY`, `CURRENCY_FLAG`, `PLAN_CURRENCY_CODES`, `PLAN_CURRENCY_OPTIONS`.
|
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,16 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [0.0.89] - 2026-10-18
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- `email.complained` in `WEBHOOK_EVENTS` (now 113 names): the platform fires it
|
|
13
|
+
when a recipient reports a message as spam. Before, a complaint arrived as
|
|
14
|
+
`email.bounced`; a handler that caught complaints there should switch on
|
|
15
|
+
`email.complained` too. The payload is the same as `email.bounced`
|
|
16
|
+
(`trackingCode`, `recipientEmail`, `emailHistoryId`, `audienceId`, `subject`).
|
|
17
|
+
|
|
8
18
|
## [0.0.88] - 2026-10-18
|
|
9
19
|
|
|
10
20
|
### Changed
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});let e=!0;function t(t,...n){e&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(t,...n)}function n(e,...t){console.error(e,...t)}function r(e,t){const n=AbortSignal.any;if("function"==typeof n)return n([e,t]);const r=new AbortController,s=e=>{r.signal.aborted||r.abort(e.reason)};for(const n of[e,t]){if(n.aborted){s(n);break}n.addEventListener("abort",()=>s(n),{once:!0})}return r.signal}async function s(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function i(e,t="Request failed"){if(!e.ok){let n,r=t;try{const t=await s(e);r=t.message||t.error||r,"string"==typeof t.code&&(n=t.code)}catch{r=function(e,t){const n={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${n})`)}(e,t).message}throw Object.assign(new Error(r),{status:e.status,...n?{code:n}:{}})}try{return await s(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class o extends Error{constructor(e,t,n,r){super(e),this.code=t,this.context=n,this.originalError=r,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,o)}}const a=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1},this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}configure(t){this.config={...this.config,...t},void 0!==t.enableConsoleLogging&&function(t){void 0!==t.enableLogging&&(e=t.enableLogging)}({enableLogging:t.enableConsoleLogging})}handleError(e,r={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const s=e instanceof Error?e:new o("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",r),i=s instanceof o?s:new o(s.message,"SDK_ERROR",r,s);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${r.component||"Unknown"}:`,{message:i.message,code:i.code,context:i.context,originalError:i.originalError,stack:i.stack}),this.config.onError)try{this.config.onError(i,r)}catch(e){n("[SDK Error Handler] Error in custom error callback:",e)}for(const e of this.listeners)try{e(i,r)}catch(e){n("[SDK Error Handler] Error in error listener:",e)}this.config.showUserNotifications&&this.notifyUser(i,r)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...n)=>e(...n).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...n)=>{try{return e(...n)}catch(e){throw this.handleError(e,t),e}}}};function c(e,t={}){a.handleError(e,t)}function l(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return c(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function u(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){c(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function d(e,t){const n=l(e);if(!n)return null;try{const r=JSON.parse(n);return t&&!t(r)?(c(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),u(e),null):r}catch(t){return c(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),u(e),null}}function p(e,t){try{!function(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){c(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){c(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const h="saas-session-id",f="saas-device-id";function g(){return function(){if("undefined"==typeof window)return null;try{return l(h)}catch(e){return c(e,{component:"auth-utils",action:"getSessionId",metadata:{key:h}}),null}}()}function m(){const e=g(),t={};e&&(t["x-session-id"]=e);const n=function(){if("undefined"==typeof window)return null;try{return l(f)??null}catch(e){return c(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:f}}),null}}();return n&&(t["x-device-id"]=n),t}const y=new WeakSet,w=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),k="SDK is not ready (missing serverUrl, version, or orgId)";class b{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(k);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(k)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:m()}url(e){const t=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${t}`}buildHeaders(e){const t={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(t,e.headers),null==e.body||t["Content-Type"]||(t["Content-Type"]="application/json"),t}reportError(e,t){y.has(e)||(y.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}static delay(e,t){return new Promise((n,r)=>{const s=()=>{clearTimeout(i),r(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return s();const i=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})})}async executeFetchUrl(e,t,n){const s=(t.method??"GET").toUpperCase(),i=n??e,o=this.buildHeaders(t),a={...t,headers:o},c=w.has(s);let l,u;if(this._timeout>0){u=new AbortController;const e=u;l=setTimeout(()=>e.abort(),this._timeout),a.signal=t.signal?r(t.signal,e.signal):e.signal}const d=e=>{if(u?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${s} ${i}`);return this.reportError(e,{method:s,path:i}),e}return e},p=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const n=this._fetch.bind(globalThis),r=await n(e,a);if(this._debug&&console.log(`[BuildBase] ${s} ${e} → ${r.status}`),401===r.status&&this._onUnauthorized&&this._onUnauthorized(),r.status>=500&&c&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await b.delay(e,a.signal),p(t+1)}return r}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw d(e);if(c&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await b.delay(e,a.signal)}catch(e){throw d(e)}return p(t+1)}throw e instanceof Error&&this.reportError(e,{method:s,path:i}),e}};try{return await p(0)}finally{void 0!==l&&clearTimeout(l)}}async fetchJson(e,t={},n="Request failed"){this.ensureReady();try{const r=await this.executeFetch(e,t);return await i(r,n)}catch(n){throw n instanceof Error&&this.reportError(n,{method:(t.method??"GET").toUpperCase(),path:e}),n}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchUnwrapped(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);return r.ok||await this.throwResponseError(r,n),this.unwrapResponse(r,n)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async fetchForeign(e,t={}){return this._fetch.call(globalThis,e,t)}async throwResponseError(e,t){let n=t;try{n=(await e.json()).message||n}catch{n=`${t} (${e.status}: ${e.statusText})`}throw Object.assign(new Error(n),{status:e.status})}apiPath(e,...t){return e.reduce((e,n,r)=>e+n+(r<t.length?encodeURIComponent(String(t[r])):""),"")}async unwrapResponse(e,t){const n=await e.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||t);return void 0!==n.data?n.data:n}return n}}class v extends b{constructor(e){super({...e,basePath:"beta",requireOrgId:!0})}getAuthHeaders(){return{}}async fetchConfig(){return this.fetchJson(`config?orgId=${encodeURIComponent(this.orgId)}`,{},"Failed to fetch beta form configuration")}async submitBetaUser(e){return this.fetchJson("submit",{method:"POST",body:JSON.stringify(e)},"Failed to submit beta user request")}}class S extends b{constructor(e){super(e)}async list(e){const t=await this.fetchJson("devices",{signal:e},"Failed to load devices");return t?.devices??[]}async rename(e,t,n){await this.fetchJson(this.apiPath`devices/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename device")}async signOut(e,t){return this.fetchJson(this.apiPath`devices/${e}`,{method:"DELETE",signal:t},"Failed to sign out device")}async forget(e,t){return this.fetchJson(`${this.apiPath`devices/${e}`}?forget=true`,{method:"DELETE",signal:t},"Failed to forget device")}}function x(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))void 0!==r&&""!==r&&!1!==r&&t.set(n,String(r));const n=t.toString();return n?`?${n}`:""}const E=e=>JSON.stringify(e?{workspaceId:e}:{});class _ extends b{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}class I extends b{constructor(e){super(e)}async list(e){const t=await this.fetchJson("sessions",{signal:e},"Failed to load sessions");return t?.sessions??[]}async revoke(e,t){await this.fetchJson(this.apiPath`sessions/${e}`,{method:"DELETE",signal:t},"Failed to sign out session")}}class P extends b{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}const A=5242880,U={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml"};function $(e){if(e.type)return e.type;const t=(e.name??"").split(".").pop()?.toLowerCase()??"";return U[t]??""}class T extends b{constructor(e){super(e)}async upload(e,t){const{purpose:n,signal:s}=t,i=await this.fetchJson("uploads",{method:"POST",body:JSON.stringify({purpose:n,name:e.name??"file",size:e.size,contentType:$(e)}),signal:s},"Could not start the upload");let o;const a=new AbortController,c=setTimeout(()=>a.abort(),12e4);try{o=await this.fetchForeign(i.url,{method:"PUT",headers:i.headers,body:e,signal:s?r(s,a.signal):a.signal})}catch(e){if(s?.aborted)throw e;throw new Error("The upload to storage did not finish. Check the connection and try again.")}finally{clearTimeout(c)}if(!o.ok)throw Object.assign(new Error(`The upload to storage was refused (HTTP ${o.status}). Try again.`),{status:o.status});return this.fetchJson(this.apiPath`uploads/${i.uploadId}/complete`,{method:"POST",body:"{}",signal:s},"Could not finish the upload")}}class C extends b{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const n=await this.unwrapResponse(t,"Failed to fetch user attributes");return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const n=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof n&&null!==n?n:{}}}const O={NOT_FOUND:"INVITATION_NOT_FOUND",EXPIRED:"INVITATION_EXPIRED",ALREADY_HANDLED:"INVITATION_ALREADY_HANDLED",EMAIL_MISMATCH:"INVITATION_EMAIL_MISMATCH",EMAIL_NOT_VERIFIED:"EMAIL_NOT_VERIFIED",INVITES_DISABLED:"WORKSPACE_INVITES_DISABLED",RATE_LIMITED:"INVITATION_RATE_LIMITED",EMAIL_FAILED:"INVITATION_EMAIL_FAILED",SEAT_LIMIT:"SEAT_LIMIT_REACHED",USER_BLOCKED:"USER_BLOCKED",NO_SENDER_CONFIGURED:"NO_SENDER_CONFIGURED"},R={402:O.SEAT_LIMIT,404:O.NOT_FOUND,409:O.ALREADY_HANDLED,410:O.EXPIRED,429:O.RATE_LIMITED,502:O.EMAIL_FAILED,503:O.NO_SENDER_CONFIGURED};function N(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function F(e){return"string"==typeof e&&e?e:void 0}async function W(e,t){let n=null;try{n=await e.json()}catch{n=null}return function(e,t,n){const r=t&&"object"==typeof t?t:{},s=F(r.message)??F(r.error)??n,i={status:e,code:F(r.code)??R[e]??`HTTP_${e}`,currentUserCount:N(r.currentUserCount),limit:N(r.limit),retryAfterSeconds:N(r.retryAfterSeconds),invitedEmail:F(r.invitedEmail),invitationId:F(r.invitationId),invitationStatus:F(r.status)};return Object.assign(new Error(s),i)}(e.status,n,t)}class L extends b{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){try{return await this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}catch(n){const r=n?.status;if(400===r&&e.trackingAttribution){const{trackingAttribution:n,...r}=e;return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(r),signal:t},"Failed to create workspace")}throw n}}async updateWorkspace(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:n},"Failed to update workspace")}async deleteWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE",signal:t},"Failed to delete workspace")}async getWorkspaceUsers(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{signal:t},"Failed to fetch workspace users")}async addUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to invite member")}async fetchInvitation(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);if(!r.ok)throw await W(r,n);return i(r,n)}async listInvitations(e,t){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{signal:t},"Failed to fetch invitations")}async inviteMember(e,t,n){const r={email:t.email,role:t.role};return t.landingUrl&&(r.landingUrl=t.landingUrl),this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{method:"POST",body:JSON.stringify(r),signal:n},"Failed to send invitation")}async resendInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}/resend`,{method:"POST",signal:n},"Failed to resend invitation")}async revokeInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}`,{method:"DELETE",signal:n},"Failed to revoke invitation")}async myInvitations(e){return this.fetchInvitation("invitations",{signal:e},"Failed to fetch your invitations")}async acceptInvitation(e,t,n){return this.fetchInvitation(this.apiPath`invitations/${e}/accept`,{method:"PATCH",signal:n,...t?.token?{body:JSON.stringify({token:t.token})}:{}},"Failed to accept invitation")}async declineInvitation(e,t){return this.fetchInvitation(this.apiPath`invitations/${e}/reject`,{method:"PATCH",signal:t},"Failed to decline invitation")}async previewInvitation(e,t){if(!this.orgId)throw new Error("orgId is required for previewInvitation");return this.fetchInvitation(this.apiPath`${this.orgId}/invitations/preview/${e}`,{signal:t},"Failed to load invitation")}async removeUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:n},"Failed to remove user")}async updateUser(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(n),signal:r},"Failed to update user")}async updateSettings(e,t){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:n},"Failed to update workspace permissions")}async getMyPermissions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/permissions/me`,{signal:t},"Failed to fetch workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:n}}),signal:r},"Failed to update feature")}async getWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{signal:t},"Failed to fetch workspace")}async getProfile(e){return this.fetchJson("profile",{signal:e},"Failed to fetch profile")}async updateUserProfile(e,t){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update user profile")}async getPasskeys(e){const t=await this.fetchJson("passkeys",{signal:e},"Failed to fetch passkeys");return t?.passkeys??[]}async renamePasskey(e,t,n){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename passkey")}async deletePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE",signal:t},"Failed to remove passkey")}async getCurrentSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{signal:t},"Failed to fetch subscription")}async getPlanGroup(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`,{signal:t},"Failed to fetch plan group")}async getPlanGroupByVersion(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch plan group version")}async getPlanGroupVersions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group/versions`,{signal:t},"Failed to fetch plan group versions")}async getPublicPlans(e,t){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");return this.fetchUnwrapped(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`,{signal:t},"Failed to fetch plans")}async getPublicCreditPackages(e){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");return this.fetchUnwrapped(this.apiPath`${this.orgId}/credit-packages`,{signal:e},"Failed to fetch credit packages")}async getPlanGroupVersion(e,t){return this.fetchUnwrapped(this.apiPath`plan-group-versions/${e}`,{signal:t},"Failed to fetch plan group version")}async createCheckoutSession(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create checkout session")}async selectFreePlan(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:n},"Failed to select free plan")}async updateSubscription(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:n},"Failed to update subscription")}async createBillingPortalSession(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:n})}async listInvoices(e,t=10,n,r){const s=new URLSearchParams;return s.append("limit",t.toString()),n&&s.append("starting_after",n),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`,{signal:r},"Failed to fetch invoices")}async getInvoice(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:n},"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST",signal:t},"Failed to cancel subscription")}async resumeSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST",signal:t},"Failed to resume subscription")}async recordUsage(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record usage")}async recordUsageBatch(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch quota usage status")}async getAllQuotaUsage(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/all`,{signal:t},"Failed to fetch all quota usage")}async getUsageLogs(e,t,n){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch usage logs")}async sendNotification(e,t,n,r,s){const i={event:t};return n&&(i.userId=n),r&&(i.data=r),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(i),signal:s},"Failed to send notification")}async getNotificationEvents(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{signal:t},"Failed to fetch notification events")}async getNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{signal:t},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t,n){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update notification preferences")).notificationPreferences??{}}async getMyNotificationPreferences(e,t){const n=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{signal:t},"Failed to fetch your notification preferences");return{defaults:n?.defaults??{},mine:n?.mine??{}}}async updateMyNotificationPreferences(e,t,n){const r=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update your notification preferences");return{defaults:r?.defaults??{},mine:r?.mine??{}}}async getCreditBalance(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits`,{signal:t},"Failed to fetch credit balance")}async consumeCredits(e,t,n){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:n});if(!r.ok){if(402===r.status){const e=await r.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(r,"Failed to consume credits")}return this.unwrapResponse(r,"Failed to consume credits")}async purchaseCredits(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const n=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return n.docs??n}async getCreditTransactions(e,t,n){const r=new URLSearchParams;t?.type&&r.append("type",t.type),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,n){const r=new URLSearchParams;t?.status&&r.append("status",t.status),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,n){const r=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+r,{signal:n},"Failed to fetch expiring credits")}}exports.ApiVersion=void 0,(exports.ApiVersion||(exports.ApiVersion={})).V1="v1";const D={UserCreated:"user:created",UserUpdated:"user:updated",WorkspaceChanged:"workspace:changed",WorkspaceUpdated:"workspace:updated",WorkspaceUserAdded:"workspace:user-added",WorkspaceUserRemoved:"workspace:user-removed",WorkspaceUserRoleChanged:"workspace:user-role-changed",WorkspaceCreated:"workspace:created",WorkspaceDeleted:"workspace:deleted",WorkspaceInvitationSent:"workspace:invitation-sent",WorkspaceInvitationAccepted:"workspace:invitation-accepted",WorkspaceInvitationDeclined:"workspace:invitation-declined",WorkspaceInvitationRevoked:"workspace:invitation-revoked"};class M{constructor(){this.callbacks=null,this.listeners=new Map}setCallbacks(e){this.callbacks=e}getCallbacks(){return this.callbacks}async emit(e,t){if(this.callbacks?.handleEvent)try{await this.callbacks.handleEvent(e,t)}catch(t){c(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}const n=this.listeners.get(e);if(n)for(const r of[...n])try{r(t)}catch(t){c(t,{component:"EventEmitter",action:"notifyListener",metadata:{eventType:e}})}}on(e,t){const n=this.listeners.get(e)??new Set;return n.add(t),this.listeners.set(e,n),()=>{this.listeners.get(e)?.delete(t)}}async emitUserCreated(e){await this.emit(D.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(D.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(D.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(D.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(D.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceInvitationSent(e,t){await this.emit(D.WorkspaceInvitationSent,{invitation:e,workspaceId:t})}async emitWorkspaceInvitationAccepted(e,t){await this.emit(D.WorkspaceInvitationAccepted,{invitation:e,workspace:t})}async emitWorkspaceInvitationDeclined(e){await this.emit(D.WorkspaceInvitationDeclined,{invitation:e})}async emitWorkspaceInvitationRevoked(e,t){await this.emit(D.WorkspaceInvitationRevoked,{invitationId:e,workspaceId:t})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(D.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(D.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(D.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(D.WorkspaceDeleted,{workspace:e})}}const J=new M,B=globalThis;function j(e){const t=Symbol.for(`@buildbase/sdk.invalidation.${e}`),n=B[t]??(B[t]=new Set);return{subscribe:e=>(n.add(e),()=>{n.delete(e)}),invalidate(){n.forEach(e=>e())},reset(){n.clear()}}}const q=j("credit-balance").invalidate,V=j("quota-usage").invalidate,z=j("subscription").invalidate,K="bb",G={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},H={Success:"success",Cancel:"cancel",Error:"error"},Q={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function Y(e,t){const n=t??("undefined"!=typeof window?window.location.href:"https://localhost");let r;try{r=new URL(n)}catch{throw new Error(`createBBUrl: invalid base URL: ${JSON.stringify(n)}`)}return r.search="",r.searchParams.set(K,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}const X="__buildbaseBeforeLeave",Z=globalThis,ee=Z[X]??(Z[X]=new Set);function te(e,t={}){if(!e||"string"!=typeof e)return null;if(/^\/(?![/\\])/.test(e))return e;let n;try{n=new URL(e)}catch{return null}const r="https:"===n.protocol,s="http:"===n.protocol&&("localhost"===n.hostname||"127.0.0.1"===n.hostname||"[::1]"===n.hostname);if(!r&&!s)return null;const{sameOrigin:i,allowedOrigins:o}=t;return i||o?.length?i&&"undefined"!=typeof window&&window.location&&n.origin===window.location.origin||o?.some(e=>e.replace(/\/+$/,"")===n.origin)?e:null:e}const ne="saas-auth-intent";function re(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}const se={usd:"$",eur:"€",gbp:"£",jpy:"¥",cad:"CA$",aud:"A$",chf:"CHF",cny:"¥",hkd:"HK$",sgd:"S$",inr:"₹",mxn:"MX$",brl:"R$",nzd:"NZ$",sek:"kr",nok:"kr",dkk:"kr",pln:"zł",thb:"฿"},ie={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function oe(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return se[t]??t.toUpperCase()}const ae=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],ce=ae.map(e=>({value:e,label:`${e.toUpperCase()} (${oe(e)})`})),le=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),ue=new Set(["bhd","jod","kwd","omr","tnd"]),de=new Map;function pe(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(le.has(t))return 0;if(ue.has(t))return 3;if("isk"===t)return 2;let n=de.get(t);if(void 0===n){try{n=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{n=2}de.set(t,n)}return n}function he(e,t){const n=pe(t);return 0===n?e.toLocaleString("en-US"):(e/10**n).toFixed(n)}function fe(e,t){return oe(t)+he(e,t)}const ge={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};const me={included:"included",then:"then",hardLimit:"hard limit"};const ye={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"};function we(e,t){const n=e.pricingVariants;if(!n?.length)return null;const r=t.toLowerCase();return n.find(e=>e.currency?.toLowerCase()===r)??null}function ke(e,t,n){const r=we(e,t);if(!r?.basePricing)return null;const s=r.basePricing[n];return null!=s?s:null}function be(e,t,n,r){const s=we(e,t),i=s?.quotaOverages?.[n];if(i)return i[r]}function ve(e,t){const n=we(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function Se(e,t,n){const r=ve(e,t);return r?.perSeat?r.perSeat[n]??null:null}function xe(e,t){return Math.max(0,e-(t||0))}function Ee(e,t,n,r){const s=ve(e,t);if(!s)return null;return xe(r,s.includedSeats)*(Se(e,t,n)??0)}const _e={WORKSPACE_SETTINGS_VIEW:"workspace:settings:view",WORKSPACE_SETTINGS_EDIT:"workspace:settings:edit",WORKSPACE_DELETE:"workspace:delete",WORKSPACE_MEMBERS_VIEW:"workspace:members:view",WORKSPACE_MEMBERS_INVITE:"workspace:members:invite",WORKSPACE_MEMBERS_REMOVE:"workspace:members:remove",WORKSPACE_MEMBERS_ROLE_CHANGE:"workspace:members:role-change",WORKSPACE_FEATURES_VIEW:"workspace:features:view",WORKSPACE_FEATURES_EDIT:"workspace:features:edit",WORKSPACE_BILLING_VIEW:"workspace:billing:view",WORKSPACE_BILLING_MANAGE:"workspace:billing:manage",WORKSPACE_USAGE_VIEW:"workspace:usage:view",WORKSPACE_USAGE_RECORD:"workspace:usage:record"},Ie=Object.values(_e),Pe={admin:Ie.filter(e=>e!==_e.WORKSPACE_DELETE),editor:[_e.WORKSPACE_SETTINGS_VIEW,_e.WORKSPACE_MEMBERS_VIEW,_e.WORKSPACE_FEATURES_VIEW,_e.WORKSPACE_BILLING_VIEW,_e.WORKSPACE_USAGE_VIEW,_e.WORKSPACE_USAGE_RECORD],viewer:[_e.WORKSPACE_SETTINGS_VIEW,_e.WORKSPACE_MEMBERS_VIEW]},Ae="viewer";function Ue(e){const t=new Set;for(const n of Object.values(e))for(const e of n)t.add(e);return Array.from(t)}function $e(e){const{userId:t,workspace:n,settings:r,appPermissions:s}=e;if(!n||!t)return new Set;if(function(e,t){if(!t)return!1;const n=(r=e.createdBy)?"string"==typeof r?r:"object"==typeof r&&"_id"in r&&"string"==typeof r._id?r._id:null:null;var r;return null!==n&&n===t}(n,t)){const e=new Set(Ie);if(s)for(const t of Ue(s))e.add(t);if(n.permissions)for(const t of Ue(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of Ue(r.workspace.permissions))e.add(t);return e}const i=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const n=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return n&&"object"==typeof n&&"role"in n&&"string"==typeof n.role?n.role:null}(n,t);return i?Te(i,e):new Set}function Te(e,t,n={}){const{workspace:r,settings:s,appPermissions:i}=t;if(!r)return new Set;const o=r.permissions,a=s?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),l=e=>e.filter(e=>!e.startsWith("workspace:")),u=e=>!!o&&e in o,d=e=>!!a&&e in a,p=e=>u(e)||d(e)||e in Pe;let h,f=e;if(!p(e)){const e=s?.workspace?.defaultRole;if(!e||"admin"===e||!p(e))return new Set;f=e}h=u(f)?c(o[f]):d(f)?c(a[f]):Pe[f]??[];const g=new Set(h),m=new Set((s?.workspace?.customPermissions??[]).map(e=>e.key)),y=i?.[f]?l(i[f]).filter(e=>!m.has(e)):[];let w;w=u(f)?l(o[f]):d(f)?[...l(a[f]),...y]:i?.[f]?l(i[f]):[];for(const e of w)g.add(e);if("admin"===f){for(const e of Pe.admin)g.add(e);for(const e of m)g.add(e);if(i)for(const e of l(Ue(i)))g.add(e)}return!1!==n.applyRestrictions&&function(e,t,n){if(!n?.workspace)return;const{canInviteMembers:r}=n.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(_e.WORKSPACE_MEMBERS_INVITE)}(g,f,s),g}function Ce(e,t){const n=$e(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}const Oe="App";var Re;function Ne(e){if(!e)return 0;const t=new Date(e).getTime();return Number.isNaN(t)?0:t}function Fe(e){const t=e=>"invited"===e.status?0:1;return[...e].sort((e,n)=>t(e)-t(n)||Ne(n.invitedAt)-Ne(e.invitedAt))}function We(e,t=new Date){return"invited"===e.status&&(null===e.validTill||void 0===e.validTill||Ne(e.validTill)>t.getTime())}exports.AuthStatus=void 0,(Re=exports.AuthStatus||(exports.AuthStatus={})).loading="loading",Re.redirecting="redirecting",Re.authenticated="authenticated",Re.unauthenticated="unauthenticated",Re.authenticating="authenticating";const Le="saas-pending-invite",De=/^[0-9a-f]{64}$/;function Me(e){return"object"==typeof e&&null!==e&&"string"==typeof e.token&&"string"==typeof e.orgId&&"number"==typeof e.createdAt}const Je={User:["user.registered","user.logged_in","user.new_device_login","user.email_verified","user.password_changed","user.password_reset_requested","user.profile_updated","user.tag_added","user.tag_removed","user.blocked","user.unblocked"],Organization:["organization.member_invited","organization.member_accepted","organization.member_role_changed","organization.member_removed","organization.public_write_limit_reached","organization.end_user_ceiling_reached"],Workspace:["workspace.created","workspace.updated","workspace.deleted","workspace.settings_updated","workspace.features_updated","workspace.member_added","workspace.member_removed","workspace.member_role_changed","workspace.member_invited","workspace.invitation_accepted","workspace.invitation_declined","workspace.invitation_revoked","workspace.invitation_expired"],Subscription:["subscription.created","subscription.updated","subscription.upgraded","subscription.canceled","subscription.cancel_scheduled","subscription.resumed","subscription.suspended","subscription.trial_started","subscription.trial_will_end","subscription.trial_expired","subscription.downgraded"],Payment:["payment.succeeded","payment.failed","payment.action_required","payment.refunded"],Quota:["quota.limit_exceeded"],Credit:["credit.purchased","credit.consumed","credit.expired","credit.granted","credit.revoked","credit.low_balance"],Workflow:["workflow.created","workflow.deleted","workflow.published","workflow.paused","workflow.resumed","workflow.instance_completed","workflow.instance_failed"],Audience:["audience.member_created","audience.member_updated","audience.added_to_list","audience.removed_from_list","audience.attribute_changed","audience.tag_added","audience.tag_removed","audience.unsubscribed","audience.resubscribed","audience.email_invalidated","audience.blocked","audience.unblocked","audience.import_completed","audience.list_created","audience.list_updated","audience.list_deleted"],Email:["email.domain_added","email.domain_verified","email.sent","email.opened","email.clicked","email.bounced","email.unsubscribed","email.campaign_sent"],Push:["push.campaign_sent"],Auth:["auth.method_deleted","auth.domain_added","auth.domain_verified","auth.domain_deleted","auth.client_self_registered"],Token:["token.created","token.updated","token.revoked"],"Group version":["group_version.published"],Form:["form.submitted"],Blog:["blog.published","blog.updated","blog.unpublished","blog.deleted"],Doc:["doc.published","doc.updated","doc.unpublished","doc.deleted"],FAQ:["faq.updated"],"FAQ collection":["faq_collection.updated"],Testimonial:["testimonial.updated","testimonial.deleted"],"Rich content":["rich_content.updated","rich_content.deleted"],Collection:["collection.version_published","collection.record_created","collection.record_updated","collection.record_deleted"]},Be=Object.values(Je).flat(),je=new Set(Be);const qe=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]),Ve=(e,t)=>e>>>t|e<<32-t;function ze(e){let t=1779033703,n=3144134277,r=1013904242,s=2773480762,i=1359893119,o=2600822924,a=528734635,c=1541459225;const l=e.length,u=l+1,d=u+(56-u%64+64)%64+8,p=new Uint8Array(d);p.set(e,0),p[l]=128;const h=8*l,f=Math.floor(h/4294967296),g=h>>>0;p[d-8]=f>>>24&255,p[d-7]=f>>>16&255,p[d-6]=f>>>8&255,p[d-5]=255&f,p[d-4]=g>>>24&255,p[d-3]=g>>>16&255,p[d-2]=g>>>8&255,p[d-1]=255&g;const m=new Uint32Array(64);for(let e=0;e<d;e+=64){for(let t=0;t<16;t++){const n=e+4*t;m[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=Ve(m[e-15],7)^Ve(m[e-15],18)^m[e-15]>>>3,n=Ve(m[e-2],17)^Ve(m[e-2],19)^m[e-2]>>>10;m[e]=m[e-16]+t+m[e-7]+n>>>0}let l=t,u=n,d=r,h=s,f=i,g=o,y=a,w=c;for(let e=0;e<64;e++){const t=w+(Ve(f,6)^Ve(f,11)^Ve(f,25))+(f&g^~f&y)+qe[e]+m[e]>>>0,n=l&u^l&d^u&d;w=y,y=g,g=f,f=h+t>>>0,h=d,d=u,u=l,l=t+((Ve(l,2)^Ve(l,13)^Ve(l,22))+n>>>0)>>>0}t=t+l>>>0,n=n+u>>>0,r=r+d>>>0,s=s+h>>>0,i=i+f>>>0,o=o+g>>>0,a=a+y>>>0,c=c+w>>>0}const y=new Uint8Array(32),w=[t,n,r,s,i,o,a,c];for(let e=0;e<8;e++)y[4*e]=w[e]>>>24&255,y[4*e+1]=w[e]>>>16&255,y[4*e+2]=w[e]>>>8&255,y[4*e+3]=255&w[e];return y}function Ke(e){return(new TextEncoder).encode(e)}function Ge(e,t){let n=e;n.length>64&&(n=ze(n));const r=new Uint8Array(64),s=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<n.length?n[e]:0;r[e]=54^t,s[e]=92^t}const i=ze(Qe(r,t));return ze(Qe(s,i))}function He(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}function Qe(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function Ye(e){const{body:t,signature:n,timestamp:r,secret:s,maxAgeSeconds:i=300}=e;if(!(n&&r&&s&&t))return!1;const o="sha256=";if(!n.startsWith(o))return!1;const a=n.slice(7);if(i>0){const e=parseInt(r,10);if(isNaN(e))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-e)>i)return!1}const c=function(e){if(e.length%2!=0)return null;const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++){const r=parseInt(e.slice(2*n,2*n+2),16);if(Number.isNaN(r))return null;t[n]=r}return t}(a);if(!c)return!1;const l=Ge(Ke(s),Ke(`${r}.${t}`));return c.length===l.length&&He(c,l)}const Xe=300,Ze="/.well-known/oauth-protected-resource",et="/.well-known/agent-skills",tt="/.well-known/api-catalog",nt="/.well-known/mcp/server-card.json",rt="/.well-known/agent-card.json",st="application/json",it="application/linkset+json",ot="text/markdown; charset=utf-8",at="text/plain; charset=utf-8",ct="application/xml; charset=utf-8",lt=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function ut(e){return e.replace(/\/+$/,"")}function dt(e){return`public, max-age=${e}, s-maxage=${e}`}function pt(e){return"sha256:"+function(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}(ze(Ke(e)))}const ht=function(){const e=new Map;return{get(t){const n=e.get(t);if(n){if(!(n.expiresAt<=Date.now()))return n.value;e.delete(t)}},set(t,n,r){e.set(t,{value:n,expiresAt:Date.now()+1e3*r})},delete(t){e.delete(t)},clear(){e.clear()}}}(),ft=new Set;function gt(e){return e.cache??ht}function mt(e){let t;const n=new Promise((e,n)=>{t=setTimeout(()=>n(new Error("discovery cache timed out")),500)});return Promise.race([Promise.resolve(e),n]).finally(()=>clearTimeout(t))}async function yt(e,t){try{const n=await mt(e.get(t));return null==n?{hit:!1}:{hit:!0,value:JSON.parse(n)}}catch{return{hit:!1}}}async function wt(e,t,n,r){try{await mt(e.set(t,JSON.stringify(n),r)),e!==ht&&ft.add(t)}catch{}}async function kt(e,t,n,r){if(!r||r<=0)return e(t,n);const s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await e(t,{...n,signal:s.signal})}finally{clearTimeout(i)}}async function bt(e){const t=e.cacheTtlSeconds??Xe,n=gt(e),r=`buildbase:agent-readiness:${ut(e.serverUrl)}::${e.orgId}`,s=await yt(n,r);if(s.hit)return s.value;const i=e.fetch??fetch,o=`${ut(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let a={enabled:!1};try{const t=await kt(i,o,{headers:{Accept:st}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(a=e)}}catch{}return await wt(n,r,a,t),a}function vt(e,t){const n=ut(e.siteUrl),r={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:Ze};t.authorizationServer?.metadataUrl&&(r.oauth_authorization_server=t.authorizationServer.metadataUrl,r.openid_configuration="/.well-known/openid-configuration"),(t.authorizationServer||e.authMd)&&(r.auth="/auth.md"),e.skills?.length&&(r.agent_skills=`${et}/index.json`),e.apiCatalog?.length&&(r.api_catalog=tt),e.mcpServerCard&&(r.mcp_server_card=nt),!1!==e.a2aCard&&(r.a2a_agent_card=rt),e.llmsFullTxt&&(r.llms_full_txt="/llms-full.txt");return Lt({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:n,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:n},capabilities:r,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}function St(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const n="/"===t?"":t.replace(/\/+$/,"");return Ze+n}function xt(e,t,n){const r=t.protectedResources??[];if(!r.length)return null;const s=e.replace(/\/+$/,"")||Ze,i=n??`${ut(t.serverUrl)}/org/${t.orgId}`,o=t.scopes?.map(e=>e.name),a=r.map(e=>{const n=e.resource??ut(t.siteUrl),r=e.scopes??o;return{path:St(n),metadata:{resource:n,authorization_servers:[i],bearer_methods_supported:e.bearerMethods??["header"],...r?.length?{scopes_supported:r}:{},...e.documentationUrl?{resource_documentation:e.documentationUrl}:{}}}}),c=a.find(e=>e.path===s);return c?Lt(c.metadata,t):s===Ze&&1===a.length?Lt(a[0].metadata,t):null}function Et(e){const t=e.skills??[];if(!t.length)return null;const n=ut(e.siteUrl);return Lt({$schema:"https://schemas.agentskills.io/discovery/0.2.0/schema.json",skills:t.map(e=>({name:e.name,type:e.type??"skill-md",description:e.description,url:`${n}${_t(e)}`,digest:pt(e.content)}))},e)}function _t(e){return e.path??`${et}/${e.name}/SKILL.md`}function It(e,t){const n=(t.skills??[]).find(t=>_t(t)===e);return n?{status:200,contentType:"text/markdown; charset=utf-8",body:n.content,cacheControl:dt(t.cacheTtlSeconds??Xe)}:null}function Pt(e){if(!e.security)return null;const t=(Array.isArray(e.security.contact)?e.security.contact:[e.security.contact]).map(e=>`Contact: ${e}`);return e.security.expires&&t.push(`Expires: ${e.security.expires}`),e.security.policy&&t.push(`Policy: ${e.security.policy}`),{status:200,contentType:at,body:t.join("\n")+"\n",cacheControl:dt(e.cacheTtlSeconds??Xe)}}function At(e){return e.llmsTxt?{status:200,contentType:at,body:e.llmsTxt,cacheControl:dt(e.cacheTtlSeconds??Xe)}:null}function Ut(e){return e.llmsFullTxt?{status:200,contentType:at,body:e.llmsFullTxt,cacheControl:dt(e.cacheTtlSeconds??Xe)}:null}function $t(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},n=ut(e.siteUrl),r=t.serviceUrl??n,s=t.transportProtocol??"http",i=t.skills??((e.skills??[]).length?(e.skills??[]).map(e=>({id:e.name,name:e.name,description:e.description,tags:["discovery"]})):[{id:"site-content",name:"Site content",description:`Read ${e.site.name}'s public content and machine-readable discovery documents (llms.txt, sitemap, API catalog).`,tags:["content"]}]);return Lt({protocolVersion:"0.3.0",name:t.name??e.site.name,version:t.version??"1.0.0",description:t.description??e.site.description??`${e.site.name} — agent-accessible web application.`,url:r,preferredTransport:s,supportedInterfaces:[{serviceUrl:r,transportProtocol:s}],provider:e.site.provider?{organization:e.site.provider.name,url:e.site.provider.url}:{organization:e.site.name,url:n},capabilities:t.capabilities??{streaming:!1,pushNotifications:!1},defaultInputModes:["text/plain","application/json"],defaultOutputModes:["text/plain","application/json"],skills:i,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}},e)}function Tt(e){const t=e.webBotAuth?.keys;return t?.length?{status:200,contentType:"application/http-message-signatures-directory+json",body:JSON.stringify({keys:t},null,2),cacheControl:dt(e.cacheTtlSeconds??Xe)}:null}function Ct(e){return e.endsWith(".json")||e.includes(".well-known/")?st:e.endsWith(".md")?ot:e.endsWith(".xml")?ct:at}function Ot(e){const t=e.apiCatalog??[];if(!t.length)return null;const n=t.map(e=>({anchor:e.anchor,...e.title?{title:e.title}:{},...e.serviceDesc?{"service-desc":[{href:e.serviceDesc}]}:{},...e.serviceDoc?{"service-doc":[{href:e.serviceDoc}]}:{},...e.status?{status:[{href:e.status}]}:{}}));return{status:200,contentType:it,body:JSON.stringify({linkset:n},null,2),cacheControl:dt(e.cacheTtlSeconds??Xe)}}function Rt(e){const t=e??{tools:!0},n={tools:!1,resources:!1,prompts:!1};for(const[e,r]of Object.entries(t))n[e]=!1!==r&&null!=r;return n}function Nt(e){const t=e.mcpServerCard;return t?Lt({$schema:"https://modelcontextprotocol.io/schemas/server-card/v1.0",version:"1.0",protocolVersion:t.protocolVersion??"2025-11-25",serverInfo:{name:t.name,version:t.version},...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},capabilities:Rt(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}function Ft(e){const t=e.mcpServerCard;if(!t)return null;const n=ut(e.siteUrl);let r;try{r={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${St(t.endpoint)}`}}catch{}return Lt({$schema:"https://modelcontextprotocol.io/schemas/mcp-discovery/v1.0",version:"1.0",servers:[{name:t.name,...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},version:t.version,capabilities:Rt(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${n}${nt}`,...r?{authentication:r}:{}}]},e)}function Wt(e,t){const n=dt(e.cacheTtlSeconds??Xe);if(e.authMd)return{status:200,contentType:ot,body:e.authMd,cacheControl:n};const r=t.authorizationServer;if(!r)return null;const s=`# Agent Authentication\n\n${e.site.name} supports AI-agent access via OAuth 2.0 (authorization code + PKCE).\n\n## Authorization server\n- Issuer: \`${r.issuer}\`\n- Metadata (RFC 8414): ${r.metadataUrl}\n\nFetch the metadata document above for the \`authorization_endpoint\`, \`token_endpoint\`, supported grant types / PKCE methods, and — when the app allows it — the dynamic client \`registration_endpoint\` (RFC 7591).\n\n## Protected resources (RFC 9728)\nSee \`/.well-known/oauth-protected-resource\`, which lists the resource, its supported scopes, and the authorization server(s) that can issue tokens for it.\n\n## How an agent authenticates\n1. Discover this document and \`/.well-known/oauth-protected-resource\`.\n2. Fetch the authorization-server metadata for the endpoints.\n3. Register a client (dynamic registration) or use a pre-issued client_id.\n4. Run the authorization-code flow with PKCE (S256), requesting the scopes and target \`resource\`.\n5. Exchange the code for an access token and call the API with \`Authorization: Bearer <token>\`.\n\nDocumentation: ${e.site.documentationUrl??e.siteUrl}\n`;return{status:200,contentType:ot,body:s,cacheControl:n}}function Lt(e,t){return{status:200,contentType:st,body:JSON.stringify(e,null,2),cacheControl:dt(t.cacheTtlSeconds??Xe)}}function Dt(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function Mt(e,t){const n=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${Dt(e)}`);if(t){const e=[...void 0!==t.search?["search="+(t.search?"yes":"no")]:[],...void 0!==t.aiInput?["ai-input="+(t.aiInput?"yes":"no")]:[],...void 0!==t.aiTrain?["ai-train="+(t.aiTrain?"yes":"no")]:[]];e.length&&n.push(`Content-Signal: ${e.join(", ")}`)}for(const t of e.allow??[])n.push(`Allow: ${Dt(t)}`);for(const t of e.disallow??[])n.push(`Disallow: ${Dt(t)}`);return void 0!==e.crawlDelay&&n.push(`Crawl-delay: ${Dt(e.crawlDelay)}`),n.join("\n")}function Jt(e){const t=e.robots??{},n=ut(e.siteUrl),r=t.policies??[{userAgent:"*",allow:["/"]}],s=t.aiBots??"allow",i="allow"===s?[{userAgent:[...lt],allow:["/"]}]:"deny"===s?[{userAgent:[...lt],disallow:["/"]}]:s,o=t.sitemaps??(e.sitemap?[`${n}/sitemap.xml`]:[]),a=[`# robots.txt — agent-ready. See ${n}/llms.txt and ${n}/.well-known/agent.json`,...r.map((e,n)=>Mt(e,0===n?t.contentSignals:void 0)),...i.map(e=>Mt(e)),...o.length?[o.map(e=>`Sitemap: ${Dt(e)}`).join("\n")]:[]];return{status:200,contentType:at,body:a.join("\n\n")+"\n",cacheControl:dt(e.cacheTtlSeconds??Xe)}}function Bt(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function jt(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function qt(e){const t=e.sitemap?.urls;if(!t?.length)return null;const n=ut(e.siteUrl),r='<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'+t.map(e=>{const t="string"==typeof e?{loc:e}:e;return` <url>\n${[` <loc>${jt(/^https?:\/\//.test(t.loc)?t.loc:`${n}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${jt(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${jt(String(t.changefreq))}</changefreq>`]:[],...void 0!==t.priority?[` <priority>${Bt(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n";return{status:200,contentType:ct,body:r,cacheControl:dt(e.cacheTtlSeconds??Xe)}}function Vt(e){if(!e)return!1;let t=0,n=0;for(const r of e.split(",")){const[e,...s]=r.trim().split(";"),i=e.trim().toLowerCase();let o=1;for(const e of s){const[t,n]=e.split("=").map(e=>e.trim());if("q"===t){const e=Number(n);Number.isNaN(e)||(o=e)}}"text/markdown"===i||"text/x-markdown"===i?t=Math.max(t,o):"text/html"!==i&&"text/*"!==i&&"*/*"!==i||(n=Math.max(n,o))}return t>0&&t>=n}async function zt(e,t){const n=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===n){return vt(t,await bt(t))}if(n===rt)return $t(t);if("/.well-known/http-message-signatures-directory"===n)return Tt(t);if("/.well-known/security.txt"===n)return Pt(t);if(n===`${et}/index.json`)return Et(t);if(n.startsWith(`${et}/`)&&n.endsWith("SKILL.md"))return It(n,t);if("/.well-known/oauth-authorization-server"===n||"/.well-known/openid-configuration"===n){const e=(await bt(t)).authorizationServer;if(!e?.metadataUrl)return null;const n=await async function(e,t){const n=t.cacheTtlSeconds??Xe,r=gt(t),s=`buildbase:as-metadata:${e}`,i=await yt(r,s);if(i.hit)return i.value;const o=t.fetch??fetch;let a=null;try{const n=await kt(o,e,{headers:{Accept:st}},t.fetchTimeoutMs??5e3);if(n.ok){const e=await n.json();e&&"object"==typeof e&&(a=e)}}catch{}return await wt(r,s,a,n),a}(e.metadataUrl,t);return Lt(n?n:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(n===tt)return Ot(t);if(n===nt)return Nt(t);if("/.well-known/mcp.json"===n)return Ft(t);if(n.startsWith(Ze)){const e=await bt(t);return xt(n,t,e.authorizationServer?.issuer)}return null}function Kt(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 Gt(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4==0?"":"=".repeat(4-t.length%4),r=atob(t+n),s=new Uint8Array(r.length);for(let e=0;e<r.length;e++)s[e]=r.charCodeAt(e);return s}class Ht extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function Qt(e){const t=JSON.parse((new TextDecoder).decode(Gt(e)));if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("JWT segment is not a JSON object");return t}function Yt(e,t,n={}){const r=n.clockToleranceSec??60,s=n.requireExp??!0;if(!e||!t)throw new Ht("invalid_token","Missing token or client secret");const i=e.split(".");if(3!==i.length)throw new Ht("invalid_token","Malformed JWT");const[o,a,c]=i;let l,u;try{l=Qt(o),u=Qt(a)}catch{throw new Ht("invalid_token","Unreadable JWT segments")}if("HS256"!==l.alg)throw new Ht("invalid_algorithm",`Unexpected JWT alg: ${String(l.alg)}`);const d=Ge(Ke(t),Ke(`${o}.${a}`));let p;try{p=Gt(c)}catch{throw new Ht("invalid_signature","Unreadable JWT signature")}if(!He(d,p))throw new Ht("invalid_signature","JWT signature verification failed");!function(e){for(const t of["iss","sub","jti"])if(void 0!==e[t]&&"string"!=typeof e[t])throw new Ht("invalid_token",`JWT ${t} claim must be a string`);for(const t of["exp","nbf","iat"]){const n=e[t];if(void 0!==n&&("number"!=typeof n||!Number.isFinite(n)))throw new Ht("invalid_token",`JWT ${t} claim must be a finite number`)}const t=e.aud;if(!(void 0===t||"string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new Ht("invalid_token","JWT aud claim must be a string or string array")}(u);const h=Math.floor(Date.now()/1e3);if(s&&"number"!=typeof u.exp)throw new Ht("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof u.exp&&h>u.exp+r)throw new Ht("token_expired","JWT has expired");if("number"==typeof u.nbf&&h+r<u.nbf)throw new Ht("token_not_yet_valid","JWT is not yet valid");if(void 0!==n.issuer&&u.iss!==n.issuer)throw new Ht("invalid_issuer","JWT issuer mismatch");if(void 0!==n.audience){const e=u.aud;if(!(Array.isArray(e)?e.includes(n.audience):e===n.audience))throw new Ht("invalid_audience","JWT audience mismatch")}return u}function Xt(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function Zt(e){return Kt(Ke(JSON.stringify(e)))}function en(e,t,n){if(!t)throw new Ht("invalid_secret","Missing signing secret");const r=Math.floor(Date.now()/1e3),s={iat:r,exp:r+(n?.expiresInSec??3600),...e},i=`${Zt({alg:"HS256",typ:"JWT"})}.${Zt(s)}`;return`${i}.${Kt(Ge(Ke(t),Ke(i)))}`}function tn(e){const t=Xt(e.authorization);if(!t)throw new Ht("invalid_token","Missing Bearer token");return Yt(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function nn(e){const t=Xt(e.authorization);if(!t)throw new Ht("invalid_token","Missing Bearer token");return Yt(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function rn(e){return{success:!0,token:e.token,message:e.message??"ok",..."number"==typeof e.expiresIn?{expiresIn:e.expiresIn}:{}}}function sn(e){return{success:!1,token:"",message:e}}function on(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}const an=12,cn=16;function ln(){const e=globalThis.crypto;if(!e?.subtle)throw new Error("WebCrypto is unavailable in this runtime — agent-auth session encryption requires globalThis.crypto.subtle (Node 18+, Bun, Deno, edge, browsers).");return e.subtle}const un=new Map;function dn(e){let t=un.get(e);return t||(t=(async()=>{const t=await ln().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return ln().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),un.set(e,t)),t}function pn(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(t){const n=globalThis.crypto.getRandomValues(new Uint8Array(an)),r=await dn(e),s=new Uint8Array(await ln().encrypt({name:"AES-GCM",iv:n},r,(new TextEncoder).encode(t))),i=s.subarray(s.length-cn),o=s.subarray(0,s.length-cn),a=new Uint8Array(28+o.length);return a.set(n,0),a.set(i,an),a.set(o,28),Kt(a)},async decryptSessionRef(t){try{const n=Gt(t);if(n.length<=28)return null;const r=n.slice(0,an),s=n.subarray(an,28),i=n.subarray(28),o=new Uint8Array(i.length+cn);o.set(i,0),o.set(s,i.length);const a=await dn(e),c=await ln().decrypt({name:"AES-GCM",iv:r},a,o);return(new TextDecoder).decode(c)}catch{return null}}}}function hn(e,t,n){const r=globalThis.process?.env;"1"===r?.MCP_AUTH_DEBUG&&console.warn(`[buildbase/mcp-auth] audience rejected (${n}): received aud=${JSON.stringify(e)} expected one of ${JSON.stringify(t)}`)}const fn=function(){const e=new Map;return{get(t){const n=e.get(t);if(n){if(!(n.expiresAt<=Date.now()))return n.value;e.delete(t)}},set(t,n,r){e.set(t,{value:n,expiresAt:Date.now()+1e3*r})},delete(t){e.delete(t)},clear(){e.clear()}}}(),gn=e=>e.replace(/\/+$/,""),mn=(e,t)=>`buildbase:org-region:${gn(e)}::${t}`;function yn(e){const{serverUrl:t,orgId:n,version:r="v1",region:s,getSessionId:i,timeout:o,maxRetries:a,debug:c,headers:l,onError:u,fetch:d}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!n)throw new Error("BuildBase: orgId is required");const p={...void 0!==o&&{timeout:o},...void 0!==a&&{maxRetries:a},...void 0!==c&&{debug:c},...l&&{headers:l},...u&&{onError:u},...d&&{fetch:d}},h=e=>{const s={serverUrl:t,version:r,orgId:n,sessionId:e,...p};return{workspace:new L(s),user:new C(s),settings:new P(s),push:new _(s),devices:new S(s),uploads:new T(s),sessions:new I(s)}},f=new L({serverUrl:t,version:r,orgId:n,...p}),g=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,n)=>(await e()).workspace.updateWorkspace(t,n),delete:async t=>(await e()).workspace.deleteWorkspace(t),permissions:async t=>(await e()).workspace.getMyPermissions(t),can:async(t,n)=>{const{permissions:r}=await(await e()).workspace.getMyPermissions(t),s=new Set(r);return(Array.isArray(n)?n:[n]).every(e=>s.has(e))}},invitations:{list:async t=>(await e()).workspace.listInvitations(t),create:async(t,n,r,s)=>(await e()).workspace.inviteMember(t,{email:n,role:r,landingUrl:s}),resend:async(t,n)=>(await e()).workspace.resendInvitation(t,n),revoke:async(t,n)=>(await e()).workspace.revokeInvitation(t,n)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,n,r)=>(await e()).workspace.addUser(t,{email:n,role:r}),remove:async(t,n)=>(await e()).workspace.removeUser(t,n),updateRole:async(t,n,r)=>(await e()).workspace.updateUser(t,n,{role:r}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,n)=>(await e()).workspace.createCheckoutSession(t,n),update:async(t,n)=>(await e()).workspace.updateSubscription(t,n),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,n)=>(await e()).workspace.createBillingPortalSession(t,n)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>f.getPublicPlans(e),getVersion:e=>f.getPlanGroupVersion(e)},invoices:{list:async(t,n,r)=>(await e()).workspace.listInvoices(t,n,r),get:async(t,n)=>(await e()).workspace.getInvoice(t,n)},usage:{record:async(t,n)=>(await e()).workspace.recordUsage(t,n),recordBatch:async(t,n)=>(await e()).workspace.recordUsageBatch(t,n),getQuota:async(t,n)=>(await e()).workspace.getQuotaUsageStatus(t,n),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,n)=>(await e()).workspace.getUsageLogs(t,n)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,n,r)=>(await e()).workspace.updateFeature(t,n,r)},notification:{send:async(t,n,r,s)=>(await e()).workspace.sendNotification(t,n,r,s)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,n)=>(await e()).workspace.consumeCredits(t,n),purchase:async(t,n)=>(await e()).workspace.purchaseCredits(t,n),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,n)=>(await e()).workspace.getCreditTransactions(t,n),getBuckets:async(t,n)=>(await e()).workspace.getCreditBuckets(t,n),getExpiring:async(t,n)=>(await e()).workspace.getExpiringCredits(t,n),getPublicPackages:()=>f.getPublicCreditPackages()},permissions:{check:async(t,n,r)=>{const s=await e(),[i,o,a]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),c=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return Ce(r,{userId:n,workspaceRole:c?.role??null,workspace:i,settings:o})},resolve:async(t,n)=>{const r=await e(),[s,i,o]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),a=o.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return $e({userId:n,workspaceRole:a?.role??null,workspace:s,settings:i})}},devices:{list:async()=>(await e()).devices.list(),rename:async(t,n)=>(await e()).devices.rename(t,n),signOut:async t=>(await e()).devices.signOut(t),forget:async t=>(await e()).devices.forget(t)},sessions:{list:async()=>(await e()).sessions.list(),revoke:async t=>(await e()).sessions.revoke(t)}}),m=g(async()=>h(await(async()=>{if(!i)throw new Error("BuildBase: getSessionId callback is required for authenticated calls. Pass it in BuildBase({ getSessionId: ... }) or use withSession(id) / client.forSession(id).");const e=await i();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{...void 0!==s&&{region:s},auth:async()=>{if(!i)return null;const e=await i();return e?{sessionId:e}:null},withSession:e=>{const t=h(e);return g(async()=>t)},client:{forSession:h},...m}}exports.AI_BOT_USER_AGENTS=lt,exports.APP_PERMISSION_FALLBACK_GROUP=Oe,exports.AppBridgeError=Ht,exports.AuthApi=class extends b{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n="Failed to initiate authentication",r=e=>this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});let s=await r(e);if(400===s.status&&(e.trackingConsent||e.trackingIdentity||e.trackingAttribution||e.invitationToken)){const{trackingConsent:t,trackingIdentity:n,trackingAttribution:i,invitationToken:o,...a}=e;s=await r(a)}return s.ok||await this.throwResponseError(s,n),this.unwrapResponse(s,n)}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}async getDeviceToken(e,t){try{const n=await this.fetchUnwrapped("device-token",{headers:{"x-session-id":e},signal:t},"Failed to fetch device token");return n?.deviceToken??""}catch{return""}}async logout(e,t,n){await this.fetchJson("logout",{method:"POST",...e?{headers:{"x-session-id":e}}:{},...t?.all?{body:JSON.stringify({all:!0})}:{},signal:n},"Failed to sign out")}},exports.BBAction=G,exports.BBScreen=Q,exports.BBStatus=H,exports.BB_PARAM=K,exports.BaseApi=b,exports.BetaForm=class{constructor(e){this.api=new v(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},n=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),r=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),s=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),i=t?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:n,language:r,timezone:s,currency:i}})}},exports.BillingIntervals=ye,exports.BuildBase=yn,exports.CURRENCY_DISPLAY=se,exports.CURRENCY_FLAG=ie,exports.CreditBucketSource={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},exports.CreditBucketStatus={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},exports.CreditTransactionType={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"},exports.DEFAULT_ROLE_PERMISSIONS=Pe,exports.DISCOVERY_CACHE_TIMEOUT_MS=500,exports.DunningState={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},exports.EventEmitter=M,exports.FALLBACK_WORKSPACE_ROLE=Ae,exports.INVITATION_ERROR_CODE=O,exports.InvoiceStatuses={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},exports.NotificationsApi=class extends b{constructor(e){super(e)}async list(e={},t){const n=await this.fetchJson(`notifications${x({workspaceId:e.workspaceId,unread:e.unread,archived:e.archived,page:e.page,limit:e.limit})}`,{signal:t},"Failed to load notifications");return{notifications:n?.notifications??[],page:n?.page??e.page??1,limit:n?.limit??e.limit??20,total:n?.total??0,hasNextPage:Boolean(n?.hasNextPage)}}async counts(e,t){const n=await this.fetchJson(`notifications/unread-count${x({workspaceId:e})}`,{signal:t},"Failed to load notification count");return{unread:n?.unread??0,unseen:n?.unseen??0}}markRead(e){return this.itemAction(this.apiPath`notifications/${e}/read`,"POST",!0)}markUnread(e){return this.itemAction(this.apiPath`notifications/${e}/unread`,"POST")}archive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"POST")}unarchive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"DELETE")}async markAllRead(e){await this.fetchJson("notifications/read-all",{method:"POST",body:E(e)},"Failed to mark notifications read")}async markSeen(e){await this.fetchJson("notifications/seen",{method:"POST",body:E(e)},"Failed to mark notifications seen")}async itemAction(e,t,n=!1){return this.fetchJson(e,n?{method:t,keepalive:n}:{method:t},"Failed to update notification")}},exports.PLAN_CURRENCY_CODES=ae,exports.PLAN_CURRENCY_OPTIONS=ce,exports.PUSH_SERVICE_WORKER_SCRIPT="\n// BuildBase Push Notification Service Worker\n// Place this file in your app's public directory (e.g. public/push-sw.js)\n\nself.addEventListener('push', function(event) {\n if (!event.data) return;\n\n let payload;\n try {\n payload = event.data.json();\n } catch (e) {\n console.error('[PushSW] Push payload is not JSON:', e);\n return;\n }\n if (!payload || typeof payload !== 'object') return;\n\n // i18n exception: service workers run outside the SDK's translation\n // provider, so this last-resort fallback stays English. The server should\n // always send a localized payload.title.\n const title = payload.title || 'Notification';\n // The tracked click URL (/api/push-track/link/...) wins over any url in\n // payload.data, so a click is always counted.\n const data = Object.assign({}, payload.data && typeof payload.data === 'object' ? payload.data : {});\n if (payload.url) data.url = payload.url;\n // A notification with the same tag replaces the earlier one instead of\n // stacking. No tag means every notification is shown on its own.\n const tag = payload.tag ? String(payload.tag) : undefined;\n const actions = Array.isArray(payload.actions)\n ? payload.actions.filter(function(a) {\n return a && typeof a.action === 'string' && typeof a.title === 'string';\n })\n : undefined;\n\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.badge || payload.icon || undefined,\n image: payload.image || undefined,\n tag: tag,\n // The browser rejects renotify without a tag.\n renotify: tag ? !!payload.renotify : false,\n actions: actions && actions.length ? actions : undefined,\n silent: !!payload.silent,\n requireInteraction: !!payload.requireInteraction,\n timestamp: typeof payload.timestamp === 'number' ? payload.timestamp : undefined,\n dir: payload.dir === 'ltr' || payload.dir === 'rtl' ? payload.dir : 'auto',\n data: data,\n };\n\n event.waitUntil(\n Promise.resolve()\n .then(function() {\n return self.registration.showNotification(title, options);\n })\n .catch(function(e) {\n // A field this browser refuses must not cost the user the\n // notification: show it again with the basics only.\n console.error('[PushSW] Failed to show notification, retrying without rich options:', e);\n return self.registration.showNotification(title, {\n body: options.body,\n icon: options.icon,\n tag: tag,\n data: data,\n });\n })\n );\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\n // A click on an action button (event.action is its id) opens the same\n // tracked URL as a click on the notification body.\n const url = event.notification.data && event.notification.data.url;\n if (url) {\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {\n for (let i = 0; i < clientList.length; i++) {\n const client = clientList[i];\n if (client.url === url && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(url);\n }\n })\n );\n }\n});\n",exports.Permission=_e,exports.PushApi=_,exports.SDKEvent=D,exports.SettingsApi=P,exports.SubscriptionItemType={Feature:"feature",Limit:"limit",Quota:"quota"},exports.SubscriptionStatus={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},exports.UPLOAD_ACCEPT="image/png,image/jpeg,image/gif,image/webp,image/svg+xml",exports.UPLOAD_MAX_BYTES=A,exports.UploadsApi=T,exports.UserApi=C,exports.WEBHOOK_EVENTS=Be,exports.WEBHOOK_EVENTS_BY_CATEGORY=Je,exports.WorkspaceApi=L,exports.actionableInvitations=function(e,t=new Date){return Fe(e.filter(e=>We(e,t)))},exports.appPermissionCatalogue=function(e,t){const n=e?.workspace?.customPermissions??[],r=new Map;for(const e of n)e?.key&&!e.key.startsWith("workspace:")&&r.set(e.key,{key:e.key,label:e.label||e.key,group:e.group||Oe});for(const e of Object.values(t??{}))for(const t of e??[])t.startsWith("workspace:")||r.has(t)||r.set(t,{key:t,label:t,group:Oe});return[...r.values()].sort((e,t)=>(e.group??"").localeCompare(t.group??"")||e.key.localeCompare(t.key))},exports.appTokenFailure=sn,exports.appTokenSuccess=rn,exports.bearerChallenge=function(e){const t=[`Bearer resource_metadata="${on(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${on(e.error)}"`),e.errorDescription&&t.push(`error_description="${on(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}},exports.buildA2AAgentCard=$t,exports.buildAgentCard=vt,exports.buildAgentSkillsIndex=Et,exports.buildApiCatalog=Ot,exports.buildAuthMd=Wt,exports.buildDiscoveryLinkHeader=function(e){const t=ut(e.siteUrl),n=[`<${t}/llms.txt>; rel="describedby"; type="text/plain"`,`<${t}/.well-known/agent.json>; rel="describedby"; type="application/json"`];if(!1!==e.a2aCard&&n.push(`<${t}${rt}>; rel="describedby"; type="application/json"`),e.sitemap||e.robots?.sitemaps?.length){const r=e.robots?.sitemaps?.[0]??`${t}/sitemap.xml`;n.push(`<${r}>; rel="sitemap"; type="application/xml"`)}return e.apiCatalog?.length&&n.push(`<${t}${tt}>; rel="api-catalog"; type="${it}"`),e.mcpServerCard&&n.push(`<${t}${nt}>; rel="mcp-server"; type="application/json"`),n.join(", ")},exports.buildDnsAidRecords=function(e){let t;try{t=new URL(e.siteUrl).hostname}catch{return[]}const n=[{name:`_index._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${t}. alpn="h2" port=443`}];if(!1!==e.a2aCard&&n.push({name:`_a2a._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${t}. alpn="h2" port=443`}),e.mcpServerCard){let r=t;try{r=new URL(e.mcpServerCard.endpoint).hostname}catch{}n.push({name:`_mcp._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${r}. alpn="h2" port=443`})}return n},exports.buildLlmsFullTxt=Ut,exports.buildLlmsTxt=At,exports.buildMcpDiscoveryManifest=Ft,exports.buildMcpServerCard=Nt,exports.buildProtectedResourceMetadata=xt,exports.buildRobotsTxt=Jt,exports.buildSecurityTxt=Pt,exports.buildSitemap=qt,exports.buildSkillMd=It,exports.buildWebBotAuthDirectory=Tt,exports.buildbaseAuth=function(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const n=pn(t),r=e.resource?Array.isArray(e.resource)?e.resource:[e.resource]:[];let s=e.resourceMetadataUrl;if(!s&&r.length)try{const e=new URL(r[0]),t="/"===e.pathname?"":e.pathname.replace(/\/+$/,"");s=`${e.origin}/.well-known/oauth-protected-resource${t}`}catch{}return{resourceMetadataUrl:s,verify:async s=>{let i;try{i=Yt(s,t,{...e.verify})}catch{return null}if(r.length){const t=i.aud?Array.isArray(i.aud)?i.aud:[i.aud]:[];if(!t.length&&e.requireAudience)return hn(t,r,"token carries no aud claim"),null;if(t.length&&!t.some(e=>r.includes(e)))return hn(t,r,"aud does not include this resource"),null}const o="string"==typeof i.sid?await n.decryptSessionRef(i.sid):null,a=Array.isArray(i.scope)?i.scope.filter(e=>"string"==typeof e):"string"==typeof i.scope?i.scope.split(" ").filter(Boolean):void 0;return{sessionId:o??"",userId:"string"==typeof i.userId?i.userId:"string"==typeof i.sub?i.sub:void 0,workspaceId:"string"==typeof i.workspaceId?i.workspaceId:void 0,scopes:a,claims:i}}}},exports.calculateBillableSeats=xe,exports.calculateSeatOverageCents=Ee,exports.calculateTotalSubscriptionCents=function(e,t,n,r){const s=ke(e,t,n);return null===s?null:void 0===r?s:s+(Ee(e,t,n,r)??0)},exports.cleanBBParams=function(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(K)&&(e.searchParams.delete(K),window.history.replaceState({},"",e.toString()))}catch{}},exports.clearAgentReadinessCache=function(e){ht.clear();const t=e;if(t?.delete){for(const e of ft)try{const n=t.delete(e);n&&"function"==typeof n.then&&n.catch(()=>{})}catch{}ft.clear()}else ft.clear()},exports.clearAuthIntent=function(){u(ne)},exports.clearPendingInvite=function(){u(Le)},exports.clearResolvedServerUrl=async function(e){const t=mn(e.centralUrl,e.orgId),n=e.cache;if(fn.delete?.(t),n?.delete)try{await n.delete(t)}catch{}},exports.consumeAuthIntent=function(){const e=d(ne,re);return u(ne),e?Date.now()-e.createdAt>6e5?null:te(e.returnUrl,{sameOrigin:!0}):null},exports.createBBUrl=Y,exports.createCheckoutRedirectUrls=function(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:Y({action:G.Checkout,status:H.Success,ws:e,screen:Q.Subscription},n),cancelUrl:Y({action:G.Checkout,status:H.Cancel,ws:e,screen:Q.Subscription},n)}},exports.createCreditPurchaseRedirectUrls=function(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:Y({action:G.CreditPurchase,status:H.Success,ws:e,screen:Q.Credits},n),cancelUrl:Y({action:G.CreditPurchase,status:H.Cancel,ws:e,screen:Q.Credits},n)}},exports.createSessionRefCrypto=pn,exports.default=yn,exports.eventEmitter=J,exports.extractBearerToken=Xt,exports.fetchAgentReadiness=bt,exports.formatCents=fe,exports.formatMinorAmountIntl=function(e,t,n="en-US"){const r=(t??"").trim(),s=pe(r),i=e/10**s;if(!r)return i.toFixed(s);try{return new Intl.NumberFormat(n,{style:"currency",currency:r.toUpperCase(),minimumFractionDigits:s,maximumFractionDigits:s}).format(i)}catch{return oe(r)+(0===s?i.toLocaleString("en-US"):i.toFixed(s))}},exports.formatOverageRate=function(e,t,n,r,s){if(null==e||e<0)return null;const i={...ge,...r},o=null!=t&&t>=1?t:1,a=oe(n),c=he(e,n);return 1===o?`${a}${c}/${i.unit}`:`${a}${c}/${o.toLocaleString(s)} ${i.units}`},exports.formatOverageRateWithLabel=function(e,t,n,r,s,i,o){if(null==e||e<0)return null;const a={...ge,...i},c=null!=t&&t>=1?t:1,l=oe(r),u=he(e,r);if(n){const e=s??(n.endsWith("s")?n:`${n}s`);return c>=2?`${l}${u}/${c.toLocaleString(o)} ${e}`:`${l}${u}/${n}`}return 1===c?`${l}${u}/${a.unit}`:`${l}${u}/${c.toLocaleString(o)} ${a.units}`},exports.formatQuotaIncludedOverage=function(e,t,n,r,s,i,o,a,c){const l={...ge,...o};if(!1===a)return null!=e?`${l.included}: ${e.toLocaleString(c)} (${l.hardLimit})`:o?.hardLimit??"Hard limit";const u=i??(n.endsWith("s")?n:`${n}s`),d=null!=s&&s>=2?`${s.toLocaleString(c)} ${u}`:n;return null!=e&&null!=t?`${l.included}: ${e.toLocaleString(c)}, ${l.afterThat} ${fe(t,r)}/${d}`:null!=e?`${l.included}: ${e.toLocaleString(c)}`:null!=t?`${l.afterIncluded}: ${fe(t,r)}/${d}`:"—"},exports.formatQuotaWithPrice=function(e,t,n={}){const{overageInCents:r=!0,currency:s}=n,i={...me,...n.labels},o=n.currencySymbol??oe(s??"");if(null==e)return"—";const{included:a,overage:c}=e,l=`${a} ${i.included}`;if(!1===e.allowOverage)return`${l} (${i.hardLimit})`;if(null==c)return l;const u=pe(s),d=r&&u>0?c/10**u:c,p="number"==typeof d&&Number.isFinite(d)?0===u?d.toLocaleString("en-US"):d.toFixed(u):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${i.then} ${o}${p}${h}`},exports.formatUploadLimit=function(e,t){const n=1048576,[r,s]=e>=n?[e/n,"megabyte"]:[e/1024,"kilobyte"];try{return new Intl.NumberFormat(t,{style:"unit",unit:s,unitDisplay:"short",maximumFractionDigits:1}).format(r)}catch{return`${Math.round(10*r)/10} ${"megabyte"===s?"MB":"KB"}`}},exports.getAvailableBillingIntervals=function(e,t){return[ye.Monthly,ye.Quarterly,ye.Yearly].filter(n=>n===ye.Monthly||e.some(e=>null!=ke(e,t,n)))},exports.getAvailableCurrenciesFromPlans=function(e){const t=new Set;for(const n of e)n.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()},exports.getBasePriceCents=ke,exports.getBillingIntervalAndCurrencyFromPriceId=function(e,t){if(!e)return null;for(const n of t){const t=n.pricingVariants;if(t?.length)for(const n of t){const t=n.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:n.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:n.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:n.currency}}}}return null},exports.getCurrencyDecimals=pe,exports.getCurrencyFlag=function(e){return e&&e.trim()?ie[e.trim().toLowerCase()]??"":""},exports.getCurrencySymbol=oe,exports.getDisplayCurrency=function(e,t){const n=we(e,t);return n?n.currency:e.plan?.currency??""},exports.getPerSeatPriceCents=Se,exports.getPricingVariant=we,exports.getQuotaDisplayValue=function(e,t){if(null==e)return null;const n=e[t??"monthly"];return n?{included:n.included,...void 0!==n.overage&&{overage:n.overage},...void 0!==n.unitSize&&{unitSize:n.unitSize},allowOverage:!1!==e.allowOverage}:null},exports.getQuotaDisplayWithVariant=function(e,t,n,r){const s=e.quotas?.[n];if(null==s)return null;const i=s[r];if(!i)return null;const o=be(e,t,n,r);return{included:i.included,...void 0!==i.unitSize&&{unitSize:i.unitSize},...void 0!==o&&{overage:o},allowOverage:!1!==s.allowOverage}},exports.getQuotaOverageCents=be,exports.getQuotaUnitLabelFromName=function(e,t="unit"){const n=(e||"").trim().toLowerCase();if(!n)return t;const r=n.split(/\s+/)[0]??n;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(r)?r:r.endsWith("ies")&&r.length>3?r.slice(0,-3)+"y":r.endsWith("ses")||r.endsWith("xes")||r.endsWith("zes")||r.endsWith("ches")||r.endsWith("shes")?r.slice(0,-2):r.endsWith("s")&&!r.endsWith("ss")&&r.length>1?r.slice(0,-1):r||t},exports.getSeatPricing=ve,exports.getStripePriceIdForInterval=function(e,t,n){const r=we(e,t);if(!r?.stripePrices)return null;const s=n===ye.Monthly?"monthlyPriceId":n===ye.Yearly?"yearlyPriceId":"quarterlyPriceId",i=n===ye.Monthly?"monthly":n===ye.Yearly?"yearly":void 0;return r.stripePrices[s]??(i?r.stripePrices[i]:void 0)??null},exports.handleAppRevokeRequest=async function(e){let t;try{t=nn(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof Ht?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}},exports.handleAppTokenRequest=async function(e){let t;try{t=tn(e)}catch(e){return{status:401,body:sn(e instanceof Ht?e.code:"invalid_token")}}return{status:200,body:rn(await e.mintToken(t))}},exports.hasPermission=Ce,exports.invalidateCreditBalance=q,exports.invalidateQuotaUsage=V,exports.invalidateSubscription=z,exports.inviterNameOf=function(e){const t=e.invitedBy;return t&&"string"!=typeof t&&(t.name||t.email)||null},exports.isInvitationActionable=We,exports.isInvitationError=function(e){return e instanceof Error&&"number"==typeof e.status},exports.isInvitationLapsed=function(e,t=new Date){return"expired"===e.status||"invited"===e.status&&!We(e,t)},exports.isWebhookEvent=function(e){return je.has(e)},exports.isZeroDecimalCurrency=function(e){return""!==(e??"").trim()&&0===pe(e)},exports.minorAmountToDisplay=he,exports.mintAgentToken=async function(e){const{claims:t,secret:n}=e,r=e.expiresInSec??3600,s=t.resource&&t.resource.length?1===t.resource.length?t.resource[0]:t.resource:void 0,i=t.sessionId?await pn(n).encryptSessionRef(t.sessionId):void 0;return{token:en({sub:t.id,userId:t.id,email:t.email,...t.name?{name:t.name}:{},...t.scope?{scope:t.scope}:{},...s?{aud:s}:{},...i?{sid:i}:{},...e.extraClaims},n,{expiresInSec:r}),expiresIn:r}},exports.negotiateMarkdown=function(e,t,n){const r=Vt(e);return{status:200,contentType:r?ot:"text/html; charset=utf-8",body:r?t.markdown:t.html,cacheControl:dt(n?.cacheTtlSeconds??Xe),vary:"Accept"}},exports.parkPendingInvite=function(e,t){De.test(e)&&t&&p(Le,{token:e,orgId:t,createdAt:Date.now()})},exports.parseWebhookEvent=function(e){if(!Ye(e))return null;try{return JSON.parse(e.body)}catch{return null}},exports.pickDefaultRole=function(e,t){return t&&"admin"!==t&&e.includes(t)?t:e.includes(Ae)?Ae:e.find(e=>"admin"!==e)??""},exports.preflightUpload=function(e,t){return t.enabled?e.size>t.maxFileBytes?"tooLarge":null:"disabled"},exports.provideWebMcpTools=function(e){const t=globalThis.navigator;return!!t?.modelContext?.provideContext&&(t.modelContext.provideContext({tools:e}),!0)},exports.readBBParams=function(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(K);if(!e)return null;const t=function(e){const t={};if(!e)return t;const n=e.split(",");for(const e of n){const n=e.indexOf(":");if(-1===n)continue;const r=decodeURIComponent(e.slice(0,n)),s=decodeURIComponent(e.slice(n+1));r&&(t[r]=s)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}},exports.readPendingInvite=function(e,t=Date.now()){const n=d(Le,Me);return n?t-n.createdAt>864e5?(u(Le),null):n.orgId!==e?null:De.test(n.token)?n.token:(u(Le),null):null},exports.resendCooldownSeconds=function(e,t=new Date){const n=Ne(e.resendAvailableAt);return n?Math.max(0,Math.ceil((n-t.getTime())/1e3)):0},exports.resolveAgentPath=async function(e,t){const n=e.replace(/\/+$/,"")||e,r=function(e,t){const n=t.extraPaths?.[e];if(void 0===n)return null;const r="string"==typeof n?{body:n}:n;return{status:r.status??200,contentType:r.contentType??Ct(e),body:r.body,cacheControl:r.cacheControl??dt(t.cacheTtlSeconds??Xe)}}(n,t);return r||("/robots.txt"===n?Jt(t):"/llms-full.txt"===n?Ut(t):"/sitemap.xml"===n?qt(t):"/llms.txt"===n?At(t):"/auth.md"===n?Wt(t,await bt(t)):"/security.txt"===n?Pt(t):n.startsWith("/.well-known")?zt(n,t):null)},exports.resolveMaxUsers=function(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=ve(t,n);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=r&&r>0?{maxUsers:r,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}},exports.resolvePermissions=$e,exports.resolveRolePermissions=Te,exports.resolveServerUrl=async function(e){const{orgId:t,centralUrl:n,apiKey:r,timeoutMs:s=5e3}=e;if(!t)throw new Error("resolveServerUrl: orgId is required");if(!n)throw new Error("resolveServerUrl: centralUrl is required");const i=e.cache??fn,o=mn(n,t);try{const e=await i.get(o);if(e)return JSON.parse(e)}catch{}const a=e.fetch??fetch,c=`${gn(n)}/api/organizations/orgs/${encodeURIComponent(t)}/region`,l=new AbortController,u=s>0?setTimeout(()=>l.abort(),s):null;let d;try{d=await a(c,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},signal:l.signal})}finally{u&&clearTimeout(u)}if(!d.ok)throw new Error(`resolveServerUrl: central answered ${d.status} for org ${t}`);const p=await d.json(),h=p?.data??p;if(!h||"string"!=typeof h.serverUrl||!h.serverUrl)throw new Error(`resolveServerUrl: central returned no serverUrl for org ${t}`);const f={orgId:h.orgId||t,region:h.region||"us",cellId:h.cellId||"us",serverUrl:gn(h.serverUrl)},g=function(e){const t=e.headers.get("cache-control")||"";if(/(?:^|[\s,])(?:no-store|no-cache)(?:$|[\s,=])/i.test(t))return 0;const n=/max-age=(\d+)/i.exec(t);if(!n)return 300;const r=Number(n[1]);return!Number.isFinite(r)||r<0?300:Math.min(r,3600)}(d);if(g>0)try{await i.set(o,JSON.stringify(f),g)}catch{}return f},exports.resolveWellKnown=zt,exports.safeRedirect=function(e,t="/",n={}){if("undefined"==typeof window||!window.location)return!1;const r=te(e,n)??te(t)??"/";return function(e){if("undefined"==typeof window||!window.location||0===ee.size)return;let t;try{t=new URL(e,window.location.href).origin}catch{return}if(t!==window.location.origin)for(const e of ee)try{e()}catch{}}(r),window.location.href=r,!0},exports.saveAuthIntent=function(e){te(e,{sameOrigin:!0})&&p(ne,{returnUrl:e,createdAt:Date.now()})},exports.sha256Digest=pt,exports.signClientJwt=en,exports.sortInvitations=Fe,exports.uploadFailureOf=function(e){const{status:t,code:n}=e??{};return"UPLOAD_TOO_LARGE"===n||413===t?"tooLarge":"INVALID_UPLOAD"===n?"invalid":"UPLOADS_DISABLED"===n?"disabled":"USER_UPLOAD_LIMIT"===n?"userLimit":"UPLOADS_UNAVAILABLE"===n||429===t||501===t||503===t?"unavailable":"failed"},exports.uploadPolicyOf=function(e){const t=e?.uploads,n=Number(t?.maxFileBytes);return{enabled:!!t&&!1!==t.enabled,maxFileBytes:Number.isFinite(n)&&n>0?Math.min(n,A):A}},exports.validateInvite=function(e){const{memberCount:t,maxUsersConfig:n,hasSubscription:r=!0,requireSubscription:s=!1}=e;if(s&&!r)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:i,source:o}=n;if(i<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=i){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[o]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[o]??"users.memberLimitMessage",blockMessageValues:{maxUsers:i}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}},exports.validateRedirectUrl=te,exports.verifyAppRevokeRequest=nn,exports.verifyAppTokenRequest=tn,exports.verifyClientJwt=Yt,exports.verifyWebhookSignature=Ye,exports.wantsMarkdown=Vt,exports.workspaceIdOf=function(e){return"object"==typeof e.workspace&&e.workspace?e.workspace._id:e.workspace},exports.workspaceNameOf=function(e){return"object"==typeof e.workspace&&e.workspace&&e.workspace.name||""};
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});let e=!0;function t(t,...n){e&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(t,...n)}function n(e,...t){console.error(e,...t)}function r(e,t){const n=AbortSignal.any;if("function"==typeof n)return n([e,t]);const r=new AbortController,s=e=>{r.signal.aborted||r.abort(e.reason)};for(const n of[e,t]){if(n.aborted){s(n);break}n.addEventListener("abort",()=>s(n),{once:!0})}return r.signal}async function s(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function i(e,t="Request failed"){if(!e.ok){let n,r=t;try{const t=await s(e);r=t.message||t.error||r,"string"==typeof t.code&&(n=t.code)}catch{r=function(e,t){const n={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${n})`)}(e,t).message}throw Object.assign(new Error(r),{status:e.status,...n?{code:n}:{}})}try{return await s(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class o extends Error{constructor(e,t,n,r){super(e),this.code=t,this.context=n,this.originalError=r,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,o)}}const a=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1},this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}configure(t){this.config={...this.config,...t},void 0!==t.enableConsoleLogging&&function(t){void 0!==t.enableLogging&&(e=t.enableLogging)}({enableLogging:t.enableConsoleLogging})}handleError(e,r={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const s=e instanceof Error?e:new o("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",r),i=s instanceof o?s:new o(s.message,"SDK_ERROR",r,s);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${r.component||"Unknown"}:`,{message:i.message,code:i.code,context:i.context,originalError:i.originalError,stack:i.stack}),this.config.onError)try{this.config.onError(i,r)}catch(e){n("[SDK Error Handler] Error in custom error callback:",e)}for(const e of this.listeners)try{e(i,r)}catch(e){n("[SDK Error Handler] Error in error listener:",e)}this.config.showUserNotifications&&this.notifyUser(i,r)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...n)=>e(...n).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...n)=>{try{return e(...n)}catch(e){throw this.handleError(e,t),e}}}};function c(e,t={}){a.handleError(e,t)}function l(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return c(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function u(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){c(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function d(e,t){const n=l(e);if(!n)return null;try{const r=JSON.parse(n);return t&&!t(r)?(c(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),u(e),null):r}catch(t){return c(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),u(e),null}}function p(e,t){try{!function(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){c(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){c(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const h="saas-session-id",f="saas-device-id";function g(){return function(){if("undefined"==typeof window)return null;try{return l(h)}catch(e){return c(e,{component:"auth-utils",action:"getSessionId",metadata:{key:h}}),null}}()}function m(){const e=g(),t={};e&&(t["x-session-id"]=e);const n=function(){if("undefined"==typeof window)return null;try{return l(f)??null}catch(e){return c(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:f}}),null}}();return n&&(t["x-device-id"]=n),t}const y=new WeakSet,w=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),k="SDK is not ready (missing serverUrl, version, or orgId)";class b{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(k);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(k)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:m()}url(e){const t=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${t}`}buildHeaders(e){const t={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(t,e.headers),null==e.body||t["Content-Type"]||(t["Content-Type"]="application/json"),t}reportError(e,t){y.has(e)||(y.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}static delay(e,t){return new Promise((n,r)=>{const s=()=>{clearTimeout(i),r(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return s();const i=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})})}async executeFetchUrl(e,t,n){const s=(t.method??"GET").toUpperCase(),i=n??e,o=this.buildHeaders(t),a={...t,headers:o},c=w.has(s);let l,u;if(this._timeout>0){u=new AbortController;const e=u;l=setTimeout(()=>e.abort(),this._timeout),a.signal=t.signal?r(t.signal,e.signal):e.signal}const d=e=>{if(u?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${s} ${i}`);return this.reportError(e,{method:s,path:i}),e}return e},p=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const n=this._fetch.bind(globalThis),r=await n(e,a);if(this._debug&&console.log(`[BuildBase] ${s} ${e} → ${r.status}`),401===r.status&&this._onUnauthorized&&this._onUnauthorized(),r.status>=500&&c&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await b.delay(e,a.signal),p(t+1)}return r}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw d(e);if(c&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await b.delay(e,a.signal)}catch(e){throw d(e)}return p(t+1)}throw e instanceof Error&&this.reportError(e,{method:s,path:i}),e}};try{return await p(0)}finally{void 0!==l&&clearTimeout(l)}}async fetchJson(e,t={},n="Request failed"){this.ensureReady();try{const r=await this.executeFetch(e,t);return await i(r,n)}catch(n){throw n instanceof Error&&this.reportError(n,{method:(t.method??"GET").toUpperCase(),path:e}),n}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchUnwrapped(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);return r.ok||await this.throwResponseError(r,n),this.unwrapResponse(r,n)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async fetchForeign(e,t={}){return this._fetch.call(globalThis,e,t)}async throwResponseError(e,t){let n=t;try{n=(await e.json()).message||n}catch{n=`${t} (${e.status}: ${e.statusText})`}throw Object.assign(new Error(n),{status:e.status})}apiPath(e,...t){return e.reduce((e,n,r)=>e+n+(r<t.length?encodeURIComponent(String(t[r])):""),"")}async unwrapResponse(e,t){const n=await e.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||t);return void 0!==n.data?n.data:n}return n}}class v extends b{constructor(e){super({...e,basePath:"beta",requireOrgId:!0})}getAuthHeaders(){return{}}async fetchConfig(){return this.fetchJson(`config?orgId=${encodeURIComponent(this.orgId)}`,{},"Failed to fetch beta form configuration")}async submitBetaUser(e){return this.fetchJson("submit",{method:"POST",body:JSON.stringify(e)},"Failed to submit beta user request")}}class S extends b{constructor(e){super(e)}async list(e){const t=await this.fetchJson("devices",{signal:e},"Failed to load devices");return t?.devices??[]}async rename(e,t,n){await this.fetchJson(this.apiPath`devices/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename device")}async signOut(e,t){return this.fetchJson(this.apiPath`devices/${e}`,{method:"DELETE",signal:t},"Failed to sign out device")}async forget(e,t){return this.fetchJson(`${this.apiPath`devices/${e}`}?forget=true`,{method:"DELETE",signal:t},"Failed to forget device")}}function x(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))void 0!==r&&""!==r&&!1!==r&&t.set(n,String(r));const n=t.toString();return n?`?${n}`:""}const E=e=>JSON.stringify(e?{workspaceId:e}:{});class _ extends b{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}class I extends b{constructor(e){super(e)}async list(e){const t=await this.fetchJson("sessions",{signal:e},"Failed to load sessions");return t?.sessions??[]}async revoke(e,t){await this.fetchJson(this.apiPath`sessions/${e}`,{method:"DELETE",signal:t},"Failed to sign out session")}}class P extends b{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}const A=5242880,U={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml"};function $(e){if(e.type)return e.type;const t=(e.name??"").split(".").pop()?.toLowerCase()??"";return U[t]??""}class T extends b{constructor(e){super(e)}async upload(e,t){const{purpose:n,signal:s}=t,i=await this.fetchJson("uploads",{method:"POST",body:JSON.stringify({purpose:n,name:e.name??"file",size:e.size,contentType:$(e)}),signal:s},"Could not start the upload");let o;const a=new AbortController,c=setTimeout(()=>a.abort(),12e4);try{o=await this.fetchForeign(i.url,{method:"PUT",headers:i.headers,body:e,signal:s?r(s,a.signal):a.signal})}catch(e){if(s?.aborted)throw e;throw new Error("The upload to storage did not finish. Check the connection and try again.")}finally{clearTimeout(c)}if(!o.ok)throw Object.assign(new Error(`The upload to storage was refused (HTTP ${o.status}). Try again.`),{status:o.status});return this.fetchJson(this.apiPath`uploads/${i.uploadId}/complete`,{method:"POST",body:"{}",signal:s},"Could not finish the upload")}}class C extends b{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const n=await this.unwrapResponse(t,"Failed to fetch user attributes");return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const n=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof n&&null!==n?n:{}}}const O={NOT_FOUND:"INVITATION_NOT_FOUND",EXPIRED:"INVITATION_EXPIRED",ALREADY_HANDLED:"INVITATION_ALREADY_HANDLED",EMAIL_MISMATCH:"INVITATION_EMAIL_MISMATCH",EMAIL_NOT_VERIFIED:"EMAIL_NOT_VERIFIED",INVITES_DISABLED:"WORKSPACE_INVITES_DISABLED",RATE_LIMITED:"INVITATION_RATE_LIMITED",EMAIL_FAILED:"INVITATION_EMAIL_FAILED",SEAT_LIMIT:"SEAT_LIMIT_REACHED",USER_BLOCKED:"USER_BLOCKED",NO_SENDER_CONFIGURED:"NO_SENDER_CONFIGURED"},R={402:O.SEAT_LIMIT,404:O.NOT_FOUND,409:O.ALREADY_HANDLED,410:O.EXPIRED,429:O.RATE_LIMITED,502:O.EMAIL_FAILED,503:O.NO_SENDER_CONFIGURED};function N(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function F(e){return"string"==typeof e&&e?e:void 0}async function W(e,t){let n=null;try{n=await e.json()}catch{n=null}return function(e,t,n){const r=t&&"object"==typeof t?t:{},s=F(r.message)??F(r.error)??n,i={status:e,code:F(r.code)??R[e]??`HTTP_${e}`,currentUserCount:N(r.currentUserCount),limit:N(r.limit),retryAfterSeconds:N(r.retryAfterSeconds),invitedEmail:F(r.invitedEmail),invitationId:F(r.invitationId),invitationStatus:F(r.status)};return Object.assign(new Error(s),i)}(e.status,n,t)}class L extends b{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){try{return await this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}catch(n){const r=n?.status;if(400===r&&e.trackingAttribution){const{trackingAttribution:n,...r}=e;return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(r),signal:t},"Failed to create workspace")}throw n}}async updateWorkspace(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:n},"Failed to update workspace")}async deleteWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE",signal:t},"Failed to delete workspace")}async getWorkspaceUsers(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{signal:t},"Failed to fetch workspace users")}async addUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to invite member")}async fetchInvitation(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);if(!r.ok)throw await W(r,n);return i(r,n)}async listInvitations(e,t){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{signal:t},"Failed to fetch invitations")}async inviteMember(e,t,n){const r={email:t.email,role:t.role};return t.landingUrl&&(r.landingUrl=t.landingUrl),this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{method:"POST",body:JSON.stringify(r),signal:n},"Failed to send invitation")}async resendInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}/resend`,{method:"POST",signal:n},"Failed to resend invitation")}async revokeInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}`,{method:"DELETE",signal:n},"Failed to revoke invitation")}async myInvitations(e){return this.fetchInvitation("invitations",{signal:e},"Failed to fetch your invitations")}async acceptInvitation(e,t,n){return this.fetchInvitation(this.apiPath`invitations/${e}/accept`,{method:"PATCH",signal:n,...t?.token?{body:JSON.stringify({token:t.token})}:{}},"Failed to accept invitation")}async declineInvitation(e,t){return this.fetchInvitation(this.apiPath`invitations/${e}/reject`,{method:"PATCH",signal:t},"Failed to decline invitation")}async previewInvitation(e,t){if(!this.orgId)throw new Error("orgId is required for previewInvitation");return this.fetchInvitation(this.apiPath`${this.orgId}/invitations/preview/${e}`,{signal:t},"Failed to load invitation")}async removeUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:n},"Failed to remove user")}async updateUser(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(n),signal:r},"Failed to update user")}async updateSettings(e,t){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:n},"Failed to update workspace permissions")}async getMyPermissions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/permissions/me`,{signal:t},"Failed to fetch workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:n}}),signal:r},"Failed to update feature")}async getWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{signal:t},"Failed to fetch workspace")}async getProfile(e){return this.fetchJson("profile",{signal:e},"Failed to fetch profile")}async updateUserProfile(e,t){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update user profile")}async getPasskeys(e){const t=await this.fetchJson("passkeys",{signal:e},"Failed to fetch passkeys");return t?.passkeys??[]}async renamePasskey(e,t,n){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename passkey")}async deletePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE",signal:t},"Failed to remove passkey")}async getCurrentSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{signal:t},"Failed to fetch subscription")}async getPlanGroup(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`,{signal:t},"Failed to fetch plan group")}async getPlanGroupByVersion(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch plan group version")}async getPlanGroupVersions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group/versions`,{signal:t},"Failed to fetch plan group versions")}async getPublicPlans(e,t){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");return this.fetchUnwrapped(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`,{signal:t},"Failed to fetch plans")}async getPublicCreditPackages(e){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");return this.fetchUnwrapped(this.apiPath`${this.orgId}/credit-packages`,{signal:e},"Failed to fetch credit packages")}async getPlanGroupVersion(e,t){return this.fetchUnwrapped(this.apiPath`plan-group-versions/${e}`,{signal:t},"Failed to fetch plan group version")}async createCheckoutSession(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create checkout session")}async selectFreePlan(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:n},"Failed to select free plan")}async updateSubscription(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:n},"Failed to update subscription")}async createBillingPortalSession(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:n})}async listInvoices(e,t=10,n,r){const s=new URLSearchParams;return s.append("limit",t.toString()),n&&s.append("starting_after",n),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`,{signal:r},"Failed to fetch invoices")}async getInvoice(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:n},"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST",signal:t},"Failed to cancel subscription")}async resumeSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST",signal:t},"Failed to resume subscription")}async recordUsage(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record usage")}async recordUsageBatch(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch quota usage status")}async getAllQuotaUsage(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/all`,{signal:t},"Failed to fetch all quota usage")}async getUsageLogs(e,t,n){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch usage logs")}async sendNotification(e,t,n,r,s){const i={event:t};return n&&(i.userId=n),r&&(i.data=r),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(i),signal:s},"Failed to send notification")}async getNotificationEvents(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{signal:t},"Failed to fetch notification events")}async getNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{signal:t},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t,n){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update notification preferences")).notificationPreferences??{}}async getMyNotificationPreferences(e,t){const n=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{signal:t},"Failed to fetch your notification preferences");return{defaults:n?.defaults??{},mine:n?.mine??{}}}async updateMyNotificationPreferences(e,t,n){const r=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update your notification preferences");return{defaults:r?.defaults??{},mine:r?.mine??{}}}async getCreditBalance(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits`,{signal:t},"Failed to fetch credit balance")}async consumeCredits(e,t,n){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:n});if(!r.ok){if(402===r.status){const e=await r.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(r,"Failed to consume credits")}return this.unwrapResponse(r,"Failed to consume credits")}async purchaseCredits(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const n=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return n.docs??n}async getCreditTransactions(e,t,n){const r=new URLSearchParams;t?.type&&r.append("type",t.type),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,n){const r=new URLSearchParams;t?.status&&r.append("status",t.status),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,n){const r=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+r,{signal:n},"Failed to fetch expiring credits")}}exports.ApiVersion=void 0,(exports.ApiVersion||(exports.ApiVersion={})).V1="v1";const D={UserCreated:"user:created",UserUpdated:"user:updated",WorkspaceChanged:"workspace:changed",WorkspaceUpdated:"workspace:updated",WorkspaceUserAdded:"workspace:user-added",WorkspaceUserRemoved:"workspace:user-removed",WorkspaceUserRoleChanged:"workspace:user-role-changed",WorkspaceCreated:"workspace:created",WorkspaceDeleted:"workspace:deleted",WorkspaceInvitationSent:"workspace:invitation-sent",WorkspaceInvitationAccepted:"workspace:invitation-accepted",WorkspaceInvitationDeclined:"workspace:invitation-declined",WorkspaceInvitationRevoked:"workspace:invitation-revoked"};class M{constructor(){this.callbacks=null,this.listeners=new Map}setCallbacks(e){this.callbacks=e}getCallbacks(){return this.callbacks}async emit(e,t){if(this.callbacks?.handleEvent)try{await this.callbacks.handleEvent(e,t)}catch(t){c(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}const n=this.listeners.get(e);if(n)for(const r of[...n])try{r(t)}catch(t){c(t,{component:"EventEmitter",action:"notifyListener",metadata:{eventType:e}})}}on(e,t){const n=this.listeners.get(e)??new Set;return n.add(t),this.listeners.set(e,n),()=>{this.listeners.get(e)?.delete(t)}}async emitUserCreated(e){await this.emit(D.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(D.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(D.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(D.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(D.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceInvitationSent(e,t){await this.emit(D.WorkspaceInvitationSent,{invitation:e,workspaceId:t})}async emitWorkspaceInvitationAccepted(e,t){await this.emit(D.WorkspaceInvitationAccepted,{invitation:e,workspace:t})}async emitWorkspaceInvitationDeclined(e){await this.emit(D.WorkspaceInvitationDeclined,{invitation:e})}async emitWorkspaceInvitationRevoked(e,t){await this.emit(D.WorkspaceInvitationRevoked,{invitationId:e,workspaceId:t})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(D.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(D.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(D.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(D.WorkspaceDeleted,{workspace:e})}}const J=new M,B=globalThis;function j(e){const t=Symbol.for(`@buildbase/sdk.invalidation.${e}`),n=B[t]??(B[t]=new Set);return{subscribe:e=>(n.add(e),()=>{n.delete(e)}),invalidate(){n.forEach(e=>e())},reset(){n.clear()}}}const q=j("credit-balance").invalidate,V=j("quota-usage").invalidate,z=j("subscription").invalidate,K="bb",G={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},H={Success:"success",Cancel:"cancel",Error:"error"},Q={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function Y(e,t){const n=t??("undefined"!=typeof window?window.location.href:"https://localhost");let r;try{r=new URL(n)}catch{throw new Error(`createBBUrl: invalid base URL: ${JSON.stringify(n)}`)}return r.search="",r.searchParams.set(K,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}const X="__buildbaseBeforeLeave",Z=globalThis,ee=Z[X]??(Z[X]=new Set);function te(e,t={}){if(!e||"string"!=typeof e)return null;if(/^\/(?![/\\])/.test(e))return e;let n;try{n=new URL(e)}catch{return null}const r="https:"===n.protocol,s="http:"===n.protocol&&("localhost"===n.hostname||"127.0.0.1"===n.hostname||"[::1]"===n.hostname);if(!r&&!s)return null;const{sameOrigin:i,allowedOrigins:o}=t;return i||o?.length?i&&"undefined"!=typeof window&&window.location&&n.origin===window.location.origin||o?.some(e=>e.replace(/\/+$/,"")===n.origin)?e:null:e}const ne="saas-auth-intent";function re(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}const se={usd:"$",eur:"€",gbp:"£",jpy:"¥",cad:"CA$",aud:"A$",chf:"CHF",cny:"¥",hkd:"HK$",sgd:"S$",inr:"₹",mxn:"MX$",brl:"R$",nzd:"NZ$",sek:"kr",nok:"kr",dkk:"kr",pln:"zł",thb:"฿"},ie={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function oe(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return se[t]??t.toUpperCase()}const ae=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],ce=ae.map(e=>({value:e,label:`${e.toUpperCase()} (${oe(e)})`})),le=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),ue=new Set(["bhd","jod","kwd","omr","tnd"]),de=new Map;function pe(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(le.has(t))return 0;if(ue.has(t))return 3;if("isk"===t)return 2;let n=de.get(t);if(void 0===n){try{n=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{n=2}de.set(t,n)}return n}function he(e,t){const n=pe(t);return 0===n?e.toLocaleString("en-US"):(e/10**n).toFixed(n)}function fe(e,t){return oe(t)+he(e,t)}const ge={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};const me={included:"included",then:"then",hardLimit:"hard limit"};const ye={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"};function we(e,t){const n=e.pricingVariants;if(!n?.length)return null;const r=t.toLowerCase();return n.find(e=>e.currency?.toLowerCase()===r)??null}function ke(e,t,n){const r=we(e,t);if(!r?.basePricing)return null;const s=r.basePricing[n];return null!=s?s:null}function be(e,t,n,r){const s=we(e,t),i=s?.quotaOverages?.[n];if(i)return i[r]}function ve(e,t){const n=we(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function Se(e,t,n){const r=ve(e,t);return r?.perSeat?r.perSeat[n]??null:null}function xe(e,t){return Math.max(0,e-(t||0))}function Ee(e,t,n,r){const s=ve(e,t);if(!s)return null;return xe(r,s.includedSeats)*(Se(e,t,n)??0)}const _e={WORKSPACE_SETTINGS_VIEW:"workspace:settings:view",WORKSPACE_SETTINGS_EDIT:"workspace:settings:edit",WORKSPACE_DELETE:"workspace:delete",WORKSPACE_MEMBERS_VIEW:"workspace:members:view",WORKSPACE_MEMBERS_INVITE:"workspace:members:invite",WORKSPACE_MEMBERS_REMOVE:"workspace:members:remove",WORKSPACE_MEMBERS_ROLE_CHANGE:"workspace:members:role-change",WORKSPACE_FEATURES_VIEW:"workspace:features:view",WORKSPACE_FEATURES_EDIT:"workspace:features:edit",WORKSPACE_BILLING_VIEW:"workspace:billing:view",WORKSPACE_BILLING_MANAGE:"workspace:billing:manage",WORKSPACE_USAGE_VIEW:"workspace:usage:view",WORKSPACE_USAGE_RECORD:"workspace:usage:record"},Ie=Object.values(_e),Pe={admin:Ie.filter(e=>e!==_e.WORKSPACE_DELETE),editor:[_e.WORKSPACE_SETTINGS_VIEW,_e.WORKSPACE_MEMBERS_VIEW,_e.WORKSPACE_FEATURES_VIEW,_e.WORKSPACE_BILLING_VIEW,_e.WORKSPACE_USAGE_VIEW,_e.WORKSPACE_USAGE_RECORD],viewer:[_e.WORKSPACE_SETTINGS_VIEW,_e.WORKSPACE_MEMBERS_VIEW]},Ae="viewer";function Ue(e){const t=new Set;for(const n of Object.values(e))for(const e of n)t.add(e);return Array.from(t)}function $e(e){const{userId:t,workspace:n,settings:r,appPermissions:s}=e;if(!n||!t)return new Set;if(function(e,t){if(!t)return!1;const n=(r=e.createdBy)?"string"==typeof r?r:"object"==typeof r&&"_id"in r&&"string"==typeof r._id?r._id:null:null;var r;return null!==n&&n===t}(n,t)){const e=new Set(Ie);if(s)for(const t of Ue(s))e.add(t);if(n.permissions)for(const t of Ue(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of Ue(r.workspace.permissions))e.add(t);return e}const i=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const n=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return n&&"object"==typeof n&&"role"in n&&"string"==typeof n.role?n.role:null}(n,t);return i?Te(i,e):new Set}function Te(e,t,n={}){const{workspace:r,settings:s,appPermissions:i}=t;if(!r)return new Set;const o=r.permissions,a=s?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),l=e=>e.filter(e=>!e.startsWith("workspace:")),u=e=>!!o&&e in o,d=e=>!!a&&e in a,p=e=>u(e)||d(e)||e in Pe;let h,f=e;if(!p(e)){const e=s?.workspace?.defaultRole;if(!e||"admin"===e||!p(e))return new Set;f=e}h=u(f)?c(o[f]):d(f)?c(a[f]):Pe[f]??[];const g=new Set(h),m=new Set((s?.workspace?.customPermissions??[]).map(e=>e.key)),y=i?.[f]?l(i[f]).filter(e=>!m.has(e)):[];let w;w=u(f)?l(o[f]):d(f)?[...l(a[f]),...y]:i?.[f]?l(i[f]):[];for(const e of w)g.add(e);if("admin"===f){for(const e of Pe.admin)g.add(e);for(const e of m)g.add(e);if(i)for(const e of l(Ue(i)))g.add(e)}return!1!==n.applyRestrictions&&function(e,t,n){if(!n?.workspace)return;const{canInviteMembers:r}=n.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(_e.WORKSPACE_MEMBERS_INVITE)}(g,f,s),g}function Ce(e,t){const n=$e(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}const Oe="App";var Re;function Ne(e){if(!e)return 0;const t=new Date(e).getTime();return Number.isNaN(t)?0:t}function Fe(e){const t=e=>"invited"===e.status?0:1;return[...e].sort((e,n)=>t(e)-t(n)||Ne(n.invitedAt)-Ne(e.invitedAt))}function We(e,t=new Date){return"invited"===e.status&&(null===e.validTill||void 0===e.validTill||Ne(e.validTill)>t.getTime())}exports.AuthStatus=void 0,(Re=exports.AuthStatus||(exports.AuthStatus={})).loading="loading",Re.redirecting="redirecting",Re.authenticated="authenticated",Re.unauthenticated="unauthenticated",Re.authenticating="authenticating";const Le="saas-pending-invite",De=/^[0-9a-f]{64}$/;function Me(e){return"object"==typeof e&&null!==e&&"string"==typeof e.token&&"string"==typeof e.orgId&&"number"==typeof e.createdAt}const Je={User:["user.registered","user.logged_in","user.new_device_login","user.email_verified","user.password_changed","user.password_reset_requested","user.profile_updated","user.tag_added","user.tag_removed","user.blocked","user.unblocked"],Organization:["organization.member_invited","organization.member_accepted","organization.member_role_changed","organization.member_removed","organization.public_write_limit_reached","organization.end_user_ceiling_reached"],Workspace:["workspace.created","workspace.updated","workspace.deleted","workspace.settings_updated","workspace.features_updated","workspace.member_added","workspace.member_removed","workspace.member_role_changed","workspace.member_invited","workspace.invitation_accepted","workspace.invitation_declined","workspace.invitation_revoked","workspace.invitation_expired"],Subscription:["subscription.created","subscription.updated","subscription.upgraded","subscription.canceled","subscription.cancel_scheduled","subscription.resumed","subscription.suspended","subscription.trial_started","subscription.trial_will_end","subscription.trial_expired","subscription.downgraded"],Payment:["payment.succeeded","payment.failed","payment.action_required","payment.refunded"],Quota:["quota.limit_exceeded"],Credit:["credit.purchased","credit.consumed","credit.expired","credit.granted","credit.revoked","credit.low_balance"],Workflow:["workflow.created","workflow.deleted","workflow.published","workflow.paused","workflow.resumed","workflow.instance_completed","workflow.instance_failed"],Audience:["audience.member_created","audience.member_updated","audience.added_to_list","audience.removed_from_list","audience.attribute_changed","audience.tag_added","audience.tag_removed","audience.unsubscribed","audience.resubscribed","audience.email_invalidated","audience.blocked","audience.unblocked","audience.import_completed","audience.list_created","audience.list_updated","audience.list_deleted"],Email:["email.domain_added","email.domain_verified","email.sent","email.opened","email.clicked","email.bounced","email.complained","email.unsubscribed","email.campaign_sent"],Push:["push.campaign_sent"],Auth:["auth.method_deleted","auth.domain_added","auth.domain_verified","auth.domain_deleted","auth.client_self_registered"],Token:["token.created","token.updated","token.revoked"],"Group version":["group_version.published"],Form:["form.submitted"],Blog:["blog.published","blog.updated","blog.unpublished","blog.deleted"],Doc:["doc.published","doc.updated","doc.unpublished","doc.deleted"],FAQ:["faq.updated"],"FAQ collection":["faq_collection.updated"],Testimonial:["testimonial.updated","testimonial.deleted"],"Rich content":["rich_content.updated","rich_content.deleted"],Collection:["collection.version_published","collection.record_created","collection.record_updated","collection.record_deleted"]},Be=Object.values(Je).flat(),je=new Set(Be);const qe=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]),Ve=(e,t)=>e>>>t|e<<32-t;function ze(e){let t=1779033703,n=3144134277,r=1013904242,s=2773480762,i=1359893119,o=2600822924,a=528734635,c=1541459225;const l=e.length,u=l+1,d=u+(56-u%64+64)%64+8,p=new Uint8Array(d);p.set(e,0),p[l]=128;const h=8*l,f=Math.floor(h/4294967296),g=h>>>0;p[d-8]=f>>>24&255,p[d-7]=f>>>16&255,p[d-6]=f>>>8&255,p[d-5]=255&f,p[d-4]=g>>>24&255,p[d-3]=g>>>16&255,p[d-2]=g>>>8&255,p[d-1]=255&g;const m=new Uint32Array(64);for(let e=0;e<d;e+=64){for(let t=0;t<16;t++){const n=e+4*t;m[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=Ve(m[e-15],7)^Ve(m[e-15],18)^m[e-15]>>>3,n=Ve(m[e-2],17)^Ve(m[e-2],19)^m[e-2]>>>10;m[e]=m[e-16]+t+m[e-7]+n>>>0}let l=t,u=n,d=r,h=s,f=i,g=o,y=a,w=c;for(let e=0;e<64;e++){const t=w+(Ve(f,6)^Ve(f,11)^Ve(f,25))+(f&g^~f&y)+qe[e]+m[e]>>>0,n=l&u^l&d^u&d;w=y,y=g,g=f,f=h+t>>>0,h=d,d=u,u=l,l=t+((Ve(l,2)^Ve(l,13)^Ve(l,22))+n>>>0)>>>0}t=t+l>>>0,n=n+u>>>0,r=r+d>>>0,s=s+h>>>0,i=i+f>>>0,o=o+g>>>0,a=a+y>>>0,c=c+w>>>0}const y=new Uint8Array(32),w=[t,n,r,s,i,o,a,c];for(let e=0;e<8;e++)y[4*e]=w[e]>>>24&255,y[4*e+1]=w[e]>>>16&255,y[4*e+2]=w[e]>>>8&255,y[4*e+3]=255&w[e];return y}function Ke(e){return(new TextEncoder).encode(e)}function Ge(e,t){let n=e;n.length>64&&(n=ze(n));const r=new Uint8Array(64),s=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<n.length?n[e]:0;r[e]=54^t,s[e]=92^t}const i=ze(Qe(r,t));return ze(Qe(s,i))}function He(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}function Qe(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function Ye(e){const{body:t,signature:n,timestamp:r,secret:s,maxAgeSeconds:i=300}=e;if(!(n&&r&&s&&t))return!1;const o="sha256=";if(!n.startsWith(o))return!1;const a=n.slice(7);if(i>0){const e=parseInt(r,10);if(isNaN(e))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-e)>i)return!1}const c=function(e){if(e.length%2!=0)return null;const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++){const r=parseInt(e.slice(2*n,2*n+2),16);if(Number.isNaN(r))return null;t[n]=r}return t}(a);if(!c)return!1;const l=Ge(Ke(s),Ke(`${r}.${t}`));return c.length===l.length&&He(c,l)}const Xe=300,Ze="/.well-known/oauth-protected-resource",et="/.well-known/agent-skills",tt="/.well-known/api-catalog",nt="/.well-known/mcp/server-card.json",rt="/.well-known/agent-card.json",st="application/json",it="application/linkset+json",ot="text/markdown; charset=utf-8",at="text/plain; charset=utf-8",ct="application/xml; charset=utf-8",lt=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function ut(e){return e.replace(/\/+$/,"")}function dt(e){return`public, max-age=${e}, s-maxage=${e}`}function pt(e){return"sha256:"+function(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}(ze(Ke(e)))}const ht=function(){const e=new Map;return{get(t){const n=e.get(t);if(n){if(!(n.expiresAt<=Date.now()))return n.value;e.delete(t)}},set(t,n,r){e.set(t,{value:n,expiresAt:Date.now()+1e3*r})},delete(t){e.delete(t)},clear(){e.clear()}}}(),ft=new Set;function gt(e){return e.cache??ht}function mt(e){let t;const n=new Promise((e,n)=>{t=setTimeout(()=>n(new Error("discovery cache timed out")),500)});return Promise.race([Promise.resolve(e),n]).finally(()=>clearTimeout(t))}async function yt(e,t){try{const n=await mt(e.get(t));return null==n?{hit:!1}:{hit:!0,value:JSON.parse(n)}}catch{return{hit:!1}}}async function wt(e,t,n,r){try{await mt(e.set(t,JSON.stringify(n),r)),e!==ht&&ft.add(t)}catch{}}async function kt(e,t,n,r){if(!r||r<=0)return e(t,n);const s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await e(t,{...n,signal:s.signal})}finally{clearTimeout(i)}}async function bt(e){const t=e.cacheTtlSeconds??Xe,n=gt(e),r=`buildbase:agent-readiness:${ut(e.serverUrl)}::${e.orgId}`,s=await yt(n,r);if(s.hit)return s.value;const i=e.fetch??fetch,o=`${ut(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let a={enabled:!1};try{const t=await kt(i,o,{headers:{Accept:st}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(a=e)}}catch{}return await wt(n,r,a,t),a}function vt(e,t){const n=ut(e.siteUrl),r={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:Ze};t.authorizationServer?.metadataUrl&&(r.oauth_authorization_server=t.authorizationServer.metadataUrl,r.openid_configuration="/.well-known/openid-configuration"),(t.authorizationServer||e.authMd)&&(r.auth="/auth.md"),e.skills?.length&&(r.agent_skills=`${et}/index.json`),e.apiCatalog?.length&&(r.api_catalog=tt),e.mcpServerCard&&(r.mcp_server_card=nt),!1!==e.a2aCard&&(r.a2a_agent_card=rt),e.llmsFullTxt&&(r.llms_full_txt="/llms-full.txt");return Lt({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:n,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:n},capabilities:r,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}function St(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const n="/"===t?"":t.replace(/\/+$/,"");return Ze+n}function xt(e,t,n){const r=t.protectedResources??[];if(!r.length)return null;const s=e.replace(/\/+$/,"")||Ze,i=n??`${ut(t.serverUrl)}/org/${t.orgId}`,o=t.scopes?.map(e=>e.name),a=r.map(e=>{const n=e.resource??ut(t.siteUrl),r=e.scopes??o;return{path:St(n),metadata:{resource:n,authorization_servers:[i],bearer_methods_supported:e.bearerMethods??["header"],...r?.length?{scopes_supported:r}:{},...e.documentationUrl?{resource_documentation:e.documentationUrl}:{}}}}),c=a.find(e=>e.path===s);return c?Lt(c.metadata,t):s===Ze&&1===a.length?Lt(a[0].metadata,t):null}function Et(e){const t=e.skills??[];if(!t.length)return null;const n=ut(e.siteUrl);return Lt({$schema:"https://schemas.agentskills.io/discovery/0.2.0/schema.json",skills:t.map(e=>({name:e.name,type:e.type??"skill-md",description:e.description,url:`${n}${_t(e)}`,digest:pt(e.content)}))},e)}function _t(e){return e.path??`${et}/${e.name}/SKILL.md`}function It(e,t){const n=(t.skills??[]).find(t=>_t(t)===e);return n?{status:200,contentType:"text/markdown; charset=utf-8",body:n.content,cacheControl:dt(t.cacheTtlSeconds??Xe)}:null}function Pt(e){if(!e.security)return null;const t=(Array.isArray(e.security.contact)?e.security.contact:[e.security.contact]).map(e=>`Contact: ${e}`);return e.security.expires&&t.push(`Expires: ${e.security.expires}`),e.security.policy&&t.push(`Policy: ${e.security.policy}`),{status:200,contentType:at,body:t.join("\n")+"\n",cacheControl:dt(e.cacheTtlSeconds??Xe)}}function At(e){return e.llmsTxt?{status:200,contentType:at,body:e.llmsTxt,cacheControl:dt(e.cacheTtlSeconds??Xe)}:null}function Ut(e){return e.llmsFullTxt?{status:200,contentType:at,body:e.llmsFullTxt,cacheControl:dt(e.cacheTtlSeconds??Xe)}:null}function $t(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},n=ut(e.siteUrl),r=t.serviceUrl??n,s=t.transportProtocol??"http",i=t.skills??((e.skills??[]).length?(e.skills??[]).map(e=>({id:e.name,name:e.name,description:e.description,tags:["discovery"]})):[{id:"site-content",name:"Site content",description:`Read ${e.site.name}'s public content and machine-readable discovery documents (llms.txt, sitemap, API catalog).`,tags:["content"]}]);return Lt({protocolVersion:"0.3.0",name:t.name??e.site.name,version:t.version??"1.0.0",description:t.description??e.site.description??`${e.site.name} — agent-accessible web application.`,url:r,preferredTransport:s,supportedInterfaces:[{serviceUrl:r,transportProtocol:s}],provider:e.site.provider?{organization:e.site.provider.name,url:e.site.provider.url}:{organization:e.site.name,url:n},capabilities:t.capabilities??{streaming:!1,pushNotifications:!1},defaultInputModes:["text/plain","application/json"],defaultOutputModes:["text/plain","application/json"],skills:i,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}},e)}function Tt(e){const t=e.webBotAuth?.keys;return t?.length?{status:200,contentType:"application/http-message-signatures-directory+json",body:JSON.stringify({keys:t},null,2),cacheControl:dt(e.cacheTtlSeconds??Xe)}:null}function Ct(e){return e.endsWith(".json")||e.includes(".well-known/")?st:e.endsWith(".md")?ot:e.endsWith(".xml")?ct:at}function Ot(e){const t=e.apiCatalog??[];if(!t.length)return null;const n=t.map(e=>({anchor:e.anchor,...e.title?{title:e.title}:{},...e.serviceDesc?{"service-desc":[{href:e.serviceDesc}]}:{},...e.serviceDoc?{"service-doc":[{href:e.serviceDoc}]}:{},...e.status?{status:[{href:e.status}]}:{}}));return{status:200,contentType:it,body:JSON.stringify({linkset:n},null,2),cacheControl:dt(e.cacheTtlSeconds??Xe)}}function Rt(e){const t=e??{tools:!0},n={tools:!1,resources:!1,prompts:!1};for(const[e,r]of Object.entries(t))n[e]=!1!==r&&null!=r;return n}function Nt(e){const t=e.mcpServerCard;return t?Lt({$schema:"https://modelcontextprotocol.io/schemas/server-card/v1.0",version:"1.0",protocolVersion:t.protocolVersion??"2025-11-25",serverInfo:{name:t.name,version:t.version},...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},capabilities:Rt(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}function Ft(e){const t=e.mcpServerCard;if(!t)return null;const n=ut(e.siteUrl);let r;try{r={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${St(t.endpoint)}`}}catch{}return Lt({$schema:"https://modelcontextprotocol.io/schemas/mcp-discovery/v1.0",version:"1.0",servers:[{name:t.name,...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},version:t.version,capabilities:Rt(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${n}${nt}`,...r?{authentication:r}:{}}]},e)}function Wt(e,t){const n=dt(e.cacheTtlSeconds??Xe);if(e.authMd)return{status:200,contentType:ot,body:e.authMd,cacheControl:n};const r=t.authorizationServer;if(!r)return null;const s=`# Agent Authentication\n\n${e.site.name} supports AI-agent access via OAuth 2.0 (authorization code + PKCE).\n\n## Authorization server\n- Issuer: \`${r.issuer}\`\n- Metadata (RFC 8414): ${r.metadataUrl}\n\nFetch the metadata document above for the \`authorization_endpoint\`, \`token_endpoint\`, supported grant types / PKCE methods, and — when the app allows it — the dynamic client \`registration_endpoint\` (RFC 7591).\n\n## Protected resources (RFC 9728)\nSee \`/.well-known/oauth-protected-resource\`, which lists the resource, its supported scopes, and the authorization server(s) that can issue tokens for it.\n\n## How an agent authenticates\n1. Discover this document and \`/.well-known/oauth-protected-resource\`.\n2. Fetch the authorization-server metadata for the endpoints.\n3. Register a client (dynamic registration) or use a pre-issued client_id.\n4. Run the authorization-code flow with PKCE (S256), requesting the scopes and target \`resource\`.\n5. Exchange the code for an access token and call the API with \`Authorization: Bearer <token>\`.\n\nDocumentation: ${e.site.documentationUrl??e.siteUrl}\n`;return{status:200,contentType:ot,body:s,cacheControl:n}}function Lt(e,t){return{status:200,contentType:st,body:JSON.stringify(e,null,2),cacheControl:dt(t.cacheTtlSeconds??Xe)}}function Dt(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function Mt(e,t){const n=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${Dt(e)}`);if(t){const e=[...void 0!==t.search?["search="+(t.search?"yes":"no")]:[],...void 0!==t.aiInput?["ai-input="+(t.aiInput?"yes":"no")]:[],...void 0!==t.aiTrain?["ai-train="+(t.aiTrain?"yes":"no")]:[]];e.length&&n.push(`Content-Signal: ${e.join(", ")}`)}for(const t of e.allow??[])n.push(`Allow: ${Dt(t)}`);for(const t of e.disallow??[])n.push(`Disallow: ${Dt(t)}`);return void 0!==e.crawlDelay&&n.push(`Crawl-delay: ${Dt(e.crawlDelay)}`),n.join("\n")}function Jt(e){const t=e.robots??{},n=ut(e.siteUrl),r=t.policies??[{userAgent:"*",allow:["/"]}],s=t.aiBots??"allow",i="allow"===s?[{userAgent:[...lt],allow:["/"]}]:"deny"===s?[{userAgent:[...lt],disallow:["/"]}]:s,o=t.sitemaps??(e.sitemap?[`${n}/sitemap.xml`]:[]),a=[`# robots.txt — agent-ready. See ${n}/llms.txt and ${n}/.well-known/agent.json`,...r.map((e,n)=>Mt(e,0===n?t.contentSignals:void 0)),...i.map(e=>Mt(e)),...o.length?[o.map(e=>`Sitemap: ${Dt(e)}`).join("\n")]:[]];return{status:200,contentType:at,body:a.join("\n\n")+"\n",cacheControl:dt(e.cacheTtlSeconds??Xe)}}function Bt(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function jt(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function qt(e){const t=e.sitemap?.urls;if(!t?.length)return null;const n=ut(e.siteUrl),r='<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'+t.map(e=>{const t="string"==typeof e?{loc:e}:e;return` <url>\n${[` <loc>${jt(/^https?:\/\//.test(t.loc)?t.loc:`${n}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${jt(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${jt(String(t.changefreq))}</changefreq>`]:[],...void 0!==t.priority?[` <priority>${Bt(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n";return{status:200,contentType:ct,body:r,cacheControl:dt(e.cacheTtlSeconds??Xe)}}function Vt(e){if(!e)return!1;let t=0,n=0;for(const r of e.split(",")){const[e,...s]=r.trim().split(";"),i=e.trim().toLowerCase();let o=1;for(const e of s){const[t,n]=e.split("=").map(e=>e.trim());if("q"===t){const e=Number(n);Number.isNaN(e)||(o=e)}}"text/markdown"===i||"text/x-markdown"===i?t=Math.max(t,o):"text/html"!==i&&"text/*"!==i&&"*/*"!==i||(n=Math.max(n,o))}return t>0&&t>=n}async function zt(e,t){const n=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===n){return vt(t,await bt(t))}if(n===rt)return $t(t);if("/.well-known/http-message-signatures-directory"===n)return Tt(t);if("/.well-known/security.txt"===n)return Pt(t);if(n===`${et}/index.json`)return Et(t);if(n.startsWith(`${et}/`)&&n.endsWith("SKILL.md"))return It(n,t);if("/.well-known/oauth-authorization-server"===n||"/.well-known/openid-configuration"===n){const e=(await bt(t)).authorizationServer;if(!e?.metadataUrl)return null;const n=await async function(e,t){const n=t.cacheTtlSeconds??Xe,r=gt(t),s=`buildbase:as-metadata:${e}`,i=await yt(r,s);if(i.hit)return i.value;const o=t.fetch??fetch;let a=null;try{const n=await kt(o,e,{headers:{Accept:st}},t.fetchTimeoutMs??5e3);if(n.ok){const e=await n.json();e&&"object"==typeof e&&(a=e)}}catch{}return await wt(r,s,a,n),a}(e.metadataUrl,t);return Lt(n?n:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(n===tt)return Ot(t);if(n===nt)return Nt(t);if("/.well-known/mcp.json"===n)return Ft(t);if(n.startsWith(Ze)){const e=await bt(t);return xt(n,t,e.authorizationServer?.issuer)}return null}function Kt(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 Gt(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4==0?"":"=".repeat(4-t.length%4),r=atob(t+n),s=new Uint8Array(r.length);for(let e=0;e<r.length;e++)s[e]=r.charCodeAt(e);return s}class Ht extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function Qt(e){const t=JSON.parse((new TextDecoder).decode(Gt(e)));if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("JWT segment is not a JSON object");return t}function Yt(e,t,n={}){const r=n.clockToleranceSec??60,s=n.requireExp??!0;if(!e||!t)throw new Ht("invalid_token","Missing token or client secret");const i=e.split(".");if(3!==i.length)throw new Ht("invalid_token","Malformed JWT");const[o,a,c]=i;let l,u;try{l=Qt(o),u=Qt(a)}catch{throw new Ht("invalid_token","Unreadable JWT segments")}if("HS256"!==l.alg)throw new Ht("invalid_algorithm",`Unexpected JWT alg: ${String(l.alg)}`);const d=Ge(Ke(t),Ke(`${o}.${a}`));let p;try{p=Gt(c)}catch{throw new Ht("invalid_signature","Unreadable JWT signature")}if(!He(d,p))throw new Ht("invalid_signature","JWT signature verification failed");!function(e){for(const t of["iss","sub","jti"])if(void 0!==e[t]&&"string"!=typeof e[t])throw new Ht("invalid_token",`JWT ${t} claim must be a string`);for(const t of["exp","nbf","iat"]){const n=e[t];if(void 0!==n&&("number"!=typeof n||!Number.isFinite(n)))throw new Ht("invalid_token",`JWT ${t} claim must be a finite number`)}const t=e.aud;if(!(void 0===t||"string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new Ht("invalid_token","JWT aud claim must be a string or string array")}(u);const h=Math.floor(Date.now()/1e3);if(s&&"number"!=typeof u.exp)throw new Ht("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof u.exp&&h>u.exp+r)throw new Ht("token_expired","JWT has expired");if("number"==typeof u.nbf&&h+r<u.nbf)throw new Ht("token_not_yet_valid","JWT is not yet valid");if(void 0!==n.issuer&&u.iss!==n.issuer)throw new Ht("invalid_issuer","JWT issuer mismatch");if(void 0!==n.audience){const e=u.aud;if(!(Array.isArray(e)?e.includes(n.audience):e===n.audience))throw new Ht("invalid_audience","JWT audience mismatch")}return u}function Xt(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function Zt(e){return Kt(Ke(JSON.stringify(e)))}function en(e,t,n){if(!t)throw new Ht("invalid_secret","Missing signing secret");const r=Math.floor(Date.now()/1e3),s={iat:r,exp:r+(n?.expiresInSec??3600),...e},i=`${Zt({alg:"HS256",typ:"JWT"})}.${Zt(s)}`;return`${i}.${Kt(Ge(Ke(t),Ke(i)))}`}function tn(e){const t=Xt(e.authorization);if(!t)throw new Ht("invalid_token","Missing Bearer token");return Yt(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function nn(e){const t=Xt(e.authorization);if(!t)throw new Ht("invalid_token","Missing Bearer token");return Yt(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function rn(e){return{success:!0,token:e.token,message:e.message??"ok",..."number"==typeof e.expiresIn?{expiresIn:e.expiresIn}:{}}}function sn(e){return{success:!1,token:"",message:e}}function on(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}const an=12,cn=16;function ln(){const e=globalThis.crypto;if(!e?.subtle)throw new Error("WebCrypto is unavailable in this runtime — agent-auth session encryption requires globalThis.crypto.subtle (Node 18+, Bun, Deno, edge, browsers).");return e.subtle}const un=new Map;function dn(e){let t=un.get(e);return t||(t=(async()=>{const t=await ln().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return ln().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),un.set(e,t)),t}function pn(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(t){const n=globalThis.crypto.getRandomValues(new Uint8Array(an)),r=await dn(e),s=new Uint8Array(await ln().encrypt({name:"AES-GCM",iv:n},r,(new TextEncoder).encode(t))),i=s.subarray(s.length-cn),o=s.subarray(0,s.length-cn),a=new Uint8Array(28+o.length);return a.set(n,0),a.set(i,an),a.set(o,28),Kt(a)},async decryptSessionRef(t){try{const n=Gt(t);if(n.length<=28)return null;const r=n.slice(0,an),s=n.subarray(an,28),i=n.subarray(28),o=new Uint8Array(i.length+cn);o.set(i,0),o.set(s,i.length);const a=await dn(e),c=await ln().decrypt({name:"AES-GCM",iv:r},a,o);return(new TextDecoder).decode(c)}catch{return null}}}}function hn(e,t,n){const r=globalThis.process?.env;"1"===r?.MCP_AUTH_DEBUG&&console.warn(`[buildbase/mcp-auth] audience rejected (${n}): received aud=${JSON.stringify(e)} expected one of ${JSON.stringify(t)}`)}const fn=function(){const e=new Map;return{get(t){const n=e.get(t);if(n){if(!(n.expiresAt<=Date.now()))return n.value;e.delete(t)}},set(t,n,r){e.set(t,{value:n,expiresAt:Date.now()+1e3*r})},delete(t){e.delete(t)},clear(){e.clear()}}}(),gn=e=>e.replace(/\/+$/,""),mn=(e,t)=>`buildbase:org-region:${gn(e)}::${t}`;function yn(e){const{serverUrl:t,orgId:n,version:r="v1",region:s,getSessionId:i,timeout:o,maxRetries:a,debug:c,headers:l,onError:u,fetch:d}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!n)throw new Error("BuildBase: orgId is required");const p={...void 0!==o&&{timeout:o},...void 0!==a&&{maxRetries:a},...void 0!==c&&{debug:c},...l&&{headers:l},...u&&{onError:u},...d&&{fetch:d}},h=e=>{const s={serverUrl:t,version:r,orgId:n,sessionId:e,...p};return{workspace:new L(s),user:new C(s),settings:new P(s),push:new _(s),devices:new S(s),uploads:new T(s),sessions:new I(s)}},f=new L({serverUrl:t,version:r,orgId:n,...p}),g=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,n)=>(await e()).workspace.updateWorkspace(t,n),delete:async t=>(await e()).workspace.deleteWorkspace(t),permissions:async t=>(await e()).workspace.getMyPermissions(t),can:async(t,n)=>{const{permissions:r}=await(await e()).workspace.getMyPermissions(t),s=new Set(r);return(Array.isArray(n)?n:[n]).every(e=>s.has(e))}},invitations:{list:async t=>(await e()).workspace.listInvitations(t),create:async(t,n,r,s)=>(await e()).workspace.inviteMember(t,{email:n,role:r,landingUrl:s}),resend:async(t,n)=>(await e()).workspace.resendInvitation(t,n),revoke:async(t,n)=>(await e()).workspace.revokeInvitation(t,n)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,n,r)=>(await e()).workspace.addUser(t,{email:n,role:r}),remove:async(t,n)=>(await e()).workspace.removeUser(t,n),updateRole:async(t,n,r)=>(await e()).workspace.updateUser(t,n,{role:r}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,n)=>(await e()).workspace.createCheckoutSession(t,n),update:async(t,n)=>(await e()).workspace.updateSubscription(t,n),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,n)=>(await e()).workspace.createBillingPortalSession(t,n)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>f.getPublicPlans(e),getVersion:e=>f.getPlanGroupVersion(e)},invoices:{list:async(t,n,r)=>(await e()).workspace.listInvoices(t,n,r),get:async(t,n)=>(await e()).workspace.getInvoice(t,n)},usage:{record:async(t,n)=>(await e()).workspace.recordUsage(t,n),recordBatch:async(t,n)=>(await e()).workspace.recordUsageBatch(t,n),getQuota:async(t,n)=>(await e()).workspace.getQuotaUsageStatus(t,n),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,n)=>(await e()).workspace.getUsageLogs(t,n)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,n,r)=>(await e()).workspace.updateFeature(t,n,r)},notification:{send:async(t,n,r,s)=>(await e()).workspace.sendNotification(t,n,r,s)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,n)=>(await e()).workspace.consumeCredits(t,n),purchase:async(t,n)=>(await e()).workspace.purchaseCredits(t,n),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,n)=>(await e()).workspace.getCreditTransactions(t,n),getBuckets:async(t,n)=>(await e()).workspace.getCreditBuckets(t,n),getExpiring:async(t,n)=>(await e()).workspace.getExpiringCredits(t,n),getPublicPackages:()=>f.getPublicCreditPackages()},permissions:{check:async(t,n,r)=>{const s=await e(),[i,o,a]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),c=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return Ce(r,{userId:n,workspaceRole:c?.role??null,workspace:i,settings:o})},resolve:async(t,n)=>{const r=await e(),[s,i,o]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),a=o.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return $e({userId:n,workspaceRole:a?.role??null,workspace:s,settings:i})}},devices:{list:async()=>(await e()).devices.list(),rename:async(t,n)=>(await e()).devices.rename(t,n),signOut:async t=>(await e()).devices.signOut(t),forget:async t=>(await e()).devices.forget(t)},sessions:{list:async()=>(await e()).sessions.list(),revoke:async t=>(await e()).sessions.revoke(t)}}),m=g(async()=>h(await(async()=>{if(!i)throw new Error("BuildBase: getSessionId callback is required for authenticated calls. Pass it in BuildBase({ getSessionId: ... }) or use withSession(id) / client.forSession(id).");const e=await i();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{...void 0!==s&&{region:s},auth:async()=>{if(!i)return null;const e=await i();return e?{sessionId:e}:null},withSession:e=>{const t=h(e);return g(async()=>t)},client:{forSession:h},...m}}exports.AI_BOT_USER_AGENTS=lt,exports.APP_PERMISSION_FALLBACK_GROUP=Oe,exports.AppBridgeError=Ht,exports.AuthApi=class extends b{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n="Failed to initiate authentication",r=e=>this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});let s=await r(e);if(400===s.status&&(e.trackingConsent||e.trackingIdentity||e.trackingAttribution||e.invitationToken)){const{trackingConsent:t,trackingIdentity:n,trackingAttribution:i,invitationToken:o,...a}=e;s=await r(a)}return s.ok||await this.throwResponseError(s,n),this.unwrapResponse(s,n)}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}async getDeviceToken(e,t){try{const n=await this.fetchUnwrapped("device-token",{headers:{"x-session-id":e},signal:t},"Failed to fetch device token");return n?.deviceToken??""}catch{return""}}async logout(e,t,n){await this.fetchJson("logout",{method:"POST",...e?{headers:{"x-session-id":e}}:{},...t?.all?{body:JSON.stringify({all:!0})}:{},signal:n},"Failed to sign out")}},exports.BBAction=G,exports.BBScreen=Q,exports.BBStatus=H,exports.BB_PARAM=K,exports.BaseApi=b,exports.BetaForm=class{constructor(e){this.api=new v(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},n=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),r=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),s=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),i=t?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:n,language:r,timezone:s,currency:i}})}},exports.BillingIntervals=ye,exports.BuildBase=yn,exports.CURRENCY_DISPLAY=se,exports.CURRENCY_FLAG=ie,exports.CreditBucketSource={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},exports.CreditBucketStatus={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},exports.CreditTransactionType={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"},exports.DEFAULT_ROLE_PERMISSIONS=Pe,exports.DISCOVERY_CACHE_TIMEOUT_MS=500,exports.DunningState={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},exports.EventEmitter=M,exports.FALLBACK_WORKSPACE_ROLE=Ae,exports.INVITATION_ERROR_CODE=O,exports.InvoiceStatuses={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},exports.NotificationsApi=class extends b{constructor(e){super(e)}async list(e={},t){const n=await this.fetchJson(`notifications${x({workspaceId:e.workspaceId,unread:e.unread,archived:e.archived,page:e.page,limit:e.limit})}`,{signal:t},"Failed to load notifications");return{notifications:n?.notifications??[],page:n?.page??e.page??1,limit:n?.limit??e.limit??20,total:n?.total??0,hasNextPage:Boolean(n?.hasNextPage)}}async counts(e,t){const n=await this.fetchJson(`notifications/unread-count${x({workspaceId:e})}`,{signal:t},"Failed to load notification count");return{unread:n?.unread??0,unseen:n?.unseen??0}}markRead(e){return this.itemAction(this.apiPath`notifications/${e}/read`,"POST",!0)}markUnread(e){return this.itemAction(this.apiPath`notifications/${e}/unread`,"POST")}archive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"POST")}unarchive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"DELETE")}async markAllRead(e){await this.fetchJson("notifications/read-all",{method:"POST",body:E(e)},"Failed to mark notifications read")}async markSeen(e){await this.fetchJson("notifications/seen",{method:"POST",body:E(e)},"Failed to mark notifications seen")}async itemAction(e,t,n=!1){return this.fetchJson(e,n?{method:t,keepalive:n}:{method:t},"Failed to update notification")}},exports.PLAN_CURRENCY_CODES=ae,exports.PLAN_CURRENCY_OPTIONS=ce,exports.PUSH_SERVICE_WORKER_SCRIPT="\n// BuildBase Push Notification Service Worker\n// Place this file in your app's public directory (e.g. public/push-sw.js)\n\nself.addEventListener('push', function(event) {\n if (!event.data) return;\n\n let payload;\n try {\n payload = event.data.json();\n } catch (e) {\n console.error('[PushSW] Push payload is not JSON:', e);\n return;\n }\n if (!payload || typeof payload !== 'object') return;\n\n // i18n exception: service workers run outside the SDK's translation\n // provider, so this last-resort fallback stays English. The server should\n // always send a localized payload.title.\n const title = payload.title || 'Notification';\n // The tracked click URL (/api/push-track/link/...) wins over any url in\n // payload.data, so a click is always counted.\n const data = Object.assign({}, payload.data && typeof payload.data === 'object' ? payload.data : {});\n if (payload.url) data.url = payload.url;\n // A notification with the same tag replaces the earlier one instead of\n // stacking. No tag means every notification is shown on its own.\n const tag = payload.tag ? String(payload.tag) : undefined;\n const actions = Array.isArray(payload.actions)\n ? payload.actions.filter(function(a) {\n return a && typeof a.action === 'string' && typeof a.title === 'string';\n })\n : undefined;\n\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.badge || payload.icon || undefined,\n image: payload.image || undefined,\n tag: tag,\n // The browser rejects renotify without a tag.\n renotify: tag ? !!payload.renotify : false,\n actions: actions && actions.length ? actions : undefined,\n silent: !!payload.silent,\n requireInteraction: !!payload.requireInteraction,\n timestamp: typeof payload.timestamp === 'number' ? payload.timestamp : undefined,\n dir: payload.dir === 'ltr' || payload.dir === 'rtl' ? payload.dir : 'auto',\n data: data,\n };\n\n event.waitUntil(\n Promise.resolve()\n .then(function() {\n return self.registration.showNotification(title, options);\n })\n .catch(function(e) {\n // A field this browser refuses must not cost the user the\n // notification: show it again with the basics only.\n console.error('[PushSW] Failed to show notification, retrying without rich options:', e);\n return self.registration.showNotification(title, {\n body: options.body,\n icon: options.icon,\n tag: tag,\n data: data,\n });\n })\n );\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\n // A click on an action button (event.action is its id) opens the same\n // tracked URL as a click on the notification body.\n const url = event.notification.data && event.notification.data.url;\n if (url) {\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {\n for (let i = 0; i < clientList.length; i++) {\n const client = clientList[i];\n if (client.url === url && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(url);\n }\n })\n );\n }\n});\n",exports.Permission=_e,exports.PushApi=_,exports.SDKEvent=D,exports.SettingsApi=P,exports.SubscriptionItemType={Feature:"feature",Limit:"limit",Quota:"quota"},exports.SubscriptionStatus={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},exports.UPLOAD_ACCEPT="image/png,image/jpeg,image/gif,image/webp,image/svg+xml",exports.UPLOAD_MAX_BYTES=A,exports.UploadsApi=T,exports.UserApi=C,exports.WEBHOOK_EVENTS=Be,exports.WEBHOOK_EVENTS_BY_CATEGORY=Je,exports.WorkspaceApi=L,exports.actionableInvitations=function(e,t=new Date){return Fe(e.filter(e=>We(e,t)))},exports.appPermissionCatalogue=function(e,t){const n=e?.workspace?.customPermissions??[],r=new Map;for(const e of n)e?.key&&!e.key.startsWith("workspace:")&&r.set(e.key,{key:e.key,label:e.label||e.key,group:e.group||Oe});for(const e of Object.values(t??{}))for(const t of e??[])t.startsWith("workspace:")||r.has(t)||r.set(t,{key:t,label:t,group:Oe});return[...r.values()].sort((e,t)=>(e.group??"").localeCompare(t.group??"")||e.key.localeCompare(t.key))},exports.appTokenFailure=sn,exports.appTokenSuccess=rn,exports.bearerChallenge=function(e){const t=[`Bearer resource_metadata="${on(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${on(e.error)}"`),e.errorDescription&&t.push(`error_description="${on(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}},exports.buildA2AAgentCard=$t,exports.buildAgentCard=vt,exports.buildAgentSkillsIndex=Et,exports.buildApiCatalog=Ot,exports.buildAuthMd=Wt,exports.buildDiscoveryLinkHeader=function(e){const t=ut(e.siteUrl),n=[`<${t}/llms.txt>; rel="describedby"; type="text/plain"`,`<${t}/.well-known/agent.json>; rel="describedby"; type="application/json"`];if(!1!==e.a2aCard&&n.push(`<${t}${rt}>; rel="describedby"; type="application/json"`),e.sitemap||e.robots?.sitemaps?.length){const r=e.robots?.sitemaps?.[0]??`${t}/sitemap.xml`;n.push(`<${r}>; rel="sitemap"; type="application/xml"`)}return e.apiCatalog?.length&&n.push(`<${t}${tt}>; rel="api-catalog"; type="${it}"`),e.mcpServerCard&&n.push(`<${t}${nt}>; rel="mcp-server"; type="application/json"`),n.join(", ")},exports.buildDnsAidRecords=function(e){let t;try{t=new URL(e.siteUrl).hostname}catch{return[]}const n=[{name:`_index._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${t}. alpn="h2" port=443`}];if(!1!==e.a2aCard&&n.push({name:`_a2a._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${t}. alpn="h2" port=443`}),e.mcpServerCard){let r=t;try{r=new URL(e.mcpServerCard.endpoint).hostname}catch{}n.push({name:`_mcp._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${r}. alpn="h2" port=443`})}return n},exports.buildLlmsFullTxt=Ut,exports.buildLlmsTxt=At,exports.buildMcpDiscoveryManifest=Ft,exports.buildMcpServerCard=Nt,exports.buildProtectedResourceMetadata=xt,exports.buildRobotsTxt=Jt,exports.buildSecurityTxt=Pt,exports.buildSitemap=qt,exports.buildSkillMd=It,exports.buildWebBotAuthDirectory=Tt,exports.buildbaseAuth=function(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const n=pn(t),r=e.resource?Array.isArray(e.resource)?e.resource:[e.resource]:[];let s=e.resourceMetadataUrl;if(!s&&r.length)try{const e=new URL(r[0]),t="/"===e.pathname?"":e.pathname.replace(/\/+$/,"");s=`${e.origin}/.well-known/oauth-protected-resource${t}`}catch{}return{resourceMetadataUrl:s,verify:async s=>{let i;try{i=Yt(s,t,{...e.verify})}catch{return null}if(r.length){const t=i.aud?Array.isArray(i.aud)?i.aud:[i.aud]:[];if(!t.length&&e.requireAudience)return hn(t,r,"token carries no aud claim"),null;if(t.length&&!t.some(e=>r.includes(e)))return hn(t,r,"aud does not include this resource"),null}const o="string"==typeof i.sid?await n.decryptSessionRef(i.sid):null,a=Array.isArray(i.scope)?i.scope.filter(e=>"string"==typeof e):"string"==typeof i.scope?i.scope.split(" ").filter(Boolean):void 0;return{sessionId:o??"",userId:"string"==typeof i.userId?i.userId:"string"==typeof i.sub?i.sub:void 0,workspaceId:"string"==typeof i.workspaceId?i.workspaceId:void 0,scopes:a,claims:i}}}},exports.calculateBillableSeats=xe,exports.calculateSeatOverageCents=Ee,exports.calculateTotalSubscriptionCents=function(e,t,n,r){const s=ke(e,t,n);return null===s?null:void 0===r?s:s+(Ee(e,t,n,r)??0)},exports.cleanBBParams=function(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(K)&&(e.searchParams.delete(K),window.history.replaceState({},"",e.toString()))}catch{}},exports.clearAgentReadinessCache=function(e){ht.clear();const t=e;if(t?.delete){for(const e of ft)try{const n=t.delete(e);n&&"function"==typeof n.then&&n.catch(()=>{})}catch{}ft.clear()}else ft.clear()},exports.clearAuthIntent=function(){u(ne)},exports.clearPendingInvite=function(){u(Le)},exports.clearResolvedServerUrl=async function(e){const t=mn(e.centralUrl,e.orgId),n=e.cache;if(fn.delete?.(t),n?.delete)try{await n.delete(t)}catch{}},exports.consumeAuthIntent=function(){const e=d(ne,re);return u(ne),e?Date.now()-e.createdAt>6e5?null:te(e.returnUrl,{sameOrigin:!0}):null},exports.createBBUrl=Y,exports.createCheckoutRedirectUrls=function(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:Y({action:G.Checkout,status:H.Success,ws:e,screen:Q.Subscription},n),cancelUrl:Y({action:G.Checkout,status:H.Cancel,ws:e,screen:Q.Subscription},n)}},exports.createCreditPurchaseRedirectUrls=function(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:Y({action:G.CreditPurchase,status:H.Success,ws:e,screen:Q.Credits},n),cancelUrl:Y({action:G.CreditPurchase,status:H.Cancel,ws:e,screen:Q.Credits},n)}},exports.createSessionRefCrypto=pn,exports.default=yn,exports.eventEmitter=J,exports.extractBearerToken=Xt,exports.fetchAgentReadiness=bt,exports.formatCents=fe,exports.formatMinorAmountIntl=function(e,t,n="en-US"){const r=(t??"").trim(),s=pe(r),i=e/10**s;if(!r)return i.toFixed(s);try{return new Intl.NumberFormat(n,{style:"currency",currency:r.toUpperCase(),minimumFractionDigits:s,maximumFractionDigits:s}).format(i)}catch{return oe(r)+(0===s?i.toLocaleString("en-US"):i.toFixed(s))}},exports.formatOverageRate=function(e,t,n,r,s){if(null==e||e<0)return null;const i={...ge,...r},o=null!=t&&t>=1?t:1,a=oe(n),c=he(e,n);return 1===o?`${a}${c}/${i.unit}`:`${a}${c}/${o.toLocaleString(s)} ${i.units}`},exports.formatOverageRateWithLabel=function(e,t,n,r,s,i,o){if(null==e||e<0)return null;const a={...ge,...i},c=null!=t&&t>=1?t:1,l=oe(r),u=he(e,r);if(n){const e=s??(n.endsWith("s")?n:`${n}s`);return c>=2?`${l}${u}/${c.toLocaleString(o)} ${e}`:`${l}${u}/${n}`}return 1===c?`${l}${u}/${a.unit}`:`${l}${u}/${c.toLocaleString(o)} ${a.units}`},exports.formatQuotaIncludedOverage=function(e,t,n,r,s,i,o,a,c){const l={...ge,...o};if(!1===a)return null!=e?`${l.included}: ${e.toLocaleString(c)} (${l.hardLimit})`:o?.hardLimit??"Hard limit";const u=i??(n.endsWith("s")?n:`${n}s`),d=null!=s&&s>=2?`${s.toLocaleString(c)} ${u}`:n;return null!=e&&null!=t?`${l.included}: ${e.toLocaleString(c)}, ${l.afterThat} ${fe(t,r)}/${d}`:null!=e?`${l.included}: ${e.toLocaleString(c)}`:null!=t?`${l.afterIncluded}: ${fe(t,r)}/${d}`:"—"},exports.formatQuotaWithPrice=function(e,t,n={}){const{overageInCents:r=!0,currency:s}=n,i={...me,...n.labels},o=n.currencySymbol??oe(s??"");if(null==e)return"—";const{included:a,overage:c}=e,l=`${a} ${i.included}`;if(!1===e.allowOverage)return`${l} (${i.hardLimit})`;if(null==c)return l;const u=pe(s),d=r&&u>0?c/10**u:c,p="number"==typeof d&&Number.isFinite(d)?0===u?d.toLocaleString("en-US"):d.toFixed(u):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${i.then} ${o}${p}${h}`},exports.formatUploadLimit=function(e,t){const n=1048576,[r,s]=e>=n?[e/n,"megabyte"]:[e/1024,"kilobyte"];try{return new Intl.NumberFormat(t,{style:"unit",unit:s,unitDisplay:"short",maximumFractionDigits:1}).format(r)}catch{return`${Math.round(10*r)/10} ${"megabyte"===s?"MB":"KB"}`}},exports.getAvailableBillingIntervals=function(e,t){return[ye.Monthly,ye.Quarterly,ye.Yearly].filter(n=>n===ye.Monthly||e.some(e=>null!=ke(e,t,n)))},exports.getAvailableCurrenciesFromPlans=function(e){const t=new Set;for(const n of e)n.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()},exports.getBasePriceCents=ke,exports.getBillingIntervalAndCurrencyFromPriceId=function(e,t){if(!e)return null;for(const n of t){const t=n.pricingVariants;if(t?.length)for(const n of t){const t=n.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:n.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:n.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:n.currency}}}}return null},exports.getCurrencyDecimals=pe,exports.getCurrencyFlag=function(e){return e&&e.trim()?ie[e.trim().toLowerCase()]??"":""},exports.getCurrencySymbol=oe,exports.getDisplayCurrency=function(e,t){const n=we(e,t);return n?n.currency:e.plan?.currency??""},exports.getPerSeatPriceCents=Se,exports.getPricingVariant=we,exports.getQuotaDisplayValue=function(e,t){if(null==e)return null;const n=e[t??"monthly"];return n?{included:n.included,...void 0!==n.overage&&{overage:n.overage},...void 0!==n.unitSize&&{unitSize:n.unitSize},allowOverage:!1!==e.allowOverage}:null},exports.getQuotaDisplayWithVariant=function(e,t,n,r){const s=e.quotas?.[n];if(null==s)return null;const i=s[r];if(!i)return null;const o=be(e,t,n,r);return{included:i.included,...void 0!==i.unitSize&&{unitSize:i.unitSize},...void 0!==o&&{overage:o},allowOverage:!1!==s.allowOverage}},exports.getQuotaOverageCents=be,exports.getQuotaUnitLabelFromName=function(e,t="unit"){const n=(e||"").trim().toLowerCase();if(!n)return t;const r=n.split(/\s+/)[0]??n;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(r)?r:r.endsWith("ies")&&r.length>3?r.slice(0,-3)+"y":r.endsWith("ses")||r.endsWith("xes")||r.endsWith("zes")||r.endsWith("ches")||r.endsWith("shes")?r.slice(0,-2):r.endsWith("s")&&!r.endsWith("ss")&&r.length>1?r.slice(0,-1):r||t},exports.getSeatPricing=ve,exports.getStripePriceIdForInterval=function(e,t,n){const r=we(e,t);if(!r?.stripePrices)return null;const s=n===ye.Monthly?"monthlyPriceId":n===ye.Yearly?"yearlyPriceId":"quarterlyPriceId",i=n===ye.Monthly?"monthly":n===ye.Yearly?"yearly":void 0;return r.stripePrices[s]??(i?r.stripePrices[i]:void 0)??null},exports.handleAppRevokeRequest=async function(e){let t;try{t=nn(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof Ht?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}},exports.handleAppTokenRequest=async function(e){let t;try{t=tn(e)}catch(e){return{status:401,body:sn(e instanceof Ht?e.code:"invalid_token")}}return{status:200,body:rn(await e.mintToken(t))}},exports.hasPermission=Ce,exports.invalidateCreditBalance=q,exports.invalidateQuotaUsage=V,exports.invalidateSubscription=z,exports.inviterNameOf=function(e){const t=e.invitedBy;return t&&"string"!=typeof t&&(t.name||t.email)||null},exports.isInvitationActionable=We,exports.isInvitationError=function(e){return e instanceof Error&&"number"==typeof e.status},exports.isInvitationLapsed=function(e,t=new Date){return"expired"===e.status||"invited"===e.status&&!We(e,t)},exports.isWebhookEvent=function(e){return je.has(e)},exports.isZeroDecimalCurrency=function(e){return""!==(e??"").trim()&&0===pe(e)},exports.minorAmountToDisplay=he,exports.mintAgentToken=async function(e){const{claims:t,secret:n}=e,r=e.expiresInSec??3600,s=t.resource&&t.resource.length?1===t.resource.length?t.resource[0]:t.resource:void 0,i=t.sessionId?await pn(n).encryptSessionRef(t.sessionId):void 0;return{token:en({sub:t.id,userId:t.id,email:t.email,...t.name?{name:t.name}:{},...t.scope?{scope:t.scope}:{},...s?{aud:s}:{},...i?{sid:i}:{},...e.extraClaims},n,{expiresInSec:r}),expiresIn:r}},exports.negotiateMarkdown=function(e,t,n){const r=Vt(e);return{status:200,contentType:r?ot:"text/html; charset=utf-8",body:r?t.markdown:t.html,cacheControl:dt(n?.cacheTtlSeconds??Xe),vary:"Accept"}},exports.parkPendingInvite=function(e,t){De.test(e)&&t&&p(Le,{token:e,orgId:t,createdAt:Date.now()})},exports.parseWebhookEvent=function(e){if(!Ye(e))return null;try{return JSON.parse(e.body)}catch{return null}},exports.pickDefaultRole=function(e,t){return t&&"admin"!==t&&e.includes(t)?t:e.includes(Ae)?Ae:e.find(e=>"admin"!==e)??""},exports.preflightUpload=function(e,t){return t.enabled?e.size>t.maxFileBytes?"tooLarge":null:"disabled"},exports.provideWebMcpTools=function(e){const t=globalThis.navigator;return!!t?.modelContext?.provideContext&&(t.modelContext.provideContext({tools:e}),!0)},exports.readBBParams=function(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(K);if(!e)return null;const t=function(e){const t={};if(!e)return t;const n=e.split(",");for(const e of n){const n=e.indexOf(":");if(-1===n)continue;const r=decodeURIComponent(e.slice(0,n)),s=decodeURIComponent(e.slice(n+1));r&&(t[r]=s)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}},exports.readPendingInvite=function(e,t=Date.now()){const n=d(Le,Me);return n?t-n.createdAt>864e5?(u(Le),null):n.orgId!==e?null:De.test(n.token)?n.token:(u(Le),null):null},exports.resendCooldownSeconds=function(e,t=new Date){const n=Ne(e.resendAvailableAt);return n?Math.max(0,Math.ceil((n-t.getTime())/1e3)):0},exports.resolveAgentPath=async function(e,t){const n=e.replace(/\/+$/,"")||e,r=function(e,t){const n=t.extraPaths?.[e];if(void 0===n)return null;const r="string"==typeof n?{body:n}:n;return{status:r.status??200,contentType:r.contentType??Ct(e),body:r.body,cacheControl:r.cacheControl??dt(t.cacheTtlSeconds??Xe)}}(n,t);return r||("/robots.txt"===n?Jt(t):"/llms-full.txt"===n?Ut(t):"/sitemap.xml"===n?qt(t):"/llms.txt"===n?At(t):"/auth.md"===n?Wt(t,await bt(t)):"/security.txt"===n?Pt(t):n.startsWith("/.well-known")?zt(n,t):null)},exports.resolveMaxUsers=function(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=ve(t,n);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=r&&r>0?{maxUsers:r,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}},exports.resolvePermissions=$e,exports.resolveRolePermissions=Te,exports.resolveServerUrl=async function(e){const{orgId:t,centralUrl:n,apiKey:r,timeoutMs:s=5e3}=e;if(!t)throw new Error("resolveServerUrl: orgId is required");if(!n)throw new Error("resolveServerUrl: centralUrl is required");const i=e.cache??fn,o=mn(n,t);try{const e=await i.get(o);if(e)return JSON.parse(e)}catch{}const a=e.fetch??fetch,c=`${gn(n)}/api/organizations/orgs/${encodeURIComponent(t)}/region`,l=new AbortController,u=s>0?setTimeout(()=>l.abort(),s):null;let d;try{d=await a(c,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},signal:l.signal})}finally{u&&clearTimeout(u)}if(!d.ok)throw new Error(`resolveServerUrl: central answered ${d.status} for org ${t}`);const p=await d.json(),h=p?.data??p;if(!h||"string"!=typeof h.serverUrl||!h.serverUrl)throw new Error(`resolveServerUrl: central returned no serverUrl for org ${t}`);const f={orgId:h.orgId||t,region:h.region||"us",cellId:h.cellId||"us",serverUrl:gn(h.serverUrl)},g=function(e){const t=e.headers.get("cache-control")||"";if(/(?:^|[\s,])(?:no-store|no-cache)(?:$|[\s,=])/i.test(t))return 0;const n=/max-age=(\d+)/i.exec(t);if(!n)return 300;const r=Number(n[1]);return!Number.isFinite(r)||r<0?300:Math.min(r,3600)}(d);if(g>0)try{await i.set(o,JSON.stringify(f),g)}catch{}return f},exports.resolveWellKnown=zt,exports.safeRedirect=function(e,t="/",n={}){if("undefined"==typeof window||!window.location)return!1;const r=te(e,n)??te(t)??"/";return function(e){if("undefined"==typeof window||!window.location||0===ee.size)return;let t;try{t=new URL(e,window.location.href).origin}catch{return}if(t!==window.location.origin)for(const e of ee)try{e()}catch{}}(r),window.location.href=r,!0},exports.saveAuthIntent=function(e){te(e,{sameOrigin:!0})&&p(ne,{returnUrl:e,createdAt:Date.now()})},exports.sha256Digest=pt,exports.signClientJwt=en,exports.sortInvitations=Fe,exports.uploadFailureOf=function(e){const{status:t,code:n}=e??{};return"UPLOAD_TOO_LARGE"===n||413===t?"tooLarge":"INVALID_UPLOAD"===n?"invalid":"UPLOADS_DISABLED"===n?"disabled":"USER_UPLOAD_LIMIT"===n?"userLimit":"UPLOADS_UNAVAILABLE"===n||429===t||501===t||503===t?"unavailable":"failed"},exports.uploadPolicyOf=function(e){const t=e?.uploads,n=Number(t?.maxFileBytes);return{enabled:!!t&&!1!==t.enabled,maxFileBytes:Number.isFinite(n)&&n>0?Math.min(n,A):A}},exports.validateInvite=function(e){const{memberCount:t,maxUsersConfig:n,hasSubscription:r=!0,requireSubscription:s=!1}=e;if(s&&!r)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:i,source:o}=n;if(i<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=i){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[o]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[o]??"users.memberLimitMessage",blockMessageValues:{maxUsers:i}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}},exports.validateRedirectUrl=te,exports.verifyAppRevokeRequest=nn,exports.verifyAppTokenRequest=tn,exports.verifyClientJwt=Yt,exports.verifyWebhookSignature=Ye,exports.wantsMarkdown=Vt,exports.workspaceIdOf=function(e){return"object"==typeof e.workspace&&e.workspace?e.workspace._id:e.workspace},exports.workspaceNameOf=function(e){return"object"==typeof e.workspace&&e.workspace&&e.workspace.name||""};
|
package/dist/index.d.ts
CHANGED
|
@@ -3991,7 +3991,7 @@ declare function clearPendingInvite(): void;
|
|
|
3991
3991
|
*
|
|
3992
3992
|
* Source: packages/shared/src/constants/system-events.ts (SYSTEM_EVENTS) in the
|
|
3993
3993
|
* BuildBase platform repo, grouped as its EVENT_CATEGORIES does. Copied on
|
|
3994
|
-
* 2026-10-
|
|
3994
|
+
* 2026-10-17, with email.complained added; 113 names. Refresh it when
|
|
3995
3995
|
* that file changes - the server emits exactly these names in the
|
|
3996
3996
|
* `x-buildbase-event` header and the body's `event` field, and a handler that
|
|
3997
3997
|
* switches on a name not in this list never runs.
|
|
@@ -4011,7 +4011,7 @@ declare const WEBHOOK_EVENTS_BY_CATEGORY: {
|
|
|
4011
4011
|
readonly Credit: readonly ["credit.purchased", "credit.consumed", "credit.expired", "credit.granted", "credit.revoked", "credit.low_balance"];
|
|
4012
4012
|
readonly Workflow: readonly ["workflow.created", "workflow.deleted", "workflow.published", "workflow.paused", "workflow.resumed", "workflow.instance_completed", "workflow.instance_failed"];
|
|
4013
4013
|
readonly Audience: readonly ["audience.member_created", "audience.member_updated", "audience.added_to_list", "audience.removed_from_list", "audience.attribute_changed", "audience.tag_added", "audience.tag_removed", "audience.unsubscribed", "audience.resubscribed", "audience.email_invalidated", "audience.blocked", "audience.unblocked", "audience.import_completed", "audience.list_created", "audience.list_updated", "audience.list_deleted"];
|
|
4014
|
-
readonly Email: readonly ["email.domain_added", "email.domain_verified", "email.sent", "email.opened", "email.clicked", "email.bounced", "email.unsubscribed", "email.campaign_sent"];
|
|
4014
|
+
readonly Email: readonly ["email.domain_added", "email.domain_verified", "email.sent", "email.opened", "email.clicked", "email.bounced", "email.complained", "email.unsubscribed", "email.campaign_sent"];
|
|
4015
4015
|
readonly Push: readonly ["push.campaign_sent"];
|
|
4016
4016
|
readonly Auth: readonly ["auth.method_deleted", "auth.domain_added", "auth.domain_verified", "auth.domain_deleted", "auth.client_self_registered"];
|
|
4017
4017
|
readonly Token: readonly ["token.created", "token.updated", "token.revoked"];
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
let e=!0;function t(t,...n){e&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(t,...n)}function n(e,...t){console.error(e,...t)}function r(e,t){const n=AbortSignal.any;if("function"==typeof n)return n([e,t]);const r=new AbortController,i=e=>{r.signal.aborted||r.abort(e.reason)};for(const n of[e,t]){if(n.aborted){i(n);break}n.addEventListener("abort",()=>i(n),{once:!0})}return r.signal}async function i(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function s(e,t="Request failed"){if(!e.ok){let n,r=t;try{const t=await i(e);r=t.message||t.error||r,"string"==typeof t.code&&(n=t.code)}catch{r=function(e,t){const n={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${n})`)}(e,t).message}throw Object.assign(new Error(r),{status:e.status,...n?{code:n}:{}})}try{return await i(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class a extends Error{constructor(e,t,n,r){super(e),this.code=t,this.context=n,this.originalError=r,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,a)}}const o=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1},this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}configure(t){this.config={...this.config,...t},void 0!==t.enableConsoleLogging&&function(t){void 0!==t.enableLogging&&(e=t.enableLogging)}({enableLogging:t.enableConsoleLogging})}handleError(e,r={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const i=e instanceof Error?e:new a("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",r),s=i instanceof a?i:new a(i.message,"SDK_ERROR",r,i);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${r.component||"Unknown"}:`,{message:s.message,code:s.code,context:s.context,originalError:s.originalError,stack:s.stack}),this.config.onError)try{this.config.onError(s,r)}catch(e){n("[SDK Error Handler] Error in custom error callback:",e)}for(const e of this.listeners)try{e(s,r)}catch(e){n("[SDK Error Handler] Error in error listener:",e)}this.config.showUserNotifications&&this.notifyUser(s,r)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...n)=>e(...n).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...n)=>{try{return e(...n)}catch(e){throw this.handleError(e,t),e}}}};function c(e,t={}){o.handleError(e,t)}function l(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return c(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function u(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){c(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function d(e,t){const n=l(e);if(!n)return null;try{const r=JSON.parse(n);return t&&!t(r)?(c(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),u(e),null):r}catch(t){return c(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),u(e),null}}function p(e,t){try{!function(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){c(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){c(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const h="saas-session-id",f="saas-device-id";function g(){return function(){if("undefined"==typeof window)return null;try{return l(h)}catch(e){return c(e,{component:"auth-utils",action:"getSessionId",metadata:{key:h}}),null}}()}function m(){const e=g(),t={};e&&(t["x-session-id"]=e);const n=function(){if("undefined"==typeof window)return null;try{return l(f)??null}catch(e){return c(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:f}}),null}}();return n&&(t["x-device-id"]=n),t}const w=new WeakSet,y=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),k="SDK is not ready (missing serverUrl, version, or orgId)";class b{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(k);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(k)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:m()}url(e){const t=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${t}`}buildHeaders(e){const t={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(t,e.headers),null==e.body||t["Content-Type"]||(t["Content-Type"]="application/json"),t}reportError(e,t){w.has(e)||(w.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}static delay(e,t){return new Promise((n,r)=>{const i=()=>{clearTimeout(s),r(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return i();const s=setTimeout(()=>{t?.removeEventListener("abort",i),n()},e);t?.addEventListener("abort",i,{once:!0})})}async executeFetchUrl(e,t,n){const i=(t.method??"GET").toUpperCase(),s=n??e,a=this.buildHeaders(t),o={...t,headers:a},c=y.has(i);let l,u;if(this._timeout>0){u=new AbortController;const e=u;l=setTimeout(()=>e.abort(),this._timeout),o.signal=t.signal?r(t.signal,e.signal):e.signal}const d=e=>{if(u?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${i} ${s}`);return this.reportError(e,{method:i,path:s}),e}return e},p=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const n=this._fetch.bind(globalThis),r=await n(e,o);if(this._debug&&console.log(`[BuildBase] ${i} ${e} → ${r.status}`),401===r.status&&this._onUnauthorized&&this._onUnauthorized(),r.status>=500&&c&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await b.delay(e,o.signal),p(t+1)}return r}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw d(e);if(c&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await b.delay(e,o.signal)}catch(e){throw d(e)}return p(t+1)}throw e instanceof Error&&this.reportError(e,{method:i,path:s}),e}};try{return await p(0)}finally{void 0!==l&&clearTimeout(l)}}async fetchJson(e,t={},n="Request failed"){this.ensureReady();try{const r=await this.executeFetch(e,t);return await s(r,n)}catch(n){throw n instanceof Error&&this.reportError(n,{method:(t.method??"GET").toUpperCase(),path:e}),n}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchUnwrapped(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);return r.ok||await this.throwResponseError(r,n),this.unwrapResponse(r,n)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async fetchForeign(e,t={}){return this._fetch.call(globalThis,e,t)}async throwResponseError(e,t){let n=t;try{n=(await e.json()).message||n}catch{n=`${t} (${e.status}: ${e.statusText})`}throw Object.assign(new Error(n),{status:e.status})}apiPath(e,...t){return e.reduce((e,n,r)=>e+n+(r<t.length?encodeURIComponent(String(t[r])):""),"")}async unwrapResponse(e,t){const n=await e.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||t);return void 0!==n.data?n.data:n}return n}}class v extends b{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n="Failed to initiate authentication",r=e=>this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});let i=await r(e);if(400===i.status&&(e.trackingConsent||e.trackingIdentity||e.trackingAttribution||e.invitationToken)){const{trackingConsent:t,trackingIdentity:n,trackingAttribution:s,invitationToken:a,...o}=e;i=await r(o)}return i.ok||await this.throwResponseError(i,n),this.unwrapResponse(i,n)}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}async getDeviceToken(e,t){try{const n=await this.fetchUnwrapped("device-token",{headers:{"x-session-id":e},signal:t},"Failed to fetch device token");return n?.deviceToken??""}catch{return""}}async logout(e,t,n){await this.fetchJson("logout",{method:"POST",...e?{headers:{"x-session-id":e}}:{},...t?.all?{body:JSON.stringify({all:!0})}:{},signal:n},"Failed to sign out")}}class S extends b{constructor(e){super({...e,basePath:"beta",requireOrgId:!0})}getAuthHeaders(){return{}}async fetchConfig(){return this.fetchJson(`config?orgId=${encodeURIComponent(this.orgId)}`,{},"Failed to fetch beta form configuration")}async submitBetaUser(e){return this.fetchJson("submit",{method:"POST",body:JSON.stringify(e)},"Failed to submit beta user request")}}class E{constructor(e){this.api=new S(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},n=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),r=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),i=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),s=t?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:n,language:r,timezone:i,currency:s}})}}class _ extends b{constructor(e){super(e)}async list(e){const t=await this.fetchJson("devices",{signal:e},"Failed to load devices");return t?.devices??[]}async rename(e,t,n){await this.fetchJson(this.apiPath`devices/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename device")}async signOut(e,t){return this.fetchJson(this.apiPath`devices/${e}`,{method:"DELETE",signal:t},"Failed to sign out device")}async forget(e,t){return this.fetchJson(`${this.apiPath`devices/${e}`}?forget=true`,{method:"DELETE",signal:t},"Failed to forget device")}}function I(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))void 0!==r&&""!==r&&!1!==r&&t.set(n,String(r));const n=t.toString();return n?`?${n}`:""}const $=e=>JSON.stringify(e?{workspaceId:e}:{});class P extends b{constructor(e){super(e)}async list(e={},t){const n=await this.fetchJson(`notifications${I({workspaceId:e.workspaceId,unread:e.unread,archived:e.archived,page:e.page,limit:e.limit})}`,{signal:t},"Failed to load notifications");return{notifications:n?.notifications??[],page:n?.page??e.page??1,limit:n?.limit??e.limit??20,total:n?.total??0,hasNextPage:Boolean(n?.hasNextPage)}}async counts(e,t){const n=await this.fetchJson(`notifications/unread-count${I({workspaceId:e})}`,{signal:t},"Failed to load notification count");return{unread:n?.unread??0,unseen:n?.unseen??0}}markRead(e){return this.itemAction(this.apiPath`notifications/${e}/read`,"POST",!0)}markUnread(e){return this.itemAction(this.apiPath`notifications/${e}/unread`,"POST")}archive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"POST")}unarchive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"DELETE")}async markAllRead(e){await this.fetchJson("notifications/read-all",{method:"POST",body:$(e)},"Failed to mark notifications read")}async markSeen(e){await this.fetchJson("notifications/seen",{method:"POST",body:$(e)},"Failed to mark notifications seen")}async itemAction(e,t,n=!1){return this.fetchJson(e,n?{method:t,keepalive:n}:{method:t},"Failed to update notification")}}class U extends b{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}class T extends b{constructor(e){super(e)}async list(e){const t=await this.fetchJson("sessions",{signal:e},"Failed to load sessions");return t?.sessions??[]}async revoke(e,t){await this.fetchJson(this.apiPath`sessions/${e}`,{method:"DELETE",signal:t},"Failed to sign out session")}}class A extends b{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}const C="image/png,image/jpeg,image/gif,image/webp,image/svg+xml",O=5242880,x={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml"};function R(e){if(e.type)return e.type;const t=(e.name??"").split(".").pop()?.toLowerCase()??"";return x[t]??""}function N(e){const{status:t,code:n}=e??{};return"UPLOAD_TOO_LARGE"===n||413===t?"tooLarge":"INVALID_UPLOAD"===n?"invalid":"UPLOADS_DISABLED"===n?"disabled":"USER_UPLOAD_LIMIT"===n?"userLimit":"UPLOADS_UNAVAILABLE"===n||429===t||501===t||503===t?"unavailable":"failed"}function F(e){const t=e?.uploads,n=Number(t?.maxFileBytes);return{enabled:!!t&&!1!==t.enabled,maxFileBytes:Number.isFinite(n)&&n>0?Math.min(n,O):O}}function W(e,t){return t.enabled?e.size>t.maxFileBytes?"tooLarge":null:"disabled"}function L(e,t){const n=1048576,[r,i]=e>=n?[e/n,"megabyte"]:[e/1024,"kilobyte"];try{return new Intl.NumberFormat(t,{style:"unit",unit:i,unitDisplay:"short",maximumFractionDigits:1}).format(r)}catch{return`${Math.round(10*r)/10} ${"megabyte"===i?"MB":"KB"}`}}class D extends b{constructor(e){super(e)}async upload(e,t){const{purpose:n,signal:i}=t,s=await this.fetchJson("uploads",{method:"POST",body:JSON.stringify({purpose:n,name:e.name??"file",size:e.size,contentType:R(e)}),signal:i},"Could not start the upload");let a;const o=new AbortController,c=setTimeout(()=>o.abort(),12e4);try{a=await this.fetchForeign(s.url,{method:"PUT",headers:s.headers,body:e,signal:i?r(i,o.signal):o.signal})}catch(e){if(i?.aborted)throw e;throw new Error("The upload to storage did not finish. Check the connection and try again.")}finally{clearTimeout(c)}if(!a.ok)throw Object.assign(new Error(`The upload to storage was refused (HTTP ${a.status}). Try again.`),{status:a.status});return this.fetchJson(this.apiPath`uploads/${s.uploadId}/complete`,{method:"POST",body:"{}",signal:i},"Could not finish the upload")}}class J extends b{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const n=await this.unwrapResponse(t,"Failed to fetch user attributes");return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const n=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof n&&null!==n?n:{}}}const M={NOT_FOUND:"INVITATION_NOT_FOUND",EXPIRED:"INVITATION_EXPIRED",ALREADY_HANDLED:"INVITATION_ALREADY_HANDLED",EMAIL_MISMATCH:"INVITATION_EMAIL_MISMATCH",EMAIL_NOT_VERIFIED:"EMAIL_NOT_VERIFIED",INVITES_DISABLED:"WORKSPACE_INVITES_DISABLED",RATE_LIMITED:"INVITATION_RATE_LIMITED",EMAIL_FAILED:"INVITATION_EMAIL_FAILED",SEAT_LIMIT:"SEAT_LIMIT_REACHED",USER_BLOCKED:"USER_BLOCKED",NO_SENDER_CONFIGURED:"NO_SENDER_CONFIGURED"},j={402:M.SEAT_LIMIT,404:M.NOT_FOUND,409:M.ALREADY_HANDLED,410:M.EXPIRED,429:M.RATE_LIMITED,502:M.EMAIL_FAILED,503:M.NO_SENDER_CONFIGURED};function B(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function q(e){return"string"==typeof e&&e?e:void 0}async function z(e,t){let n=null;try{n=await e.json()}catch{n=null}return function(e,t,n){const r=t&&"object"==typeof t?t:{},i=q(r.message)??q(r.error)??n,s={status:e,code:q(r.code)??j[e]??`HTTP_${e}`,currentUserCount:B(r.currentUserCount),limit:B(r.limit),retryAfterSeconds:B(r.retryAfterSeconds),invitedEmail:q(r.invitedEmail),invitationId:q(r.invitationId),invitationStatus:q(r.status)};return Object.assign(new Error(i),s)}(e.status,n,t)}function V(e){return e instanceof Error&&"number"==typeof e.status}class K extends b{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){try{return await this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}catch(n){const r=n?.status;if(400===r&&e.trackingAttribution){const{trackingAttribution:n,...r}=e;return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(r),signal:t},"Failed to create workspace")}throw n}}async updateWorkspace(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:n},"Failed to update workspace")}async deleteWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE",signal:t},"Failed to delete workspace")}async getWorkspaceUsers(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{signal:t},"Failed to fetch workspace users")}async addUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to invite member")}async fetchInvitation(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);if(!r.ok)throw await z(r,n);return s(r,n)}async listInvitations(e,t){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{signal:t},"Failed to fetch invitations")}async inviteMember(e,t,n){const r={email:t.email,role:t.role};return t.landingUrl&&(r.landingUrl=t.landingUrl),this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{method:"POST",body:JSON.stringify(r),signal:n},"Failed to send invitation")}async resendInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}/resend`,{method:"POST",signal:n},"Failed to resend invitation")}async revokeInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}`,{method:"DELETE",signal:n},"Failed to revoke invitation")}async myInvitations(e){return this.fetchInvitation("invitations",{signal:e},"Failed to fetch your invitations")}async acceptInvitation(e,t,n){return this.fetchInvitation(this.apiPath`invitations/${e}/accept`,{method:"PATCH",signal:n,...t?.token?{body:JSON.stringify({token:t.token})}:{}},"Failed to accept invitation")}async declineInvitation(e,t){return this.fetchInvitation(this.apiPath`invitations/${e}/reject`,{method:"PATCH",signal:t},"Failed to decline invitation")}async previewInvitation(e,t){if(!this.orgId)throw new Error("orgId is required for previewInvitation");return this.fetchInvitation(this.apiPath`${this.orgId}/invitations/preview/${e}`,{signal:t},"Failed to load invitation")}async removeUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:n},"Failed to remove user")}async updateUser(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(n),signal:r},"Failed to update user")}async updateSettings(e,t){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:n},"Failed to update workspace permissions")}async getMyPermissions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/permissions/me`,{signal:t},"Failed to fetch workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:n}}),signal:r},"Failed to update feature")}async getWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{signal:t},"Failed to fetch workspace")}async getProfile(e){return this.fetchJson("profile",{signal:e},"Failed to fetch profile")}async updateUserProfile(e,t){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update user profile")}async getPasskeys(e){const t=await this.fetchJson("passkeys",{signal:e},"Failed to fetch passkeys");return t?.passkeys??[]}async renamePasskey(e,t,n){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename passkey")}async deletePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE",signal:t},"Failed to remove passkey")}async getCurrentSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{signal:t},"Failed to fetch subscription")}async getPlanGroup(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`,{signal:t},"Failed to fetch plan group")}async getPlanGroupByVersion(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch plan group version")}async getPlanGroupVersions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group/versions`,{signal:t},"Failed to fetch plan group versions")}async getPublicPlans(e,t){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");return this.fetchUnwrapped(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`,{signal:t},"Failed to fetch plans")}async getPublicCreditPackages(e){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");return this.fetchUnwrapped(this.apiPath`${this.orgId}/credit-packages`,{signal:e},"Failed to fetch credit packages")}async getPlanGroupVersion(e,t){return this.fetchUnwrapped(this.apiPath`plan-group-versions/${e}`,{signal:t},"Failed to fetch plan group version")}async createCheckoutSession(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create checkout session")}async selectFreePlan(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:n},"Failed to select free plan")}async updateSubscription(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:n},"Failed to update subscription")}async createBillingPortalSession(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:n})}async listInvoices(e,t=10,n,r){const i=new URLSearchParams;return i.append("limit",t.toString()),n&&i.append("starting_after",n),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${i.toString()}`,{signal:r},"Failed to fetch invoices")}async getInvoice(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:n},"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST",signal:t},"Failed to cancel subscription")}async resumeSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST",signal:t},"Failed to resume subscription")}async recordUsage(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record usage")}async recordUsageBatch(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch quota usage status")}async getAllQuotaUsage(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/all`,{signal:t},"Failed to fetch all quota usage")}async getUsageLogs(e,t,n){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const i=r.toString(),s=this.apiPath`workspaces/${e}/subscription/usage/logs`+(i?`?${i}`:"");return this.fetchUnwrapped(s,{signal:n},"Failed to fetch usage logs")}async sendNotification(e,t,n,r,i){const s={event:t};return n&&(s.userId=n),r&&(s.data=r),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(s),signal:i},"Failed to send notification")}async getNotificationEvents(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{signal:t},"Failed to fetch notification events")}async getNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{signal:t},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t,n){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update notification preferences")).notificationPreferences??{}}async getMyNotificationPreferences(e,t){const n=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{signal:t},"Failed to fetch your notification preferences");return{defaults:n?.defaults??{},mine:n?.mine??{}}}async updateMyNotificationPreferences(e,t,n){const r=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update your notification preferences");return{defaults:r?.defaults??{},mine:r?.mine??{}}}async getCreditBalance(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits`,{signal:t},"Failed to fetch credit balance")}async consumeCredits(e,t,n){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:n});if(!r.ok){if(402===r.status){const e=await r.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(r,"Failed to consume credits")}return this.unwrapResponse(r,"Failed to consume credits")}async purchaseCredits(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const n=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return n.docs??n}async getCreditTransactions(e,t,n){const r=new URLSearchParams;t?.type&&r.append("type",t.type),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const i=r.toString(),s=this.apiPath`workspaces/${e}/credits/transactions`+(i?`?${i}`:"");return this.fetchUnwrapped(s,{signal:n},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,n){const r=new URLSearchParams;t?.status&&r.append("status",t.status),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const i=r.toString(),s=this.apiPath`workspaces/${e}/credits/buckets`+(i?`?${i}`:"");return this.fetchUnwrapped(s,{signal:n},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,n){const r=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+r,{signal:n},"Failed to fetch expiring credits")}}var G;!function(e){e.V1="v1"}(G||(G={}));const H={UserCreated:"user:created",UserUpdated:"user:updated",WorkspaceChanged:"workspace:changed",WorkspaceUpdated:"workspace:updated",WorkspaceUserAdded:"workspace:user-added",WorkspaceUserRemoved:"workspace:user-removed",WorkspaceUserRoleChanged:"workspace:user-role-changed",WorkspaceCreated:"workspace:created",WorkspaceDeleted:"workspace:deleted",WorkspaceInvitationSent:"workspace:invitation-sent",WorkspaceInvitationAccepted:"workspace:invitation-accepted",WorkspaceInvitationDeclined:"workspace:invitation-declined",WorkspaceInvitationRevoked:"workspace:invitation-revoked"};class Q{constructor(){this.callbacks=null,this.listeners=new Map}setCallbacks(e){this.callbacks=e}getCallbacks(){return this.callbacks}async emit(e,t){if(this.callbacks?.handleEvent)try{await this.callbacks.handleEvent(e,t)}catch(t){c(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}const n=this.listeners.get(e);if(n)for(const r of[...n])try{r(t)}catch(t){c(t,{component:"EventEmitter",action:"notifyListener",metadata:{eventType:e}})}}on(e,t){const n=this.listeners.get(e)??new Set;return n.add(t),this.listeners.set(e,n),()=>{this.listeners.get(e)?.delete(t)}}async emitUserCreated(e){await this.emit(H.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(H.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(H.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(H.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(H.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceInvitationSent(e,t){await this.emit(H.WorkspaceInvitationSent,{invitation:e,workspaceId:t})}async emitWorkspaceInvitationAccepted(e,t){await this.emit(H.WorkspaceInvitationAccepted,{invitation:e,workspace:t})}async emitWorkspaceInvitationDeclined(e){await this.emit(H.WorkspaceInvitationDeclined,{invitation:e})}async emitWorkspaceInvitationRevoked(e,t){await this.emit(H.WorkspaceInvitationRevoked,{invitationId:e,workspaceId:t})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(H.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(H.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(H.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(H.WorkspaceDeleted,{workspace:e})}}const Y=new Q,X=globalThis;function Z(e){const t=Symbol.for(`@buildbase/sdk.invalidation.${e}`),n=X[t]??(X[t]=new Set);return{subscribe:e=>(n.add(e),()=>{n.delete(e)}),invalidate(){n.forEach(e=>e())},reset(){n.clear()}}}const ee=Z("credit-balance").invalidate,te=Z("quota-usage").invalidate,ne=Z("subscription").invalidate,re="bb",ie={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},se={Success:"success",Cancel:"cancel",Error:"error"},ae={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function oe(e,t){const n=t??("undefined"!=typeof window?window.location.href:"https://localhost");let r;try{r=new URL(n)}catch{throw new Error(`createBBUrl: invalid base URL: ${JSON.stringify(n)}`)}return r.search="",r.searchParams.set(re,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}function ce(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:oe({action:ie.Checkout,status:se.Success,ws:e,screen:ae.Subscription},n),cancelUrl:oe({action:ie.Checkout,status:se.Cancel,ws:e,screen:ae.Subscription},n)}}function le(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:oe({action:ie.CreditPurchase,status:se.Success,ws:e,screen:ae.Credits},n),cancelUrl:oe({action:ie.CreditPurchase,status:se.Cancel,ws:e,screen:ae.Credits},n)}}function ue(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(re);if(!e)return null;const t=function(e){const t={};if(!e)return t;const n=e.split(",");for(const e of n){const n=e.indexOf(":");if(-1===n)continue;const r=decodeURIComponent(e.slice(0,n)),i=decodeURIComponent(e.slice(n+1));r&&(t[r]=i)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}}function de(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(re)&&(e.searchParams.delete(re),window.history.replaceState({},"",e.toString()))}catch{}}const pe="__buildbaseBeforeLeave",he=globalThis,fe=he[pe]??(he[pe]=new Set);function ge(e,t={}){if(!e||"string"!=typeof e)return null;if(/^\/(?![/\\])/.test(e))return e;let n;try{n=new URL(e)}catch{return null}const r="https:"===n.protocol,i="http:"===n.protocol&&("localhost"===n.hostname||"127.0.0.1"===n.hostname||"[::1]"===n.hostname);if(!r&&!i)return null;const{sameOrigin:s,allowedOrigins:a}=t;return s||a?.length?s&&"undefined"!=typeof window&&window.location&&n.origin===window.location.origin||a?.some(e=>e.replace(/\/+$/,"")===n.origin)?e:null:e}function me(e,t="/",n={}){if("undefined"==typeof window||!window.location)return!1;const r=ge(e,n)??ge(t)??"/";return function(e){if("undefined"==typeof window||!window.location||0===fe.size)return;let t;try{t=new URL(e,window.location.href).origin}catch{return}if(t!==window.location.origin)for(const e of fe)try{e()}catch{}}(r),window.location.href=r,!0}const we="saas-auth-intent";function ye(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function ke(e){ge(e,{sameOrigin:!0})&&p(we,{returnUrl:e,createdAt:Date.now()})}function be(){const e=d(we,ye);return u(we),e?Date.now()-e.createdAt>6e5?null:ge(e.returnUrl,{sameOrigin:!0}):null}function ve(){u(we)}const Se={usd:"$",eur:"€",gbp:"£",jpy:"¥",cad:"CA$",aud:"A$",chf:"CHF",cny:"¥",hkd:"HK$",sgd:"S$",inr:"₹",mxn:"MX$",brl:"R$",nzd:"NZ$",sek:"kr",nok:"kr",dkk:"kr",pln:"zł",thb:"฿"},Ee={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function _e(e){return e&&e.trim()?Ee[e.trim().toLowerCase()]??"":""}function Ie(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return Se[t]??t.toUpperCase()}const $e=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],Pe=$e.map(e=>({value:e,label:`${e.toUpperCase()} (${Ie(e)})`})),Ue=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),Te=new Set(["bhd","jod","kwd","omr","tnd"]),Ae=new Map;function Ce(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(Ue.has(t))return 0;if(Te.has(t))return 3;if("isk"===t)return 2;let n=Ae.get(t);if(void 0===n){try{n=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{n=2}Ae.set(t,n)}return n}function Oe(e){return""!==(e??"").trim()&&0===Ce(e)}function xe(e,t){const n=Ce(t);return 0===n?e.toLocaleString("en-US"):(e/10**n).toFixed(n)}function Re(e,t,n="en-US"){const r=(t??"").trim(),i=Ce(r),s=e/10**i;if(!r)return s.toFixed(i);try{return new Intl.NumberFormat(n,{style:"currency",currency:r.toUpperCase(),minimumFractionDigits:i,maximumFractionDigits:i}).format(s)}catch{return Ie(r)+(0===i?s.toLocaleString("en-US"):s.toFixed(i))}}function Ne(e,t){return Ie(t)+xe(e,t)}const Fe={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};function We(e,t,n,r,i){if(null==e||e<0)return null;const s={...Fe,...r},a=null!=t&&t>=1?t:1,o=Ie(n),c=xe(e,n);return 1===a?`${o}${c}/${s.unit}`:`${o}${c}/${a.toLocaleString(i)} ${s.units}`}function Le(e,t,n,r,i,s,a){if(null==e||e<0)return null;const o={...Fe,...s},c=null!=t&&t>=1?t:1,l=Ie(r),u=xe(e,r);if(n){const e=i??(n.endsWith("s")?n:`${n}s`);return c>=2?`${l}${u}/${c.toLocaleString(a)} ${e}`:`${l}${u}/${n}`}return 1===c?`${l}${u}/${o.unit}`:`${l}${u}/${c.toLocaleString(a)} ${o.units}`}function De(e,t="unit"){const n=(e||"").trim().toLowerCase();if(!n)return t;const r=n.split(/\s+/)[0]??n;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(r)?r:r.endsWith("ies")&&r.length>3?r.slice(0,-3)+"y":r.endsWith("ses")||r.endsWith("xes")||r.endsWith("zes")||r.endsWith("ches")||r.endsWith("shes")?r.slice(0,-2):r.endsWith("s")&&!r.endsWith("ss")&&r.length>1?r.slice(0,-1):r||t}function Je(e,t,n,r,i,s,a,o,c){const l={...Fe,...a};if(!1===o)return null!=e?`${l.included}: ${e.toLocaleString(c)} (${l.hardLimit})`:a?.hardLimit??"Hard limit";const u=s??(n.endsWith("s")?n:`${n}s`),d=null!=i&&i>=2?`${i.toLocaleString(c)} ${u}`:n;return null!=e&&null!=t?`${l.included}: ${e.toLocaleString(c)}, ${l.afterThat} ${Ne(t,r)}/${d}`:null!=e?`${l.included}: ${e.toLocaleString(c)}`:null!=t?`${l.afterIncluded}: ${Ne(t,r)}/${d}`:"—"}function Me(e,t){if(null==e)return null;const n=e[t??"monthly"];return n?{included:n.included,...void 0!==n.overage&&{overage:n.overage},...void 0!==n.unitSize&&{unitSize:n.unitSize},allowOverage:!1!==e.allowOverage}:null}const je={included:"included",then:"then",hardLimit:"hard limit"};function Be(e,t,n={}){const{overageInCents:r=!0,currency:i}=n,s={...je,...n.labels},a=n.currencySymbol??Ie(i??"");if(null==e)return"—";const{included:o,overage:c}=e,l=`${o} ${s.included}`;if(!1===e.allowOverage)return`${l} (${s.hardLimit})`;if(null==c)return l;const u=Ce(i),d=r&&u>0?c/10**u:c,p="number"==typeof d&&Number.isFinite(d)?0===u?d.toLocaleString("en-US"):d.toFixed(u):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${s.then} ${a}${p}${h}`}const qe={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},ze={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},Ve={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},Ke={Feature:"feature",Limit:"limit",Quota:"quota"},Ge={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},He={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},Qe={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},Ye={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function Xe(e,t){const n=e.pricingVariants;if(!n?.length)return null;const r=t.toLowerCase();return n.find(e=>e.currency?.toLowerCase()===r)??null}function Ze(e,t,n){const r=Xe(e,t);if(!r?.basePricing)return null;const i=r.basePricing[n];return null!=i?i:null}function et(e,t,n){const r=Xe(e,t);if(!r?.stripePrices)return null;const i=n===qe.Monthly?"monthlyPriceId":n===qe.Yearly?"yearlyPriceId":"quarterlyPriceId",s=n===qe.Monthly?"monthly":n===qe.Yearly?"yearly":void 0;return r.stripePrices[i]??(s?r.stripePrices[s]:void 0)??null}function tt(e,t,n,r){const i=Xe(e,t),s=i?.quotaOverages?.[n];if(s)return s[r]}function nt(e,t){const n=Xe(e,t);return n?n.currency:e.plan?.currency??""}function rt(e){const t=new Set;for(const n of e)n.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()}function it(e,t,n,r){const i=e.quotas?.[n];if(null==i)return null;const s=i[r];if(!s)return null;const a=tt(e,t,n,r);return{included:s.included,...void 0!==s.unitSize&&{unitSize:s.unitSize},...void 0!==a&&{overage:a},allowOverage:!1!==i.allowOverage}}function st(e,t){if(!e)return null;for(const n of t){const t=n.pricingVariants;if(t?.length)for(const n of t){const t=n.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:n.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:n.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:n.currency}}}}return null}function at(e,t){const n=Xe(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function ot(e,t,n){const r=at(e,t);return r?.perSeat?r.perSeat[n]??null:null}function ct(e,t){return Math.max(0,e-(t||0))}function lt(e,t,n,r){const i=at(e,t);if(!i)return null;return ct(r,i.includedSeats)*(ot(e,t,n)??0)}function ut(e,t,n,r){const i=Ze(e,t,n);if(null===i)return null;if(void 0===r)return i;return i+(lt(e,t,n,r)??0)}function dt(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=at(t,n);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=r&&r>0?{maxUsers:r,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function pt(e){const{memberCount:t,maxUsersConfig:n,hasSubscription:r=!0,requireSubscription:i=!1}=e;if(i&&!r)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:s,source:a}=n;if(s<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=s){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[a]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[a]??"users.memberLimitMessage",blockMessageValues:{maxUsers:s}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}function ht(e,t){return[qe.Monthly,qe.Quarterly,qe.Yearly].filter(n=>n===qe.Monthly||e.some(e=>null!=Ze(e,t,n)))}const ft={WORKSPACE_SETTINGS_VIEW:"workspace:settings:view",WORKSPACE_SETTINGS_EDIT:"workspace:settings:edit",WORKSPACE_DELETE:"workspace:delete",WORKSPACE_MEMBERS_VIEW:"workspace:members:view",WORKSPACE_MEMBERS_INVITE:"workspace:members:invite",WORKSPACE_MEMBERS_REMOVE:"workspace:members:remove",WORKSPACE_MEMBERS_ROLE_CHANGE:"workspace:members:role-change",WORKSPACE_FEATURES_VIEW:"workspace:features:view",WORKSPACE_FEATURES_EDIT:"workspace:features:edit",WORKSPACE_BILLING_VIEW:"workspace:billing:view",WORKSPACE_BILLING_MANAGE:"workspace:billing:manage",WORKSPACE_USAGE_VIEW:"workspace:usage:view",WORKSPACE_USAGE_RECORD:"workspace:usage:record"},gt=Object.values(ft),mt={admin:gt.filter(e=>e!==ft.WORKSPACE_DELETE),editor:[ft.WORKSPACE_SETTINGS_VIEW,ft.WORKSPACE_MEMBERS_VIEW,ft.WORKSPACE_FEATURES_VIEW,ft.WORKSPACE_BILLING_VIEW,ft.WORKSPACE_USAGE_VIEW,ft.WORKSPACE_USAGE_RECORD],viewer:[ft.WORKSPACE_SETTINGS_VIEW,ft.WORKSPACE_MEMBERS_VIEW]},wt="viewer";function yt(e,t){return t&&"admin"!==t&&e.includes(t)?t:e.includes(wt)?wt:e.find(e=>"admin"!==e)??""}function kt(e){const t=new Set;for(const n of Object.values(e))for(const e of n)t.add(e);return Array.from(t)}function bt(e){const{userId:t,workspace:n,settings:r,appPermissions:i}=e;if(!n||!t)return new Set;if(function(e,t){if(!t)return!1;const n=(r=e.createdBy)?"string"==typeof r?r:"object"==typeof r&&"_id"in r&&"string"==typeof r._id?r._id:null:null;var r;return null!==n&&n===t}(n,t)){const e=new Set(gt);if(i)for(const t of kt(i))e.add(t);if(n.permissions)for(const t of kt(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of kt(r.workspace.permissions))e.add(t);return e}const s=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const n=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return n&&"object"==typeof n&&"role"in n&&"string"==typeof n.role?n.role:null}(n,t);return s?vt(s,e):new Set}function vt(e,t,n={}){const{workspace:r,settings:i,appPermissions:s}=t;if(!r)return new Set;const a=r.permissions,o=i?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),l=e=>e.filter(e=>!e.startsWith("workspace:")),u=e=>!!a&&e in a,d=e=>!!o&&e in o,p=e=>u(e)||d(e)||e in mt;let h,f=e;if(!p(e)){const e=i?.workspace?.defaultRole;if(!e||"admin"===e||!p(e))return new Set;f=e}h=u(f)?c(a[f]):d(f)?c(o[f]):mt[f]??[];const g=new Set(h),m=new Set((i?.workspace?.customPermissions??[]).map(e=>e.key)),w=s?.[f]?l(s[f]).filter(e=>!m.has(e)):[];let y;y=u(f)?l(a[f]):d(f)?[...l(o[f]),...w]:s?.[f]?l(s[f]):[];for(const e of y)g.add(e);if("admin"===f){for(const e of mt.admin)g.add(e);for(const e of m)g.add(e);if(s)for(const e of l(kt(s)))g.add(e)}return!1!==n.applyRestrictions&&function(e,t,n){if(!n?.workspace)return;const{canInviteMembers:r}=n.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(ft.WORKSPACE_MEMBERS_INVITE)}(g,f,i),g}function St(e,t){const n=bt(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}const Et="App";function _t(e,t){const n=e?.workspace?.customPermissions??[],r=new Map;for(const e of n)e?.key&&!e.key.startsWith("workspace:")&&r.set(e.key,{key:e.key,label:e.label||e.key,group:e.group||Et});for(const e of Object.values(t??{}))for(const t of e??[])t.startsWith("workspace:")||r.has(t)||r.set(t,{key:t,label:t,group:Et});return[...r.values()].sort((e,t)=>(e.group??"").localeCompare(t.group??"")||e.key.localeCompare(t.key))}const It="\n// BuildBase Push Notification Service Worker\n// Place this file in your app's public directory (e.g. public/push-sw.js)\n\nself.addEventListener('push', function(event) {\n if (!event.data) return;\n\n let payload;\n try {\n payload = event.data.json();\n } catch (e) {\n console.error('[PushSW] Push payload is not JSON:', e);\n return;\n }\n if (!payload || typeof payload !== 'object') return;\n\n // i18n exception: service workers run outside the SDK's translation\n // provider, so this last-resort fallback stays English. The server should\n // always send a localized payload.title.\n const title = payload.title || 'Notification';\n // The tracked click URL (/api/push-track/link/...) wins over any url in\n // payload.data, so a click is always counted.\n const data = Object.assign({}, payload.data && typeof payload.data === 'object' ? payload.data : {});\n if (payload.url) data.url = payload.url;\n // A notification with the same tag replaces the earlier one instead of\n // stacking. No tag means every notification is shown on its own.\n const tag = payload.tag ? String(payload.tag) : undefined;\n const actions = Array.isArray(payload.actions)\n ? payload.actions.filter(function(a) {\n return a && typeof a.action === 'string' && typeof a.title === 'string';\n })\n : undefined;\n\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.badge || payload.icon || undefined,\n image: payload.image || undefined,\n tag: tag,\n // The browser rejects renotify without a tag.\n renotify: tag ? !!payload.renotify : false,\n actions: actions && actions.length ? actions : undefined,\n silent: !!payload.silent,\n requireInteraction: !!payload.requireInteraction,\n timestamp: typeof payload.timestamp === 'number' ? payload.timestamp : undefined,\n dir: payload.dir === 'ltr' || payload.dir === 'rtl' ? payload.dir : 'auto',\n data: data,\n };\n\n event.waitUntil(\n Promise.resolve()\n .then(function() {\n return self.registration.showNotification(title, options);\n })\n .catch(function(e) {\n // A field this browser refuses must not cost the user the\n // notification: show it again with the basics only.\n console.error('[PushSW] Failed to show notification, retrying without rich options:', e);\n return self.registration.showNotification(title, {\n body: options.body,\n icon: options.icon,\n tag: tag,\n data: data,\n });\n })\n );\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\n // A click on an action button (event.action is its id) opens the same\n // tracked URL as a click on the notification body.\n const url = event.notification.data && event.notification.data.url;\n if (url) {\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {\n for (let i = 0; i < clientList.length; i++) {\n const client = clientList[i];\n if (client.url === url && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(url);\n }\n })\n );\n }\n});\n";var $t;function Pt(e){if(!e)return 0;const t=new Date(e).getTime();return Number.isNaN(t)?0:t}function Ut(e){const t=e=>"invited"===e.status?0:1;return[...e].sort((e,n)=>t(e)-t(n)||Pt(n.invitedAt)-Pt(e.invitedAt))}function Tt(e,t=new Date){return"invited"===e.status&&(null===e.validTill||void 0===e.validTill||Pt(e.validTill)>t.getTime())}function At(e,t=new Date){return Ut(e.filter(e=>Tt(e,t)))}function Ct(e,t=new Date){return"expired"===e.status||"invited"===e.status&&!Tt(e,t)}function Ot(e){return"object"==typeof e.workspace&&e.workspace&&e.workspace.name||""}function xt(e){return"object"==typeof e.workspace&&e.workspace?e.workspace._id:e.workspace}function Rt(e){const t=e.invitedBy;return t&&"string"!=typeof t&&(t.name||t.email)||null}function Nt(e,t=new Date){const n=Pt(e.resendAvailableAt);return n?Math.max(0,Math.ceil((n-t.getTime())/1e3)):0}!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}($t||($t={}));const Ft="saas-pending-invite",Wt=/^[0-9a-f]{64}$/;function Lt(e){return"object"==typeof e&&null!==e&&"string"==typeof e.token&&"string"==typeof e.orgId&&"number"==typeof e.createdAt}function Dt(e,t){Wt.test(e)&&t&&p(Ft,{token:e,orgId:t,createdAt:Date.now()})}function Jt(e,t=Date.now()){const n=d(Ft,Lt);return n?t-n.createdAt>864e5?(u(Ft),null):n.orgId!==e?null:Wt.test(n.token)?n.token:(u(Ft),null):null}function Mt(){u(Ft)}const jt={User:["user.registered","user.logged_in","user.new_device_login","user.email_verified","user.password_changed","user.password_reset_requested","user.profile_updated","user.tag_added","user.tag_removed","user.blocked","user.unblocked"],Organization:["organization.member_invited","organization.member_accepted","organization.member_role_changed","organization.member_removed","organization.public_write_limit_reached","organization.end_user_ceiling_reached"],Workspace:["workspace.created","workspace.updated","workspace.deleted","workspace.settings_updated","workspace.features_updated","workspace.member_added","workspace.member_removed","workspace.member_role_changed","workspace.member_invited","workspace.invitation_accepted","workspace.invitation_declined","workspace.invitation_revoked","workspace.invitation_expired"],Subscription:["subscription.created","subscription.updated","subscription.upgraded","subscription.canceled","subscription.cancel_scheduled","subscription.resumed","subscription.suspended","subscription.trial_started","subscription.trial_will_end","subscription.trial_expired","subscription.downgraded"],Payment:["payment.succeeded","payment.failed","payment.action_required","payment.refunded"],Quota:["quota.limit_exceeded"],Credit:["credit.purchased","credit.consumed","credit.expired","credit.granted","credit.revoked","credit.low_balance"],Workflow:["workflow.created","workflow.deleted","workflow.published","workflow.paused","workflow.resumed","workflow.instance_completed","workflow.instance_failed"],Audience:["audience.member_created","audience.member_updated","audience.added_to_list","audience.removed_from_list","audience.attribute_changed","audience.tag_added","audience.tag_removed","audience.unsubscribed","audience.resubscribed","audience.email_invalidated","audience.blocked","audience.unblocked","audience.import_completed","audience.list_created","audience.list_updated","audience.list_deleted"],Email:["email.domain_added","email.domain_verified","email.sent","email.opened","email.clicked","email.bounced","email.unsubscribed","email.campaign_sent"],Push:["push.campaign_sent"],Auth:["auth.method_deleted","auth.domain_added","auth.domain_verified","auth.domain_deleted","auth.client_self_registered"],Token:["token.created","token.updated","token.revoked"],"Group version":["group_version.published"],Form:["form.submitted"],Blog:["blog.published","blog.updated","blog.unpublished","blog.deleted"],Doc:["doc.published","doc.updated","doc.unpublished","doc.deleted"],FAQ:["faq.updated"],"FAQ collection":["faq_collection.updated"],Testimonial:["testimonial.updated","testimonial.deleted"],"Rich content":["rich_content.updated","rich_content.deleted"],Collection:["collection.version_published","collection.record_created","collection.record_updated","collection.record_deleted"]},Bt=Object.values(jt).flat(),qt=new Set(Bt);function zt(e){return qt.has(e)}const Vt=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]),Kt=(e,t)=>e>>>t|e<<32-t;function Gt(e){let t=1779033703,n=3144134277,r=1013904242,i=2773480762,s=1359893119,a=2600822924,o=528734635,c=1541459225;const l=e.length,u=l+1,d=u+(56-u%64+64)%64+8,p=new Uint8Array(d);p.set(e,0),p[l]=128;const h=8*l,f=Math.floor(h/4294967296),g=h>>>0;p[d-8]=f>>>24&255,p[d-7]=f>>>16&255,p[d-6]=f>>>8&255,p[d-5]=255&f,p[d-4]=g>>>24&255,p[d-3]=g>>>16&255,p[d-2]=g>>>8&255,p[d-1]=255&g;const m=new Uint32Array(64);for(let e=0;e<d;e+=64){for(let t=0;t<16;t++){const n=e+4*t;m[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=Kt(m[e-15],7)^Kt(m[e-15],18)^m[e-15]>>>3,n=Kt(m[e-2],17)^Kt(m[e-2],19)^m[e-2]>>>10;m[e]=m[e-16]+t+m[e-7]+n>>>0}let l=t,u=n,d=r,h=i,f=s,g=a,w=o,y=c;for(let e=0;e<64;e++){const t=y+(Kt(f,6)^Kt(f,11)^Kt(f,25))+(f&g^~f&w)+Vt[e]+m[e]>>>0,n=l&u^l&d^u&d;y=w,w=g,g=f,f=h+t>>>0,h=d,d=u,u=l,l=t+((Kt(l,2)^Kt(l,13)^Kt(l,22))+n>>>0)>>>0}t=t+l>>>0,n=n+u>>>0,r=r+d>>>0,i=i+h>>>0,s=s+f>>>0,a=a+g>>>0,o=o+w>>>0,c=c+y>>>0}const w=new Uint8Array(32),y=[t,n,r,i,s,a,o,c];for(let e=0;e<8;e++)w[4*e]=y[e]>>>24&255,w[4*e+1]=y[e]>>>16&255,w[4*e+2]=y[e]>>>8&255,w[4*e+3]=255&y[e];return w}function Ht(e){return(new TextEncoder).encode(e)}function Qt(e,t){let n=e;n.length>64&&(n=Gt(n));const r=new Uint8Array(64),i=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<n.length?n[e]:0;r[e]=54^t,i[e]=92^t}const s=Gt(Xt(r,t));return Gt(Xt(i,s))}function Yt(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}function Xt(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function Zt(e){const{body:t,signature:n,timestamp:r,secret:i,maxAgeSeconds:s=300}=e;if(!(n&&r&&i&&t))return!1;const a="sha256=";if(!n.startsWith(a))return!1;const o=n.slice(7);if(s>0){const e=parseInt(r,10);if(isNaN(e))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-e)>s)return!1}const c=function(e){if(e.length%2!=0)return null;const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++){const r=parseInt(e.slice(2*n,2*n+2),16);if(Number.isNaN(r))return null;t[n]=r}return t}(o);if(!c)return!1;const l=Qt(Ht(i),Ht(`${r}.${t}`));return c.length===l.length&&Yt(c,l)}function en(e){if(!Zt(e))return null;try{return JSON.parse(e.body)}catch{return null}}const tn=300,nn="/.well-known/oauth-protected-resource",rn="/.well-known/agent-skills",sn="/.well-known/api-catalog",an="/.well-known/mcp/server-card.json",on="/.well-known/agent-card.json",cn="application/json",ln="application/linkset+json",un="text/markdown; charset=utf-8",dn="text/plain; charset=utf-8",pn="application/xml; charset=utf-8",hn=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function fn(e){return e.replace(/\/+$/,"")}function gn(e){return`public, max-age=${e}, s-maxage=${e}`}function mn(e){return"sha256:"+function(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}(Gt(Ht(e)))}const wn=function(){const e=new Map;return{get(t){const n=e.get(t);if(n){if(!(n.expiresAt<=Date.now()))return n.value;e.delete(t)}},set(t,n,r){e.set(t,{value:n,expiresAt:Date.now()+1e3*r})},delete(t){e.delete(t)},clear(){e.clear()}}}(),yn=new Set;function kn(e){return e.cache??wn}const bn=500;function vn(e){let t;const n=new Promise((e,n)=>{t=setTimeout(()=>n(new Error("discovery cache timed out")),500)});return Promise.race([Promise.resolve(e),n]).finally(()=>clearTimeout(t))}async function Sn(e,t){try{const n=await vn(e.get(t));return null==n?{hit:!1}:{hit:!0,value:JSON.parse(n)}}catch{return{hit:!1}}}async function En(e,t,n,r){try{await vn(e.set(t,JSON.stringify(n),r)),e!==wn&&yn.add(t)}catch{}}async function _n(e,t,n,r){if(!r||r<=0)return e(t,n);const i=new AbortController,s=setTimeout(()=>i.abort(),r);try{return await e(t,{...n,signal:i.signal})}finally{clearTimeout(s)}}async function In(e){const t=e.cacheTtlSeconds??tn,n=kn(e),r=`buildbase:agent-readiness:${fn(e.serverUrl)}::${e.orgId}`,i=await Sn(n,r);if(i.hit)return i.value;const s=e.fetch??fetch,a=`${fn(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let o={enabled:!1};try{const t=await _n(s,a,{headers:{Accept:cn}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(o=e)}}catch{}return await En(n,r,o,t),o}function $n(e){wn.clear();const t=e;if(t?.delete){for(const e of yn)try{const n=t.delete(e);n&&"function"==typeof n.then&&n.catch(()=>{})}catch{}yn.clear()}else yn.clear()}function Pn(e,t){const n=fn(e.siteUrl),r={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:nn};t.authorizationServer?.metadataUrl&&(r.oauth_authorization_server=t.authorizationServer.metadataUrl,r.openid_configuration="/.well-known/openid-configuration"),(t.authorizationServer||e.authMd)&&(r.auth="/auth.md"),e.skills?.length&&(r.agent_skills=`${rn}/index.json`),e.apiCatalog?.length&&(r.api_catalog=sn),e.mcpServerCard&&(r.mcp_server_card=an),!1!==e.a2aCard&&(r.a2a_agent_card=on),e.llmsFullTxt&&(r.llms_full_txt="/llms-full.txt");return zn({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:n,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:n},capabilities:r,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}function Un(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const n="/"===t?"":t.replace(/\/+$/,"");return nn+n}function Tn(e,t,n){const r=t.protectedResources??[];if(!r.length)return null;const i=e.replace(/\/+$/,"")||nn,s=n??`${fn(t.serverUrl)}/org/${t.orgId}`,a=t.scopes?.map(e=>e.name),o=r.map(e=>{const n=e.resource??fn(t.siteUrl),r=e.scopes??a;return{path:Un(n),metadata:{resource:n,authorization_servers:[s],bearer_methods_supported:e.bearerMethods??["header"],...r?.length?{scopes_supported:r}:{},...e.documentationUrl?{resource_documentation:e.documentationUrl}:{}}}}),c=o.find(e=>e.path===i);return c?zn(c.metadata,t):i===nn&&1===o.length?zn(o[0].metadata,t):null}function An(e){const t=e.skills??[];if(!t.length)return null;const n=fn(e.siteUrl);return zn({$schema:"https://schemas.agentskills.io/discovery/0.2.0/schema.json",skills:t.map(e=>({name:e.name,type:e.type??"skill-md",description:e.description,url:`${n}${Cn(e)}`,digest:mn(e.content)}))},e)}function Cn(e){return e.path??`${rn}/${e.name}/SKILL.md`}function On(e,t){const n=(t.skills??[]).find(t=>Cn(t)===e);return n?{status:200,contentType:"text/markdown; charset=utf-8",body:n.content,cacheControl:gn(t.cacheTtlSeconds??tn)}:null}function xn(e){if(!e.security)return null;const t=(Array.isArray(e.security.contact)?e.security.contact:[e.security.contact]).map(e=>`Contact: ${e}`);return e.security.expires&&t.push(`Expires: ${e.security.expires}`),e.security.policy&&t.push(`Policy: ${e.security.policy}`),{status:200,contentType:dn,body:t.join("\n")+"\n",cacheControl:gn(e.cacheTtlSeconds??tn)}}function Rn(e){return e.llmsTxt?{status:200,contentType:dn,body:e.llmsTxt,cacheControl:gn(e.cacheTtlSeconds??tn)}:null}function Nn(e){return e.llmsFullTxt?{status:200,contentType:dn,body:e.llmsFullTxt,cacheControl:gn(e.cacheTtlSeconds??tn)}:null}function Fn(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},n=fn(e.siteUrl),r=t.serviceUrl??n,i=t.transportProtocol??"http",s=t.skills??((e.skills??[]).length?(e.skills??[]).map(e=>({id:e.name,name:e.name,description:e.description,tags:["discovery"]})):[{id:"site-content",name:"Site content",description:`Read ${e.site.name}'s public content and machine-readable discovery documents (llms.txt, sitemap, API catalog).`,tags:["content"]}]);return zn({protocolVersion:"0.3.0",name:t.name??e.site.name,version:t.version??"1.0.0",description:t.description??e.site.description??`${e.site.name} — agent-accessible web application.`,url:r,preferredTransport:i,supportedInterfaces:[{serviceUrl:r,transportProtocol:i}],provider:e.site.provider?{organization:e.site.provider.name,url:e.site.provider.url}:{organization:e.site.name,url:n},capabilities:t.capabilities??{streaming:!1,pushNotifications:!1},defaultInputModes:["text/plain","application/json"],defaultOutputModes:["text/plain","application/json"],skills:s,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}},e)}function Wn(e){const t=e.webBotAuth?.keys;return t?.length?{status:200,contentType:"application/http-message-signatures-directory+json",body:JSON.stringify({keys:t},null,2),cacheControl:gn(e.cacheTtlSeconds??tn)}:null}function Ln(e){return e.endsWith(".json")||e.includes(".well-known/")?cn:e.endsWith(".md")?un:e.endsWith(".xml")?pn:dn}function Dn(e){let t;try{t=new URL(e.siteUrl).hostname}catch{return[]}const n=[{name:`_index._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${t}. alpn="h2" port=443`}];if(!1!==e.a2aCard&&n.push({name:`_a2a._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${t}. alpn="h2" port=443`}),e.mcpServerCard){let r=t;try{r=new URL(e.mcpServerCard.endpoint).hostname}catch{}n.push({name:`_mcp._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${r}. alpn="h2" port=443`})}return n}function Jn(e){const t=e.apiCatalog??[];if(!t.length)return null;const n=t.map(e=>({anchor:e.anchor,...e.title?{title:e.title}:{},...e.serviceDesc?{"service-desc":[{href:e.serviceDesc}]}:{},...e.serviceDoc?{"service-doc":[{href:e.serviceDoc}]}:{},...e.status?{status:[{href:e.status}]}:{}}));return{status:200,contentType:ln,body:JSON.stringify({linkset:n},null,2),cacheControl:gn(e.cacheTtlSeconds??tn)}}function Mn(e){const t=e??{tools:!0},n={tools:!1,resources:!1,prompts:!1};for(const[e,r]of Object.entries(t))n[e]=!1!==r&&null!=r;return n}function jn(e){const t=e.mcpServerCard;return t?zn({$schema:"https://modelcontextprotocol.io/schemas/server-card/v1.0",version:"1.0",protocolVersion:t.protocolVersion??"2025-11-25",serverInfo:{name:t.name,version:t.version},...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},capabilities:Mn(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}function Bn(e){const t=e.mcpServerCard;if(!t)return null;const n=fn(e.siteUrl);let r;try{r={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${Un(t.endpoint)}`}}catch{}return zn({$schema:"https://modelcontextprotocol.io/schemas/mcp-discovery/v1.0",version:"1.0",servers:[{name:t.name,...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},version:t.version,capabilities:Mn(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${n}${an}`,...r?{authentication:r}:{}}]},e)}function qn(e,t){const n=gn(e.cacheTtlSeconds??tn);if(e.authMd)return{status:200,contentType:un,body:e.authMd,cacheControl:n};const r=t.authorizationServer;if(!r)return null;const i=`# Agent Authentication\n\n${e.site.name} supports AI-agent access via OAuth 2.0 (authorization code + PKCE).\n\n## Authorization server\n- Issuer: \`${r.issuer}\`\n- Metadata (RFC 8414): ${r.metadataUrl}\n\nFetch the metadata document above for the \`authorization_endpoint\`, \`token_endpoint\`, supported grant types / PKCE methods, and — when the app allows it — the dynamic client \`registration_endpoint\` (RFC 7591).\n\n## Protected resources (RFC 9728)\nSee \`/.well-known/oauth-protected-resource\`, which lists the resource, its supported scopes, and the authorization server(s) that can issue tokens for it.\n\n## How an agent authenticates\n1. Discover this document and \`/.well-known/oauth-protected-resource\`.\n2. Fetch the authorization-server metadata for the endpoints.\n3. Register a client (dynamic registration) or use a pre-issued client_id.\n4. Run the authorization-code flow with PKCE (S256), requesting the scopes and target \`resource\`.\n5. Exchange the code for an access token and call the API with \`Authorization: Bearer <token>\`.\n\nDocumentation: ${e.site.documentationUrl??e.siteUrl}\n`;return{status:200,contentType:un,body:i,cacheControl:n}}function zn(e,t){return{status:200,contentType:cn,body:JSON.stringify(e,null,2),cacheControl:gn(t.cacheTtlSeconds??tn)}}function Vn(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function Kn(e,t){const n=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${Vn(e)}`);if(t){const e=[...void 0!==t.search?["search="+(t.search?"yes":"no")]:[],...void 0!==t.aiInput?["ai-input="+(t.aiInput?"yes":"no")]:[],...void 0!==t.aiTrain?["ai-train="+(t.aiTrain?"yes":"no")]:[]];e.length&&n.push(`Content-Signal: ${e.join(", ")}`)}for(const t of e.allow??[])n.push(`Allow: ${Vn(t)}`);for(const t of e.disallow??[])n.push(`Disallow: ${Vn(t)}`);return void 0!==e.crawlDelay&&n.push(`Crawl-delay: ${Vn(e.crawlDelay)}`),n.join("\n")}function Gn(e){const t=e.robots??{},n=fn(e.siteUrl),r=t.policies??[{userAgent:"*",allow:["/"]}],i=t.aiBots??"allow",s="allow"===i?[{userAgent:[...hn],allow:["/"]}]:"deny"===i?[{userAgent:[...hn],disallow:["/"]}]:i,a=t.sitemaps??(e.sitemap?[`${n}/sitemap.xml`]:[]),o=[`# robots.txt — agent-ready. See ${n}/llms.txt and ${n}/.well-known/agent.json`,...r.map((e,n)=>Kn(e,0===n?t.contentSignals:void 0)),...s.map(e=>Kn(e)),...a.length?[a.map(e=>`Sitemap: ${Vn(e)}`).join("\n")]:[]];return{status:200,contentType:dn,body:o.join("\n\n")+"\n",cacheControl:gn(e.cacheTtlSeconds??tn)}}function Hn(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function Qn(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Yn(e){const t=e.sitemap?.urls;if(!t?.length)return null;const n=fn(e.siteUrl),r='<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'+t.map(e=>{const t="string"==typeof e?{loc:e}:e;return` <url>\n${[` <loc>${Qn(/^https?:\/\//.test(t.loc)?t.loc:`${n}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${Qn(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${Qn(String(t.changefreq))}</changefreq>`]:[],...void 0!==t.priority?[` <priority>${Hn(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n";return{status:200,contentType:pn,body:r,cacheControl:gn(e.cacheTtlSeconds??tn)}}function Xn(e){if(!e)return!1;let t=0,n=0;for(const r of e.split(",")){const[e,...i]=r.trim().split(";"),s=e.trim().toLowerCase();let a=1;for(const e of i){const[t,n]=e.split("=").map(e=>e.trim());if("q"===t){const e=Number(n);Number.isNaN(e)||(a=e)}}"text/markdown"===s||"text/x-markdown"===s?t=Math.max(t,a):"text/html"!==s&&"text/*"!==s&&"*/*"!==s||(n=Math.max(n,a))}return t>0&&t>=n}function Zn(e,t,n){const r=Xn(e);return{status:200,contentType:r?un:"text/html; charset=utf-8",body:r?t.markdown:t.html,cacheControl:gn(n?.cacheTtlSeconds??tn),vary:"Accept"}}function er(e){const t=fn(e.siteUrl),n=[`<${t}/llms.txt>; rel="describedby"; type="text/plain"`,`<${t}/.well-known/agent.json>; rel="describedby"; type="application/json"`];if(!1!==e.a2aCard&&n.push(`<${t}${on}>; rel="describedby"; type="application/json"`),e.sitemap||e.robots?.sitemaps?.length){const r=e.robots?.sitemaps?.[0]??`${t}/sitemap.xml`;n.push(`<${r}>; rel="sitemap"; type="application/xml"`)}return e.apiCatalog?.length&&n.push(`<${t}${sn}>; rel="api-catalog"; type="${ln}"`),e.mcpServerCard&&n.push(`<${t}${an}>; rel="mcp-server"; type="application/json"`),n.join(", ")}async function tr(e,t){const n=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===n){return Pn(t,await In(t))}if(n===on)return Fn(t);if("/.well-known/http-message-signatures-directory"===n)return Wn(t);if("/.well-known/security.txt"===n)return xn(t);if(n===`${rn}/index.json`)return An(t);if(n.startsWith(`${rn}/`)&&n.endsWith("SKILL.md"))return On(n,t);if("/.well-known/oauth-authorization-server"===n||"/.well-known/openid-configuration"===n){const e=(await In(t)).authorizationServer;if(!e?.metadataUrl)return null;const n=await async function(e,t){const n=t.cacheTtlSeconds??tn,r=kn(t),i=`buildbase:as-metadata:${e}`,s=await Sn(r,i);if(s.hit)return s.value;const a=t.fetch??fetch;let o=null;try{const n=await _n(a,e,{headers:{Accept:cn}},t.fetchTimeoutMs??5e3);if(n.ok){const e=await n.json();e&&"object"==typeof e&&(o=e)}}catch{}return await En(r,i,o,n),o}(e.metadataUrl,t);return zn(n?n:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(n===sn)return Jn(t);if(n===an)return jn(t);if("/.well-known/mcp.json"===n)return Bn(t);if(n.startsWith(nn)){const e=await In(t);return Tn(n,t,e.authorizationServer?.issuer)}return null}async function nr(e,t){const n=e.replace(/\/+$/,"")||e,r=function(e,t){const n=t.extraPaths?.[e];if(void 0===n)return null;const r="string"==typeof n?{body:n}:n;return{status:r.status??200,contentType:r.contentType??Ln(e),body:r.body,cacheControl:r.cacheControl??gn(t.cacheTtlSeconds??tn)}}(n,t);return r||("/robots.txt"===n?Gn(t):"/llms-full.txt"===n?Nn(t):"/sitemap.xml"===n?Yn(t):"/llms.txt"===n?Rn(t):"/auth.md"===n?qn(t,await In(t)):"/security.txt"===n?xn(t):n.startsWith("/.well-known")?tr(n,t):null)}function rr(e){const t=globalThis.navigator;return!!t?.modelContext?.provideContext&&(t.modelContext.provideContext({tools:e}),!0)}function ir(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 sr(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4==0?"":"=".repeat(4-t.length%4),r=atob(t+n),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return i}class ar extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function or(e){const t=JSON.parse((new TextDecoder).decode(sr(e)));if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("JWT segment is not a JSON object");return t}function cr(e,t,n={}){const r=n.clockToleranceSec??60,i=n.requireExp??!0;if(!e||!t)throw new ar("invalid_token","Missing token or client secret");const s=e.split(".");if(3!==s.length)throw new ar("invalid_token","Malformed JWT");const[a,o,c]=s;let l,u;try{l=or(a),u=or(o)}catch{throw new ar("invalid_token","Unreadable JWT segments")}if("HS256"!==l.alg)throw new ar("invalid_algorithm",`Unexpected JWT alg: ${String(l.alg)}`);const d=Qt(Ht(t),Ht(`${a}.${o}`));let p;try{p=sr(c)}catch{throw new ar("invalid_signature","Unreadable JWT signature")}if(!Yt(d,p))throw new ar("invalid_signature","JWT signature verification failed");!function(e){for(const t of["iss","sub","jti"])if(void 0!==e[t]&&"string"!=typeof e[t])throw new ar("invalid_token",`JWT ${t} claim must be a string`);for(const t of["exp","nbf","iat"]){const n=e[t];if(void 0!==n&&("number"!=typeof n||!Number.isFinite(n)))throw new ar("invalid_token",`JWT ${t} claim must be a finite number`)}const t=e.aud;if(!(void 0===t||"string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new ar("invalid_token","JWT aud claim must be a string or string array")}(u);const h=Math.floor(Date.now()/1e3);if(i&&"number"!=typeof u.exp)throw new ar("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof u.exp&&h>u.exp+r)throw new ar("token_expired","JWT has expired");if("number"==typeof u.nbf&&h+r<u.nbf)throw new ar("token_not_yet_valid","JWT is not yet valid");if(void 0!==n.issuer&&u.iss!==n.issuer)throw new ar("invalid_issuer","JWT issuer mismatch");if(void 0!==n.audience){const e=u.aud;if(!(Array.isArray(e)?e.includes(n.audience):e===n.audience))throw new ar("invalid_audience","JWT audience mismatch")}return u}function lr(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function ur(e){return ir(Ht(JSON.stringify(e)))}function dr(e,t,n){if(!t)throw new ar("invalid_secret","Missing signing secret");const r=Math.floor(Date.now()/1e3),i={iat:r,exp:r+(n?.expiresInSec??3600),...e},s=`${ur({alg:"HS256",typ:"JWT"})}.${ur(i)}`;return`${s}.${ir(Qt(Ht(t),Ht(s)))}`}function pr(e){const t=lr(e.authorization);if(!t)throw new ar("invalid_token","Missing Bearer token");return cr(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function hr(e){const t=lr(e.authorization);if(!t)throw new ar("invalid_token","Missing Bearer token");return cr(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function fr(e){return{success:!0,token:e.token,message:e.message??"ok",..."number"==typeof e.expiresIn?{expiresIn:e.expiresIn}:{}}}function gr(e){return{success:!1,token:"",message:e}}async function mr(e){let t;try{t=pr(e)}catch(e){return{status:401,body:gr(e instanceof ar?e.code:"invalid_token")}}return{status:200,body:fr(await e.mintToken(t))}}async function wr(e){let t;try{t=hr(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof ar?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}}function yr(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}function kr(e){const t=[`Bearer resource_metadata="${yr(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${yr(e.error)}"`),e.errorDescription&&t.push(`error_description="${yr(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}const br=12,vr=16;function Sr(){const e=globalThis.crypto;if(!e?.subtle)throw new Error("WebCrypto is unavailable in this runtime — agent-auth session encryption requires globalThis.crypto.subtle (Node 18+, Bun, Deno, edge, browsers).");return e.subtle}const Er=new Map;function _r(e){let t=Er.get(e);return t||(t=(async()=>{const t=await Sr().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return Sr().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),Er.set(e,t)),t}function Ir(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(t){const n=globalThis.crypto.getRandomValues(new Uint8Array(br)),r=await _r(e),i=new Uint8Array(await Sr().encrypt({name:"AES-GCM",iv:n},r,(new TextEncoder).encode(t))),s=i.subarray(i.length-vr),a=i.subarray(0,i.length-vr),o=new Uint8Array(28+a.length);return o.set(n,0),o.set(s,br),o.set(a,28),ir(o)},async decryptSessionRef(t){try{const n=sr(t);if(n.length<=28)return null;const r=n.slice(0,br),i=n.subarray(br,28),s=n.subarray(28),a=new Uint8Array(s.length+vr);a.set(s,0),a.set(i,s.length);const o=await _r(e),c=await Sr().decrypt({name:"AES-GCM",iv:r},o,a);return(new TextDecoder).decode(c)}catch{return null}}}}async function $r(e){const{claims:t,secret:n}=e,r=e.expiresInSec??3600,i=t.resource&&t.resource.length?1===t.resource.length?t.resource[0]:t.resource:void 0,s=t.sessionId?await Ir(n).encryptSessionRef(t.sessionId):void 0;return{token:dr({sub:t.id,userId:t.id,email:t.email,...t.name?{name:t.name}:{},...t.scope?{scope:t.scope}:{},...i?{aud:i}:{},...s?{sid:s}:{},...e.extraClaims},n,{expiresInSec:r}),expiresIn:r}}function Pr(e,t,n){const r=globalThis.process?.env;"1"===r?.MCP_AUTH_DEBUG&&console.warn(`[buildbase/mcp-auth] audience rejected (${n}): received aud=${JSON.stringify(e)} expected one of ${JSON.stringify(t)}`)}function Ur(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const n=Ir(t),r=e.resource?Array.isArray(e.resource)?e.resource:[e.resource]:[];let i=e.resourceMetadataUrl;if(!i&&r.length)try{const e=new URL(r[0]),t="/"===e.pathname?"":e.pathname.replace(/\/+$/,"");i=`${e.origin}/.well-known/oauth-protected-resource${t}`}catch{}return{resourceMetadataUrl:i,verify:async i=>{let s;try{s=cr(i,t,{...e.verify})}catch{return null}if(r.length){const t=s.aud?Array.isArray(s.aud)?s.aud:[s.aud]:[];if(!t.length&&e.requireAudience)return Pr(t,r,"token carries no aud claim"),null;if(t.length&&!t.some(e=>r.includes(e)))return Pr(t,r,"aud does not include this resource"),null}const a="string"==typeof s.sid?await n.decryptSessionRef(s.sid):null,o=Array.isArray(s.scope)?s.scope.filter(e=>"string"==typeof e):"string"==typeof s.scope?s.scope.split(" ").filter(Boolean):void 0;return{sessionId:a??"",userId:"string"==typeof s.userId?s.userId:"string"==typeof s.sub?s.sub:void 0,workspaceId:"string"==typeof s.workspaceId?s.workspaceId:void 0,scopes:o,claims:s}}}}const Tr=function(){const e=new Map;return{get(t){const n=e.get(t);if(n){if(!(n.expiresAt<=Date.now()))return n.value;e.delete(t)}},set(t,n,r){e.set(t,{value:n,expiresAt:Date.now()+1e3*r})},delete(t){e.delete(t)},clear(){e.clear()}}}(),Ar=e=>e.replace(/\/+$/,""),Cr=(e,t)=>`buildbase:org-region:${Ar(e)}::${t}`;async function Or(e){const{orgId:t,centralUrl:n,apiKey:r,timeoutMs:i=5e3}=e;if(!t)throw new Error("resolveServerUrl: orgId is required");if(!n)throw new Error("resolveServerUrl: centralUrl is required");const s=e.cache??Tr,a=Cr(n,t);try{const e=await s.get(a);if(e)return JSON.parse(e)}catch{}const o=e.fetch??fetch,c=`${Ar(n)}/api/organizations/orgs/${encodeURIComponent(t)}/region`,l=new AbortController,u=i>0?setTimeout(()=>l.abort(),i):null;let d;try{d=await o(c,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},signal:l.signal})}finally{u&&clearTimeout(u)}if(!d.ok)throw new Error(`resolveServerUrl: central answered ${d.status} for org ${t}`);const p=await d.json(),h=p?.data??p;if(!h||"string"!=typeof h.serverUrl||!h.serverUrl)throw new Error(`resolveServerUrl: central returned no serverUrl for org ${t}`);const f={orgId:h.orgId||t,region:h.region||"us",cellId:h.cellId||"us",serverUrl:Ar(h.serverUrl)},g=function(e){const t=e.headers.get("cache-control")||"";if(/(?:^|[\s,])(?:no-store|no-cache)(?:$|[\s,=])/i.test(t))return 0;const n=/max-age=(\d+)/i.exec(t);if(!n)return 300;const r=Number(n[1]);return!Number.isFinite(r)||r<0?300:Math.min(r,3600)}(d);if(g>0)try{await s.set(a,JSON.stringify(f),g)}catch{}return f}async function xr(e){const t=Cr(e.centralUrl,e.orgId),n=e.cache;if(Tr.delete?.(t),n?.delete)try{await n.delete(t)}catch{}}function Rr(e){const{serverUrl:t,orgId:n,version:r="v1",region:i,getSessionId:s,timeout:a,maxRetries:o,debug:c,headers:l,onError:u,fetch:d}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!n)throw new Error("BuildBase: orgId is required");const p={...void 0!==a&&{timeout:a},...void 0!==o&&{maxRetries:o},...void 0!==c&&{debug:c},...l&&{headers:l},...u&&{onError:u},...d&&{fetch:d}},h=e=>{const i={serverUrl:t,version:r,orgId:n,sessionId:e,...p};return{workspace:new K(i),user:new J(i),settings:new A(i),push:new U(i),devices:new _(i),uploads:new D(i),sessions:new T(i)}},f=new K({serverUrl:t,version:r,orgId:n,...p}),g=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,n)=>(await e()).workspace.updateWorkspace(t,n),delete:async t=>(await e()).workspace.deleteWorkspace(t),permissions:async t=>(await e()).workspace.getMyPermissions(t),can:async(t,n)=>{const{permissions:r}=await(await e()).workspace.getMyPermissions(t),i=new Set(r);return(Array.isArray(n)?n:[n]).every(e=>i.has(e))}},invitations:{list:async t=>(await e()).workspace.listInvitations(t),create:async(t,n,r,i)=>(await e()).workspace.inviteMember(t,{email:n,role:r,landingUrl:i}),resend:async(t,n)=>(await e()).workspace.resendInvitation(t,n),revoke:async(t,n)=>(await e()).workspace.revokeInvitation(t,n)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,n,r)=>(await e()).workspace.addUser(t,{email:n,role:r}),remove:async(t,n)=>(await e()).workspace.removeUser(t,n),updateRole:async(t,n,r)=>(await e()).workspace.updateUser(t,n,{role:r}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,n)=>(await e()).workspace.createCheckoutSession(t,n),update:async(t,n)=>(await e()).workspace.updateSubscription(t,n),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,n)=>(await e()).workspace.createBillingPortalSession(t,n)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>f.getPublicPlans(e),getVersion:e=>f.getPlanGroupVersion(e)},invoices:{list:async(t,n,r)=>(await e()).workspace.listInvoices(t,n,r),get:async(t,n)=>(await e()).workspace.getInvoice(t,n)},usage:{record:async(t,n)=>(await e()).workspace.recordUsage(t,n),recordBatch:async(t,n)=>(await e()).workspace.recordUsageBatch(t,n),getQuota:async(t,n)=>(await e()).workspace.getQuotaUsageStatus(t,n),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,n)=>(await e()).workspace.getUsageLogs(t,n)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,n,r)=>(await e()).workspace.updateFeature(t,n,r)},notification:{send:async(t,n,r,i)=>(await e()).workspace.sendNotification(t,n,r,i)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,n)=>(await e()).workspace.consumeCredits(t,n),purchase:async(t,n)=>(await e()).workspace.purchaseCredits(t,n),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,n)=>(await e()).workspace.getCreditTransactions(t,n),getBuckets:async(t,n)=>(await e()).workspace.getCreditBuckets(t,n),getExpiring:async(t,n)=>(await e()).workspace.getExpiringCredits(t,n),getPublicPackages:()=>f.getPublicCreditPackages()},permissions:{check:async(t,n,r)=>{const i=await e(),[s,a,o]=await Promise.all([i.workspace.getWorkspace(t),i.settings.getSettings(),i.workspace.getWorkspaceUsers(t)]),c=o.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return St(r,{userId:n,workspaceRole:c?.role??null,workspace:s,settings:a})},resolve:async(t,n)=>{const r=await e(),[i,s,a]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),o=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return bt({userId:n,workspaceRole:o?.role??null,workspace:i,settings:s})}},devices:{list:async()=>(await e()).devices.list(),rename:async(t,n)=>(await e()).devices.rename(t,n),signOut:async t=>(await e()).devices.signOut(t),forget:async t=>(await e()).devices.forget(t)},sessions:{list:async()=>(await e()).sessions.list(),revoke:async t=>(await e()).sessions.revoke(t)}}),m=g(async()=>h(await(async()=>{if(!s)throw new Error("BuildBase: getSessionId callback is required for authenticated calls. Pass it in BuildBase({ getSessionId: ... }) or use withSession(id) / client.forSession(id).");const e=await s();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{...void 0!==i&&{region:i},auth:async()=>{if(!s)return null;const e=await s();return e?{sessionId:e}:null},withSession:e=>{const t=h(e);return g(async()=>t)},client:{forSession:h},...m}}export{hn as AI_BOT_USER_AGENTS,Et as APP_PERMISSION_FALLBACK_GROUP,G as ApiVersion,ar as AppBridgeError,v as AuthApi,$t as AuthStatus,ie as BBAction,ae as BBScreen,se as BBStatus,re as BB_PARAM,b as BaseApi,E as BetaForm,qe as BillingIntervals,Rr as BuildBase,Se as CURRENCY_DISPLAY,Ee as CURRENCY_FLAG,He as CreditBucketSource,Qe as CreditBucketStatus,Ye as CreditTransactionType,mt as DEFAULT_ROLE_PERMISSIONS,bn as DISCOVERY_CACHE_TIMEOUT_MS,Ge as DunningState,Q as EventEmitter,wt as FALLBACK_WORKSPACE_ROLE,M as INVITATION_ERROR_CODE,Ve as InvoiceStatuses,P as NotificationsApi,$e as PLAN_CURRENCY_CODES,Pe as PLAN_CURRENCY_OPTIONS,It as PUSH_SERVICE_WORKER_SCRIPT,ft as Permission,U as PushApi,H as SDKEvent,A as SettingsApi,Ke as SubscriptionItemType,ze as SubscriptionStatus,C as UPLOAD_ACCEPT,O as UPLOAD_MAX_BYTES,D as UploadsApi,J as UserApi,Bt as WEBHOOK_EVENTS,jt as WEBHOOK_EVENTS_BY_CATEGORY,K as WorkspaceApi,At as actionableInvitations,_t as appPermissionCatalogue,gr as appTokenFailure,fr as appTokenSuccess,kr as bearerChallenge,Fn as buildA2AAgentCard,Pn as buildAgentCard,An as buildAgentSkillsIndex,Jn as buildApiCatalog,qn as buildAuthMd,er as buildDiscoveryLinkHeader,Dn as buildDnsAidRecords,Nn as buildLlmsFullTxt,Rn as buildLlmsTxt,Bn as buildMcpDiscoveryManifest,jn as buildMcpServerCard,Tn as buildProtectedResourceMetadata,Gn as buildRobotsTxt,xn as buildSecurityTxt,Yn as buildSitemap,On as buildSkillMd,Wn as buildWebBotAuthDirectory,Ur as buildbaseAuth,ct as calculateBillableSeats,lt as calculateSeatOverageCents,ut as calculateTotalSubscriptionCents,de as cleanBBParams,$n as clearAgentReadinessCache,ve as clearAuthIntent,Mt as clearPendingInvite,xr as clearResolvedServerUrl,be as consumeAuthIntent,oe as createBBUrl,ce as createCheckoutRedirectUrls,le as createCreditPurchaseRedirectUrls,Ir as createSessionRefCrypto,Rr as default,Y as eventEmitter,lr as extractBearerToken,In as fetchAgentReadiness,Ne as formatCents,Re as formatMinorAmountIntl,We as formatOverageRate,Le as formatOverageRateWithLabel,Je as formatQuotaIncludedOverage,Be as formatQuotaWithPrice,L as formatUploadLimit,ht as getAvailableBillingIntervals,rt as getAvailableCurrenciesFromPlans,Ze as getBasePriceCents,st as getBillingIntervalAndCurrencyFromPriceId,Ce as getCurrencyDecimals,_e as getCurrencyFlag,Ie as getCurrencySymbol,nt as getDisplayCurrency,ot as getPerSeatPriceCents,Xe as getPricingVariant,Me as getQuotaDisplayValue,it as getQuotaDisplayWithVariant,tt as getQuotaOverageCents,De as getQuotaUnitLabelFromName,at as getSeatPricing,et as getStripePriceIdForInterval,wr as handleAppRevokeRequest,mr as handleAppTokenRequest,St as hasPermission,ee as invalidateCreditBalance,te as invalidateQuotaUsage,ne as invalidateSubscription,Rt as inviterNameOf,Tt as isInvitationActionable,V as isInvitationError,Ct as isInvitationLapsed,zt as isWebhookEvent,Oe as isZeroDecimalCurrency,xe as minorAmountToDisplay,$r as mintAgentToken,Zn as negotiateMarkdown,Dt as parkPendingInvite,en as parseWebhookEvent,yt as pickDefaultRole,W as preflightUpload,rr as provideWebMcpTools,ue as readBBParams,Jt as readPendingInvite,Nt as resendCooldownSeconds,nr as resolveAgentPath,dt as resolveMaxUsers,bt as resolvePermissions,vt as resolveRolePermissions,Or as resolveServerUrl,tr as resolveWellKnown,me as safeRedirect,ke as saveAuthIntent,mn as sha256Digest,dr as signClientJwt,Ut as sortInvitations,N as uploadFailureOf,F as uploadPolicyOf,pt as validateInvite,ge as validateRedirectUrl,hr as verifyAppRevokeRequest,pr as verifyAppTokenRequest,cr as verifyClientJwt,Zt as verifyWebhookSignature,Xn as wantsMarkdown,xt as workspaceIdOf,Ot as workspaceNameOf};
|
|
1
|
+
let e=!0;function t(t,...n){e&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(t,...n)}function n(e,...t){console.error(e,...t)}function r(e,t){const n=AbortSignal.any;if("function"==typeof n)return n([e,t]);const r=new AbortController,i=e=>{r.signal.aborted||r.abort(e.reason)};for(const n of[e,t]){if(n.aborted){i(n);break}n.addEventListener("abort",()=>i(n),{once:!0})}return r.signal}async function i(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function s(e,t="Request failed"){if(!e.ok){let n,r=t;try{const t=await i(e);r=t.message||t.error||r,"string"==typeof t.code&&(n=t.code)}catch{r=function(e,t){const n={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${n})`)}(e,t).message}throw Object.assign(new Error(r),{status:e.status,...n?{code:n}:{}})}try{return await i(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class a extends Error{constructor(e,t,n,r){super(e),this.code=t,this.context=n,this.originalError=r,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,a)}}const o=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1},this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}configure(t){this.config={...this.config,...t},void 0!==t.enableConsoleLogging&&function(t){void 0!==t.enableLogging&&(e=t.enableLogging)}({enableLogging:t.enableConsoleLogging})}handleError(e,r={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const i=e instanceof Error?e:new a("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",r),s=i instanceof a?i:new a(i.message,"SDK_ERROR",r,i);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${r.component||"Unknown"}:`,{message:s.message,code:s.code,context:s.context,originalError:s.originalError,stack:s.stack}),this.config.onError)try{this.config.onError(s,r)}catch(e){n("[SDK Error Handler] Error in custom error callback:",e)}for(const e of this.listeners)try{e(s,r)}catch(e){n("[SDK Error Handler] Error in error listener:",e)}this.config.showUserNotifications&&this.notifyUser(s,r)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...n)=>e(...n).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...n)=>{try{return e(...n)}catch(e){throw this.handleError(e,t),e}}}};function c(e,t={}){o.handleError(e,t)}function l(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return c(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function u(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){c(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function d(e,t){const n=l(e);if(!n)return null;try{const r=JSON.parse(n);return t&&!t(r)?(c(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),u(e),null):r}catch(t){return c(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),u(e),null}}function p(e,t){try{!function(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){c(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){c(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const h="saas-session-id",f="saas-device-id";function g(){return function(){if("undefined"==typeof window)return null;try{return l(h)}catch(e){return c(e,{component:"auth-utils",action:"getSessionId",metadata:{key:h}}),null}}()}function m(){const e=g(),t={};e&&(t["x-session-id"]=e);const n=function(){if("undefined"==typeof window)return null;try{return l(f)??null}catch(e){return c(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:f}}),null}}();return n&&(t["x-device-id"]=n),t}const w=new WeakSet,y=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),k="SDK is not ready (missing serverUrl, version, or orgId)";class b{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(k);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(k)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:m()}url(e){const t=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${t}`}buildHeaders(e){const t={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(t,e.headers),null==e.body||t["Content-Type"]||(t["Content-Type"]="application/json"),t}reportError(e,t){w.has(e)||(w.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}static delay(e,t){return new Promise((n,r)=>{const i=()=>{clearTimeout(s),r(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return i();const s=setTimeout(()=>{t?.removeEventListener("abort",i),n()},e);t?.addEventListener("abort",i,{once:!0})})}async executeFetchUrl(e,t,n){const i=(t.method??"GET").toUpperCase(),s=n??e,a=this.buildHeaders(t),o={...t,headers:a},c=y.has(i);let l,u;if(this._timeout>0){u=new AbortController;const e=u;l=setTimeout(()=>e.abort(),this._timeout),o.signal=t.signal?r(t.signal,e.signal):e.signal}const d=e=>{if(u?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${i} ${s}`);return this.reportError(e,{method:i,path:s}),e}return e},p=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const n=this._fetch.bind(globalThis),r=await n(e,o);if(this._debug&&console.log(`[BuildBase] ${i} ${e} → ${r.status}`),401===r.status&&this._onUnauthorized&&this._onUnauthorized(),r.status>=500&&c&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await b.delay(e,o.signal),p(t+1)}return r}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw d(e);if(c&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await b.delay(e,o.signal)}catch(e){throw d(e)}return p(t+1)}throw e instanceof Error&&this.reportError(e,{method:i,path:s}),e}};try{return await p(0)}finally{void 0!==l&&clearTimeout(l)}}async fetchJson(e,t={},n="Request failed"){this.ensureReady();try{const r=await this.executeFetch(e,t);return await s(r,n)}catch(n){throw n instanceof Error&&this.reportError(n,{method:(t.method??"GET").toUpperCase(),path:e}),n}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchUnwrapped(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);return r.ok||await this.throwResponseError(r,n),this.unwrapResponse(r,n)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async fetchForeign(e,t={}){return this._fetch.call(globalThis,e,t)}async throwResponseError(e,t){let n=t;try{n=(await e.json()).message||n}catch{n=`${t} (${e.status}: ${e.statusText})`}throw Object.assign(new Error(n),{status:e.status})}apiPath(e,...t){return e.reduce((e,n,r)=>e+n+(r<t.length?encodeURIComponent(String(t[r])):""),"")}async unwrapResponse(e,t){const n=await e.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||t);return void 0!==n.data?n.data:n}return n}}class v extends b{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n="Failed to initiate authentication",r=e=>this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});let i=await r(e);if(400===i.status&&(e.trackingConsent||e.trackingIdentity||e.trackingAttribution||e.invitationToken)){const{trackingConsent:t,trackingIdentity:n,trackingAttribution:s,invitationToken:a,...o}=e;i=await r(o)}return i.ok||await this.throwResponseError(i,n),this.unwrapResponse(i,n)}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}async getDeviceToken(e,t){try{const n=await this.fetchUnwrapped("device-token",{headers:{"x-session-id":e},signal:t},"Failed to fetch device token");return n?.deviceToken??""}catch{return""}}async logout(e,t,n){await this.fetchJson("logout",{method:"POST",...e?{headers:{"x-session-id":e}}:{},...t?.all?{body:JSON.stringify({all:!0})}:{},signal:n},"Failed to sign out")}}class S extends b{constructor(e){super({...e,basePath:"beta",requireOrgId:!0})}getAuthHeaders(){return{}}async fetchConfig(){return this.fetchJson(`config?orgId=${encodeURIComponent(this.orgId)}`,{},"Failed to fetch beta form configuration")}async submitBetaUser(e){return this.fetchJson("submit",{method:"POST",body:JSON.stringify(e)},"Failed to submit beta user request")}}class E{constructor(e){this.api=new S(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},n=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),r=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),i=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),s=t?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:n,language:r,timezone:i,currency:s}})}}class _ extends b{constructor(e){super(e)}async list(e){const t=await this.fetchJson("devices",{signal:e},"Failed to load devices");return t?.devices??[]}async rename(e,t,n){await this.fetchJson(this.apiPath`devices/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename device")}async signOut(e,t){return this.fetchJson(this.apiPath`devices/${e}`,{method:"DELETE",signal:t},"Failed to sign out device")}async forget(e,t){return this.fetchJson(`${this.apiPath`devices/${e}`}?forget=true`,{method:"DELETE",signal:t},"Failed to forget device")}}function I(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))void 0!==r&&""!==r&&!1!==r&&t.set(n,String(r));const n=t.toString();return n?`?${n}`:""}const $=e=>JSON.stringify(e?{workspaceId:e}:{});class P extends b{constructor(e){super(e)}async list(e={},t){const n=await this.fetchJson(`notifications${I({workspaceId:e.workspaceId,unread:e.unread,archived:e.archived,page:e.page,limit:e.limit})}`,{signal:t},"Failed to load notifications");return{notifications:n?.notifications??[],page:n?.page??e.page??1,limit:n?.limit??e.limit??20,total:n?.total??0,hasNextPage:Boolean(n?.hasNextPage)}}async counts(e,t){const n=await this.fetchJson(`notifications/unread-count${I({workspaceId:e})}`,{signal:t},"Failed to load notification count");return{unread:n?.unread??0,unseen:n?.unseen??0}}markRead(e){return this.itemAction(this.apiPath`notifications/${e}/read`,"POST",!0)}markUnread(e){return this.itemAction(this.apiPath`notifications/${e}/unread`,"POST")}archive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"POST")}unarchive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"DELETE")}async markAllRead(e){await this.fetchJson("notifications/read-all",{method:"POST",body:$(e)},"Failed to mark notifications read")}async markSeen(e){await this.fetchJson("notifications/seen",{method:"POST",body:$(e)},"Failed to mark notifications seen")}async itemAction(e,t,n=!1){return this.fetchJson(e,n?{method:t,keepalive:n}:{method:t},"Failed to update notification")}}class U extends b{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}class T extends b{constructor(e){super(e)}async list(e){const t=await this.fetchJson("sessions",{signal:e},"Failed to load sessions");return t?.sessions??[]}async revoke(e,t){await this.fetchJson(this.apiPath`sessions/${e}`,{method:"DELETE",signal:t},"Failed to sign out session")}}class A extends b{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}const C="image/png,image/jpeg,image/gif,image/webp,image/svg+xml",O=5242880,x={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml"};function R(e){if(e.type)return e.type;const t=(e.name??"").split(".").pop()?.toLowerCase()??"";return x[t]??""}function N(e){const{status:t,code:n}=e??{};return"UPLOAD_TOO_LARGE"===n||413===t?"tooLarge":"INVALID_UPLOAD"===n?"invalid":"UPLOADS_DISABLED"===n?"disabled":"USER_UPLOAD_LIMIT"===n?"userLimit":"UPLOADS_UNAVAILABLE"===n||429===t||501===t||503===t?"unavailable":"failed"}function F(e){const t=e?.uploads,n=Number(t?.maxFileBytes);return{enabled:!!t&&!1!==t.enabled,maxFileBytes:Number.isFinite(n)&&n>0?Math.min(n,O):O}}function W(e,t){return t.enabled?e.size>t.maxFileBytes?"tooLarge":null:"disabled"}function L(e,t){const n=1048576,[r,i]=e>=n?[e/n,"megabyte"]:[e/1024,"kilobyte"];try{return new Intl.NumberFormat(t,{style:"unit",unit:i,unitDisplay:"short",maximumFractionDigits:1}).format(r)}catch{return`${Math.round(10*r)/10} ${"megabyte"===i?"MB":"KB"}`}}class D extends b{constructor(e){super(e)}async upload(e,t){const{purpose:n,signal:i}=t,s=await this.fetchJson("uploads",{method:"POST",body:JSON.stringify({purpose:n,name:e.name??"file",size:e.size,contentType:R(e)}),signal:i},"Could not start the upload");let a;const o=new AbortController,c=setTimeout(()=>o.abort(),12e4);try{a=await this.fetchForeign(s.url,{method:"PUT",headers:s.headers,body:e,signal:i?r(i,o.signal):o.signal})}catch(e){if(i?.aborted)throw e;throw new Error("The upload to storage did not finish. Check the connection and try again.")}finally{clearTimeout(c)}if(!a.ok)throw Object.assign(new Error(`The upload to storage was refused (HTTP ${a.status}). Try again.`),{status:a.status});return this.fetchJson(this.apiPath`uploads/${s.uploadId}/complete`,{method:"POST",body:"{}",signal:i},"Could not finish the upload")}}class J extends b{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const n=await this.unwrapResponse(t,"Failed to fetch user attributes");return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const n=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof n&&null!==n?n:{}}}const M={NOT_FOUND:"INVITATION_NOT_FOUND",EXPIRED:"INVITATION_EXPIRED",ALREADY_HANDLED:"INVITATION_ALREADY_HANDLED",EMAIL_MISMATCH:"INVITATION_EMAIL_MISMATCH",EMAIL_NOT_VERIFIED:"EMAIL_NOT_VERIFIED",INVITES_DISABLED:"WORKSPACE_INVITES_DISABLED",RATE_LIMITED:"INVITATION_RATE_LIMITED",EMAIL_FAILED:"INVITATION_EMAIL_FAILED",SEAT_LIMIT:"SEAT_LIMIT_REACHED",USER_BLOCKED:"USER_BLOCKED",NO_SENDER_CONFIGURED:"NO_SENDER_CONFIGURED"},j={402:M.SEAT_LIMIT,404:M.NOT_FOUND,409:M.ALREADY_HANDLED,410:M.EXPIRED,429:M.RATE_LIMITED,502:M.EMAIL_FAILED,503:M.NO_SENDER_CONFIGURED};function B(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function q(e){return"string"==typeof e&&e?e:void 0}async function z(e,t){let n=null;try{n=await e.json()}catch{n=null}return function(e,t,n){const r=t&&"object"==typeof t?t:{},i=q(r.message)??q(r.error)??n,s={status:e,code:q(r.code)??j[e]??`HTTP_${e}`,currentUserCount:B(r.currentUserCount),limit:B(r.limit),retryAfterSeconds:B(r.retryAfterSeconds),invitedEmail:q(r.invitedEmail),invitationId:q(r.invitationId),invitationStatus:q(r.status)};return Object.assign(new Error(i),s)}(e.status,n,t)}function V(e){return e instanceof Error&&"number"==typeof e.status}class K extends b{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){try{return await this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}catch(n){const r=n?.status;if(400===r&&e.trackingAttribution){const{trackingAttribution:n,...r}=e;return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(r),signal:t},"Failed to create workspace")}throw n}}async updateWorkspace(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:n},"Failed to update workspace")}async deleteWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE",signal:t},"Failed to delete workspace")}async getWorkspaceUsers(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{signal:t},"Failed to fetch workspace users")}async addUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to invite member")}async fetchInvitation(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);if(!r.ok)throw await z(r,n);return s(r,n)}async listInvitations(e,t){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{signal:t},"Failed to fetch invitations")}async inviteMember(e,t,n){const r={email:t.email,role:t.role};return t.landingUrl&&(r.landingUrl=t.landingUrl),this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{method:"POST",body:JSON.stringify(r),signal:n},"Failed to send invitation")}async resendInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}/resend`,{method:"POST",signal:n},"Failed to resend invitation")}async revokeInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}`,{method:"DELETE",signal:n},"Failed to revoke invitation")}async myInvitations(e){return this.fetchInvitation("invitations",{signal:e},"Failed to fetch your invitations")}async acceptInvitation(e,t,n){return this.fetchInvitation(this.apiPath`invitations/${e}/accept`,{method:"PATCH",signal:n,...t?.token?{body:JSON.stringify({token:t.token})}:{}},"Failed to accept invitation")}async declineInvitation(e,t){return this.fetchInvitation(this.apiPath`invitations/${e}/reject`,{method:"PATCH",signal:t},"Failed to decline invitation")}async previewInvitation(e,t){if(!this.orgId)throw new Error("orgId is required for previewInvitation");return this.fetchInvitation(this.apiPath`${this.orgId}/invitations/preview/${e}`,{signal:t},"Failed to load invitation")}async removeUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:n},"Failed to remove user")}async updateUser(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(n),signal:r},"Failed to update user")}async updateSettings(e,t){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:n},"Failed to update workspace permissions")}async getMyPermissions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/permissions/me`,{signal:t},"Failed to fetch workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:n}}),signal:r},"Failed to update feature")}async getWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{signal:t},"Failed to fetch workspace")}async getProfile(e){return this.fetchJson("profile",{signal:e},"Failed to fetch profile")}async updateUserProfile(e,t){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update user profile")}async getPasskeys(e){const t=await this.fetchJson("passkeys",{signal:e},"Failed to fetch passkeys");return t?.passkeys??[]}async renamePasskey(e,t,n){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename passkey")}async deletePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE",signal:t},"Failed to remove passkey")}async getCurrentSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{signal:t},"Failed to fetch subscription")}async getPlanGroup(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`,{signal:t},"Failed to fetch plan group")}async getPlanGroupByVersion(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch plan group version")}async getPlanGroupVersions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group/versions`,{signal:t},"Failed to fetch plan group versions")}async getPublicPlans(e,t){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");return this.fetchUnwrapped(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`,{signal:t},"Failed to fetch plans")}async getPublicCreditPackages(e){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");return this.fetchUnwrapped(this.apiPath`${this.orgId}/credit-packages`,{signal:e},"Failed to fetch credit packages")}async getPlanGroupVersion(e,t){return this.fetchUnwrapped(this.apiPath`plan-group-versions/${e}`,{signal:t},"Failed to fetch plan group version")}async createCheckoutSession(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create checkout session")}async selectFreePlan(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:n},"Failed to select free plan")}async updateSubscription(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:n},"Failed to update subscription")}async createBillingPortalSession(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:n})}async listInvoices(e,t=10,n,r){const i=new URLSearchParams;return i.append("limit",t.toString()),n&&i.append("starting_after",n),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${i.toString()}`,{signal:r},"Failed to fetch invoices")}async getInvoice(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:n},"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST",signal:t},"Failed to cancel subscription")}async resumeSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST",signal:t},"Failed to resume subscription")}async recordUsage(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record usage")}async recordUsageBatch(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch quota usage status")}async getAllQuotaUsage(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/all`,{signal:t},"Failed to fetch all quota usage")}async getUsageLogs(e,t,n){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const i=r.toString(),s=this.apiPath`workspaces/${e}/subscription/usage/logs`+(i?`?${i}`:"");return this.fetchUnwrapped(s,{signal:n},"Failed to fetch usage logs")}async sendNotification(e,t,n,r,i){const s={event:t};return n&&(s.userId=n),r&&(s.data=r),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(s),signal:i},"Failed to send notification")}async getNotificationEvents(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{signal:t},"Failed to fetch notification events")}async getNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{signal:t},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t,n){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update notification preferences")).notificationPreferences??{}}async getMyNotificationPreferences(e,t){const n=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{signal:t},"Failed to fetch your notification preferences");return{defaults:n?.defaults??{},mine:n?.mine??{}}}async updateMyNotificationPreferences(e,t,n){const r=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update your notification preferences");return{defaults:r?.defaults??{},mine:r?.mine??{}}}async getCreditBalance(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits`,{signal:t},"Failed to fetch credit balance")}async consumeCredits(e,t,n){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:n});if(!r.ok){if(402===r.status){const e=await r.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(r,"Failed to consume credits")}return this.unwrapResponse(r,"Failed to consume credits")}async purchaseCredits(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const n=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return n.docs??n}async getCreditTransactions(e,t,n){const r=new URLSearchParams;t?.type&&r.append("type",t.type),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const i=r.toString(),s=this.apiPath`workspaces/${e}/credits/transactions`+(i?`?${i}`:"");return this.fetchUnwrapped(s,{signal:n},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,n){const r=new URLSearchParams;t?.status&&r.append("status",t.status),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const i=r.toString(),s=this.apiPath`workspaces/${e}/credits/buckets`+(i?`?${i}`:"");return this.fetchUnwrapped(s,{signal:n},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,n){const r=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+r,{signal:n},"Failed to fetch expiring credits")}}var G;!function(e){e.V1="v1"}(G||(G={}));const H={UserCreated:"user:created",UserUpdated:"user:updated",WorkspaceChanged:"workspace:changed",WorkspaceUpdated:"workspace:updated",WorkspaceUserAdded:"workspace:user-added",WorkspaceUserRemoved:"workspace:user-removed",WorkspaceUserRoleChanged:"workspace:user-role-changed",WorkspaceCreated:"workspace:created",WorkspaceDeleted:"workspace:deleted",WorkspaceInvitationSent:"workspace:invitation-sent",WorkspaceInvitationAccepted:"workspace:invitation-accepted",WorkspaceInvitationDeclined:"workspace:invitation-declined",WorkspaceInvitationRevoked:"workspace:invitation-revoked"};class Q{constructor(){this.callbacks=null,this.listeners=new Map}setCallbacks(e){this.callbacks=e}getCallbacks(){return this.callbacks}async emit(e,t){if(this.callbacks?.handleEvent)try{await this.callbacks.handleEvent(e,t)}catch(t){c(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}const n=this.listeners.get(e);if(n)for(const r of[...n])try{r(t)}catch(t){c(t,{component:"EventEmitter",action:"notifyListener",metadata:{eventType:e}})}}on(e,t){const n=this.listeners.get(e)??new Set;return n.add(t),this.listeners.set(e,n),()=>{this.listeners.get(e)?.delete(t)}}async emitUserCreated(e){await this.emit(H.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(H.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(H.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(H.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(H.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceInvitationSent(e,t){await this.emit(H.WorkspaceInvitationSent,{invitation:e,workspaceId:t})}async emitWorkspaceInvitationAccepted(e,t){await this.emit(H.WorkspaceInvitationAccepted,{invitation:e,workspace:t})}async emitWorkspaceInvitationDeclined(e){await this.emit(H.WorkspaceInvitationDeclined,{invitation:e})}async emitWorkspaceInvitationRevoked(e,t){await this.emit(H.WorkspaceInvitationRevoked,{invitationId:e,workspaceId:t})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(H.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(H.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(H.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(H.WorkspaceDeleted,{workspace:e})}}const Y=new Q,X=globalThis;function Z(e){const t=Symbol.for(`@buildbase/sdk.invalidation.${e}`),n=X[t]??(X[t]=new Set);return{subscribe:e=>(n.add(e),()=>{n.delete(e)}),invalidate(){n.forEach(e=>e())},reset(){n.clear()}}}const ee=Z("credit-balance").invalidate,te=Z("quota-usage").invalidate,ne=Z("subscription").invalidate,re="bb",ie={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},se={Success:"success",Cancel:"cancel",Error:"error"},ae={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function oe(e,t){const n=t??("undefined"!=typeof window?window.location.href:"https://localhost");let r;try{r=new URL(n)}catch{throw new Error(`createBBUrl: invalid base URL: ${JSON.stringify(n)}`)}return r.search="",r.searchParams.set(re,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}function ce(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:oe({action:ie.Checkout,status:se.Success,ws:e,screen:ae.Subscription},n),cancelUrl:oe({action:ie.Checkout,status:se.Cancel,ws:e,screen:ae.Subscription},n)}}function le(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:oe({action:ie.CreditPurchase,status:se.Success,ws:e,screen:ae.Credits},n),cancelUrl:oe({action:ie.CreditPurchase,status:se.Cancel,ws:e,screen:ae.Credits},n)}}function ue(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(re);if(!e)return null;const t=function(e){const t={};if(!e)return t;const n=e.split(",");for(const e of n){const n=e.indexOf(":");if(-1===n)continue;const r=decodeURIComponent(e.slice(0,n)),i=decodeURIComponent(e.slice(n+1));r&&(t[r]=i)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}}function de(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(re)&&(e.searchParams.delete(re),window.history.replaceState({},"",e.toString()))}catch{}}const pe="__buildbaseBeforeLeave",he=globalThis,fe=he[pe]??(he[pe]=new Set);function ge(e,t={}){if(!e||"string"!=typeof e)return null;if(/^\/(?![/\\])/.test(e))return e;let n;try{n=new URL(e)}catch{return null}const r="https:"===n.protocol,i="http:"===n.protocol&&("localhost"===n.hostname||"127.0.0.1"===n.hostname||"[::1]"===n.hostname);if(!r&&!i)return null;const{sameOrigin:s,allowedOrigins:a}=t;return s||a?.length?s&&"undefined"!=typeof window&&window.location&&n.origin===window.location.origin||a?.some(e=>e.replace(/\/+$/,"")===n.origin)?e:null:e}function me(e,t="/",n={}){if("undefined"==typeof window||!window.location)return!1;const r=ge(e,n)??ge(t)??"/";return function(e){if("undefined"==typeof window||!window.location||0===fe.size)return;let t;try{t=new URL(e,window.location.href).origin}catch{return}if(t!==window.location.origin)for(const e of fe)try{e()}catch{}}(r),window.location.href=r,!0}const we="saas-auth-intent";function ye(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function ke(e){ge(e,{sameOrigin:!0})&&p(we,{returnUrl:e,createdAt:Date.now()})}function be(){const e=d(we,ye);return u(we),e?Date.now()-e.createdAt>6e5?null:ge(e.returnUrl,{sameOrigin:!0}):null}function ve(){u(we)}const Se={usd:"$",eur:"€",gbp:"£",jpy:"¥",cad:"CA$",aud:"A$",chf:"CHF",cny:"¥",hkd:"HK$",sgd:"S$",inr:"₹",mxn:"MX$",brl:"R$",nzd:"NZ$",sek:"kr",nok:"kr",dkk:"kr",pln:"zł",thb:"฿"},Ee={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function _e(e){return e&&e.trim()?Ee[e.trim().toLowerCase()]??"":""}function Ie(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return Se[t]??t.toUpperCase()}const $e=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],Pe=$e.map(e=>({value:e,label:`${e.toUpperCase()} (${Ie(e)})`})),Ue=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),Te=new Set(["bhd","jod","kwd","omr","tnd"]),Ae=new Map;function Ce(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(Ue.has(t))return 0;if(Te.has(t))return 3;if("isk"===t)return 2;let n=Ae.get(t);if(void 0===n){try{n=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{n=2}Ae.set(t,n)}return n}function Oe(e){return""!==(e??"").trim()&&0===Ce(e)}function xe(e,t){const n=Ce(t);return 0===n?e.toLocaleString("en-US"):(e/10**n).toFixed(n)}function Re(e,t,n="en-US"){const r=(t??"").trim(),i=Ce(r),s=e/10**i;if(!r)return s.toFixed(i);try{return new Intl.NumberFormat(n,{style:"currency",currency:r.toUpperCase(),minimumFractionDigits:i,maximumFractionDigits:i}).format(s)}catch{return Ie(r)+(0===i?s.toLocaleString("en-US"):s.toFixed(i))}}function Ne(e,t){return Ie(t)+xe(e,t)}const Fe={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};function We(e,t,n,r,i){if(null==e||e<0)return null;const s={...Fe,...r},a=null!=t&&t>=1?t:1,o=Ie(n),c=xe(e,n);return 1===a?`${o}${c}/${s.unit}`:`${o}${c}/${a.toLocaleString(i)} ${s.units}`}function Le(e,t,n,r,i,s,a){if(null==e||e<0)return null;const o={...Fe,...s},c=null!=t&&t>=1?t:1,l=Ie(r),u=xe(e,r);if(n){const e=i??(n.endsWith("s")?n:`${n}s`);return c>=2?`${l}${u}/${c.toLocaleString(a)} ${e}`:`${l}${u}/${n}`}return 1===c?`${l}${u}/${o.unit}`:`${l}${u}/${c.toLocaleString(a)} ${o.units}`}function De(e,t="unit"){const n=(e||"").trim().toLowerCase();if(!n)return t;const r=n.split(/\s+/)[0]??n;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(r)?r:r.endsWith("ies")&&r.length>3?r.slice(0,-3)+"y":r.endsWith("ses")||r.endsWith("xes")||r.endsWith("zes")||r.endsWith("ches")||r.endsWith("shes")?r.slice(0,-2):r.endsWith("s")&&!r.endsWith("ss")&&r.length>1?r.slice(0,-1):r||t}function Je(e,t,n,r,i,s,a,o,c){const l={...Fe,...a};if(!1===o)return null!=e?`${l.included}: ${e.toLocaleString(c)} (${l.hardLimit})`:a?.hardLimit??"Hard limit";const u=s??(n.endsWith("s")?n:`${n}s`),d=null!=i&&i>=2?`${i.toLocaleString(c)} ${u}`:n;return null!=e&&null!=t?`${l.included}: ${e.toLocaleString(c)}, ${l.afterThat} ${Ne(t,r)}/${d}`:null!=e?`${l.included}: ${e.toLocaleString(c)}`:null!=t?`${l.afterIncluded}: ${Ne(t,r)}/${d}`:"—"}function Me(e,t){if(null==e)return null;const n=e[t??"monthly"];return n?{included:n.included,...void 0!==n.overage&&{overage:n.overage},...void 0!==n.unitSize&&{unitSize:n.unitSize},allowOverage:!1!==e.allowOverage}:null}const je={included:"included",then:"then",hardLimit:"hard limit"};function Be(e,t,n={}){const{overageInCents:r=!0,currency:i}=n,s={...je,...n.labels},a=n.currencySymbol??Ie(i??"");if(null==e)return"—";const{included:o,overage:c}=e,l=`${o} ${s.included}`;if(!1===e.allowOverage)return`${l} (${s.hardLimit})`;if(null==c)return l;const u=Ce(i),d=r&&u>0?c/10**u:c,p="number"==typeof d&&Number.isFinite(d)?0===u?d.toLocaleString("en-US"):d.toFixed(u):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${s.then} ${a}${p}${h}`}const qe={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},ze={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},Ve={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},Ke={Feature:"feature",Limit:"limit",Quota:"quota"},Ge={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},He={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},Qe={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},Ye={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function Xe(e,t){const n=e.pricingVariants;if(!n?.length)return null;const r=t.toLowerCase();return n.find(e=>e.currency?.toLowerCase()===r)??null}function Ze(e,t,n){const r=Xe(e,t);if(!r?.basePricing)return null;const i=r.basePricing[n];return null!=i?i:null}function et(e,t,n){const r=Xe(e,t);if(!r?.stripePrices)return null;const i=n===qe.Monthly?"monthlyPriceId":n===qe.Yearly?"yearlyPriceId":"quarterlyPriceId",s=n===qe.Monthly?"monthly":n===qe.Yearly?"yearly":void 0;return r.stripePrices[i]??(s?r.stripePrices[s]:void 0)??null}function tt(e,t,n,r){const i=Xe(e,t),s=i?.quotaOverages?.[n];if(s)return s[r]}function nt(e,t){const n=Xe(e,t);return n?n.currency:e.plan?.currency??""}function rt(e){const t=new Set;for(const n of e)n.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()}function it(e,t,n,r){const i=e.quotas?.[n];if(null==i)return null;const s=i[r];if(!s)return null;const a=tt(e,t,n,r);return{included:s.included,...void 0!==s.unitSize&&{unitSize:s.unitSize},...void 0!==a&&{overage:a},allowOverage:!1!==i.allowOverage}}function st(e,t){if(!e)return null;for(const n of t){const t=n.pricingVariants;if(t?.length)for(const n of t){const t=n.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:n.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:n.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:n.currency}}}}return null}function at(e,t){const n=Xe(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function ot(e,t,n){const r=at(e,t);return r?.perSeat?r.perSeat[n]??null:null}function ct(e,t){return Math.max(0,e-(t||0))}function lt(e,t,n,r){const i=at(e,t);if(!i)return null;return ct(r,i.includedSeats)*(ot(e,t,n)??0)}function ut(e,t,n,r){const i=Ze(e,t,n);if(null===i)return null;if(void 0===r)return i;return i+(lt(e,t,n,r)??0)}function dt(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=at(t,n);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=r&&r>0?{maxUsers:r,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function pt(e){const{memberCount:t,maxUsersConfig:n,hasSubscription:r=!0,requireSubscription:i=!1}=e;if(i&&!r)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:s,source:a}=n;if(s<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=s){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[a]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[a]??"users.memberLimitMessage",blockMessageValues:{maxUsers:s}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}function ht(e,t){return[qe.Monthly,qe.Quarterly,qe.Yearly].filter(n=>n===qe.Monthly||e.some(e=>null!=Ze(e,t,n)))}const ft={WORKSPACE_SETTINGS_VIEW:"workspace:settings:view",WORKSPACE_SETTINGS_EDIT:"workspace:settings:edit",WORKSPACE_DELETE:"workspace:delete",WORKSPACE_MEMBERS_VIEW:"workspace:members:view",WORKSPACE_MEMBERS_INVITE:"workspace:members:invite",WORKSPACE_MEMBERS_REMOVE:"workspace:members:remove",WORKSPACE_MEMBERS_ROLE_CHANGE:"workspace:members:role-change",WORKSPACE_FEATURES_VIEW:"workspace:features:view",WORKSPACE_FEATURES_EDIT:"workspace:features:edit",WORKSPACE_BILLING_VIEW:"workspace:billing:view",WORKSPACE_BILLING_MANAGE:"workspace:billing:manage",WORKSPACE_USAGE_VIEW:"workspace:usage:view",WORKSPACE_USAGE_RECORD:"workspace:usage:record"},gt=Object.values(ft),mt={admin:gt.filter(e=>e!==ft.WORKSPACE_DELETE),editor:[ft.WORKSPACE_SETTINGS_VIEW,ft.WORKSPACE_MEMBERS_VIEW,ft.WORKSPACE_FEATURES_VIEW,ft.WORKSPACE_BILLING_VIEW,ft.WORKSPACE_USAGE_VIEW,ft.WORKSPACE_USAGE_RECORD],viewer:[ft.WORKSPACE_SETTINGS_VIEW,ft.WORKSPACE_MEMBERS_VIEW]},wt="viewer";function yt(e,t){return t&&"admin"!==t&&e.includes(t)?t:e.includes(wt)?wt:e.find(e=>"admin"!==e)??""}function kt(e){const t=new Set;for(const n of Object.values(e))for(const e of n)t.add(e);return Array.from(t)}function bt(e){const{userId:t,workspace:n,settings:r,appPermissions:i}=e;if(!n||!t)return new Set;if(function(e,t){if(!t)return!1;const n=(r=e.createdBy)?"string"==typeof r?r:"object"==typeof r&&"_id"in r&&"string"==typeof r._id?r._id:null:null;var r;return null!==n&&n===t}(n,t)){const e=new Set(gt);if(i)for(const t of kt(i))e.add(t);if(n.permissions)for(const t of kt(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of kt(r.workspace.permissions))e.add(t);return e}const s=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const n=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return n&&"object"==typeof n&&"role"in n&&"string"==typeof n.role?n.role:null}(n,t);return s?vt(s,e):new Set}function vt(e,t,n={}){const{workspace:r,settings:i,appPermissions:s}=t;if(!r)return new Set;const a=r.permissions,o=i?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),l=e=>e.filter(e=>!e.startsWith("workspace:")),u=e=>!!a&&e in a,d=e=>!!o&&e in o,p=e=>u(e)||d(e)||e in mt;let h,f=e;if(!p(e)){const e=i?.workspace?.defaultRole;if(!e||"admin"===e||!p(e))return new Set;f=e}h=u(f)?c(a[f]):d(f)?c(o[f]):mt[f]??[];const g=new Set(h),m=new Set((i?.workspace?.customPermissions??[]).map(e=>e.key)),w=s?.[f]?l(s[f]).filter(e=>!m.has(e)):[];let y;y=u(f)?l(a[f]):d(f)?[...l(o[f]),...w]:s?.[f]?l(s[f]):[];for(const e of y)g.add(e);if("admin"===f){for(const e of mt.admin)g.add(e);for(const e of m)g.add(e);if(s)for(const e of l(kt(s)))g.add(e)}return!1!==n.applyRestrictions&&function(e,t,n){if(!n?.workspace)return;const{canInviteMembers:r}=n.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(ft.WORKSPACE_MEMBERS_INVITE)}(g,f,i),g}function St(e,t){const n=bt(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}const Et="App";function _t(e,t){const n=e?.workspace?.customPermissions??[],r=new Map;for(const e of n)e?.key&&!e.key.startsWith("workspace:")&&r.set(e.key,{key:e.key,label:e.label||e.key,group:e.group||Et});for(const e of Object.values(t??{}))for(const t of e??[])t.startsWith("workspace:")||r.has(t)||r.set(t,{key:t,label:t,group:Et});return[...r.values()].sort((e,t)=>(e.group??"").localeCompare(t.group??"")||e.key.localeCompare(t.key))}const It="\n// BuildBase Push Notification Service Worker\n// Place this file in your app's public directory (e.g. public/push-sw.js)\n\nself.addEventListener('push', function(event) {\n if (!event.data) return;\n\n let payload;\n try {\n payload = event.data.json();\n } catch (e) {\n console.error('[PushSW] Push payload is not JSON:', e);\n return;\n }\n if (!payload || typeof payload !== 'object') return;\n\n // i18n exception: service workers run outside the SDK's translation\n // provider, so this last-resort fallback stays English. The server should\n // always send a localized payload.title.\n const title = payload.title || 'Notification';\n // The tracked click URL (/api/push-track/link/...) wins over any url in\n // payload.data, so a click is always counted.\n const data = Object.assign({}, payload.data && typeof payload.data === 'object' ? payload.data : {});\n if (payload.url) data.url = payload.url;\n // A notification with the same tag replaces the earlier one instead of\n // stacking. No tag means every notification is shown on its own.\n const tag = payload.tag ? String(payload.tag) : undefined;\n const actions = Array.isArray(payload.actions)\n ? payload.actions.filter(function(a) {\n return a && typeof a.action === 'string' && typeof a.title === 'string';\n })\n : undefined;\n\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.badge || payload.icon || undefined,\n image: payload.image || undefined,\n tag: tag,\n // The browser rejects renotify without a tag.\n renotify: tag ? !!payload.renotify : false,\n actions: actions && actions.length ? actions : undefined,\n silent: !!payload.silent,\n requireInteraction: !!payload.requireInteraction,\n timestamp: typeof payload.timestamp === 'number' ? payload.timestamp : undefined,\n dir: payload.dir === 'ltr' || payload.dir === 'rtl' ? payload.dir : 'auto',\n data: data,\n };\n\n event.waitUntil(\n Promise.resolve()\n .then(function() {\n return self.registration.showNotification(title, options);\n })\n .catch(function(e) {\n // A field this browser refuses must not cost the user the\n // notification: show it again with the basics only.\n console.error('[PushSW] Failed to show notification, retrying without rich options:', e);\n return self.registration.showNotification(title, {\n body: options.body,\n icon: options.icon,\n tag: tag,\n data: data,\n });\n })\n );\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\n // A click on an action button (event.action is its id) opens the same\n // tracked URL as a click on the notification body.\n const url = event.notification.data && event.notification.data.url;\n if (url) {\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {\n for (let i = 0; i < clientList.length; i++) {\n const client = clientList[i];\n if (client.url === url && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(url);\n }\n })\n );\n }\n});\n";var $t;function Pt(e){if(!e)return 0;const t=new Date(e).getTime();return Number.isNaN(t)?0:t}function Ut(e){const t=e=>"invited"===e.status?0:1;return[...e].sort((e,n)=>t(e)-t(n)||Pt(n.invitedAt)-Pt(e.invitedAt))}function Tt(e,t=new Date){return"invited"===e.status&&(null===e.validTill||void 0===e.validTill||Pt(e.validTill)>t.getTime())}function At(e,t=new Date){return Ut(e.filter(e=>Tt(e,t)))}function Ct(e,t=new Date){return"expired"===e.status||"invited"===e.status&&!Tt(e,t)}function Ot(e){return"object"==typeof e.workspace&&e.workspace&&e.workspace.name||""}function xt(e){return"object"==typeof e.workspace&&e.workspace?e.workspace._id:e.workspace}function Rt(e){const t=e.invitedBy;return t&&"string"!=typeof t&&(t.name||t.email)||null}function Nt(e,t=new Date){const n=Pt(e.resendAvailableAt);return n?Math.max(0,Math.ceil((n-t.getTime())/1e3)):0}!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}($t||($t={}));const Ft="saas-pending-invite",Wt=/^[0-9a-f]{64}$/;function Lt(e){return"object"==typeof e&&null!==e&&"string"==typeof e.token&&"string"==typeof e.orgId&&"number"==typeof e.createdAt}function Dt(e,t){Wt.test(e)&&t&&p(Ft,{token:e,orgId:t,createdAt:Date.now()})}function Jt(e,t=Date.now()){const n=d(Ft,Lt);return n?t-n.createdAt>864e5?(u(Ft),null):n.orgId!==e?null:Wt.test(n.token)?n.token:(u(Ft),null):null}function Mt(){u(Ft)}const jt={User:["user.registered","user.logged_in","user.new_device_login","user.email_verified","user.password_changed","user.password_reset_requested","user.profile_updated","user.tag_added","user.tag_removed","user.blocked","user.unblocked"],Organization:["organization.member_invited","organization.member_accepted","organization.member_role_changed","organization.member_removed","organization.public_write_limit_reached","organization.end_user_ceiling_reached"],Workspace:["workspace.created","workspace.updated","workspace.deleted","workspace.settings_updated","workspace.features_updated","workspace.member_added","workspace.member_removed","workspace.member_role_changed","workspace.member_invited","workspace.invitation_accepted","workspace.invitation_declined","workspace.invitation_revoked","workspace.invitation_expired"],Subscription:["subscription.created","subscription.updated","subscription.upgraded","subscription.canceled","subscription.cancel_scheduled","subscription.resumed","subscription.suspended","subscription.trial_started","subscription.trial_will_end","subscription.trial_expired","subscription.downgraded"],Payment:["payment.succeeded","payment.failed","payment.action_required","payment.refunded"],Quota:["quota.limit_exceeded"],Credit:["credit.purchased","credit.consumed","credit.expired","credit.granted","credit.revoked","credit.low_balance"],Workflow:["workflow.created","workflow.deleted","workflow.published","workflow.paused","workflow.resumed","workflow.instance_completed","workflow.instance_failed"],Audience:["audience.member_created","audience.member_updated","audience.added_to_list","audience.removed_from_list","audience.attribute_changed","audience.tag_added","audience.tag_removed","audience.unsubscribed","audience.resubscribed","audience.email_invalidated","audience.blocked","audience.unblocked","audience.import_completed","audience.list_created","audience.list_updated","audience.list_deleted"],Email:["email.domain_added","email.domain_verified","email.sent","email.opened","email.clicked","email.bounced","email.complained","email.unsubscribed","email.campaign_sent"],Push:["push.campaign_sent"],Auth:["auth.method_deleted","auth.domain_added","auth.domain_verified","auth.domain_deleted","auth.client_self_registered"],Token:["token.created","token.updated","token.revoked"],"Group version":["group_version.published"],Form:["form.submitted"],Blog:["blog.published","blog.updated","blog.unpublished","blog.deleted"],Doc:["doc.published","doc.updated","doc.unpublished","doc.deleted"],FAQ:["faq.updated"],"FAQ collection":["faq_collection.updated"],Testimonial:["testimonial.updated","testimonial.deleted"],"Rich content":["rich_content.updated","rich_content.deleted"],Collection:["collection.version_published","collection.record_created","collection.record_updated","collection.record_deleted"]},Bt=Object.values(jt).flat(),qt=new Set(Bt);function zt(e){return qt.has(e)}const Vt=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]),Kt=(e,t)=>e>>>t|e<<32-t;function Gt(e){let t=1779033703,n=3144134277,r=1013904242,i=2773480762,s=1359893119,a=2600822924,o=528734635,c=1541459225;const l=e.length,u=l+1,d=u+(56-u%64+64)%64+8,p=new Uint8Array(d);p.set(e,0),p[l]=128;const h=8*l,f=Math.floor(h/4294967296),g=h>>>0;p[d-8]=f>>>24&255,p[d-7]=f>>>16&255,p[d-6]=f>>>8&255,p[d-5]=255&f,p[d-4]=g>>>24&255,p[d-3]=g>>>16&255,p[d-2]=g>>>8&255,p[d-1]=255&g;const m=new Uint32Array(64);for(let e=0;e<d;e+=64){for(let t=0;t<16;t++){const n=e+4*t;m[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=Kt(m[e-15],7)^Kt(m[e-15],18)^m[e-15]>>>3,n=Kt(m[e-2],17)^Kt(m[e-2],19)^m[e-2]>>>10;m[e]=m[e-16]+t+m[e-7]+n>>>0}let l=t,u=n,d=r,h=i,f=s,g=a,w=o,y=c;for(let e=0;e<64;e++){const t=y+(Kt(f,6)^Kt(f,11)^Kt(f,25))+(f&g^~f&w)+Vt[e]+m[e]>>>0,n=l&u^l&d^u&d;y=w,w=g,g=f,f=h+t>>>0,h=d,d=u,u=l,l=t+((Kt(l,2)^Kt(l,13)^Kt(l,22))+n>>>0)>>>0}t=t+l>>>0,n=n+u>>>0,r=r+d>>>0,i=i+h>>>0,s=s+f>>>0,a=a+g>>>0,o=o+w>>>0,c=c+y>>>0}const w=new Uint8Array(32),y=[t,n,r,i,s,a,o,c];for(let e=0;e<8;e++)w[4*e]=y[e]>>>24&255,w[4*e+1]=y[e]>>>16&255,w[4*e+2]=y[e]>>>8&255,w[4*e+3]=255&y[e];return w}function Ht(e){return(new TextEncoder).encode(e)}function Qt(e,t){let n=e;n.length>64&&(n=Gt(n));const r=new Uint8Array(64),i=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<n.length?n[e]:0;r[e]=54^t,i[e]=92^t}const s=Gt(Xt(r,t));return Gt(Xt(i,s))}function Yt(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}function Xt(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function Zt(e){const{body:t,signature:n,timestamp:r,secret:i,maxAgeSeconds:s=300}=e;if(!(n&&r&&i&&t))return!1;const a="sha256=";if(!n.startsWith(a))return!1;const o=n.slice(7);if(s>0){const e=parseInt(r,10);if(isNaN(e))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-e)>s)return!1}const c=function(e){if(e.length%2!=0)return null;const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++){const r=parseInt(e.slice(2*n,2*n+2),16);if(Number.isNaN(r))return null;t[n]=r}return t}(o);if(!c)return!1;const l=Qt(Ht(i),Ht(`${r}.${t}`));return c.length===l.length&&Yt(c,l)}function en(e){if(!Zt(e))return null;try{return JSON.parse(e.body)}catch{return null}}const tn=300,nn="/.well-known/oauth-protected-resource",rn="/.well-known/agent-skills",sn="/.well-known/api-catalog",an="/.well-known/mcp/server-card.json",on="/.well-known/agent-card.json",cn="application/json",ln="application/linkset+json",un="text/markdown; charset=utf-8",dn="text/plain; charset=utf-8",pn="application/xml; charset=utf-8",hn=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function fn(e){return e.replace(/\/+$/,"")}function gn(e){return`public, max-age=${e}, s-maxage=${e}`}function mn(e){return"sha256:"+function(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}(Gt(Ht(e)))}const wn=function(){const e=new Map;return{get(t){const n=e.get(t);if(n){if(!(n.expiresAt<=Date.now()))return n.value;e.delete(t)}},set(t,n,r){e.set(t,{value:n,expiresAt:Date.now()+1e3*r})},delete(t){e.delete(t)},clear(){e.clear()}}}(),yn=new Set;function kn(e){return e.cache??wn}const bn=500;function vn(e){let t;const n=new Promise((e,n)=>{t=setTimeout(()=>n(new Error("discovery cache timed out")),500)});return Promise.race([Promise.resolve(e),n]).finally(()=>clearTimeout(t))}async function Sn(e,t){try{const n=await vn(e.get(t));return null==n?{hit:!1}:{hit:!0,value:JSON.parse(n)}}catch{return{hit:!1}}}async function En(e,t,n,r){try{await vn(e.set(t,JSON.stringify(n),r)),e!==wn&&yn.add(t)}catch{}}async function _n(e,t,n,r){if(!r||r<=0)return e(t,n);const i=new AbortController,s=setTimeout(()=>i.abort(),r);try{return await e(t,{...n,signal:i.signal})}finally{clearTimeout(s)}}async function In(e){const t=e.cacheTtlSeconds??tn,n=kn(e),r=`buildbase:agent-readiness:${fn(e.serverUrl)}::${e.orgId}`,i=await Sn(n,r);if(i.hit)return i.value;const s=e.fetch??fetch,a=`${fn(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let o={enabled:!1};try{const t=await _n(s,a,{headers:{Accept:cn}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(o=e)}}catch{}return await En(n,r,o,t),o}function $n(e){wn.clear();const t=e;if(t?.delete){for(const e of yn)try{const n=t.delete(e);n&&"function"==typeof n.then&&n.catch(()=>{})}catch{}yn.clear()}else yn.clear()}function Pn(e,t){const n=fn(e.siteUrl),r={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:nn};t.authorizationServer?.metadataUrl&&(r.oauth_authorization_server=t.authorizationServer.metadataUrl,r.openid_configuration="/.well-known/openid-configuration"),(t.authorizationServer||e.authMd)&&(r.auth="/auth.md"),e.skills?.length&&(r.agent_skills=`${rn}/index.json`),e.apiCatalog?.length&&(r.api_catalog=sn),e.mcpServerCard&&(r.mcp_server_card=an),!1!==e.a2aCard&&(r.a2a_agent_card=on),e.llmsFullTxt&&(r.llms_full_txt="/llms-full.txt");return zn({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:n,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:n},capabilities:r,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}function Un(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const n="/"===t?"":t.replace(/\/+$/,"");return nn+n}function Tn(e,t,n){const r=t.protectedResources??[];if(!r.length)return null;const i=e.replace(/\/+$/,"")||nn,s=n??`${fn(t.serverUrl)}/org/${t.orgId}`,a=t.scopes?.map(e=>e.name),o=r.map(e=>{const n=e.resource??fn(t.siteUrl),r=e.scopes??a;return{path:Un(n),metadata:{resource:n,authorization_servers:[s],bearer_methods_supported:e.bearerMethods??["header"],...r?.length?{scopes_supported:r}:{},...e.documentationUrl?{resource_documentation:e.documentationUrl}:{}}}}),c=o.find(e=>e.path===i);return c?zn(c.metadata,t):i===nn&&1===o.length?zn(o[0].metadata,t):null}function An(e){const t=e.skills??[];if(!t.length)return null;const n=fn(e.siteUrl);return zn({$schema:"https://schemas.agentskills.io/discovery/0.2.0/schema.json",skills:t.map(e=>({name:e.name,type:e.type??"skill-md",description:e.description,url:`${n}${Cn(e)}`,digest:mn(e.content)}))},e)}function Cn(e){return e.path??`${rn}/${e.name}/SKILL.md`}function On(e,t){const n=(t.skills??[]).find(t=>Cn(t)===e);return n?{status:200,contentType:"text/markdown; charset=utf-8",body:n.content,cacheControl:gn(t.cacheTtlSeconds??tn)}:null}function xn(e){if(!e.security)return null;const t=(Array.isArray(e.security.contact)?e.security.contact:[e.security.contact]).map(e=>`Contact: ${e}`);return e.security.expires&&t.push(`Expires: ${e.security.expires}`),e.security.policy&&t.push(`Policy: ${e.security.policy}`),{status:200,contentType:dn,body:t.join("\n")+"\n",cacheControl:gn(e.cacheTtlSeconds??tn)}}function Rn(e){return e.llmsTxt?{status:200,contentType:dn,body:e.llmsTxt,cacheControl:gn(e.cacheTtlSeconds??tn)}:null}function Nn(e){return e.llmsFullTxt?{status:200,contentType:dn,body:e.llmsFullTxt,cacheControl:gn(e.cacheTtlSeconds??tn)}:null}function Fn(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},n=fn(e.siteUrl),r=t.serviceUrl??n,i=t.transportProtocol??"http",s=t.skills??((e.skills??[]).length?(e.skills??[]).map(e=>({id:e.name,name:e.name,description:e.description,tags:["discovery"]})):[{id:"site-content",name:"Site content",description:`Read ${e.site.name}'s public content and machine-readable discovery documents (llms.txt, sitemap, API catalog).`,tags:["content"]}]);return zn({protocolVersion:"0.3.0",name:t.name??e.site.name,version:t.version??"1.0.0",description:t.description??e.site.description??`${e.site.name} — agent-accessible web application.`,url:r,preferredTransport:i,supportedInterfaces:[{serviceUrl:r,transportProtocol:i}],provider:e.site.provider?{organization:e.site.provider.name,url:e.site.provider.url}:{organization:e.site.name,url:n},capabilities:t.capabilities??{streaming:!1,pushNotifications:!1},defaultInputModes:["text/plain","application/json"],defaultOutputModes:["text/plain","application/json"],skills:s,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}},e)}function Wn(e){const t=e.webBotAuth?.keys;return t?.length?{status:200,contentType:"application/http-message-signatures-directory+json",body:JSON.stringify({keys:t},null,2),cacheControl:gn(e.cacheTtlSeconds??tn)}:null}function Ln(e){return e.endsWith(".json")||e.includes(".well-known/")?cn:e.endsWith(".md")?un:e.endsWith(".xml")?pn:dn}function Dn(e){let t;try{t=new URL(e.siteUrl).hostname}catch{return[]}const n=[{name:`_index._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${t}. alpn="h2" port=443`}];if(!1!==e.a2aCard&&n.push({name:`_a2a._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${t}. alpn="h2" port=443`}),e.mcpServerCard){let r=t;try{r=new URL(e.mcpServerCard.endpoint).hostname}catch{}n.push({name:`_mcp._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${r}. alpn="h2" port=443`})}return n}function Jn(e){const t=e.apiCatalog??[];if(!t.length)return null;const n=t.map(e=>({anchor:e.anchor,...e.title?{title:e.title}:{},...e.serviceDesc?{"service-desc":[{href:e.serviceDesc}]}:{},...e.serviceDoc?{"service-doc":[{href:e.serviceDoc}]}:{},...e.status?{status:[{href:e.status}]}:{}}));return{status:200,contentType:ln,body:JSON.stringify({linkset:n},null,2),cacheControl:gn(e.cacheTtlSeconds??tn)}}function Mn(e){const t=e??{tools:!0},n={tools:!1,resources:!1,prompts:!1};for(const[e,r]of Object.entries(t))n[e]=!1!==r&&null!=r;return n}function jn(e){const t=e.mcpServerCard;return t?zn({$schema:"https://modelcontextprotocol.io/schemas/server-card/v1.0",version:"1.0",protocolVersion:t.protocolVersion??"2025-11-25",serverInfo:{name:t.name,version:t.version},...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},capabilities:Mn(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}function Bn(e){const t=e.mcpServerCard;if(!t)return null;const n=fn(e.siteUrl);let r;try{r={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${Un(t.endpoint)}`}}catch{}return zn({$schema:"https://modelcontextprotocol.io/schemas/mcp-discovery/v1.0",version:"1.0",servers:[{name:t.name,...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},version:t.version,capabilities:Mn(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${n}${an}`,...r?{authentication:r}:{}}]},e)}function qn(e,t){const n=gn(e.cacheTtlSeconds??tn);if(e.authMd)return{status:200,contentType:un,body:e.authMd,cacheControl:n};const r=t.authorizationServer;if(!r)return null;const i=`# Agent Authentication\n\n${e.site.name} supports AI-agent access via OAuth 2.0 (authorization code + PKCE).\n\n## Authorization server\n- Issuer: \`${r.issuer}\`\n- Metadata (RFC 8414): ${r.metadataUrl}\n\nFetch the metadata document above for the \`authorization_endpoint\`, \`token_endpoint\`, supported grant types / PKCE methods, and — when the app allows it — the dynamic client \`registration_endpoint\` (RFC 7591).\n\n## Protected resources (RFC 9728)\nSee \`/.well-known/oauth-protected-resource\`, which lists the resource, its supported scopes, and the authorization server(s) that can issue tokens for it.\n\n## How an agent authenticates\n1. Discover this document and \`/.well-known/oauth-protected-resource\`.\n2. Fetch the authorization-server metadata for the endpoints.\n3. Register a client (dynamic registration) or use a pre-issued client_id.\n4. Run the authorization-code flow with PKCE (S256), requesting the scopes and target \`resource\`.\n5. Exchange the code for an access token and call the API with \`Authorization: Bearer <token>\`.\n\nDocumentation: ${e.site.documentationUrl??e.siteUrl}\n`;return{status:200,contentType:un,body:i,cacheControl:n}}function zn(e,t){return{status:200,contentType:cn,body:JSON.stringify(e,null,2),cacheControl:gn(t.cacheTtlSeconds??tn)}}function Vn(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function Kn(e,t){const n=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${Vn(e)}`);if(t){const e=[...void 0!==t.search?["search="+(t.search?"yes":"no")]:[],...void 0!==t.aiInput?["ai-input="+(t.aiInput?"yes":"no")]:[],...void 0!==t.aiTrain?["ai-train="+(t.aiTrain?"yes":"no")]:[]];e.length&&n.push(`Content-Signal: ${e.join(", ")}`)}for(const t of e.allow??[])n.push(`Allow: ${Vn(t)}`);for(const t of e.disallow??[])n.push(`Disallow: ${Vn(t)}`);return void 0!==e.crawlDelay&&n.push(`Crawl-delay: ${Vn(e.crawlDelay)}`),n.join("\n")}function Gn(e){const t=e.robots??{},n=fn(e.siteUrl),r=t.policies??[{userAgent:"*",allow:["/"]}],i=t.aiBots??"allow",s="allow"===i?[{userAgent:[...hn],allow:["/"]}]:"deny"===i?[{userAgent:[...hn],disallow:["/"]}]:i,a=t.sitemaps??(e.sitemap?[`${n}/sitemap.xml`]:[]),o=[`# robots.txt — agent-ready. See ${n}/llms.txt and ${n}/.well-known/agent.json`,...r.map((e,n)=>Kn(e,0===n?t.contentSignals:void 0)),...s.map(e=>Kn(e)),...a.length?[a.map(e=>`Sitemap: ${Vn(e)}`).join("\n")]:[]];return{status:200,contentType:dn,body:o.join("\n\n")+"\n",cacheControl:gn(e.cacheTtlSeconds??tn)}}function Hn(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function Qn(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Yn(e){const t=e.sitemap?.urls;if(!t?.length)return null;const n=fn(e.siteUrl),r='<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'+t.map(e=>{const t="string"==typeof e?{loc:e}:e;return` <url>\n${[` <loc>${Qn(/^https?:\/\//.test(t.loc)?t.loc:`${n}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${Qn(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${Qn(String(t.changefreq))}</changefreq>`]:[],...void 0!==t.priority?[` <priority>${Hn(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n";return{status:200,contentType:pn,body:r,cacheControl:gn(e.cacheTtlSeconds??tn)}}function Xn(e){if(!e)return!1;let t=0,n=0;for(const r of e.split(",")){const[e,...i]=r.trim().split(";"),s=e.trim().toLowerCase();let a=1;for(const e of i){const[t,n]=e.split("=").map(e=>e.trim());if("q"===t){const e=Number(n);Number.isNaN(e)||(a=e)}}"text/markdown"===s||"text/x-markdown"===s?t=Math.max(t,a):"text/html"!==s&&"text/*"!==s&&"*/*"!==s||(n=Math.max(n,a))}return t>0&&t>=n}function Zn(e,t,n){const r=Xn(e);return{status:200,contentType:r?un:"text/html; charset=utf-8",body:r?t.markdown:t.html,cacheControl:gn(n?.cacheTtlSeconds??tn),vary:"Accept"}}function er(e){const t=fn(e.siteUrl),n=[`<${t}/llms.txt>; rel="describedby"; type="text/plain"`,`<${t}/.well-known/agent.json>; rel="describedby"; type="application/json"`];if(!1!==e.a2aCard&&n.push(`<${t}${on}>; rel="describedby"; type="application/json"`),e.sitemap||e.robots?.sitemaps?.length){const r=e.robots?.sitemaps?.[0]??`${t}/sitemap.xml`;n.push(`<${r}>; rel="sitemap"; type="application/xml"`)}return e.apiCatalog?.length&&n.push(`<${t}${sn}>; rel="api-catalog"; type="${ln}"`),e.mcpServerCard&&n.push(`<${t}${an}>; rel="mcp-server"; type="application/json"`),n.join(", ")}async function tr(e,t){const n=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===n){return Pn(t,await In(t))}if(n===on)return Fn(t);if("/.well-known/http-message-signatures-directory"===n)return Wn(t);if("/.well-known/security.txt"===n)return xn(t);if(n===`${rn}/index.json`)return An(t);if(n.startsWith(`${rn}/`)&&n.endsWith("SKILL.md"))return On(n,t);if("/.well-known/oauth-authorization-server"===n||"/.well-known/openid-configuration"===n){const e=(await In(t)).authorizationServer;if(!e?.metadataUrl)return null;const n=await async function(e,t){const n=t.cacheTtlSeconds??tn,r=kn(t),i=`buildbase:as-metadata:${e}`,s=await Sn(r,i);if(s.hit)return s.value;const a=t.fetch??fetch;let o=null;try{const n=await _n(a,e,{headers:{Accept:cn}},t.fetchTimeoutMs??5e3);if(n.ok){const e=await n.json();e&&"object"==typeof e&&(o=e)}}catch{}return await En(r,i,o,n),o}(e.metadataUrl,t);return zn(n?n:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(n===sn)return Jn(t);if(n===an)return jn(t);if("/.well-known/mcp.json"===n)return Bn(t);if(n.startsWith(nn)){const e=await In(t);return Tn(n,t,e.authorizationServer?.issuer)}return null}async function nr(e,t){const n=e.replace(/\/+$/,"")||e,r=function(e,t){const n=t.extraPaths?.[e];if(void 0===n)return null;const r="string"==typeof n?{body:n}:n;return{status:r.status??200,contentType:r.contentType??Ln(e),body:r.body,cacheControl:r.cacheControl??gn(t.cacheTtlSeconds??tn)}}(n,t);return r||("/robots.txt"===n?Gn(t):"/llms-full.txt"===n?Nn(t):"/sitemap.xml"===n?Yn(t):"/llms.txt"===n?Rn(t):"/auth.md"===n?qn(t,await In(t)):"/security.txt"===n?xn(t):n.startsWith("/.well-known")?tr(n,t):null)}function rr(e){const t=globalThis.navigator;return!!t?.modelContext?.provideContext&&(t.modelContext.provideContext({tools:e}),!0)}function ir(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 sr(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4==0?"":"=".repeat(4-t.length%4),r=atob(t+n),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return i}class ar extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function or(e){const t=JSON.parse((new TextDecoder).decode(sr(e)));if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("JWT segment is not a JSON object");return t}function cr(e,t,n={}){const r=n.clockToleranceSec??60,i=n.requireExp??!0;if(!e||!t)throw new ar("invalid_token","Missing token or client secret");const s=e.split(".");if(3!==s.length)throw new ar("invalid_token","Malformed JWT");const[a,o,c]=s;let l,u;try{l=or(a),u=or(o)}catch{throw new ar("invalid_token","Unreadable JWT segments")}if("HS256"!==l.alg)throw new ar("invalid_algorithm",`Unexpected JWT alg: ${String(l.alg)}`);const d=Qt(Ht(t),Ht(`${a}.${o}`));let p;try{p=sr(c)}catch{throw new ar("invalid_signature","Unreadable JWT signature")}if(!Yt(d,p))throw new ar("invalid_signature","JWT signature verification failed");!function(e){for(const t of["iss","sub","jti"])if(void 0!==e[t]&&"string"!=typeof e[t])throw new ar("invalid_token",`JWT ${t} claim must be a string`);for(const t of["exp","nbf","iat"]){const n=e[t];if(void 0!==n&&("number"!=typeof n||!Number.isFinite(n)))throw new ar("invalid_token",`JWT ${t} claim must be a finite number`)}const t=e.aud;if(!(void 0===t||"string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new ar("invalid_token","JWT aud claim must be a string or string array")}(u);const h=Math.floor(Date.now()/1e3);if(i&&"number"!=typeof u.exp)throw new ar("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof u.exp&&h>u.exp+r)throw new ar("token_expired","JWT has expired");if("number"==typeof u.nbf&&h+r<u.nbf)throw new ar("token_not_yet_valid","JWT is not yet valid");if(void 0!==n.issuer&&u.iss!==n.issuer)throw new ar("invalid_issuer","JWT issuer mismatch");if(void 0!==n.audience){const e=u.aud;if(!(Array.isArray(e)?e.includes(n.audience):e===n.audience))throw new ar("invalid_audience","JWT audience mismatch")}return u}function lr(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function ur(e){return ir(Ht(JSON.stringify(e)))}function dr(e,t,n){if(!t)throw new ar("invalid_secret","Missing signing secret");const r=Math.floor(Date.now()/1e3),i={iat:r,exp:r+(n?.expiresInSec??3600),...e},s=`${ur({alg:"HS256",typ:"JWT"})}.${ur(i)}`;return`${s}.${ir(Qt(Ht(t),Ht(s)))}`}function pr(e){const t=lr(e.authorization);if(!t)throw new ar("invalid_token","Missing Bearer token");return cr(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function hr(e){const t=lr(e.authorization);if(!t)throw new ar("invalid_token","Missing Bearer token");return cr(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function fr(e){return{success:!0,token:e.token,message:e.message??"ok",..."number"==typeof e.expiresIn?{expiresIn:e.expiresIn}:{}}}function gr(e){return{success:!1,token:"",message:e}}async function mr(e){let t;try{t=pr(e)}catch(e){return{status:401,body:gr(e instanceof ar?e.code:"invalid_token")}}return{status:200,body:fr(await e.mintToken(t))}}async function wr(e){let t;try{t=hr(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof ar?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}}function yr(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}function kr(e){const t=[`Bearer resource_metadata="${yr(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${yr(e.error)}"`),e.errorDescription&&t.push(`error_description="${yr(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}const br=12,vr=16;function Sr(){const e=globalThis.crypto;if(!e?.subtle)throw new Error("WebCrypto is unavailable in this runtime — agent-auth session encryption requires globalThis.crypto.subtle (Node 18+, Bun, Deno, edge, browsers).");return e.subtle}const Er=new Map;function _r(e){let t=Er.get(e);return t||(t=(async()=>{const t=await Sr().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return Sr().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),Er.set(e,t)),t}function Ir(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(t){const n=globalThis.crypto.getRandomValues(new Uint8Array(br)),r=await _r(e),i=new Uint8Array(await Sr().encrypt({name:"AES-GCM",iv:n},r,(new TextEncoder).encode(t))),s=i.subarray(i.length-vr),a=i.subarray(0,i.length-vr),o=new Uint8Array(28+a.length);return o.set(n,0),o.set(s,br),o.set(a,28),ir(o)},async decryptSessionRef(t){try{const n=sr(t);if(n.length<=28)return null;const r=n.slice(0,br),i=n.subarray(br,28),s=n.subarray(28),a=new Uint8Array(s.length+vr);a.set(s,0),a.set(i,s.length);const o=await _r(e),c=await Sr().decrypt({name:"AES-GCM",iv:r},o,a);return(new TextDecoder).decode(c)}catch{return null}}}}async function $r(e){const{claims:t,secret:n}=e,r=e.expiresInSec??3600,i=t.resource&&t.resource.length?1===t.resource.length?t.resource[0]:t.resource:void 0,s=t.sessionId?await Ir(n).encryptSessionRef(t.sessionId):void 0;return{token:dr({sub:t.id,userId:t.id,email:t.email,...t.name?{name:t.name}:{},...t.scope?{scope:t.scope}:{},...i?{aud:i}:{},...s?{sid:s}:{},...e.extraClaims},n,{expiresInSec:r}),expiresIn:r}}function Pr(e,t,n){const r=globalThis.process?.env;"1"===r?.MCP_AUTH_DEBUG&&console.warn(`[buildbase/mcp-auth] audience rejected (${n}): received aud=${JSON.stringify(e)} expected one of ${JSON.stringify(t)}`)}function Ur(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const n=Ir(t),r=e.resource?Array.isArray(e.resource)?e.resource:[e.resource]:[];let i=e.resourceMetadataUrl;if(!i&&r.length)try{const e=new URL(r[0]),t="/"===e.pathname?"":e.pathname.replace(/\/+$/,"");i=`${e.origin}/.well-known/oauth-protected-resource${t}`}catch{}return{resourceMetadataUrl:i,verify:async i=>{let s;try{s=cr(i,t,{...e.verify})}catch{return null}if(r.length){const t=s.aud?Array.isArray(s.aud)?s.aud:[s.aud]:[];if(!t.length&&e.requireAudience)return Pr(t,r,"token carries no aud claim"),null;if(t.length&&!t.some(e=>r.includes(e)))return Pr(t,r,"aud does not include this resource"),null}const a="string"==typeof s.sid?await n.decryptSessionRef(s.sid):null,o=Array.isArray(s.scope)?s.scope.filter(e=>"string"==typeof e):"string"==typeof s.scope?s.scope.split(" ").filter(Boolean):void 0;return{sessionId:a??"",userId:"string"==typeof s.userId?s.userId:"string"==typeof s.sub?s.sub:void 0,workspaceId:"string"==typeof s.workspaceId?s.workspaceId:void 0,scopes:o,claims:s}}}}const Tr=function(){const e=new Map;return{get(t){const n=e.get(t);if(n){if(!(n.expiresAt<=Date.now()))return n.value;e.delete(t)}},set(t,n,r){e.set(t,{value:n,expiresAt:Date.now()+1e3*r})},delete(t){e.delete(t)},clear(){e.clear()}}}(),Ar=e=>e.replace(/\/+$/,""),Cr=(e,t)=>`buildbase:org-region:${Ar(e)}::${t}`;async function Or(e){const{orgId:t,centralUrl:n,apiKey:r,timeoutMs:i=5e3}=e;if(!t)throw new Error("resolveServerUrl: orgId is required");if(!n)throw new Error("resolveServerUrl: centralUrl is required");const s=e.cache??Tr,a=Cr(n,t);try{const e=await s.get(a);if(e)return JSON.parse(e)}catch{}const o=e.fetch??fetch,c=`${Ar(n)}/api/organizations/orgs/${encodeURIComponent(t)}/region`,l=new AbortController,u=i>0?setTimeout(()=>l.abort(),i):null;let d;try{d=await o(c,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},signal:l.signal})}finally{u&&clearTimeout(u)}if(!d.ok)throw new Error(`resolveServerUrl: central answered ${d.status} for org ${t}`);const p=await d.json(),h=p?.data??p;if(!h||"string"!=typeof h.serverUrl||!h.serverUrl)throw new Error(`resolveServerUrl: central returned no serverUrl for org ${t}`);const f={orgId:h.orgId||t,region:h.region||"us",cellId:h.cellId||"us",serverUrl:Ar(h.serverUrl)},g=function(e){const t=e.headers.get("cache-control")||"";if(/(?:^|[\s,])(?:no-store|no-cache)(?:$|[\s,=])/i.test(t))return 0;const n=/max-age=(\d+)/i.exec(t);if(!n)return 300;const r=Number(n[1]);return!Number.isFinite(r)||r<0?300:Math.min(r,3600)}(d);if(g>0)try{await s.set(a,JSON.stringify(f),g)}catch{}return f}async function xr(e){const t=Cr(e.centralUrl,e.orgId),n=e.cache;if(Tr.delete?.(t),n?.delete)try{await n.delete(t)}catch{}}function Rr(e){const{serverUrl:t,orgId:n,version:r="v1",region:i,getSessionId:s,timeout:a,maxRetries:o,debug:c,headers:l,onError:u,fetch:d}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!n)throw new Error("BuildBase: orgId is required");const p={...void 0!==a&&{timeout:a},...void 0!==o&&{maxRetries:o},...void 0!==c&&{debug:c},...l&&{headers:l},...u&&{onError:u},...d&&{fetch:d}},h=e=>{const i={serverUrl:t,version:r,orgId:n,sessionId:e,...p};return{workspace:new K(i),user:new J(i),settings:new A(i),push:new U(i),devices:new _(i),uploads:new D(i),sessions:new T(i)}},f=new K({serverUrl:t,version:r,orgId:n,...p}),g=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,n)=>(await e()).workspace.updateWorkspace(t,n),delete:async t=>(await e()).workspace.deleteWorkspace(t),permissions:async t=>(await e()).workspace.getMyPermissions(t),can:async(t,n)=>{const{permissions:r}=await(await e()).workspace.getMyPermissions(t),i=new Set(r);return(Array.isArray(n)?n:[n]).every(e=>i.has(e))}},invitations:{list:async t=>(await e()).workspace.listInvitations(t),create:async(t,n,r,i)=>(await e()).workspace.inviteMember(t,{email:n,role:r,landingUrl:i}),resend:async(t,n)=>(await e()).workspace.resendInvitation(t,n),revoke:async(t,n)=>(await e()).workspace.revokeInvitation(t,n)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,n,r)=>(await e()).workspace.addUser(t,{email:n,role:r}),remove:async(t,n)=>(await e()).workspace.removeUser(t,n),updateRole:async(t,n,r)=>(await e()).workspace.updateUser(t,n,{role:r}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,n)=>(await e()).workspace.createCheckoutSession(t,n),update:async(t,n)=>(await e()).workspace.updateSubscription(t,n),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,n)=>(await e()).workspace.createBillingPortalSession(t,n)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>f.getPublicPlans(e),getVersion:e=>f.getPlanGroupVersion(e)},invoices:{list:async(t,n,r)=>(await e()).workspace.listInvoices(t,n,r),get:async(t,n)=>(await e()).workspace.getInvoice(t,n)},usage:{record:async(t,n)=>(await e()).workspace.recordUsage(t,n),recordBatch:async(t,n)=>(await e()).workspace.recordUsageBatch(t,n),getQuota:async(t,n)=>(await e()).workspace.getQuotaUsageStatus(t,n),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,n)=>(await e()).workspace.getUsageLogs(t,n)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,n,r)=>(await e()).workspace.updateFeature(t,n,r)},notification:{send:async(t,n,r,i)=>(await e()).workspace.sendNotification(t,n,r,i)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,n)=>(await e()).workspace.consumeCredits(t,n),purchase:async(t,n)=>(await e()).workspace.purchaseCredits(t,n),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,n)=>(await e()).workspace.getCreditTransactions(t,n),getBuckets:async(t,n)=>(await e()).workspace.getCreditBuckets(t,n),getExpiring:async(t,n)=>(await e()).workspace.getExpiringCredits(t,n),getPublicPackages:()=>f.getPublicCreditPackages()},permissions:{check:async(t,n,r)=>{const i=await e(),[s,a,o]=await Promise.all([i.workspace.getWorkspace(t),i.settings.getSettings(),i.workspace.getWorkspaceUsers(t)]),c=o.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return St(r,{userId:n,workspaceRole:c?.role??null,workspace:s,settings:a})},resolve:async(t,n)=>{const r=await e(),[i,s,a]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),o=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return bt({userId:n,workspaceRole:o?.role??null,workspace:i,settings:s})}},devices:{list:async()=>(await e()).devices.list(),rename:async(t,n)=>(await e()).devices.rename(t,n),signOut:async t=>(await e()).devices.signOut(t),forget:async t=>(await e()).devices.forget(t)},sessions:{list:async()=>(await e()).sessions.list(),revoke:async t=>(await e()).sessions.revoke(t)}}),m=g(async()=>h(await(async()=>{if(!s)throw new Error("BuildBase: getSessionId callback is required for authenticated calls. Pass it in BuildBase({ getSessionId: ... }) or use withSession(id) / client.forSession(id).");const e=await s();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{...void 0!==i&&{region:i},auth:async()=>{if(!s)return null;const e=await s();return e?{sessionId:e}:null},withSession:e=>{const t=h(e);return g(async()=>t)},client:{forSession:h},...m}}export{hn as AI_BOT_USER_AGENTS,Et as APP_PERMISSION_FALLBACK_GROUP,G as ApiVersion,ar as AppBridgeError,v as AuthApi,$t as AuthStatus,ie as BBAction,ae as BBScreen,se as BBStatus,re as BB_PARAM,b as BaseApi,E as BetaForm,qe as BillingIntervals,Rr as BuildBase,Se as CURRENCY_DISPLAY,Ee as CURRENCY_FLAG,He as CreditBucketSource,Qe as CreditBucketStatus,Ye as CreditTransactionType,mt as DEFAULT_ROLE_PERMISSIONS,bn as DISCOVERY_CACHE_TIMEOUT_MS,Ge as DunningState,Q as EventEmitter,wt as FALLBACK_WORKSPACE_ROLE,M as INVITATION_ERROR_CODE,Ve as InvoiceStatuses,P as NotificationsApi,$e as PLAN_CURRENCY_CODES,Pe as PLAN_CURRENCY_OPTIONS,It as PUSH_SERVICE_WORKER_SCRIPT,ft as Permission,U as PushApi,H as SDKEvent,A as SettingsApi,Ke as SubscriptionItemType,ze as SubscriptionStatus,C as UPLOAD_ACCEPT,O as UPLOAD_MAX_BYTES,D as UploadsApi,J as UserApi,Bt as WEBHOOK_EVENTS,jt as WEBHOOK_EVENTS_BY_CATEGORY,K as WorkspaceApi,At as actionableInvitations,_t as appPermissionCatalogue,gr as appTokenFailure,fr as appTokenSuccess,kr as bearerChallenge,Fn as buildA2AAgentCard,Pn as buildAgentCard,An as buildAgentSkillsIndex,Jn as buildApiCatalog,qn as buildAuthMd,er as buildDiscoveryLinkHeader,Dn as buildDnsAidRecords,Nn as buildLlmsFullTxt,Rn as buildLlmsTxt,Bn as buildMcpDiscoveryManifest,jn as buildMcpServerCard,Tn as buildProtectedResourceMetadata,Gn as buildRobotsTxt,xn as buildSecurityTxt,Yn as buildSitemap,On as buildSkillMd,Wn as buildWebBotAuthDirectory,Ur as buildbaseAuth,ct as calculateBillableSeats,lt as calculateSeatOverageCents,ut as calculateTotalSubscriptionCents,de as cleanBBParams,$n as clearAgentReadinessCache,ve as clearAuthIntent,Mt as clearPendingInvite,xr as clearResolvedServerUrl,be as consumeAuthIntent,oe as createBBUrl,ce as createCheckoutRedirectUrls,le as createCreditPurchaseRedirectUrls,Ir as createSessionRefCrypto,Rr as default,Y as eventEmitter,lr as extractBearerToken,In as fetchAgentReadiness,Ne as formatCents,Re as formatMinorAmountIntl,We as formatOverageRate,Le as formatOverageRateWithLabel,Je as formatQuotaIncludedOverage,Be as formatQuotaWithPrice,L as formatUploadLimit,ht as getAvailableBillingIntervals,rt as getAvailableCurrenciesFromPlans,Ze as getBasePriceCents,st as getBillingIntervalAndCurrencyFromPriceId,Ce as getCurrencyDecimals,_e as getCurrencyFlag,Ie as getCurrencySymbol,nt as getDisplayCurrency,ot as getPerSeatPriceCents,Xe as getPricingVariant,Me as getQuotaDisplayValue,it as getQuotaDisplayWithVariant,tt as getQuotaOverageCents,De as getQuotaUnitLabelFromName,at as getSeatPricing,et as getStripePriceIdForInterval,wr as handleAppRevokeRequest,mr as handleAppTokenRequest,St as hasPermission,ee as invalidateCreditBalance,te as invalidateQuotaUsage,ne as invalidateSubscription,Rt as inviterNameOf,Tt as isInvitationActionable,V as isInvitationError,Ct as isInvitationLapsed,zt as isWebhookEvent,Oe as isZeroDecimalCurrency,xe as minorAmountToDisplay,$r as mintAgentToken,Zn as negotiateMarkdown,Dt as parkPendingInvite,en as parseWebhookEvent,yt as pickDefaultRole,W as preflightUpload,rr as provideWebMcpTools,ue as readBBParams,Jt as readPendingInvite,Nt as resendCooldownSeconds,nr as resolveAgentPath,dt as resolveMaxUsers,bt as resolvePermissions,vt as resolveRolePermissions,Or as resolveServerUrl,tr as resolveWellKnown,me as safeRedirect,ke as saveAuthIntent,mn as sha256Digest,dr as signClientJwt,Ut as sortInvitations,N as uploadFailureOf,F as uploadPolicyOf,pt as validateInvite,ge as validateRedirectUrl,hr as verifyAppRevokeRequest,pr as verifyAppTokenRequest,cr as verifyClientJwt,Zt as verifyWebhookSignature,Xn as wantsMarkdown,xt as workspaceIdOf,Ot as workspaceNameOf};
|