@buildbase/sdk 0.0.46 → 0.0.48

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/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){const s=this.url(e),r=(t.method??"GET").toUpperCase(),n=this.buildHeaders(t),o={...t,headers:n};let i;if(this._timeout>0){const e=new AbortController;i=setTimeout(()=>e.abort(),this._timeout),o.signal=t.signal?AbortSignal.any([t.signal,e.signal]):e.signal}const a=async t=>{try{const e=this._fetch.bind(globalThis),n=await e(s,o);if(this._debug&&console.log(`[BuildBase] ${r} ${s} → ${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)),a(t+1)}return n}catch(s){if(s instanceof Error&&"AbortError"===s.name){if(void 0!==i){const t=new Error(`Request timeout after ${this._timeout}ms: ${r} ${e}`);throw this._onError?.(t,{method:r,path:e}),t}throw s}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)),a(t+1)}throw s instanceof Error&&this._onError?.(s,{method:r,path:e}),s}};try{return await a(0)}finally{void 0!==i&&clearTimeout(i)}}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 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 fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},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 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 $(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const P=$().invalidate,I=$().invalidate,C=$().invalidate,U="bb",F={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",Invite:"invite"},_={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 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(U,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:_.Success,ws:e,screen:O.Subscription},s),cancelUrl:W({action:F.Checkout,status:_.Cancel,ws:e,screen:O.Subscription},s)}}function N(e,t){const s=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:W({action:F.CreditPurchase,status:_.Success,ws:e,screen:O.Credits},s),cancelUrl:W({action:F.CreditPurchase,status:_.Cancel,ws:e,screen:O.Credits},s)}}function T(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(U);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(U)&&(e.searchParams.delete(U),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 z(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return D[t]??t.toUpperCase()}const H=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],Q=H.map(e=>({value:e,label:`${e.toUpperCase()} (${z(e)})`}));function Y(e,t){return z(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=z(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=z(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??z(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 $e(e,t,s,r){const n=Ee(e,t);if(!n)return null;return ve(r,n.includedSeats)*(Re(e,t,s)??0)}function Pe(e,t,s,r){const n=ge(e,t,s);if(null===n)return null;if(void 0===r)return n;return n+($e(e,t,s,r)??0)}function Ie(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 Ce(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 Ue={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(Ue),_e={admin:Fe.filter(e=>e!==Ue.WORKSPACE_DELETE),member:[Ue.WORKSPACE_SETTINGS_VIEW,Ue.WORKSPACE_MEMBERS_VIEW,Ue.WORKSPACE_FEATURES_VIEW,Ue.WORKSPACE_BILLING_VIEW,Ue.WORKSPACE_USAGE_VIEW],viewer:[Ue.WORKSPACE_SETTINGS_VIEW,Ue.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 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 Oe(n))e.add(t);if(s.permissions)for(const t of Oe(s.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of Oe(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=_e[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=_e[r?.workspace?.defaultRole??"member"]??_e.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(Ue.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,O as BBScreen,_ as BBStatus,U 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,_e as DEFAULT_ROLE_PERMISSIONS,le as DunningState,R as EventEmitter,ce as InvoiceStatuses,H as PLAN_CURRENCY_CODES,Q as PLAN_CURRENCY_OPTIONS,Ne as PUSH_SERVICE_WORKER_SCRIPT,Ue 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,$e as calculateSeatOverageCents,Pe 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,z 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,P as invalidateCreditBalance,I as invalidateQuotaUsage,C as invalidateSubscription,xe as parseWebhookEvent,T as readBBParams,Ie as resolveMaxUsers,We as resolvePermissions,L as safeRedirect,M as saveAuthIntent,Ce 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 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};
@@ -27,6 +27,19 @@ interface IUser extends IDocument {
27
27
  currency?: string;
28
28
  attributes?: Record<string, string | number | boolean>;
29
29
  }
30
+ /** A registered passkey (WebAuthn credential) — no key material exposed. */
31
+ interface IPasskeySummary {
32
+ id: string;
33
+ name: string;
34
+ deviceType?: string;
35
+ backedUp?: boolean;
36
+ lastUsedAt?: string;
37
+ createdAt?: string;
38
+ /** Auth domain the credential is bound to */
39
+ rpId?: string;
40
+ /** False when the org's auth domain changed and this credential can no longer be used to sign in */
41
+ active?: boolean;
42
+ }
30
43
  interface IAsset extends IDocument {
31
44
  _id: string;
32
45
  createdAt: string;
@@ -1110,6 +1123,8 @@ declare abstract class BaseApi {
1110
1123
  private buildHeaders;
1111
1124
  /** Execute fetch with timeout, retries, debug logging, and error callback. */
1112
1125
  private executeFetch;
1126
+ /** Internal: execute fetch against a resolved URL with timeout, retries, debug logging, and error callback. */
1127
+ private executeFetchUrl;
1113
1128
  /**
1114
1129
  * Execute request and parse JSON with handleApiResponse (throws on !response.ok).
1115
1130
  * Use for standard JSON APIs.
@@ -1120,6 +1135,12 @@ declare abstract class BaseApi {
1120
1135
  * Caller is responsible for checking response.ok and parsing body.
1121
1136
  */
1122
1137
  protected fetchResponse(path: string, init?: RequestInit): Promise<Response>;
1138
+ /**
1139
+ * Execute request against an absolute URL (bypasses baseUrl).
1140
+ * Useful for endpoints outside the default basePath (e.g. /auth vs /public).
1141
+ * Gets the same timeout, retry, header-merge, and error-callback handling as fetchResponse.
1142
+ */
1143
+ protected fetchAbsoluteUrl(absoluteUrl: string, init?: RequestInit): Promise<Response>;
1123
1144
  /**
1124
1145
  * Throw an error from a failed response.
1125
1146
  * Tries to parse JSON error body; falls back to status-based message.
@@ -1144,6 +1165,7 @@ interface AuthRequestParams {
1144
1165
  success: string;
1145
1166
  error: string;
1146
1167
  };
1168
+ state?: string;
1147
1169
  }
1148
1170
  interface AuthRequestResponse {
1149
1171
  success: boolean;
@@ -1158,8 +1180,8 @@ declare class AuthApi extends BaseApi {
1158
1180
  });
1159
1181
  /**
1160
1182
  * Initiate OAuth sign-in flow. Returns redirect URL to the auth provider.
1161
- * Uses /api/v1/auth/request — auth endpoints sit outside the /public basePath,
1162
- * so we build the URL directly instead of using fetchResponse.
1183
+ * Auth endpoints sit at /api/v1/auth/ (outside the /public basePath),
1184
+ * so we use fetchAbsoluteUrl to get timeout, retry, and error handling via BaseApi.
1163
1185
  */
1164
1186
  requestAuth(params: AuthRequestParams): Promise<AuthRequestResponse>;
1165
1187
  /** Fetch user profile with the given session ID (used after OAuth redirect or from storage). */
@@ -1351,6 +1373,9 @@ declare class WorkspaceApi extends BaseApi {
1351
1373
  getWorkspace(workspaceId: string): Promise<IWorkspace>;
1352
1374
  getProfile(): Promise<IUser>;
1353
1375
  updateUserProfile(config: Partial<IUser>): Promise<IUser>;
1376
+ getPasskeys(): Promise<IPasskeySummary[]>;
1377
+ renamePasskey(passkeyId: string, name: string): Promise<void>;
1378
+ deletePasskey(passkeyId: string): Promise<void>;
1354
1379
  /**
1355
1380
  * Get current subscription for a workspace
1356
1381
  * Returns subscription details including plan, plan version, and group information
@@ -2162,14 +2187,59 @@ interface BetaFormResponse {
2162
2187
  message: string;
2163
2188
  }
2164
2189
 
2190
+ /** Props passed to the custom loadingComponent render function. */
2191
+ interface LoadingProps {
2192
+ /** Human-readable, locale-aware message describing what's happening */
2193
+ message: string;
2194
+ }
2195
+ interface FullScreenLoaderContextValue {
2196
+ /** Show the full-screen loader with a message */
2197
+ show: (message: string) => void;
2198
+ /** Hide the full-screen loader */
2199
+ hide: () => void;
2200
+ /** Whether the loader is currently visible */
2201
+ visible: boolean;
2202
+ /** Current loader message */
2203
+ message: string;
2204
+ }
2205
+ /**
2206
+ * Hook to control the full-screen loader from anywhere in the SDK.
2207
+ *
2208
+ * @example
2209
+ * ```tsx
2210
+ * const { show, hide } = useFullScreenLoader();
2211
+ *
2212
+ * show('Processing payment...');
2213
+ * await processPayment();
2214
+ * hide();
2215
+ * ```
2216
+ */
2217
+ declare function useFullScreenLoader(): FullScreenLoaderContextValue;
2218
+
2165
2219
  /**
2166
2220
  * Type-safe translation keys for the BuildBase SDK.
2167
2221
  * All user-facing strings are defined here.
2168
2222
  */
2169
2223
  interface SDKMessages {
2224
+ security: {
2225
+ inactive: string;
2226
+ inactiveHint: string;
2227
+ passkeysTitle: string;
2228
+ passkeysDescription: string;
2229
+ noPasskeys: string;
2230
+ addHint: string;
2231
+ rename: string;
2232
+ remove: string;
2233
+ removeTitle: string;
2234
+ removeDescription: string;
2235
+ renamePlaceholder: string;
2236
+ lastUsed: string;
2237
+ added: string;
2238
+ };
2170
2239
  settings: {
2171
2240
  titles: {
2172
2241
  profile: string;
2242
+ security: string;
2173
2243
  general: string;
2174
2244
  users: string;
2175
2245
  subscription: string;
@@ -2184,6 +2254,7 @@ interface SDKMessages {
2184
2254
  account: string;
2185
2255
  workspace: string;
2186
2256
  profile: string;
2257
+ security: string;
2187
2258
  general: string;
2188
2259
  users: string;
2189
2260
  subscription: string;
@@ -2712,6 +2783,13 @@ interface SDKMessages {
2712
2783
  errorLoading: string;
2713
2784
  insufficientCredits: string;
2714
2785
  };
2786
+ loading: {
2787
+ restoringSession: string;
2788
+ redirecting: string;
2789
+ signingIn: string;
2790
+ verifyingAccount: string;
2791
+ almostThere: string;
2792
+ };
2715
2793
  errors: {
2716
2794
  networkError: string;
2717
2795
  unauthorized: string;
@@ -2842,6 +2920,41 @@ interface SaaSOSProviderProps extends IOsState {
2842
2920
  * ```
2843
2921
  */
2844
2922
  getCheckoutStripeParams?: GetCheckoutStripeParams;
2923
+ /**
2924
+ * Custom content or render function for the full-screen loading overlay.
2925
+ * Used during auth code exchange, and available to any SDK feature via `useFullScreenLoader()`.
2926
+ * The SDK handles the full-screen white backdrop, centering, and messages — you just render.
2927
+ *
2928
+ * - Pass a `ReactNode` for static content (logo, spinner).
2929
+ * - Pass a function to receive `{ message }` — the SDK manages which message to show.
2930
+ *
2931
+ * If not provided, a default spinner with status message is shown.
2932
+ *
2933
+ * @example Static content
2934
+ * ```tsx
2935
+ * <SaaSOSProvider
2936
+ * loadingComponent={
2937
+ * <>
2938
+ * <img src="/logo.svg" alt="Logo" />
2939
+ * <p>Signing you in...</p>
2940
+ * </>
2941
+ * }
2942
+ * >
2943
+ * ```
2944
+ *
2945
+ * @example Render function with message
2946
+ * ```tsx
2947
+ * <SaaSOSProvider
2948
+ * loadingComponent={({ message }) => (
2949
+ * <>
2950
+ * <img src="/logo.svg" alt="Logo" />
2951
+ * <p>{message}</p>
2952
+ * </>
2953
+ * )}
2954
+ * >
2955
+ * ```
2956
+ */
2957
+ loadingComponent?: react__default.ReactNode | ((props: LoadingProps) => react__default.ReactNode);
2845
2958
  }
2846
2959
  declare const SaaSOSProvider: react__default.FC<SaaSOSProviderProps>;
2847
2960
 
@@ -2923,6 +3036,7 @@ declare const WhenUnauthenticated: {
2923
3036
 
2924
3037
  declare const SettingsScreen: {
2925
3038
  readonly Profile: "profile";
3039
+ readonly Security: "security";
2926
3040
  readonly General: "general";
2927
3041
  readonly Users: "users";
2928
3042
  readonly Subscription: "subscription";
@@ -5242,6 +5356,37 @@ interface PricingPageProps {
5242
5356
  */
5243
5357
  declare function PricingPage({ slug, children, loadingFallback, errorFallback, redirectBaseUrl, }: PricingPageProps): react_jsx_runtime.JSX.Element;
5244
5358
 
5359
+ interface FullScreenLoaderProps {
5360
+ /** Content to display centered on screen. Falls back to a default spinner + message. */
5361
+ children?: react__default.ReactNode;
5362
+ /** Message shown below the default spinner (only used when no children are provided). Defaults to "Loading..." */
5363
+ message?: string;
5364
+ /** Background color of the overlay. Defaults to white (dark mode: near-black). */
5365
+ backgroundColor?: string;
5366
+ }
5367
+ /**
5368
+ * Full-screen overlay that centers its content.
5369
+ * Uses inline styles — works without any CSS imports.
5370
+ * Respects dark mode and reduced-motion preferences.
5371
+ *
5372
+ * @example Default spinner
5373
+ * ```tsx
5374
+ * <FullScreenLoader message="Signing you in..." />
5375
+ * ```
5376
+ *
5377
+ * @example Custom content
5378
+ * ```tsx
5379
+ * <FullScreenLoader>
5380
+ * <img src="/logo.svg" alt="Logo" />
5381
+ * <p>Loading your workspace...</p>
5382
+ * </FullScreenLoader>
5383
+ * ```
5384
+ */
5385
+ declare const FullScreenLoader: {
5386
+ ({ children, message, backgroundColor, }: FullScreenLoaderProps): react_jsx_runtime.JSX.Element;
5387
+ displayName: string;
5388
+ };
5389
+
5245
5390
  declare function WorkspaceSwitcher(props: {
5246
5391
  trigger: (isLoading: boolean, currentWorkspace: IWorkspace | null) => ReactNode;
5247
5392
  }): react_jsx_runtime.JSX.Element;
@@ -5280,5 +5425,48 @@ declare const PushNotificationProvider: react__default.FC<PushNotificationProvid
5280
5425
  */
5281
5426
  declare function usePushNotifications(): PushNotificationContextValue;
5282
5427
 
5283
- export { ApiVersion, AuthApi, AuthStatus, BBAction, BBScreen, BBStatus, BB_PARAM, BaseApi, BetaForm, BillingIntervals, CURRENCY_DISPLAY, CURRENCY_FLAG, CreditActionsProvider, CreditBalance, CreditBalanceContextProvider, CreditBucketSource, CreditBucketStatus, CreditStorePage, CreditTransactionType, DEFAULT_ROLE_PERMISSIONS, DunningState, EventEmitter, InvoiceStatuses, PLAN_CURRENCY_CODES, PLAN_CURRENCY_OPTIONS, PUSH_SERVICE_WORKER_SCRIPT, Permission, PricingPage, PushApi, PushNotificationProvider, QuotaUsageContextProvider, SDKEvent, SETTINGS_SCREENS, SUPPORTED_LOCALES, SaaSOSProvider, SettingsApi, SettingsScreen, SubscriptionContextProvider, SubscriptionItemType, SubscriptionStatus, UserApi, WhenAuthenticated, WhenCreditsAvailable, WhenCreditsExhausted, WhenCreditsLow, WhenNoSubscription, WhenNotTrialing, WhenPermission, WhenQuotaAvailable, WhenQuotaExhausted, WhenQuotaOverage, WhenQuotaThreshold, WhenRoles, WhenSubscription, WhenSubscriptionToPlans, WhenTrialEnding, WhenTrialing, WhenUnauthenticated, WhenUserFeatureDisabled, WhenUserFeatureEnabled, WhenWorkspaceFeatureDisabled, WhenWorkspaceFeatureEnabled, WhenWorkspaceRoles, WorkspaceApi, WorkspaceSwitcher, calculateBillableSeats, calculateSeatOverageCents, calculateTotalSubscriptionCents, cleanBBParams, clearAuthIntent, consumeAuthIntent, createBBUrl, createCheckoutRedirectUrls, createCreditPurchaseRedirectUrls, eventEmitter, formatCents, formatOverageRate, formatOverageRateWithLabel, formatQuotaIncludedOverage, formatQuotaWithPrice, getAvailableCurrenciesFromPlans, getBasePriceCents, getBillingIntervalAndCurrencyFromPriceId, getCurrencyFlag, getCurrencySymbol, getDisplayCurrency, getPerSeatPriceCents, getPricingVariant, getQuotaDisplayValue, getQuotaDisplayWithVariant, getQuotaOverageCents, getQuotaUnitLabelFromName, getSeatPricing, getStripePriceIdForInterval, hasPermission, invalidateCreditBalance, invalidateQuotaUsage, invalidateSubscription, readBBParams, resolveMaxUsers, resolvePermissions, safeRedirect, saveAuthIntent, useAllQuotaUsage, useBillingPortal, useCancelSubscription, useConsumeCredits, useCreateCheckoutSession, useCreditBalance, useCreditBalanceContext, useCreditPackages, useCreditTransactions, useExpiringCredits, useInvoice, useInvoices, usePermissions, usePlanGroup, usePlanGroupVersions, usePublicCreditPackages, usePublicPlanGroupVersion, usePublicPlans, usePurchaseCredits, usePushNotifications, useQuotaUsageContext, useQuotaUsageStatus, useRecordUsage, useResumeSubscription, useSaaSAuth, useSaaSOs, useSaaSSettings, useSaaSWorkspaces, useSeatStatus, useSubscription, useSubscriptionContext, useSubscriptionManagement, useTranslation, useTrialStatus, useUpdateSubscription, useUsageLogs, useUserAttributes, useUserFeatures, validateInvite, validateRedirectUrl };
5284
- export type { BBActionType, BBScreenType, BBStatusType, BetaFormData, BetaFormResponse, BillingInterval, CheckoutResult, CreditActionsDetails, CreditBalanceContextValue, CreditBalanceDetails, CreditBucketSourceType, CreditBucketStatusType, CreditStorePageDetails, CreditTransactionTypeValue, DunningStateType, EventData, EventType, FormatQuotaWithPriceOptions, GetCheckoutStripeParams, IAllQuotaUsageResponse, IBaseApiConfig, IBasePricing, IBetaConfig, ICheckoutSessionRequest, ICheckoutSessionResponse, ICheckoutStripeOptions, IConsumeCreditsRequest, IConsumeCreditsResponse, ICreditBalance, ICreditBucket, ICreditBucketsQuery, ICreditBucketsResponse, ICreditPackage, ICreditPackagePricingVariant, ICreditPurchaseRequest, ICreditPurchaseResponse, ICreditTransaction, ICreditTransactionsQuery, ICreditTransactionsResponse, IEventCallbacks, IExpiringCreditsResponse, IInvoice, IInvoiceListResponse, IInvoiceResponse, IOsConfig, IOsState, IPlan, IPlanGroup, IPlanGroupInfo, IPlanGroupLatestVersion, IPlanGroupResponse, IPlanGroupVersion, IPlanGroupVersionWithPlans, IPlanGroupVersionsResponse, IPlanVersion, IPlanVersionSummary, IPlanVersionWithPlan, IPricingVariant, IPublicCreditPackage, IPublicCreditPackagesResponse, IPublicPlanItem, IPublicPlanItemCategory, IPublicPlanVersion, IPublicPlansResponse, IQuotaByInterval, IQuotaIntervalValue, IQuotaOveragePriceIdsByInterval, IQuotaOveragesByInterval, IQuotaUsageStatus, IQuotaUsageStatusResponse, IRecordUsageRequest, IRecordUsageResponse, IStripePricesByInterval, ISubscription, ISubscriptionItem, ISubscriptionResponse, ISubscriptionUpdateRequest, ISubscriptionUpdateResponse, IUsageLogEntry, IUsageLogsQuery, IUsageLogsResponse, InviteBlockReason, InviteValidation, InvoiceStatus, InvoiceStatusType, MaxUsersConfig, NotificationData, NotificationEvent, NotificationResult, OnWorkspaceChangeParams, PermissionContext, PermissionKey, PlanVersionWithPricingVariants, PricingPageDetails, PricingPageProps, QuotaDisplayValue, QuotaDisplayWithOverage, QuotaUsageContextValue, RolePermissionMap, SDKLocale, SDKMessages, SaaSOSProviderProps, SeatStatus, SubscriptionContextValue, SubscriptionItemTypeValue, SubscriptionStatusType, TrialStatus, UserCreatedEventData, UserUpdatedEventData, WorkspaceChangedEventData, WorkspaceCreatedEventData, WorkspaceDeletedEventData, WorkspaceSettingsSection, WorkspaceUpdatedEventData, WorkspaceUserAddedEventData, WorkspaceUserRemovedEventData, WorkspaceUserRoleChangedEventData };
5428
+ interface SettingsManagerState {
5429
+ open: boolean;
5430
+ section: WorkspaceSettingsSection;
5431
+ /** Optional params carried from BB URL (e.g. plan selection from pricing page). Cleared on close. */
5432
+ params?: Record<string, string>;
5433
+ }
5434
+ /**
5435
+ * Global settings manager for workspace settings dialog
5436
+ * Handles opening/closing the dialog internally
5437
+ */
5438
+ declare class WorkspaceSettingsManager {
5439
+ private listeners;
5440
+ private currentState;
5441
+ /**
5442
+ * Subscribe to settings dialog state changes
5443
+ */
5444
+ subscribe(listener: (state: SettingsManagerState) => void): () => void;
5445
+ /**
5446
+ * Get current state
5447
+ */
5448
+ getState(): SettingsManagerState;
5449
+ /**
5450
+ * Open workspace settings dialog
5451
+ * @param section - Optional section to open to (defaults to 'profile')
5452
+ * @param params - Optional params to pass to the section (e.g. plan selection from BB URL)
5453
+ */
5454
+ openWorkspaceSettings(section?: WorkspaceSettingsSection, params?: Record<string, string>): void;
5455
+ /**
5456
+ * Close settings dialog
5457
+ */
5458
+ closeSettings(): void;
5459
+ /**
5460
+ * Change section without opening/closing
5461
+ */
5462
+ setSection(section: WorkspaceSettingsSection): void;
5463
+ /**
5464
+ * Clear params without changing open/section state
5465
+ */
5466
+ clearParams(): void;
5467
+ private notifyListeners;
5468
+ }
5469
+ declare const workspaceSettingsManager: WorkspaceSettingsManager;
5470
+
5471
+ export { ApiVersion, AuthApi, AuthStatus, BBAction, BBScreen, BBStatus, BB_PARAM, BaseApi, BetaForm, BillingIntervals, CURRENCY_DISPLAY, CURRENCY_FLAG, CreditActionsProvider, CreditBalance, CreditBalanceContextProvider, CreditBucketSource, CreditBucketStatus, CreditStorePage, CreditTransactionType, DEFAULT_ROLE_PERMISSIONS, DunningState, EventEmitter, FullScreenLoader, InvoiceStatuses, PLAN_CURRENCY_CODES, PLAN_CURRENCY_OPTIONS, PUSH_SERVICE_WORKER_SCRIPT, Permission, PricingPage, PushApi, PushNotificationProvider, QuotaUsageContextProvider, SDKEvent, SETTINGS_SCREENS, SUPPORTED_LOCALES, SaaSOSProvider, SettingsApi, SettingsScreen, SubscriptionContextProvider, SubscriptionItemType, SubscriptionStatus, UserApi, WhenAuthenticated, WhenCreditsAvailable, WhenCreditsExhausted, WhenCreditsLow, WhenNoSubscription, WhenNotTrialing, WhenPermission, WhenQuotaAvailable, WhenQuotaExhausted, WhenQuotaOverage, WhenQuotaThreshold, WhenRoles, WhenSubscription, WhenSubscriptionToPlans, WhenTrialEnding, WhenTrialing, WhenUnauthenticated, WhenUserFeatureDisabled, WhenUserFeatureEnabled, WhenWorkspaceFeatureDisabled, WhenWorkspaceFeatureEnabled, WhenWorkspaceRoles, WorkspaceApi, WorkspaceSwitcher, calculateBillableSeats, calculateSeatOverageCents, calculateTotalSubscriptionCents, cleanBBParams, clearAuthIntent, consumeAuthIntent, createBBUrl, createCheckoutRedirectUrls, createCreditPurchaseRedirectUrls, eventEmitter, formatCents, formatOverageRate, formatOverageRateWithLabel, formatQuotaIncludedOverage, formatQuotaWithPrice, getAvailableCurrenciesFromPlans, getBasePriceCents, getBillingIntervalAndCurrencyFromPriceId, getCurrencyFlag, getCurrencySymbol, getDisplayCurrency, getPerSeatPriceCents, getPricingVariant, getQuotaDisplayValue, getQuotaDisplayWithVariant, getQuotaOverageCents, getQuotaUnitLabelFromName, getSeatPricing, getStripePriceIdForInterval, hasPermission, invalidateCreditBalance, invalidateQuotaUsage, invalidateSubscription, readBBParams, resolveMaxUsers, resolvePermissions, safeRedirect, saveAuthIntent, useAllQuotaUsage, useBillingPortal, useCancelSubscription, useConsumeCredits, useCreateCheckoutSession, useCreditBalance, useCreditBalanceContext, useCreditPackages, useCreditTransactions, useExpiringCredits, useFullScreenLoader, useInvoice, useInvoices, usePermissions, usePlanGroup, usePlanGroupVersions, usePublicCreditPackages, usePublicPlanGroupVersion, usePublicPlans, usePurchaseCredits, usePushNotifications, useQuotaUsageContext, useQuotaUsageStatus, useRecordUsage, useResumeSubscription, useSaaSAuth, useSaaSOs, useSaaSSettings, useSaaSWorkspaces, useSeatStatus, useSubscription, useSubscriptionContext, useSubscriptionManagement, useTranslation, useTrialStatus, useUpdateSubscription, useUsageLogs, useUserAttributes, useUserFeatures, validateInvite, validateRedirectUrl, workspaceSettingsManager };
5472
+ export type { BBActionType, BBScreenType, BBStatusType, BetaFormData, BetaFormResponse, BillingInterval, CheckoutResult, CreditActionsDetails, CreditBalanceContextValue, CreditBalanceDetails, CreditBucketSourceType, CreditBucketStatusType, CreditStorePageDetails, CreditTransactionTypeValue, DunningStateType, EventData, EventType, FormatQuotaWithPriceOptions, FullScreenLoaderProps, GetCheckoutStripeParams, IAllQuotaUsageResponse, IBaseApiConfig, IBasePricing, IBetaConfig, ICheckoutSessionRequest, ICheckoutSessionResponse, ICheckoutStripeOptions, IConsumeCreditsRequest, IConsumeCreditsResponse, ICreditBalance, ICreditBucket, ICreditBucketsQuery, ICreditBucketsResponse, ICreditPackage, ICreditPackagePricingVariant, ICreditPurchaseRequest, ICreditPurchaseResponse, ICreditTransaction, ICreditTransactionsQuery, ICreditTransactionsResponse, IEventCallbacks, IExpiringCreditsResponse, IInvoice, IInvoiceListResponse, IInvoiceResponse, IOsConfig, IOsState, IPlan, IPlanGroup, IPlanGroupInfo, IPlanGroupLatestVersion, IPlanGroupResponse, IPlanGroupVersion, IPlanGroupVersionWithPlans, IPlanGroupVersionsResponse, IPlanVersion, IPlanVersionSummary, IPlanVersionWithPlan, IPricingVariant, IPublicCreditPackage, IPublicCreditPackagesResponse, IPublicPlanItem, IPublicPlanItemCategory, IPublicPlanVersion, IPublicPlansResponse, IQuotaByInterval, IQuotaIntervalValue, IQuotaOveragePriceIdsByInterval, IQuotaOveragesByInterval, IQuotaUsageStatus, IQuotaUsageStatusResponse, IRecordUsageRequest, IRecordUsageResponse, IStripePricesByInterval, ISubscription, ISubscriptionItem, ISubscriptionResponse, ISubscriptionUpdateRequest, ISubscriptionUpdateResponse, IUsageLogEntry, IUsageLogsQuery, IUsageLogsResponse, InviteBlockReason, InviteValidation, InvoiceStatus, InvoiceStatusType, LoadingProps, MaxUsersConfig, NotificationData, NotificationEvent, NotificationResult, OnWorkspaceChangeParams, PermissionContext, PermissionKey, PlanVersionWithPricingVariants, PricingPageDetails, PricingPageProps, QuotaDisplayValue, QuotaDisplayWithOverage, QuotaUsageContextValue, RolePermissionMap, SDKLocale, SDKMessages, SaaSOSProviderProps, SeatStatus, SettingsManagerState, SubscriptionContextValue, SubscriptionItemTypeValue, SubscriptionStatusType, TrialStatus, UserCreatedEventData, UserUpdatedEventData, WorkspaceChangedEventData, WorkspaceCreatedEventData, WorkspaceDeletedEventData, WorkspaceSettingsSection, WorkspaceUpdatedEventData, WorkspaceUserAddedEventData, WorkspaceUserRemovedEventData, WorkspaceUserRoleChangedEventData };