@buildbase/sdk 0.0.48 → 0.0.49
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 +119 -0
- package/CHANGELOG.md +42 -0
- package/README.md +198 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +376 -2
- package/dist/index.mjs +1 -1
- package/dist/react/{index.js → index.cjs} +5 -5
- package/dist/react/index.d.ts +2 -0
- package/dist/react/index.mjs +5 -5
- package/package.json +11 -9
- package/dist/index.js +0 -1
- /package/dist/data/{index.js → index.cjs} +0 -0
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
let e=!0;function t(t,...s){e&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(t,...s)}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 r(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await s(e);r=t.message||t.error||r}catch{r=function(e,t){const s={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}: ${s})`)}(e,t).message}throw new Error(r)}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 n extends Error{constructor(e,t,s,r){super(e),this.code=t,this.context=s,this.originalError=r,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,n)}}const o=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}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,s={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const r=e instanceof Error?e:new n("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",s),o=r instanceof n?r:new n(r.message,"SDK_ERROR",s,r);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${s.component||"Unknown"}:`,{message:o.message,code:o.code,context:o.context,originalError:o.originalError,stack:o.stack}),this.config.onError)try{this.config.onError(o,s)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(o,s)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...s)=>e(...s).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...s)=>{try{return e(...s)}catch(e){throw this.handleError(e,t),e}}}};function i(e,t={}){o.handleError(e,t)}function a(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return i(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function c(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){i(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function u(e,t){try{!function(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){i(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){i(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const l="saas-session-id";function d(){return function(){if("undefined"==typeof window)return null;try{return a(l)}catch(e){return i(e,{component:"auth-utils",action:"getSessionId",metadata:{key:l}}),null}}()}const p="SDK is not ready (missing serverUrl, version, or orgId)";class h{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(p);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(p)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:function(){const e=d(),t={};return e&&(t["x-session-id"]=e),t}()}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}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}async executeFetchUrl(e,t,s){const r=(t.method??"GET").toUpperCase(),n=s??e,o=this.buildHeaders(t),i={...t,headers:o};let a;if(this._timeout>0){const e=new AbortController;a=setTimeout(()=>e.abort(),this._timeout),i.signal=t.signal?AbortSignal.any([t.signal,e.signal]):e.signal}const c=async t=>{try{const s=this._fetch.bind(globalThis),n=await s(e,i);if(this._debug&&console.log(`[BuildBase] ${r} ${e} → ${n.status}`),401===n.status&&this._onUnauthorized&&this._onUnauthorized(),n.status>=500&&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 new Promise(t=>setTimeout(t,e)),c(t+1)}return n}catch(e){if(e instanceof Error&&"AbortError"===e.name){if(void 0!==a){const e=new Error(`Request timeout after ${this._timeout}ms: ${r} ${n}`);throw this._onError?.(e,{method:r,path:n}),e}throw e}if(t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),c(t+1)}throw e instanceof Error&&this._onError?.(e,{method:r,path:n}),e}};try{return await c(0)}finally{void 0!==a&&clearTimeout(a)}}async fetchJson(e,t={},s="Request failed"){this.ensureReady();try{const n=await this.executeFetch(e,t);return await r(n,s)}catch(s){throw s instanceof Error&&this._onError?.(s,{method:(t.method??"GET").toUpperCase(),path:e}),s}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let s=t;try{s=(await e.json()).message||s}catch{s=`${t} (${e.status}: ${e.statusText})`}throw new Error(s)}async unwrapResponse(e,t){const s=await e.json();if(void 0!==s.success){if(!s.success)throw new Error(s.message||t);return s.data||s}return s}}class f extends h{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,s=await this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});return s.ok||await this.throwResponseError(s,"Failed to initiate authentication"),s.json()}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}}class g extends h{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 w{constructor(e){this.api=new g(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},s=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),n=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),o=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:s,language:r,timezone:n,currency:o}})}}class y extends h{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 m extends h{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class k extends h{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 s=await this.unwrapResponse(t,"Failed to fetch user attributes");return s&&"object"==typeof s&&!Array.isArray(s)?s:{}}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(`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 s=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof s&&null!==s?s:{}}}class b extends h{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(){return this.fetchJson("workspaces",{},"Failed to fetch workspaces")}async createWorkspace(e){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e)},"Failed to create workspace")}async updateWorkspace(e,t){return this.fetchJson(`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t)},"Failed to update workspace")}async deleteWorkspace(e){return this.fetchJson(`workspaces/${e}`,{method:"DELETE"},"Failed to delete workspace")}async getWorkspaceUsers(e){return this.fetchJson(`workspaces/${e}/users`,{},"Failed to fetch workspace users")}async addUser(e,t){return this.fetchJson(`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t)},"Failed to invite member")}async removeUser(e,t){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,t,s){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(s)},"Failed to update user")}async updateSettings(e){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e)},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t){return this.fetchJson(`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t})},"Failed to update workspace permissions")}async getFeatures(){return this.fetchJson("workspaces/features",{},"Failed to fetch features")}async updateFeature(e,t,s){return this.fetchJson(`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:s}})},"Failed to update feature")}async getWorkspace(e){return this.fetchJson(`workspaces/${e}`,{},"Failed to fetch workspace")}async getProfile(){return this.fetchJson("profile",{},"Failed to fetch profile")}async updateUserProfile(e){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e)},"Failed to update user profile")}async getPasskeys(){const e=await this.fetchJson("passkeys",{},"Failed to fetch passkeys");return e?.passkeys??[]}async renamePasskey(e,t){await this.fetchJson(`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t})},"Failed to rename passkey")}async deletePasskey(e){await this.fetchJson(`passkeys/${e}`,{method:"DELETE"},"Failed to remove passkey")}async getCurrentSubscription(e){const t=await this.fetchResponse(`workspaces/${e}/subscription`);return t.ok||await this.throwResponseError(t,"Failed to fetch subscription"),this.unwrapResponse(t,"Failed to fetch subscription")}async getPlanGroup(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/plan-group`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group"),this.unwrapResponse(t,"Failed to fetch plan group")}async getPlanGroupByVersion(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/plan-group?groupVersionId=${encodeURIComponent(t)}`);return s.ok||await this.throwResponseError(s,"Failed to fetch plan group version"),this.unwrapResponse(s,"Failed to fetch plan group version")}async getPlanGroupVersions(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/plan-group/versions`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group versions"),this.unwrapResponse(t,"Failed to fetch plan group versions")}async getPublicPlans(e){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");const t=await this.fetchResponse(`${this.orgId}/plans/${encodeURIComponent(e)}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plans"),this.unwrapResponse(t,"Failed to fetch plans")}async getPublicCreditPackages(){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");const e=await this.fetchResponse(`${this.orgId}/credit-packages`);return e.ok||await this.throwResponseError(e,"Failed to fetch credit packages"),this.unwrapResponse(e,"Failed to fetch credit packages")}async getPlanGroupVersion(e){const t=await this.fetchResponse(`plan-group-versions/${e}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group version"),this.unwrapResponse(t,"Failed to fetch plan group version")}async createCheckoutSession(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to create checkout session"),this.unwrapResponse(s,"Failed to create checkout session")}async selectFreePlan(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t})});return s.ok||await this.throwResponseError(s,"Failed to select free plan"),s.json()}async updateSubscription(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to update subscription"),this.unwrapResponse(s,"Failed to update subscription")}async createBillingPortalSession(e,t){return this.fetchJson(`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{})})}async listInvoices(e,t=10,s){const r=new URLSearchParams;r.append("limit",t.toString()),s&&r.append("starting_after",s);const n=await this.fetchResponse(`workspaces/${e}/subscription/invoices?${r.toString()}`);return n.ok||await this.throwResponseError(n,"Failed to fetch invoices"),this.unwrapResponse(n,"Failed to fetch invoices")}async getInvoice(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/invoices/${t}`);return s.ok||await this.throwResponseError(s,"Failed to fetch invoice"),this.unwrapResponse(s,"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to cancel subscription"),this.unwrapResponse(t,"Failed to cancel subscription")}async resumeSubscription(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/resume`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to resume subscription"),this.unwrapResponse(t,"Failed to resume subscription")}async recordUsage(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to record usage"),this.unwrapResponse(s,"Failed to record usage")}async recordUsageBatch(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to record batch usage"),this.unwrapResponse(s,"Failed to record batch usage")}async getQuotaUsageStatus(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/usage/status?quotaSlug=${encodeURIComponent(t)}`);return s.ok||await this.throwResponseError(s,"Failed to fetch quota usage status"),this.unwrapResponse(s,"Failed to fetch quota usage status")}async getAllQuotaUsage(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/usage/all`);return t.ok||await this.throwResponseError(t,"Failed to fetch all quota usage"),this.unwrapResponse(t,"Failed to fetch all quota usage")}async getUsageLogs(e,t){const s=new URLSearchParams;t?.quotaSlug&&s.append("quotaSlug",t.quotaSlug),t?.from&&s.append("from",t.from),t?.to&&s.append("to",t.to),t?.source&&s.append("source",t.source),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const r=s.toString(),n=`workspaces/${e}/subscription/usage/logs${r?`?${r}`:""}`,o=await this.fetchResponse(n);return o.ok||await this.throwResponseError(o,"Failed to fetch usage logs"),this.unwrapResponse(o,"Failed to fetch usage logs")}async sendNotification(e,t,s,r){const n={event:t};return s&&(n.userId=s),r&&(n.data=r),this.fetchJson(`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(n)},"Failed to send notification")}async getNotificationEvents(e){return this.fetchJson(`workspaces/${e}/notification-events`,{},"Failed to fetch notification events")}async getNotificationPreferences(e){return(await this.fetchJson(`workspaces/${e}/notification-preferences`,{},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t){return(await this.fetchJson(`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t})},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e){const t=await this.fetchResponse(`workspaces/${e}/credits`);return t.ok||await this.throwResponseError(t,"Failed to fetch credit balance"),this.unwrapResponse(t,"Failed to fetch credit balance")}async consumeCredits(e,t){const s=await this.fetchResponse(`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t)});if(!s.ok){if(402===s.status){const e=await s.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(s,"Failed to consume credits")}return this.unwrapResponse(s,"Failed to consume credits")}async purchaseCredits(e,t){const s=await this.fetchResponse(`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to create credit purchase checkout"),this.unwrapResponse(s,"Failed to create credit purchase checkout")}async getCreditPackages(e){const t=await this.fetchResponse(`workspaces/${e}/credits/packages`);t.ok||await this.throwResponseError(t,"Failed to fetch credit packages");const s=await this.unwrapResponse(t,"Failed to fetch credit packages");return s.docs??s}async getCreditTransactions(e,t){const s=new URLSearchParams;t?.type&&s.append("type",t.type),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const r=s.toString(),n=`workspaces/${e}/credits/transactions${r?`?${r}`:""}`,o=await this.fetchResponse(n);return o.ok||await this.throwResponseError(o,"Failed to fetch credit transactions"),this.unwrapResponse(o,"Failed to fetch credit transactions")}async getCreditBuckets(e,t){const s=new URLSearchParams;t?.status&&s.append("status",t.status),t?.source&&s.append("source",t.source),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const r=s.toString(),n=`workspaces/${e}/credits/buckets${r?`?${r}`:""}`,o=await this.fetchResponse(n);return o.ok||await this.throwResponseError(o,"Failed to fetch credit buckets"),this.unwrapResponse(o,"Failed to fetch credit buckets")}async getExpiringCredits(e,t){const s=t?`?days=${t}`:"",r=await this.fetchResponse(`workspaces/${e}/credits/expiring${s}`);return r.ok||await this.throwResponseError(r,"Failed to fetch expiring credits"),this.unwrapResponse(r,"Failed to fetch expiring credits")}}var S;!function(e){e.V1="v1"}(S||(S={}));const E={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"};class R{constructor(){this.callbacks=null}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){i(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(E.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(E.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(E.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(E.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,s){await this.emit(E.WorkspaceUserAdded,{userId:e,workspace:t,role:s})}async emitWorkspaceUserRemoved(e,t,s){await this.emit(E.WorkspaceUserRemoved,{userId:e,workspace:t,role:s})}async emitWorkspaceUserRoleChanged(e,t,s,r){await this.emit(E.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:s,newRole:r})}async emitWorkspaceCreated(e){await this.emit(E.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(E.WorkspaceDeleted,{workspace:e})}}const v=new R;function P(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const $=P().invalidate,U=P().invalidate,I=P().invalidate,C="bb",F={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",Invite:"invite"},O={Success:"success",Cancel:"cancel",Error:"error"},_={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function W(e,t){let s;try{const e=t||("undefined"!=typeof window?window.location.href:"https://localhost");s=new URL(e),s.search=""}catch{s=new URL("https://localhost")}return s.searchParams.set(C,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),s.toString()}function A(e,t){const s=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:W({action:F.Checkout,status:O.Success,ws:e,screen:_.Subscription},s),cancelUrl:W({action:F.Checkout,status:O.Cancel,ws:e,screen:_.Subscription},s)}}function N(e,t){const s=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:W({action:F.CreditPurchase,status:O.Success,ws:e,screen:_.Credits},s),cancelUrl:W({action:F.CreditPurchase,status:O.Cancel,ws:e,screen:_.Credits},s)}}function T(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(C);if(!e)return null;const t=function(e){const t={};if(!e)return t;const s=e.split(",");for(const e of s){const s=e.indexOf(":");if(-1===s)continue;const r=decodeURIComponent(e.slice(0,s)),n=decodeURIComponent(e.slice(s+1));r&&(t[r]=n)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}}function J(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(C)&&(e.searchParams.delete(C),window.history.replaceState({},"",e.toString()))}catch{}}function x(e){if(!e||"string"!=typeof e)return null;try{const t=new URL(e);return"https:"===t.protocol?e:"http:"!==t.protocol||"localhost"!==t.hostname&&"127.0.0.1"!==t.hostname&&"::1"!==t.hostname?null:e}catch{return null}}function L(e,t="/"){const s=x(e);window.location.href=s||t}const B="saas-auth-intent";function q(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function M(e){x(e)&&u(B,{returnUrl:e,createdAt:Date.now()})}function V(){const e=function(e,t){const s=a(e);if(!s)return null;try{const r=JSON.parse(s);return t&&!t(r)?(i(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null):r}catch(t){return i(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null}}(B,q);return c(B),e?Date.now()-e.createdAt>6e5?null:x(e.returnUrl):null}function K(){c(B)}const D={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:"฿"},G={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function j(e){return e&&e.trim()?G[e.trim().toLowerCase()]??"":""}function H(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return D[t]??t.toUpperCase()}const z=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],Q=z.map(e=>({value:e,label:`${e.toUpperCase()} (${H(e)})`}));function Y(e,t){return H(t)+(e/100).toFixed(2)}const Z={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included"};function X(e,t,s,r){if(null==e||e<0)return null;const n={...Z,...r},o=null!=t&&t>=1?t:1,i=H(s),a=(e/100).toFixed(2);return 1===o?`${i}${a}/${n.unit}`:`${i}${a}/${o.toLocaleString()} ${n.units}`}function ee(e,t,s,r,n,o){if(null==e||e<0)return null;const i={...Z,...o},a=null!=t&&t>=1?t:1,c=H(r),u=(e/100).toFixed(2);if(s){const e=n??(s.endsWith("s")?s:`${s}s`);return a>=2?`${c}${u}/${a.toLocaleString()} ${e}`:`${c}${u}/${s}`}return 1===a?`${c}${u}/${i.unit}`:`${c}${u}/${a.toLocaleString()} ${i.units}`}function te(e,t="unit"){const s=(e||"").trim().toLowerCase();if(!s)return t;const r=s.split(/\s+/)[0]??s;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 se(e,t,s,r,n,o,i,a){const c={...Z,...i};if(!1===a)return null!=e?`${c.included}: ${e.toLocaleString()} (${c.hardLimit??"hard limit"})`:c.hardLimit??"Hard limit";const u=o??(s.endsWith("s")?s:`${s}s`),l=null!=n&&n>=2?`${n.toLocaleString()} ${u}`:s;return null!=e&&null!=t?`${c.included}: ${e.toLocaleString()}, ${c.afterThat} ${Y(t,r)}/${l}`:null!=e?`${c.included}: ${e.toLocaleString()}`:null!=t?`${c.afterIncluded}: ${Y(t,r)}/${l}`:"—"}function re(e,t){if(null==e)return null;const s=e[t??"monthly"];return s?{included:s.included,...void 0!==s.overage&&{overage:s.overage},...void 0!==s.unitSize&&{unitSize:s.unitSize},allowOverage:!1!==e.allowOverage}:null}const ne={included:"included",then:"then"};function oe(e,t,s={}){const{overageInCents:r=!0,currency:n}=s,o=s.labels??ne,i=s.currencySymbol??H(n??"");if(null==e)return"—";const{included:a,overage:c}=e,u=`${a} ${o.included}`;if(!1===e.allowOverage)return`${u} (hard limit)`;if(null==c)return u;const l=r?c/100:c,d="number"==typeof l&&Number.isFinite(l)?l.toFixed(2):String(c),p=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${u}, ${o.then} ${i}${d}${p}`}const ie={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},ae={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},ce={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},ue={Feature:"feature",Limit:"limit",Quota:"quota"},le={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},de={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},pe={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},he={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function fe(e,t){const s=e.pricingVariants;if(!s?.length)return null;const r=t.toLowerCase();return s.find(e=>e.currency?.toLowerCase()===r)??null}function ge(e,t,s){const r=fe(e,t);if(!r?.basePricing)return null;const n=r.basePricing[s];return null!=n?n:null}function we(e,t,s){const r=fe(e,t);if(!r?.stripePrices)return null;const n=s===ie.Monthly?"monthlyPriceId":s===ie.Yearly?"yearlyPriceId":"quarterlyPriceId",o=s===ie.Monthly?"monthly":s===ie.Yearly?"yearly":void 0;return r.stripePrices[n]??(o?r.stripePrices[o]:void 0)??null}function ye(e,t,s,r){const n=fe(e,t),o=n?.quotaOverages?.[s];if(o)return o[r]}function me(e,t){const s=fe(e,t);return s?s.currency:e.plan?.currency??""}function ke(e){const t=new Set;for(const s of e)s.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()}function be(e,t,s,r){const n=e.quotas?.[s];if(null==n)return null;const o=n[r];if(!o)return null;const i=ye(e,t,s,r);return{included:o.included,...void 0!==o.unitSize&&{unitSize:o.unitSize},...void 0!==i&&{overage:i},allowOverage:!1!==n.allowOverage}}function Se(e,t){if(!e)return null;for(const s of t){const t=s.pricingVariants;if(t?.length)for(const s of t){const t=s.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:s.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:s.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:s.currency}}}}return null}function Ee(e,t){const s=fe(e,t);return s?.seatPricing?.enabled?s.seatPricing:null}function Re(e,t,s){const r=Ee(e,t);return r?.perSeat?r.perSeat[s]??null:null}function ve(e,t){return Math.max(0,e-(t||0))}function Pe(e,t,s,r){const n=Ee(e,t);if(!n)return null;return ve(r,n.includedSeats)*(Re(e,t,s)??0)}function $e(e,t,s,r){const n=ge(e,t,s);if(null===n)return null;if(void 0===r)return n;return n+(Pe(e,t,s,r)??0)}function Ue(e){const{planVersion:t,currency:s="usd",settingsMaxUsers:r}=e;if(t){const e=Ee(t,s);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 Ie(e){const{memberCount:t,maxUsersConfig:s,hasSubscription:r=!0,requireSubscription:n=!1}=e;if(n&&!r)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:o,source:i}=s;if(o<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=o){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[i]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[i]??"users.memberLimitMessage",blockMessageValues:{maxUsers:o}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}const Ce={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"},Fe=Object.values(Ce),Oe={admin:Fe.filter(e=>e!==Ce.WORKSPACE_DELETE),member:[Ce.WORKSPACE_SETTINGS_VIEW,Ce.WORKSPACE_MEMBERS_VIEW,Ce.WORKSPACE_FEATURES_VIEW,Ce.WORKSPACE_BILLING_VIEW,Ce.WORKSPACE_USAGE_VIEW],viewer:[Ce.WORKSPACE_SETTINGS_VIEW,Ce.WORKSPACE_MEMBERS_VIEW]};function _e(e){const t=new Set;for(const s of Object.values(e))for(const e of s)t.add(e);return Array.from(t)}function We(e){const{userId:t,workspace:s,settings:r,appPermissions:n}=e;if(!s||!t)return new Set;if(function(e,t){if(!t)return!1;const s=(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!==s&&s===t}(s,t)){const e=new Set(Fe);if(n)for(const t of _e(n))e.add(t);if(s.permissions)for(const t of _e(s.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of _e(r.workspace.permissions))e.add(t);return e}const o=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const s=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return s&&"object"==typeof s&&"role"in s&&"string"==typeof s.role?s.role:null}(s,t);if(!o)return new Set;const i=s.permissions,a=r?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=i?.[o]?c(i[o]):[],d=a?.[o]?c(a[o]):[],p=Oe[o]??[];let h;if(l.length>0)h=l;else if(d.length>0)h=d;else if(p.length>0)h=p;else{h=Oe[r?.workspace?.defaultRole??"member"]??Oe.member??[]}const f=new Set(h),g=i?.[o]?u(i[o]):[],w=n?.[o]?u(n[o]):[],y=g.length>0?g:w;for(const e of y)f.add(e);return function(e,t,s){if(!s?.workspace)return;const{canInviteMembers:r}=s.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(Ce.WORKSPACE_MEMBERS_INVITE)}(f,o,r),f}function Ae(e,t){const s=We(t);return Array.isArray(e)?e.every(e=>s.has(e)):s.has(e)}const Ne="\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 try {\n const payload = event.data.json();\n const title = payload.title || 'Notification';\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.icon || undefined,\n data: { url: payload.url, ...(payload.data || {}) },\n tag: 'buildbase-push-' + Date.now(),\n };\n\n event.waitUntil(\n self.registration.showNotification(title, options)\n );\n } catch (e) {\n console.error('[PushSW] Failed to show notification:', e);\n }\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\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 Te;function Je(e){const{body:t,signature:s,timestamp:r,secret:n,maxAgeSeconds:o=300}=e;if(!(s&&r&&n&&t))return!1;const i="sha256=";if(!s.startsWith(i))return!1;const a=s.slice(7);if(o>0){const e=parseInt(r,10);if(isNaN(e))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-e)>o)return!1}try{const e=require("crypto"),s=e.createHmac("sha256",n).update(`${r}.${t}`).digest("hex"),o=Buffer.from(a,"hex"),i=Buffer.from(s,"hex");return o.length===i.length&&e.timingSafeEqual(o,i)}catch{return!1}}function xe(e){if(!Je(e))return null;try{return JSON.parse(e.body)}catch{return null}}function Le(e){const{serverUrl:t,orgId:s,version:r="v1",getSessionId:n,timeout:o,maxRetries:i,debug:a,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!s)throw new Error("BuildBase: orgId is required");const d={...void 0!==o&&{timeout:o},...void 0!==i&&{maxRetries:i},...void 0!==a&&{debug:a},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},p=e=>{const n={serverUrl:t,version:r,orgId:s,sessionId:e,...d};return{workspace:new b(n),user:new k(n),settings:new m(n),push:new y(n)}},h=new b({serverUrl:t,version:r,orgId:s,...d}),f=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,s)=>(await e()).workspace.updateWorkspace(t,s),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,s,r)=>(await e()).workspace.addUser(t,{email:s,role:r}),remove:async(t,s)=>(await e()).workspace.removeUser(t,s),updateRole:async(t,s,r)=>(await e()).workspace.updateUser(t,s,{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,s)=>(await e()).workspace.createCheckoutSession(t,s),update:async(t,s)=>(await e()).workspace.updateSubscription(t,s),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,s)=>(await e()).workspace.createBillingPortalSession(t,s)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>h.getPublicPlans(e),getVersion:e=>h.getPlanGroupVersion(e)},invoices:{list:async(t,s,r)=>(await e()).workspace.listInvoices(t,s,r),get:async(t,s)=>(await e()).workspace.getInvoice(t,s)},usage:{record:async(t,s)=>(await e()).workspace.recordUsage(t,s),recordBatch:async(t,s)=>(await e()).workspace.recordUsageBatch(t,s),getQuota:async(t,s)=>(await e()).workspace.getQuotaUsageStatus(t,s),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,s)=>(await e()).workspace.getUsageLogs(t,s)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,s,r)=>(await e()).workspace.updateFeature(t,s,r)},notification:{send:async(t,s,r,n)=>(await e()).workspace.sendNotification(t,s,r,n)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,s)=>(await e()).workspace.consumeCredits(t,s),purchase:async(t,s)=>(await e()).workspace.purchaseCredits(t,s),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,s)=>(await e()).workspace.getCreditTransactions(t,s),getBuckets:async(t,s)=>(await e()).workspace.getCreditBuckets(t,s),getExpiring:async(t,s)=>(await e()).workspace.getExpiringCredits(t,s),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,s,r)=>{const n=await e(),[o,i,a]=await Promise.all([n.workspace.getWorkspace(t),n.settings.getSettings(),n.workspace.getWorkspaceUsers(t)]),c=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===s);return Ae(r,{userId:s,workspaceRole:c?.role??null,workspace:o,settings:i})},resolve:async(t,s)=>{const r=await e(),[n,o,i]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),a=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===s);return We({userId:s,workspaceRole:a?.role??null,workspace:n,settings:o})}}}),g=f(async()=>p(await(async()=>{if(!n)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 n();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{auth:async()=>{if(!n)return null;const e=await n();return e?{sessionId:e}:null},withSession:e=>{const t=p(e);return f(async()=>t)},client:{forSession:p},...g}}!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(Te||(Te={}));export{S as ApiVersion,f as AuthApi,Te as AuthStatus,F as BBAction,_ as BBScreen,O as BBStatus,C as BB_PARAM,h as BaseApi,w as BetaForm,ie as BillingIntervals,Le as BuildBase,D as CURRENCY_DISPLAY,G as CURRENCY_FLAG,de as CreditBucketSource,pe as CreditBucketStatus,he as CreditTransactionType,Oe as DEFAULT_ROLE_PERMISSIONS,le as DunningState,R as EventEmitter,ce as InvoiceStatuses,z as PLAN_CURRENCY_CODES,Q as PLAN_CURRENCY_OPTIONS,Ne as PUSH_SERVICE_WORKER_SCRIPT,Ce as Permission,y as PushApi,E as SDKEvent,m as SettingsApi,ue as SubscriptionItemType,ae as SubscriptionStatus,k as UserApi,b as WorkspaceApi,ve as calculateBillableSeats,Pe as calculateSeatOverageCents,$e as calculateTotalSubscriptionCents,J as cleanBBParams,K as clearAuthIntent,V as consumeAuthIntent,W as createBBUrl,A as createCheckoutRedirectUrls,N as createCreditPurchaseRedirectUrls,Le as default,v as eventEmitter,Y as formatCents,X as formatOverageRate,ee as formatOverageRateWithLabel,se as formatQuotaIncludedOverage,oe as formatQuotaWithPrice,ke as getAvailableCurrenciesFromPlans,ge as getBasePriceCents,Se as getBillingIntervalAndCurrencyFromPriceId,j as getCurrencyFlag,H as getCurrencySymbol,me as getDisplayCurrency,Re as getPerSeatPriceCents,fe as getPricingVariant,re as getQuotaDisplayValue,be as getQuotaDisplayWithVariant,ye as getQuotaOverageCents,te as getQuotaUnitLabelFromName,Ee as getSeatPricing,we as getStripePriceIdForInterval,Ae as hasPermission,$ as invalidateCreditBalance,U as invalidateQuotaUsage,I as invalidateSubscription,xe as parseWebhookEvent,T as readBBParams,Ue as resolveMaxUsers,We as resolvePermissions,L as safeRedirect,M as saveAuthIntent,Ie as validateInvite,x as validateRedirectUrl,Je as verifyWebhookSignature};
|
|
1
|
+
let e=!0;function t(t,...s){e&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(t,...s)}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 n(e,t="Request failed"){if(!e.ok){let n=t;try{const t=await s(e);n=t.message||t.error||n}catch{n=function(e,t){const s={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}: ${s})`)}(e,t).message}throw new Error(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 r extends Error{constructor(e,t,s,n){super(e),this.code=t,this.context=s,this.originalError=n,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,r)}}const o=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}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,s={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const n=e instanceof Error?e:new r("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",s),o=n instanceof r?n:new r(n.message,"SDK_ERROR",s,n);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${s.component||"Unknown"}:`,{message:o.message,code:o.code,context:o.context,originalError:o.originalError,stack:o.stack}),this.config.onError)try{this.config.onError(o,s)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(o,s)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...s)=>e(...s).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...s)=>{try{return e(...s)}catch(e){throw this.handleError(e,t),e}}}};function i(e,t={}){o.handleError(e,t)}function a(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return i(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function c(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){i(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function u(e,t){try{!function(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){i(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){i(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const l="saas-session-id";function d(){return function(){if("undefined"==typeof window)return null;try{return a(l)}catch(e){return i(e,{component:"auth-utils",action:"getSessionId",metadata:{key:l}}),null}}()}const p=new WeakSet,h="SDK is not ready (missing serverUrl, version, or orgId)";class f{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(h);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(h)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:function(){const e=d(),t={};return e&&(t["x-session-id"]=e),t}()}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){p.has(e)||(p.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}async executeFetchUrl(e,t,s){const n=(t.method??"GET").toUpperCase(),r=s??e,o=this.buildHeaders(t),i={...t,headers:o};let a;if(this._timeout>0){const e=new AbortController;a=setTimeout(()=>e.abort(),this._timeout),i.signal=t.signal?AbortSignal.any([t.signal,e.signal]):e.signal}const c=async t=>{try{const s=this._fetch.bind(globalThis),r=await s(e,i);if(this._debug&&console.log(`[BuildBase] ${n} ${e} → ${r.status}`),401===r.status&&this._onUnauthorized&&this._onUnauthorized(),r.status>=500&&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 new Promise(t=>setTimeout(t,e)),c(t+1)}return r}catch(e){if(e instanceof Error&&"AbortError"===e.name){if(void 0!==a){const e=new Error(`Request timeout after ${this._timeout}ms: ${n} ${r}`);throw this.reportError(e,{method:n,path:r}),e}throw e}if(t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),c(t+1)}throw e instanceof Error&&this.reportError(e,{method:n,path:r}),e}};try{return await c(0)}finally{void 0!==a&&clearTimeout(a)}}async fetchJson(e,t={},s="Request failed"){this.ensureReady();try{const r=await this.executeFetch(e,t);return await n(r,s)}catch(s){throw s instanceof Error&&this.reportError(s,{method:(t.method??"GET").toUpperCase(),path:e}),s}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let s=t;try{s=(await e.json()).message||s}catch{s=`${t} (${e.status}: ${e.statusText})`}throw new Error(s)}async unwrapResponse(e,t){const s=await e.json();if(void 0!==s.success){if(!s.success)throw new Error(s.message||t);return s.data||s}return s}}class g extends f{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,s=await this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});return s.ok||await this.throwResponseError(s,"Failed to initiate authentication"),s.json()}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}}class w extends f{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 y{constructor(e){this.api=new w(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},s=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),n=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),r=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),o=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:s,language:n,timezone:r,currency:o}})}}class m extends f{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 k extends f{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class b extends f{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 s=await this.unwrapResponse(t,"Failed to fetch user attributes");return s&&"object"==typeof s&&!Array.isArray(s)?s:{}}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(`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 s=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof s&&null!==s?s:{}}}class S extends f{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(){return this.fetchJson("workspaces",{},"Failed to fetch workspaces")}async createWorkspace(e){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e)},"Failed to create workspace")}async updateWorkspace(e,t){return this.fetchJson(`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t)},"Failed to update workspace")}async deleteWorkspace(e){return this.fetchJson(`workspaces/${e}`,{method:"DELETE"},"Failed to delete workspace")}async getWorkspaceUsers(e){return this.fetchJson(`workspaces/${e}/users`,{},"Failed to fetch workspace users")}async addUser(e,t){return this.fetchJson(`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t)},"Failed to invite member")}async removeUser(e,t){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,t,s){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(s)},"Failed to update user")}async updateSettings(e){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e)},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t){return this.fetchJson(`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t})},"Failed to update workspace permissions")}async getFeatures(){return this.fetchJson("workspaces/features",{},"Failed to fetch features")}async updateFeature(e,t,s){return this.fetchJson(`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:s}})},"Failed to update feature")}async getWorkspace(e){return this.fetchJson(`workspaces/${e}`,{},"Failed to fetch workspace")}async getProfile(){return this.fetchJson("profile",{},"Failed to fetch profile")}async updateUserProfile(e){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e)},"Failed to update user profile")}async getPasskeys(){const e=await this.fetchJson("passkeys",{},"Failed to fetch passkeys");return e?.passkeys??[]}async renamePasskey(e,t){await this.fetchJson(`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t})},"Failed to rename passkey")}async deletePasskey(e){await this.fetchJson(`passkeys/${e}`,{method:"DELETE"},"Failed to remove passkey")}async getCurrentSubscription(e){const t=await this.fetchResponse(`workspaces/${e}/subscription`);return t.ok||await this.throwResponseError(t,"Failed to fetch subscription"),this.unwrapResponse(t,"Failed to fetch subscription")}async getPlanGroup(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/plan-group`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group"),this.unwrapResponse(t,"Failed to fetch plan group")}async getPlanGroupByVersion(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/plan-group?groupVersionId=${encodeURIComponent(t)}`);return s.ok||await this.throwResponseError(s,"Failed to fetch plan group version"),this.unwrapResponse(s,"Failed to fetch plan group version")}async getPlanGroupVersions(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/plan-group/versions`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group versions"),this.unwrapResponse(t,"Failed to fetch plan group versions")}async getPublicPlans(e){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");const t=await this.fetchResponse(`${this.orgId}/plans/${encodeURIComponent(e)}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plans"),this.unwrapResponse(t,"Failed to fetch plans")}async getPublicCreditPackages(){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");const e=await this.fetchResponse(`${this.orgId}/credit-packages`);return e.ok||await this.throwResponseError(e,"Failed to fetch credit packages"),this.unwrapResponse(e,"Failed to fetch credit packages")}async getPlanGroupVersion(e){const t=await this.fetchResponse(`plan-group-versions/${e}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group version"),this.unwrapResponse(t,"Failed to fetch plan group version")}async createCheckoutSession(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to create checkout session"),this.unwrapResponse(s,"Failed to create checkout session")}async selectFreePlan(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t})});return s.ok||await this.throwResponseError(s,"Failed to select free plan"),s.json()}async updateSubscription(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to update subscription"),this.unwrapResponse(s,"Failed to update subscription")}async createBillingPortalSession(e,t){return this.fetchJson(`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{})})}async listInvoices(e,t=10,s){const n=new URLSearchParams;n.append("limit",t.toString()),s&&n.append("starting_after",s);const r=await this.fetchResponse(`workspaces/${e}/subscription/invoices?${n.toString()}`);return r.ok||await this.throwResponseError(r,"Failed to fetch invoices"),this.unwrapResponse(r,"Failed to fetch invoices")}async getInvoice(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/invoices/${t}`);return s.ok||await this.throwResponseError(s,"Failed to fetch invoice"),this.unwrapResponse(s,"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to cancel subscription"),this.unwrapResponse(t,"Failed to cancel subscription")}async resumeSubscription(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/resume`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to resume subscription"),this.unwrapResponse(t,"Failed to resume subscription")}async recordUsage(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to record usage"),this.unwrapResponse(s,"Failed to record usage")}async recordUsageBatch(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to record batch usage"),this.unwrapResponse(s,"Failed to record batch usage")}async getQuotaUsageStatus(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/usage/status?quotaSlug=${encodeURIComponent(t)}`);return s.ok||await this.throwResponseError(s,"Failed to fetch quota usage status"),this.unwrapResponse(s,"Failed to fetch quota usage status")}async getAllQuotaUsage(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/usage/all`);return t.ok||await this.throwResponseError(t,"Failed to fetch all quota usage"),this.unwrapResponse(t,"Failed to fetch all quota usage")}async getUsageLogs(e,t){const s=new URLSearchParams;t?.quotaSlug&&s.append("quotaSlug",t.quotaSlug),t?.from&&s.append("from",t.from),t?.to&&s.append("to",t.to),t?.source&&s.append("source",t.source),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const n=s.toString(),r=`workspaces/${e}/subscription/usage/logs${n?`?${n}`:""}`,o=await this.fetchResponse(r);return o.ok||await this.throwResponseError(o,"Failed to fetch usage logs"),this.unwrapResponse(o,"Failed to fetch usage logs")}async sendNotification(e,t,s,n){const r={event:t};return s&&(r.userId=s),n&&(r.data=n),this.fetchJson(`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(r)},"Failed to send notification")}async getNotificationEvents(e){return this.fetchJson(`workspaces/${e}/notification-events`,{},"Failed to fetch notification events")}async getNotificationPreferences(e){return(await this.fetchJson(`workspaces/${e}/notification-preferences`,{},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t){return(await this.fetchJson(`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t})},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e){const t=await this.fetchResponse(`workspaces/${e}/credits`);return t.ok||await this.throwResponseError(t,"Failed to fetch credit balance"),this.unwrapResponse(t,"Failed to fetch credit balance")}async consumeCredits(e,t){const s=await this.fetchResponse(`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t)});if(!s.ok){if(402===s.status){const e=await s.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(s,"Failed to consume credits")}return this.unwrapResponse(s,"Failed to consume credits")}async purchaseCredits(e,t){const s=await this.fetchResponse(`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to create credit purchase checkout"),this.unwrapResponse(s,"Failed to create credit purchase checkout")}async getCreditPackages(e){const t=await this.fetchResponse(`workspaces/${e}/credits/packages`);t.ok||await this.throwResponseError(t,"Failed to fetch credit packages");const s=await this.unwrapResponse(t,"Failed to fetch credit packages");return s.docs??s}async getCreditTransactions(e,t){const s=new URLSearchParams;t?.type&&s.append("type",t.type),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const n=s.toString(),r=`workspaces/${e}/credits/transactions${n?`?${n}`:""}`,o=await this.fetchResponse(r);return o.ok||await this.throwResponseError(o,"Failed to fetch credit transactions"),this.unwrapResponse(o,"Failed to fetch credit transactions")}async getCreditBuckets(e,t){const s=new URLSearchParams;t?.status&&s.append("status",t.status),t?.source&&s.append("source",t.source),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const n=s.toString(),r=`workspaces/${e}/credits/buckets${n?`?${n}`:""}`,o=await this.fetchResponse(r);return o.ok||await this.throwResponseError(o,"Failed to fetch credit buckets"),this.unwrapResponse(o,"Failed to fetch credit buckets")}async getExpiringCredits(e,t){const s=t?`?days=${t}`:"",n=await this.fetchResponse(`workspaces/${e}/credits/expiring${s}`);return n.ok||await this.throwResponseError(n,"Failed to fetch expiring credits"),this.unwrapResponse(n,"Failed to fetch expiring credits")}}var E;!function(e){e.V1="v1"}(E||(E={}));const v={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"};class R{constructor(){this.callbacks=null}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){i(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(v.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(v.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(v.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(v.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,s){await this.emit(v.WorkspaceUserAdded,{userId:e,workspace:t,role:s})}async emitWorkspaceUserRemoved(e,t,s){await this.emit(v.WorkspaceUserRemoved,{userId:e,workspace:t,role:s})}async emitWorkspaceUserRoleChanged(e,t,s,n){await this.emit(v.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:s,newRole:n})}async emitWorkspaceCreated(e){await this.emit(v.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(v.WorkspaceDeleted,{workspace:e})}}const $=new R;function P(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const U=P().invalidate,I=P().invalidate,C=P().invalidate,_="bb",F={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",Invite:"invite"},W={Success:"success",Cancel:"cancel",Error:"error"},O={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function A(e,t){let s;try{const e=t||("undefined"!=typeof window?window.location.href:"https://localhost");s=new URL(e),s.search=""}catch{s=new URL("https://localhost")}return s.searchParams.set(_,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),s.toString()}function T(e,t){const s=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:A({action:F.Checkout,status:W.Success,ws:e,screen:O.Subscription},s),cancelUrl:A({action:F.Checkout,status:W.Cancel,ws:e,screen:O.Subscription},s)}}function x(e,t){const s=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:A({action:F.CreditPurchase,status:W.Success,ws:e,screen:O.Credits},s),cancelUrl:A({action:F.CreditPurchase,status:W.Cancel,ws:e,screen:O.Credits},s)}}function N(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(_);if(!e)return null;const t=function(e){const t={};if(!e)return t;const s=e.split(",");for(const e of s){const s=e.indexOf(":");if(-1===s)continue;const n=decodeURIComponent(e.slice(0,s)),r=decodeURIComponent(e.slice(s+1));n&&(t[n]=r)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}}function J(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(_)&&(e.searchParams.delete(_),window.history.replaceState({},"",e.toString()))}catch{}}function L(e){if(!e||"string"!=typeof e)return null;try{const t=new URL(e);return"https:"===t.protocol?e:"http:"!==t.protocol||"localhost"!==t.hostname&&"127.0.0.1"!==t.hostname&&"::1"!==t.hostname?null:e}catch{return null}}function B(e,t="/"){const s=L(e);window.location.href=s||t}const M="saas-auth-intent";function q(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function V(e){L(e)&&u(M,{returnUrl:e,createdAt:Date.now()})}function D(){const e=function(e,t){const s=a(e);if(!s)return null;try{const n=JSON.parse(s);return t&&!t(n)?(i(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null):n}catch(t){return i(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null}}(M,q);return c(M),e?Date.now()-e.createdAt>6e5?null:L(e.returnUrl):null}function K(){c(M)}const j={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:"฿"},z={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function G(e){return e&&e.trim()?z[e.trim().toLowerCase()]??"":""}function H(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return j[t]??t.toUpperCase()}const Q=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],Y=Q.map(e=>({value:e,label:`${e.toUpperCase()} (${H(e)})`}));function Z(e,t){return H(t)+(e/100).toFixed(2)}const X={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included"};function ee(e,t,s,n){if(null==e||e<0)return null;const r={...X,...n},o=null!=t&&t>=1?t:1,i=H(s),a=(e/100).toFixed(2);return 1===o?`${i}${a}/${r.unit}`:`${i}${a}/${o.toLocaleString()} ${r.units}`}function te(e,t,s,n,r,o){if(null==e||e<0)return null;const i={...X,...o},a=null!=t&&t>=1?t:1,c=H(n),u=(e/100).toFixed(2);if(s){const e=r??(s.endsWith("s")?s:`${s}s`);return a>=2?`${c}${u}/${a.toLocaleString()} ${e}`:`${c}${u}/${s}`}return 1===a?`${c}${u}/${i.unit}`:`${c}${u}/${a.toLocaleString()} ${i.units}`}function se(e,t="unit"){const s=(e||"").trim().toLowerCase();if(!s)return t;const n=s.split(/\s+/)[0]??s;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(n)?n:n.endsWith("ies")&&n.length>3?n.slice(0,-3)+"y":n.endsWith("ses")||n.endsWith("xes")||n.endsWith("zes")||n.endsWith("ches")||n.endsWith("shes")?n.slice(0,-2):n.endsWith("s")&&!n.endsWith("ss")&&n.length>1?n.slice(0,-1):n||t}function ne(e,t,s,n,r,o,i,a){const c={...X,...i};if(!1===a)return null!=e?`${c.included}: ${e.toLocaleString()} (${c.hardLimit??"hard limit"})`:c.hardLimit??"Hard limit";const u=o??(s.endsWith("s")?s:`${s}s`),l=null!=r&&r>=2?`${r.toLocaleString()} ${u}`:s;return null!=e&&null!=t?`${c.included}: ${e.toLocaleString()}, ${c.afterThat} ${Z(t,n)}/${l}`:null!=e?`${c.included}: ${e.toLocaleString()}`:null!=t?`${c.afterIncluded}: ${Z(t,n)}/${l}`:"—"}function re(e,t){if(null==e)return null;const s=e[t??"monthly"];return s?{included:s.included,...void 0!==s.overage&&{overage:s.overage},...void 0!==s.unitSize&&{unitSize:s.unitSize},allowOverage:!1!==e.allowOverage}:null}const oe={included:"included",then:"then"};function ie(e,t,s={}){const{overageInCents:n=!0,currency:r}=s,o=s.labels??oe,i=s.currencySymbol??H(r??"");if(null==e)return"—";const{included:a,overage:c}=e,u=`${a} ${o.included}`;if(!1===e.allowOverage)return`${u} (hard limit)`;if(null==c)return u;const l=n?c/100:c,d="number"==typeof l&&Number.isFinite(l)?l.toFixed(2):String(c),p=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${u}, ${o.then} ${i}${d}${p}`}const ae={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},ce={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},ue={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},le={Feature:"feature",Limit:"limit",Quota:"quota"},de={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},pe={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},he={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},fe={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function ge(e,t){const s=e.pricingVariants;if(!s?.length)return null;const n=t.toLowerCase();return s.find(e=>e.currency?.toLowerCase()===n)??null}function we(e,t,s){const n=ge(e,t);if(!n?.basePricing)return null;const r=n.basePricing[s];return null!=r?r:null}function ye(e,t,s){const n=ge(e,t);if(!n?.stripePrices)return null;const r=s===ae.Monthly?"monthlyPriceId":s===ae.Yearly?"yearlyPriceId":"quarterlyPriceId",o=s===ae.Monthly?"monthly":s===ae.Yearly?"yearly":void 0;return n.stripePrices[r]??(o?n.stripePrices[o]:void 0)??null}function me(e,t,s,n){const r=ge(e,t),o=r?.quotaOverages?.[s];if(o)return o[n]}function ke(e,t){const s=ge(e,t);return s?s.currency:e.plan?.currency??""}function be(e){const t=new Set;for(const s of e)s.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()}function Se(e,t,s,n){const r=e.quotas?.[s];if(null==r)return null;const o=r[n];if(!o)return null;const i=me(e,t,s,n);return{included:o.included,...void 0!==o.unitSize&&{unitSize:o.unitSize},...void 0!==i&&{overage:i},allowOverage:!1!==r.allowOverage}}function Ee(e,t){if(!e)return null;for(const s of t){const t=s.pricingVariants;if(t?.length)for(const s of t){const t=s.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:s.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:s.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:s.currency}}}}return null}function ve(e,t){const s=ge(e,t);return s?.seatPricing?.enabled?s.seatPricing:null}function Re(e,t,s){const n=ve(e,t);return n?.perSeat?n.perSeat[s]??null:null}function $e(e,t){return Math.max(0,e-(t||0))}function Pe(e,t,s,n){const r=ve(e,t);if(!r)return null;return $e(n,r.includedSeats)*(Re(e,t,s)??0)}function Ue(e,t,s,n){const r=we(e,t,s);if(null===r)return null;if(void 0===n)return r;return r+(Pe(e,t,s,n)??0)}function Ie(e){const{planVersion:t,currency:s="usd",settingsMaxUsers:n}=e;if(t){const e=ve(t,s);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=n&&n>0?{maxUsers:n,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function Ce(e){const{memberCount:t,maxUsersConfig:s,hasSubscription:n=!0,requireSubscription:r=!1}=e;if(r&&!n)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:o,source:i}=s;if(o<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=o){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[i]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[i]??"users.memberLimitMessage",blockMessageValues:{maxUsers:o}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}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"},Fe=Object.values(_e),We={admin:Fe.filter(e=>e!==_e.WORKSPACE_DELETE),member:[_e.WORKSPACE_SETTINGS_VIEW,_e.WORKSPACE_MEMBERS_VIEW,_e.WORKSPACE_FEATURES_VIEW,_e.WORKSPACE_BILLING_VIEW,_e.WORKSPACE_USAGE_VIEW],viewer:[_e.WORKSPACE_SETTINGS_VIEW,_e.WORKSPACE_MEMBERS_VIEW]};function Oe(e){const t=new Set;for(const s of Object.values(e))for(const e of s)t.add(e);return Array.from(t)}function Ae(e){const{userId:t,workspace:s,settings:n,appPermissions:r}=e;if(!s||!t)return new Set;if(function(e,t){if(!t)return!1;const s=(n=e.createdBy)?"string"==typeof n?n:"object"==typeof n&&"_id"in n&&"string"==typeof n._id?n._id:null:null;var n;return null!==s&&s===t}(s,t)){const e=new Set(Fe);if(r)for(const t of Oe(r))e.add(t);if(s.permissions)for(const t of Oe(s.permissions))e.add(t);if(n?.workspace?.permissions)for(const t of Oe(n.workspace.permissions))e.add(t);return e}const o=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const s=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return s&&"object"==typeof s&&"role"in s&&"string"==typeof s.role?s.role:null}(s,t);if(!o)return new Set;const i=s.permissions,a=n?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=i?.[o]?c(i[o]):[],d=a?.[o]?c(a[o]):[],p=We[o]??[];let h;if(l.length>0)h=l;else if(d.length>0)h=d;else if(p.length>0)h=p;else{h=We[n?.workspace?.defaultRole??"member"]??We.member??[]}const f=new Set(h),g=i?.[o]?u(i[o]):[],w=r?.[o]?u(r[o]):[],y=g.length>0?g:w;for(const e of y)f.add(e);return function(e,t,s){if(!s?.workspace)return;const{canInviteMembers:n}=s.workspace;(!1===n||"admin-only"===n&&"admin"!==t)&&e.delete(_e.WORKSPACE_MEMBERS_INVITE)}(f,o,n),f}function Te(e,t){const s=Ae(t);return Array.isArray(e)?e.every(e=>s.has(e)):s.has(e)}const xe="\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 try {\n const payload = event.data.json();\n const title = payload.title || 'Notification';\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.icon || undefined,\n data: { url: payload.url, ...(payload.data || {}) },\n tag: 'buildbase-push-' + Date.now(),\n };\n\n event.waitUntil(\n self.registration.showNotification(title, options)\n );\n } catch (e) {\n console.error('[PushSW] Failed to show notification:', e);\n }\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\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 Ne;function Je(e){const{body:t,signature:s,timestamp:n,secret:r,maxAgeSeconds:o=300}=e;if(!(s&&n&&r&&t))return!1;const i="sha256=";if(!s.startsWith(i))return!1;const a=s.slice(7);if(o>0){const e=parseInt(n,10);if(isNaN(e))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-e)>o)return!1}try{const e=require("crypto"),s=e.createHmac("sha256",r).update(`${n}.${t}`).digest("hex"),o=Buffer.from(a,"hex"),i=Buffer.from(s,"hex");return o.length===i.length&&e.timingSafeEqual(o,i)}catch{return!1}}function Le(e){if(!Je(e))return null;try{return JSON.parse(e.body)}catch{return null}}!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(Ne||(Ne={}));const Be=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]),Me=(e,t)=>e>>>t|e<<32-t;function qe(e){let t=1779033703,s=3144134277,n=1013904242,r=2773480762,o=1359893119,i=2600822924,a=528734635,c=1541459225;const u=e.length,l=u+1,d=l+(56-l%64+64)%64+8,p=new Uint8Array(d);p.set(e,0),p[u]=128;const h=8*u,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 w=new Uint32Array(64);for(let e=0;e<d;e+=64){for(let t=0;t<16;t++){const s=e+4*t;w[t]=p[s]<<24|p[s+1]<<16|p[s+2]<<8|p[s+3]}for(let e=16;e<64;e++){const t=Me(w[e-15],7)^Me(w[e-15],18)^w[e-15]>>>3,s=Me(w[e-2],17)^Me(w[e-2],19)^w[e-2]>>>10;w[e]=w[e-16]+t+w[e-7]+s>>>0}let u=t,l=s,d=n,h=r,f=o,g=i,y=a,m=c;for(let e=0;e<64;e++){const t=m+(Me(f,6)^Me(f,11)^Me(f,25))+(f&g^~f&y)+Be[e]+w[e]>>>0,s=u&l^u&d^l&d;m=y,y=g,g=f,f=h+t>>>0,h=d,d=l,l=u,u=t+((Me(u,2)^Me(u,13)^Me(u,22))+s>>>0)>>>0}t=t+u>>>0,s=s+l>>>0,n=n+d>>>0,r=r+h>>>0,o=o+f>>>0,i=i+g>>>0,a=a+y>>>0,c=c+m>>>0}const y=new Uint8Array(32),m=[t,s,n,r,o,i,a,c];for(let e=0;e<8;e++)y[4*e]=m[e]>>>24&255,y[4*e+1]=m[e]>>>16&255,y[4*e+2]=m[e]>>>8&255,y[4*e+3]=255&m[e];return y}function Ve(e){return(new TextEncoder).encode(e)}function De(e,t){const s=new Uint8Array(e.length+t.length);return s.set(e,0),s.set(t,e.length),s}const Ke=300,je="/.well-known/oauth-protected-resource",ze="/.well-known/agent-skills",Ge="application/json",He="text/plain; charset=utf-8";function Qe(e){return e.replace(/\/+$/,"")}function Ye(e){return`public, max-age=${e}, s-maxage=${e}`}function Ze(e){return"sha256:"+function(e){let t="";for(let s=0;s<e.length;s++)t+=e[s].toString(16).padStart(2,"0");return t}(qe(Ve(e)))}const Xe=new Map;async function et(e){const t=e.cacheTtlSeconds??Ke,s=`${Qe(e.serverUrl)}::${e.orgId}`,n=Xe.get(s);if(n&&n.expiresAt>Date.now())return n.value;const r=e.fetch??fetch,o=`${Qe(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let i={enabled:!1};try{const e=await r(o,{headers:{Accept:Ge}});if(e.ok){const t=await e.json();t&&"object"==typeof t&&(i=t)}}catch{}return Xe.set(s,{value:i,expiresAt:Date.now()+1e3*t}),i}function tt(){Xe.clear()}function st(e,t){const s=Qe(e.siteUrl),n={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:je};t.authorizationServer?.metadataUrl&&(n.oauth_authorization_server=t.authorizationServer.metadataUrl),e.skills?.length&&(n.agent_skills=`${ze}/index.json`);return ut({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:s,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:s},capabilities:n,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}function nt(e,t,s){const n=s.protectedResources??[];if(!n.length)return null;const r=e.replace(/\/+$/,"")||je,o=n.find(e=>function(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const s="/"===t?"":t.replace(/\/+$/,"");return je+s}(e.resource)===r);return o?ut(o.metadata,t):r===je&&1===n.length?ut(n[0].metadata,t):null}function rt(e){const t=e.skills??[];if(!t.length)return null;const s=Qe(e.siteUrl);return ut({$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:`${s}${ot(e)}`,digest:Ze(e.content)}))},e)}function ot(e){return e.path??`${ze}/${e.name}/SKILL.md`}function it(e,t){const s=(t.skills??[]).find(t=>ot(t)===e);return s?{status:200,contentType:"text/markdown; charset=utf-8",body:s.content,cacheControl:Ye(t.cacheTtlSeconds??Ke)}:null}function at(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:He,body:t.join("\n")+"\n",cacheControl:Ye(e.cacheTtlSeconds??Ke)}}function ct(e,t){return t.llmsTxt?{status:200,contentType:He,body:t.llmsTxt,cacheControl:Ye(e.cacheTtlSeconds??Ke)}:null}function ut(e,t){return{status:200,contentType:Ge,body:JSON.stringify(e,null,2),cacheControl:Ye(t.cacheTtlSeconds??Ke)}}async function lt(e,t){const s=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===s){return st(t,await et(t))}if("/.well-known/security.txt"===s)return at(t);if(s===`${ze}/index.json`)return rt(t);if(s.startsWith(`${ze}/`)&&s.endsWith("SKILL.md"))return it(s,t);if("/.well-known/oauth-authorization-server"===s){const e=await et(t),s=e.authorizationServer?.metadataUrl;return s?ut({...e.authorizationServer?.issuer?{issuer:e.authorizationServer.issuer}:{},oauth_authorization_server_metadata:s},t):null}if(s.startsWith(je)){return nt(s,t,await et(t))}return null}class dt extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function pt(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),s=t.length%4==0?"":"=".repeat(4-t.length%4),n=atob(t+s),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}function ht(e){return JSON.parse((new TextDecoder).decode(pt(e)))}function ft(e,t,s=60){if(!e||!t)throw new dt("invalid_token","Missing token or client secret");const n=e.split(".");if(3!==n.length)throw new dt("invalid_token","Malformed JWT");const[r,o,i]=n,a=function(e,t){let s=e;s.length>64&&(s=qe(s));const n=new Uint8Array(64),r=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<s.length?s[e]:0;n[e]=54^t,r[e]=92^t}const o=qe(De(n,t));return qe(De(r,o))}(Ve(t),Ve(`${r}.${o}`));let c,u,l;try{c=pt(i)}catch{throw new dt("invalid_signature","Unreadable JWT signature")}if(!function(e,t){if(e.length!==t.length)return!1;let s=0;for(let n=0;n<e.length;n++)s|=e[n]^t[n];return 0===s}(a,c))throw new dt("invalid_signature","JWT signature verification failed");try{u=ht(r),l=ht(o)}catch{throw new dt("invalid_token","Unreadable JWT segments")}if("HS256"!==u.alg)throw new dt("invalid_algorithm",`Unexpected JWT alg: ${String(u.alg)}`);const d=Math.floor(Date.now()/1e3);if("number"==typeof l.exp&&d>l.exp+s)throw new dt("token_expired","JWT has expired");if("number"==typeof l.nbf&&d+s<l.nbf)throw new dt("token_not_yet_valid","JWT is not yet valid");return l}function gt(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function wt(e){const t=gt(e.authorization);if(!t)throw new dt("invalid_token","Missing Bearer token");return ft(t,e.clientSecret,e.clockToleranceSec)}function yt(e){const t=gt(e.authorization);if(!t)throw new dt("invalid_token","Missing Bearer token");return ft(t,e.clientSecret,e.clockToleranceSec)}function mt(e){return{success:!0,token:e.token,message:e.message??"ok",..."number"==typeof e.expiresIn?{expiresIn:e.expiresIn}:{}}}function kt(e){return{success:!1,token:"",message:e}}async function bt(e){let t;try{t=wt(e)}catch(e){return{status:401,body:kt(e instanceof dt?e.code:"invalid_token")}}return{status:200,body:mt(await e.mintToken(t))}}async function St(e){let t;try{t=yt(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof dt?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}}function Et(e){const t=[`Bearer resource_metadata="${e.resourceMetadataUrl}"`];return e.error&&t.push(`error="${e.error}"`),e.errorDescription&&t.push(`error_description="${e.errorDescription}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}function vt(e){const{serverUrl:t,orgId:s,version:n="v1",getSessionId:r,timeout:o,maxRetries:i,debug:a,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!s)throw new Error("BuildBase: orgId is required");const d={...void 0!==o&&{timeout:o},...void 0!==i&&{maxRetries:i},...void 0!==a&&{debug:a},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},p=e=>{const r={serverUrl:t,version:n,orgId:s,sessionId:e,...d};return{workspace:new S(r),user:new b(r),settings:new k(r),push:new m(r)}},h=new S({serverUrl:t,version:n,orgId:s,...d}),f=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,s)=>(await e()).workspace.updateWorkspace(t,s),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,s,n)=>(await e()).workspace.addUser(t,{email:s,role:n}),remove:async(t,s)=>(await e()).workspace.removeUser(t,s),updateRole:async(t,s,n)=>(await e()).workspace.updateUser(t,s,{role:n}),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,s)=>(await e()).workspace.createCheckoutSession(t,s),update:async(t,s)=>(await e()).workspace.updateSubscription(t,s),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,s)=>(await e()).workspace.createBillingPortalSession(t,s)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>h.getPublicPlans(e),getVersion:e=>h.getPlanGroupVersion(e)},invoices:{list:async(t,s,n)=>(await e()).workspace.listInvoices(t,s,n),get:async(t,s)=>(await e()).workspace.getInvoice(t,s)},usage:{record:async(t,s)=>(await e()).workspace.recordUsage(t,s),recordBatch:async(t,s)=>(await e()).workspace.recordUsageBatch(t,s),getQuota:async(t,s)=>(await e()).workspace.getQuotaUsageStatus(t,s),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,s)=>(await e()).workspace.getUsageLogs(t,s)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,s,n)=>(await e()).workspace.updateFeature(t,s,n)},notification:{send:async(t,s,n,r)=>(await e()).workspace.sendNotification(t,s,n,r)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,s)=>(await e()).workspace.consumeCredits(t,s),purchase:async(t,s)=>(await e()).workspace.purchaseCredits(t,s),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,s)=>(await e()).workspace.getCreditTransactions(t,s),getBuckets:async(t,s)=>(await e()).workspace.getCreditBuckets(t,s),getExpiring:async(t,s)=>(await e()).workspace.getExpiringCredits(t,s),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,s,n)=>{const r=await e(),[o,i,a]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),c=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===s);return Te(n,{userId:s,workspaceRole:c?.role??null,workspace:o,settings:i})},resolve:async(t,s)=>{const n=await e(),[r,o,i]=await Promise.all([n.workspace.getWorkspace(t),n.settings.getSettings(),n.workspace.getWorkspaceUsers(t)]),a=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===s);return Ae({userId:s,workspaceRole:a?.role??null,workspace:r,settings:o})}}}),g=f(async()=>p(await(async()=>{if(!r)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 r();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{auth:async()=>{if(!r)return null;const e=await r();return e?{sessionId:e}:null},withSession:e=>{const t=p(e);return f(async()=>t)},client:{forSession:p},...g}}export{E as ApiVersion,dt as AppBridgeError,g as AuthApi,Ne as AuthStatus,F as BBAction,O as BBScreen,W as BBStatus,_ as BB_PARAM,f as BaseApi,y as BetaForm,ae as BillingIntervals,vt as BuildBase,j as CURRENCY_DISPLAY,z as CURRENCY_FLAG,pe as CreditBucketSource,he as CreditBucketStatus,fe as CreditTransactionType,We as DEFAULT_ROLE_PERMISSIONS,de as DunningState,R as EventEmitter,ue as InvoiceStatuses,Q as PLAN_CURRENCY_CODES,Y as PLAN_CURRENCY_OPTIONS,xe as PUSH_SERVICE_WORKER_SCRIPT,_e as Permission,m as PushApi,v as SDKEvent,k as SettingsApi,le as SubscriptionItemType,ce as SubscriptionStatus,b as UserApi,S as WorkspaceApi,kt as appTokenFailure,mt as appTokenSuccess,Et as bearerChallenge,st as buildAgentCard,rt as buildAgentSkillsIndex,ct as buildLlmsTxt,nt as buildProtectedResourceMetadata,at as buildSecurityTxt,it as buildSkillMd,$e as calculateBillableSeats,Pe as calculateSeatOverageCents,Ue as calculateTotalSubscriptionCents,J as cleanBBParams,tt as clearAgentReadinessCache,K as clearAuthIntent,D as consumeAuthIntent,A as createBBUrl,T as createCheckoutRedirectUrls,x as createCreditPurchaseRedirectUrls,vt as default,$ as eventEmitter,gt as extractBearerToken,et as fetchAgentReadiness,Z as formatCents,ee as formatOverageRate,te as formatOverageRateWithLabel,ne as formatQuotaIncludedOverage,ie as formatQuotaWithPrice,be as getAvailableCurrenciesFromPlans,we as getBasePriceCents,Ee as getBillingIntervalAndCurrencyFromPriceId,G as getCurrencyFlag,H as getCurrencySymbol,ke as getDisplayCurrency,Re as getPerSeatPriceCents,ge as getPricingVariant,re as getQuotaDisplayValue,Se as getQuotaDisplayWithVariant,me as getQuotaOverageCents,se as getQuotaUnitLabelFromName,ve as getSeatPricing,ye as getStripePriceIdForInterval,St as handleAppRevokeRequest,bt as handleAppTokenRequest,Te as hasPermission,U as invalidateCreditBalance,I as invalidateQuotaUsage,C as invalidateSubscription,Le as parseWebhookEvent,N as readBBParams,Ie as resolveMaxUsers,Ae as resolvePermissions,lt as resolveWellKnown,B as safeRedirect,V as saveAuthIntent,Ze as sha256Digest,Ce as validateInvite,L as validateRedirectUrl,yt as verifyAppRevokeRequest,wt as verifyAppTokenRequest,ft as verifyClientJwt,Je as verifyWebhookSignature};
|