@buildbase/sdk 0.0.45 → 0.0.47

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,t){try{const s=await e.json();return s?.message||s?.error||t}catch{return t}}async function r(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function n(e,t="Request failed"){if(!e.ok){let s=t;try{const t=await r(e);s=t.message||t.error||s}catch{s=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(s)}try{return await r(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class a extends Error{constructor(e,t,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,a)}}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 a("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",s),n=r instanceof a?r:new a(r.message,"SDK_ERROR",s,r);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${s.component||"Unknown"}:`,{message:n.message,code:n.code,context:n.context,originalError:n.originalError,stack:n.stack}),this.config.onError)try{this.config.onError(n,s)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(n,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 c(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 u(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){i(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function l(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 d="saas-session-id";function h(){return function(){if("undefined"==typeof window)return null;try{return c(d)}catch(e){return i(e,{component:"auth-utils",action:"getSessionId",metadata:{key:d}}),null}}()}const p="SDK is not ready (missing serverUrl, version, or orgId)";class f{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._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=h(),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),a={...t,headers:n};let o;if(this._timeout>0){const e=new AbortController;o=setTimeout(()=>e.abort(),this._timeout),a.signal=t.signal?AbortSignal.any([t.signal,e.signal]):e.signal}const i=async t=>{try{const e=this._fetch.bind(globalThis),n=await e(s,a);if(this._debug&&console.log(`[BuildBase] ${r} ${s} → ${n.status}`),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)),i(t+1)}return n}catch(s){if(s instanceof Error&&"AbortError"===s.name){if(void 0!==o){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)),i(t+1)}throw s instanceof Error&&this._onError?.(s,{method:r,path:e}),s}};try{return await i(0)}finally{void 0!==o&&clearTimeout(o)}}async fetchJson(e,t={},s="Request failed"){this.ensureReady();try{const r=await this.executeFetch(e,t);return await n(r,s)}catch(s){throw s instanceof Error&&this._onError?.(s,{method:(t.method??"GET").toUpperCase(),path:e}),s}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}}class g extends f{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)});if(!s.ok){let e="Failed to initiate authentication";try{e=(await s.json()).message||e}catch{e=`Failed to initiate authentication (${s.status}: ${s.statusText})`}throw new Error(e)}return s.json()}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}}class w extends f{constructor(e){super({...e,basePath:"beta",requireOrgId:!0})}getAuthHeaders(){return{}}async fetchConfig(){return this.fetchJson(`config?orgId=${encodeURIComponent(this.orgId)}`,{},"Failed to fetch beta form configuration")}async submitBetaUser(e){return this.fetchJson("submit",{method:"POST",body:JSON.stringify(e)},"Failed to submit beta user request")}}class y{constructor(e){this.api=new w(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},s=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),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),a=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:a}})}}class m extends f{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}class k extends f{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class b extends f{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});if(!t.ok)throw new Error(await s(t,"Failed to fetch user attributes"));const r=await t.json();return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}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});if(!t.ok)throw new Error(await s(t,"Failed to fetch user features"));const r=await t.json();return"object"==typeof r&&null!==r?r:{}}}class S extends f{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(){return this.fetchJson("workspaces",{},"Failed to fetch workspaces")}async createWorkspace(e){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e)},"Failed to create workspace")}async updateWorkspace(e,t){return this.fetchJson(`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t)},"Failed to update workspace")}async deleteWorkspace(e){return this.fetchJson(`workspaces/${e}`,{method:"DELETE"},"Failed to delete workspace")}async getWorkspaceUsers(e){return this.fetchJson(`workspaces/${e}/users`,{},"Failed to fetch workspace users")}async addUser(e,t){return this.fetchJson(`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t)},"Failed to invite member")}async removeUser(e,t){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,t,s){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(s)},"Failed to update user")}async updateSettings(e){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e)},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t){return this.fetchJson(`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t})},"Failed to update workspace permissions")}async getFeatures(){return this.fetchJson("workspaces/features",{},"Failed to fetch features")}async updateFeature(e,t,s){return this.fetchJson(`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:s}})},"Failed to update feature")}async getWorkspace(e){return this.fetchJson(`workspaces/${e}`,{},"Failed to fetch workspace")}async getProfile(){return this.fetchJson("profile",{},"Failed to fetch profile")}async updateUserProfile(e){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e)},"Failed to update user profile")}async getCurrentSubscription(e){const t=await this.fetchResponse(`workspaces/${e}/subscription`);if(!t.ok){let e="Failed to fetch subscription";try{e=(await t.json()).message||e}catch{e=404===t.status?"Workspace not found or no subscription available":401===t.status?"Unauthorized - Please check your session":`Failed to fetch subscription (${t.status}: ${t.statusText})`}throw new Error(e)}const s=await t.json();if(void 0!==s.success){if(!s.success)throw new Error(s.message||"Failed to fetch subscription");return s.data||s}return s}async getPlanGroup(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/plan-group`);if(!t.ok){let e="Failed to fetch plan group";try{e=(await t.json()).message||e}catch{e=404===t.status?"No plan group found for this workspace":401===t.status?"Unauthorized - Please check your session":`Failed to fetch plan group (${t.status}: ${t.statusText})`}throw new Error(e)}const s=await t.json();if(void 0!==s.success){if(!s.success)throw new Error(s.message||"Failed to fetch plan group");return s.data||s}return s}async getPlanGroupByVersion(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/plan-group?groupVersionId=${encodeURIComponent(t)}`);if(!s.ok){let e="Failed to fetch plan group version";try{e=(await s.json()).message||e}catch{e=404===s.status?"Plan group version not found":401===s.status?"Unauthorized - Please check your session":`Failed to fetch plan group version (${s.status}: ${s.statusText})`}throw new Error(e)}const r=await s.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to fetch plan group version");return r.data||r}return r}async getPlanGroupVersions(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/plan-group/versions`);if(!t.ok){let e="Failed to fetch plan group versions";try{e=(await t.json()).message||e}catch{e=404===t.status?"No plan group versions found":401===t.status?"Unauthorized - Please check your session":`Failed to fetch plan group versions (${t.status}: ${t.statusText})`}throw new Error(e)}const s=await t.json();if(void 0!==s.success){if(!s.success)throw new Error(s.message||"Failed to fetch plan group versions");return s.data||s}return s}async getPublicPlans(e){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");const t=await this.fetchResponse(`${this.orgId}/plans/${encodeURIComponent(e)}`);if(!t.ok){let s="Failed to fetch plans";try{s=(await t.json()).message||s}catch{s=404===t.status?`Plans "${e}" not found`:`Failed to fetch plans (${t.status}: ${t.statusText})`}throw new Error(s)}const s=await t.json();if(void 0!==s.success&&!s.success)throw new Error(s.message||"Failed to fetch plans");return s.data??s}async getPublicCreditPackages(){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");const e=await this.fetchResponse(`${this.orgId}/credit-packages`);if(!e.ok){let t="Failed to fetch credit packages";try{t=(await e.json()).message||t}catch{t=`Failed to fetch credit packages (${e.status}: ${e.statusText})`}throw new Error(t)}const t=await e.json();if(void 0!==t.success&&!t.success)throw new Error(t.message||"Failed to fetch credit packages");return t.data??t}async getPlanGroupVersion(e){const t=await this.fetchResponse(`plan-group-versions/${e}`);if(!t.ok){let e="Failed to fetch plan group version";try{e=(await t.json()).message||e}catch{e=404===t.status?"Plan group version not found":401===t.status?"Unauthorized - Please check your session":`Failed to fetch plan group version (${t.status}: ${t.statusText})`}throw new Error(e)}const s=await t.json();if(void 0!==s.success){if(!s.success)throw new Error(s.message||"Failed to fetch plan group version");return s.data||s}return s}async createCheckoutSession(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});if(!s.ok){let e="Failed to create checkout session";try{e=(await s.json()).message||e}catch{e=`Failed to create checkout session (${s.status}: ${s.statusText})`}throw new Error(e)}const r=await s.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to create checkout session");return r.data||r}return r}async selectFreePlan(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t})});if(!s.ok){let e="Failed to select free plan";try{e=(await s.json()).message||e}catch{e=`Failed to select free plan (${s.status}: ${s.statusText})`}throw new Error(e)}const r=await s.json();return r.data||r}async updateSubscription(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});if(!s.ok){let e="Failed to update subscription";try{e=(await s.json()).message||e}catch{e=`Failed to update subscription (${s.status}: ${s.statusText})`}throw new Error(e)}const r=await s.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to update subscription");return r.data?.checkoutUrl||r.checkoutUrl,r.data||r}return r.checkoutUrl,r}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()}`,{});if(!n.ok){let e="Failed to fetch invoices";try{e=(await n.json()).message||e}catch{e=404===n.status?"Workspace not found or no invoices available":401===n.status?"Unauthorized - Please check your session":`Failed to fetch invoices (${n.status}: ${n.statusText})`}throw new Error(e)}const a=await n.json();if(void 0!==a.success){if(!a.success)throw new Error(a.message||"Failed to fetch invoices");return a}return a}async getInvoice(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/invoices/${t}`,{});if(!s.ok){let e="Failed to fetch invoice";try{e=(await s.json()).message||e}catch{e=404===s.status?"Invoice not found":401===s.status?"Unauthorized - Please check your session":`Failed to fetch invoice (${s.status}: ${s.statusText})`}throw new Error(e)}const r=await s.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to fetch invoice");return r}return r}async cancelSubscriptionAtPeriodEnd(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST"});if(!t.ok){let e="Failed to cancel subscription";try{e=(await t.json()).message||e}catch{e=404===t.status?"Subscription not found":401===t.status?"Unauthorized - Please check your session":`Failed to cancel subscription (${t.status}: ${t.statusText})`}throw new Error(e)}const s=await t.json();if(void 0!==s.success){if(!s.success)throw new Error(s.message||"Failed to cancel subscription");return s.data||s}return s}async resumeSubscription(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/resume`,{method:"POST"});if(!t.ok){let e="Failed to resume subscription";try{e=(await t.json()).message||e}catch{e=404===t.status?"Subscription not found":401===t.status?"Unauthorized - Please check your session":`Failed to resume subscription (${t.status}: ${t.statusText})`}throw new Error(e)}const s=await t.json();if(void 0!==s.success){if(!s.success)throw new Error(s.message||"Failed to resume subscription");return s.data||s}return s}async recordUsage(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});if(!s.ok){let e="Failed to record usage";try{e=(await s.json()).message||e}catch{e=`Failed to record usage (${s.status}: ${s.statusText})`}throw new Error(e)}const r=await s.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to record usage");return r.data||r}return r}async recordUsageBatch(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t)});if(!s.ok){let e="Failed to record batch usage";try{e=(await s.json()).message||e}catch{e=`Failed to record batch usage (${s.status}: ${s.statusText})`}throw new Error(e)}const r=await s.json();return r.data||r}async getQuotaUsageStatus(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/usage/status?quotaSlug=${encodeURIComponent(t)}`);if(!s.ok){let e="Failed to fetch quota usage status";try{e=(await s.json()).message||e}catch{e=404===s.status?"Workspace not found or no subscription available":401===s.status?"Unauthorized - Please check your session":`Failed to fetch quota usage status (${s.status}: ${s.statusText})`}throw new Error(e)}const r=await s.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to fetch quota usage status");return r.data||r}return r}async getAllQuotaUsage(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/usage/all`);if(!t.ok){let e="Failed to fetch all quota usage";try{e=(await t.json()).message||e}catch{e=404===t.status?"Workspace not found or no subscription available":401===t.status?"Unauthorized - Please check your session":`Failed to fetch all quota usage (${t.status}: ${t.statusText})`}throw new Error(e)}const s=await t.json();if(void 0!==s.success){if(!s.success)throw new Error(s.message||"Failed to fetch all quota usage");return s.data||s}return s}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}`:""}`,a=await this.fetchResponse(n);if(!a.ok){let e="Failed to fetch usage logs";try{e=(await a.json()).message||e}catch{e=404===a.status?"Workspace not found":401===a.status?"Unauthorized - Please check your session":`Failed to fetch usage logs (${a.status}: ${a.statusText})`}throw new Error(e)}const o=await a.json();if(void 0!==o.success){if(!o.success)throw new Error(o.message||"Failed to fetch usage logs");return o.data||o}return o}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`);if(!t.ok){let e="Failed to fetch credit balance";try{e=(await t.json()).message||e}catch{e=404===t.status?"Workspace not found":401===t.status?"Unauthorized - Please check your session":`Failed to fetch credit balance (${t.status}: ${t.statusText})`}throw new Error(e)}const s=await t.json();if(void 0!==s.success){if(!s.success)throw new Error(s.message||"Failed to fetch credit balance");return s.data||s}return s}async consumeCredits(e,t){const s=await this.fetchResponse(`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t)});if(!s.ok){const e=await s.json().catch(()=>({}));if(402===s.status){const t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}throw new Error(e.message||`Failed to consume credits (${s.status}: ${s.statusText})`)}const r=await s.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to consume credits");return r.data||r}return r}async purchaseCredits(e,t){const s=await this.fetchResponse(`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t)});if(!s.ok){let e="Failed to create credit purchase checkout";try{e=(await s.json()).message||e}catch{e=`Failed to create credit purchase checkout (${s.status}: ${s.statusText})`}throw new Error(e)}const r=await s.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||"Failed to create credit purchase checkout");return r.data||r}return r}async getCreditPackages(e){const t=await this.fetchResponse(`workspaces/${e}/credits/packages`);if(!t.ok){let e="Failed to fetch credit packages";try{e=(await t.json()).message||e}catch{e=`Failed to fetch credit packages (${t.status}: ${t.statusText})`}throw new Error(e)}const s=await t.json();if(void 0!==s.success){if(!s.success)throw new Error(s.message||"Failed to fetch credit packages");const e=s.data||s;return e.docs??e}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}`:""}`,a=await this.fetchResponse(n);if(!a.ok){let e="Failed to fetch credit transactions";try{e=(await a.json()).message||e}catch{e=`Failed to fetch credit transactions (${a.status}: ${a.statusText})`}throw new Error(e)}const o=await a.json();if(void 0!==o.success){if(!o.success)throw new Error(o.message||"Failed to fetch credit transactions");return o.data||o}return o}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}`:""}`,a=await this.fetchResponse(n);if(!a.ok){let e="Failed to fetch credit buckets";try{e=(await a.json()).message||e}catch{e=`Failed to fetch credit buckets (${a.status}: ${a.statusText})`}throw new Error(e)}const o=await a.json();if(void 0!==o.success){if(!o.success)throw new Error(o.message||"Failed to fetch credit buckets");return o.data||o}return o}async getExpiringCredits(e,t){const s=t?`?days=${t}`:"",r=await this.fetchResponse(`workspaces/${e}/credits/expiring${s}`);if(!r.ok){let e="Failed to fetch expiring credits";try{e=(await r.json()).message||e}catch{e=`Failed to fetch expiring credits (${r.status}: ${r.statusText})`}throw new Error(e)}const n=await r.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||"Failed to fetch expiring credits");return n.data||n}return n}}var E;!function(e){e.V1="v1"}(E||(E={}));const v={UserCreated:"user:created",UserUpdated:"user:updated",WorkspaceChanged:"workspace:changed",WorkspaceUpdated:"workspace:updated",WorkspaceUserAdded:"workspace:user-added",WorkspaceUserRemoved:"workspace:user-removed",WorkspaceUserRoleChanged:"workspace:user-role-changed",WorkspaceCreated:"workspace:created",WorkspaceDeleted:"workspace:deleted"};class ${constructor(){this.callbacks=null}setCallbacks(e){this.callbacks=e}getCallbacks(){return this.callbacks}async emit(e,t){if(this.callbacks?.handleEvent)try{await this.callbacks.handleEvent(e,t)}catch(t){i(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(v.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(v.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(v.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(v.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,s){await this.emit(v.WorkspaceUserAdded,{userId:e,workspace:t,role:s})}async emitWorkspaceUserRemoved(e,t,s){await this.emit(v.WorkspaceUserRemoved,{userId:e,workspace:t,role:s})}async emitWorkspaceUserRoleChanged(e,t,s,r){await this.emit(v.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:s,newRole:r})}async emitWorkspaceCreated(e){await this.emit(v.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(v.WorkspaceDeleted,{workspace:e})}}const P=new $,F=new Set;function U(){F.forEach(e=>e())}const I=new Set;function R(){I.forEach(e=>e())}const C=new Set;function O(){C.forEach(e=>e())}const T="bb",W={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",Invite:"invite"},_={Success:"success",Cancel:"cancel",Error:"error"},x={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function A(e,t){let s;try{const e=t||("undefined"!=typeof window?window.location.href:"https://localhost");s=new URL(e),s.search=""}catch{s=new URL("https://localhost")}return s.searchParams.set(T,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),s.toString()}function N(e,t){const s=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:A({action:W.Checkout,status:_.Success,ws:e,screen:x.Subscription},s),cancelUrl:A({action:W.Checkout,status:_.Cancel,ws:e,screen:x.Subscription},s)}}function j(e,t){const s=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:A({action:W.CreditPurchase,status:_.Success,ws:e,screen:x.Credits},s),cancelUrl:A({action:W.CreditPurchase,status:_.Cancel,ws:e,screen:x.Credits},s)}}function J(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(T);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 L(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(T)&&(e.searchParams.delete(T),window.history.replaceState({},"",e.toString()))}catch{}}function B(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 q(e,t="/"){const s=B(e);window.location.href=s||t}const M="saas-auth-intent";function V(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function K(e){B(e)&&l(M,{returnUrl:e,createdAt:Date.now()})}function z(){const e=function(e,t){const s=c(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}}),u(e),null):r}catch(t){return i(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),u(e),null}}(M,V);return u(M),e?Date.now()-e.createdAt>6e5?null:B(e.returnUrl):null}function D(){u(M)}const G={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:"฿"},H={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function Q(e){return e&&e.trim()?H[e.trim().toLowerCase()]??"":""}function Y(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return G[t]??t.toUpperCase()}const Z=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],X=Z.map(e=>({value:e,label:`${e.toUpperCase()} (${Y(e)})`}));function ee(e,t){return Y(t)+(e/100).toFixed(2)}const te={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included"};function se(e,t,s,r){if(null==e||e<0)return null;const n={...te,...r},a=null!=t&&t>=1?t:1,o=Y(s),i=(e/100).toFixed(2);return 1===a?`${o}${i}/${n.unit}`:`${o}${i}/${a.toLocaleString()} ${n.units}`}function re(e,t,s,r,n,a){if(null==e||e<0)return null;const o={...te,...a},i=null!=t&&t>=1?t:1,c=Y(r),u=(e/100).toFixed(2);if(s){const e=n??(s.endsWith("s")?s:`${s}s`);return i>=2?`${c}${u}/${i.toLocaleString()} ${e}`:`${c}${u}/${s}`}return 1===i?`${c}${u}/${o.unit}`:`${c}${u}/${i.toLocaleString()} ${o.units}`}function ne(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 ae(e,t,s,r,n,a,o,i){const c={...te,...o};if(!1===i)return null!=e?`${c.included}: ${e.toLocaleString()} (${c.hardLimit??"hard limit"})`:c.hardLimit??"Hard limit";const u=a??(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} ${ee(t,r)}/${l}`:null!=e?`${c.included}: ${e.toLocaleString()}`:null!=t?`${c.afterIncluded}: ${ee(t,r)}/${l}`:"—"}function oe(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 ie={included:"included",then:"then"};function ce(e,t,s={}){const{overageInCents:r=!0,currency:n}=s,a=s.labels??ie,o=s.currencySymbol??Y(n??"");if(null==e)return"—";const{included:i,overage:c}=e,u=`${i} ${a.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),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${u}, ${a.then} ${o}${d}${h}`}const ue={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},le={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},de={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},he={Feature:"feature",Limit:"limit",Quota:"quota"},pe={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},fe={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},ge={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},we={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function ye(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 me(e,t,s){const r=ye(e,t);if(!r?.basePricing)return null;const n=r.basePricing[s];return null!=n?n:null}function ke(e,t,s){const r=ye(e,t);if(!r?.stripePrices)return null;const n=s===ue.Monthly?"monthlyPriceId":s===ue.Yearly?"yearlyPriceId":"quarterlyPriceId",a=s===ue.Monthly?"monthly":s===ue.Yearly?"yearly":void 0;return r.stripePrices[n]??(a?r.stripePrices[a]:void 0)??null}function be(e,t,s,r){const n=ye(e,t),a=n?.quotaOverages?.[s];if(a)return a[r]}function Se(e,t){const s=ye(e,t);return s?s.currency:e.plan?.currency??""}function Ee(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 ve(e,t,s,r){const n=e.quotas?.[s];if(null==n)return null;const a=n[r];if(!a)return null;const o=be(e,t,s,r);return{included:a.included,...void 0!==a.unitSize&&{unitSize:a.unitSize},...void 0!==o&&{overage:o},allowOverage:!1!==n.allowOverage}}function $e(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 Pe(e,t){const s=ye(e,t);return s?.seatPricing?.enabled?s.seatPricing:null}function Fe(e,t,s){const r=Pe(e,t);return r?.perSeat?r.perSeat[s]??null:null}function Ue(e,t){return Math.max(0,e-(t||0))}function Ie(e,t,s,r){const n=Pe(e,t);if(!n)return null;return Ue(r,n.includedSeats)*(Fe(e,t,s)??0)}function Re(e,t,s,r){const n=me(e,t,s);if(null===n)return null;if(void 0===r)return n;return n+(Ie(e,t,s,r)??0)}function Ce(e){const{planVersion:t,currency:s="usd",settingsMaxUsers:r}=e;if(t){const e=Pe(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 Oe(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:a,source:o}=s;if(a<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=a){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[o]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[o]??"users.memberLimitMessage",blockMessageValues:{maxUsers:a}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}const Te={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"},We=Object.values(Te),_e={admin:We.filter(e=>e!==Te.WORKSPACE_DELETE),member:[Te.WORKSPACE_SETTINGS_VIEW,Te.WORKSPACE_MEMBERS_VIEW,Te.WORKSPACE_FEATURES_VIEW,Te.WORKSPACE_BILLING_VIEW,Te.WORKSPACE_USAGE_VIEW],viewer:[Te.WORKSPACE_SETTINGS_VIEW,Te.WORKSPACE_MEMBERS_VIEW]};function xe(e){const t=new Set;for(const s of Object.values(e))for(const e of s)t.add(e);return Array.from(t)}function Ae(e){const{userId:t,workspace:s,settings: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(We);if(n)for(const t of xe(n))e.add(t);if(s.permissions)for(const t of xe(s.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of xe(r.workspace.permissions))e.add(t);return e}const a=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(!a)return new Set;const o=s.permissions,i=r?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=o?.[a]?c(o[a]):[],d=i?.[a]?c(i[a]):[],h=_e[a]??[];let p;if(l.length>0)p=l;else if(d.length>0)p=d;else if(h.length>0)p=h;else{p=_e[r?.workspace?.defaultRole??"member"]??_e.member??[]}const f=new Set(p),g=o?.[a]?u(o[a]):[],w=n?.[a]?u(n[a]):[],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(Te.WORKSPACE_MEMBERS_INVITE)}(f,a,r),f}function Ne(e,t){const s=Ae(t);return Array.isArray(e)?e.every(e=>s.has(e)):s.has(e)}const je="\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 var payload = event.data.json();\n var title = payload.title || 'Notification';\n var 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 var 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 (var i = 0; i < clientList.length; i++) {\n var 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 Je;function Le(e){const{body:t,signature:s,timestamp:r,secret:n,maxAgeSeconds:a=300}=e;if(!(s&&r&&n&&t))return!1;const o="sha256=";if(!s.startsWith(o))return!1;const i=s.slice(7);if(a>0){const e=parseInt(r,10);if(isNaN(e))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-e)>a)return!1}try{const e=require("crypto"),s=e.createHmac("sha256",n).update(`${r}.${t}`).digest("hex"),a=Buffer.from(i,"hex"),o=Buffer.from(s,"hex");return a.length===o.length&&e.timingSafeEqual(a,o)}catch{return!1}}function Be(e){if(!Le(e))return null;try{return JSON.parse(e.body)}catch{return null}}function qe(e){const{serverUrl:t,orgId:s,version:r="v1",getSessionId:n,timeout:a,maxRetries:o,debug:i,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!==a&&{timeout:a},...void 0!==o&&{maxRetries:o},...void 0!==i&&{debug:i},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},h=e=>{const n={serverUrl:t,version:r,orgId:s,sessionId:e,...d};return{workspace:new S(n),user:new b(n),settings:new k(n),push:new m(n)}},p=new S({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=>p.getPublicPlans(e),getVersion:e=>p.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:()=>p.getPublicCreditPackages()},permissions:{check:async(t,s,r)=>{const n=await e(),[a,o,i]=await Promise.all([n.workspace.getWorkspace(t),n.settings.getSettings(),n.workspace.getWorkspaceUsers(t)]),c=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===s);return Ne(r,{userId:s,workspaceRole:c?.role??null,workspace:a,settings:o})},resolve:async(t,s)=>{const r=await e(),[n,a,o]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),i=o.find(e=>("string"==typeof e.user?e.user:e.user._id)===s);return Ae({userId:s,workspaceRole:i?.role??null,workspace:n,settings:a})}}}),g=f(async()=>h(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=h(e);return f(async()=>t)},client:{forSession:h},...g}}!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(Je||(Je={}));export{E as ApiVersion,g as AuthApi,Je as AuthStatus,W as BBAction,x as BBScreen,_ as BBStatus,T as BB_PARAM,f as BaseApi,y as BetaForm,ue as BillingIntervals,qe as BuildBase,G as CURRENCY_DISPLAY,H as CURRENCY_FLAG,fe as CreditBucketSource,ge as CreditBucketStatus,we as CreditTransactionType,_e as DEFAULT_ROLE_PERMISSIONS,pe as DunningState,$ as EventEmitter,de as InvoiceStatuses,Z as PLAN_CURRENCY_CODES,X as PLAN_CURRENCY_OPTIONS,je as PUSH_SERVICE_WORKER_SCRIPT,Te as Permission,m as PushApi,v as SDKEvent,k as SettingsApi,he as SubscriptionItemType,le as SubscriptionStatus,b as UserApi,S as WorkspaceApi,Ue as calculateBillableSeats,Ie as calculateSeatOverageCents,Re as calculateTotalSubscriptionCents,L as cleanBBParams,D as clearAuthIntent,z as consumeAuthIntent,A as createBBUrl,N as createCheckoutRedirectUrls,j as createCreditPurchaseRedirectUrls,qe as default,P as eventEmitter,ee as formatCents,se as formatOverageRate,re as formatOverageRateWithLabel,ae as formatQuotaIncludedOverage,ce as formatQuotaWithPrice,Ee as getAvailableCurrenciesFromPlans,me as getBasePriceCents,$e as getBillingIntervalAndCurrencyFromPriceId,Q as getCurrencyFlag,Y as getCurrencySymbol,Se as getDisplayCurrency,Fe as getPerSeatPriceCents,ye as getPricingVariant,oe as getQuotaDisplayValue,ve as getQuotaDisplayWithVariant,be as getQuotaOverageCents,ne as getQuotaUnitLabelFromName,Pe as getSeatPricing,ke as getStripePriceIdForInterval,Ne as hasPermission,U as invalidateCreditBalance,R as invalidateQuotaUsage,O as invalidateSubscription,Be as parseWebhookEvent,J as readBBParams,Ce as resolveMaxUsers,Ae as resolvePermissions,q as safeRedirect,K as saveAuthIntent,Oe as validateInvite,B as validateRedirectUrl,Le 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){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};
@@ -99,6 +99,8 @@ type DunningStateType = (typeof DunningState)[keyof typeof DunningState];
99
99
  interface ISubscription {
100
100
  _id: string;
101
101
  subscriptionStatus: SubscriptionStatusType;
102
+ /** Stripe Subscription ID (e.g. 'sub_...'). Present when linked to Stripe. */
103
+ subscriptionId?: string;
102
104
  stripePriceId?: string;
103
105
  stripeCurrentPeriodEnd?: string;
104
106
  /** When the current monthly usage period ends (quotas reset on this date). */
@@ -537,12 +539,10 @@ interface IInvoice {
537
539
  subscription: string;
538
540
  }
539
541
  interface IInvoiceListResponse {
540
- success: boolean;
541
542
  invoices: IInvoice[];
542
543
  has_more: boolean;
543
544
  }
544
545
  interface IInvoiceResponse {
545
- success: boolean;
546
546
  invoice: IInvoice;
547
547
  }
548
548
  /** Request body for POST .../workspaces/:id/subscription/usage */
@@ -1066,6 +1066,8 @@ interface IBaseApiConfig {
1066
1066
  method: string;
1067
1067
  path: string;
1068
1068
  }) => void;
1069
+ /** Called when any request receives a 401 response (session expired mid-use). */
1070
+ onUnauthorized?: () => void;
1069
1071
  /** Custom fetch implementation. */
1070
1072
  fetch?: typeof globalThis.fetch;
1071
1073
  }
@@ -1089,6 +1091,7 @@ declare abstract class BaseApi {
1089
1091
  private readonly _debug;
1090
1092
  private readonly _customHeaders;
1091
1093
  private readonly _onError?;
1094
+ private readonly _onUnauthorized?;
1092
1095
  private readonly _fetch;
1093
1096
  constructor(config: IBaseApiConfig);
1094
1097
  /** Throws if config is not ready for API calls. Called automatically by fetchJson/fetchResponse. */
@@ -1117,6 +1120,16 @@ declare abstract class BaseApi {
1117
1120
  * Caller is responsible for checking response.ok and parsing body.
1118
1121
  */
1119
1122
  protected fetchResponse(path: string, init?: RequestInit): Promise<Response>;
1123
+ /**
1124
+ * Throw an error from a failed response.
1125
+ * Tries to parse JSON error body; falls back to status-based message.
1126
+ */
1127
+ protected throwResponseError(response: Response, defaultMsg: string): Promise<never>;
1128
+ /**
1129
+ * Parse JSON and unwrap `{ success, data }` envelope if present.
1130
+ * Throws if `success` is explicitly `false`.
1131
+ */
1132
+ protected unwrapResponse<T>(response: Response, defaultMsg: string): Promise<T>;
1120
1133
  }
1121
1134
 
1122
1135
  /**
@@ -1145,7 +1158,8 @@ declare class AuthApi extends BaseApi {
1145
1158
  });
1146
1159
  /**
1147
1160
  * Initiate OAuth sign-in flow. Returns redirect URL to the auth provider.
1148
- * Uses /api/v1/auth/request (no 'public' prefix — auth endpoints are at the root).
1161
+ * Uses /api/v1/auth/request — auth endpoints sit outside the /public basePath,
1162
+ * so we build the URL directly instead of using fetchResponse.
1149
1163
  */
1150
1164
  requestAuth(params: AuthRequestParams): Promise<AuthRequestResponse>;
1151
1165
  /** Fetch user profile with the given session ID (used after OAuth redirect or from storage). */
@@ -1298,6 +1312,7 @@ interface NotificationEvent {
1298
1312
  declare class WorkspaceApi extends BaseApi {
1299
1313
  constructor(config: IOsConfig & {
1300
1314
  sessionId?: string;
1315
+ onUnauthorized?: () => void;
1301
1316
  });
1302
1317
  getWorkspaces(): Promise<IWorkspace[]>;
1303
1318
  createWorkspace(data: {
@@ -1671,23 +1686,11 @@ declare class EventEmitter {
1671
1686
  }
1672
1687
  declare const eventEmitter: EventEmitter;
1673
1688
 
1674
- /**
1675
- * Notify all subscribers to refetch credit balance (e.g. after consume or purchase).
1676
- * Called internally by useConsumeCredits, usePurchaseCredits on success.
1677
- */
1678
- declare function invalidateCreditBalance(): void;
1689
+ declare const invalidateCreditBalance: () => void;
1679
1690
 
1680
- /**
1681
- * Notify all subscribers to refetch quota usage (e.g. after recording usage).
1682
- * Called internally by useRecordUsage on success.
1683
- */
1684
- declare function invalidateQuotaUsage(): void;
1691
+ declare const invalidateQuotaUsage: () => void;
1685
1692
 
1686
- /**
1687
- * Notify all subscribers to refetch subscription (e.g. after update/cancel/resume).
1688
- * Called internally by useUpdateSubscription, useCancelSubscription, useResumeSubscription on success.
1689
- */
1690
- declare function invalidateSubscription(): void;
1693
+ declare const invalidateSubscription: () => void;
1691
1694
 
1692
1695
  /**
1693
1696
  * BuildBase URL parameter utilities.
@@ -2148,7 +2151,7 @@ declare function hasPermission(permission: string | string[], ctx: PermissionCon
2148
2151
  *
2149
2152
  * Or manually create `public/push-sw.js` with this content.
2150
2153
  */
2151
- declare const PUSH_SERVICE_WORKER_SCRIPT = "\n// BuildBase Push Notification Service Worker\n// Place this file in your app's public directory (e.g. public/push-sw.js)\n\nself.addEventListener('push', function(event) {\n if (!event.data) return;\n\n try {\n var payload = event.data.json();\n var title = payload.title || 'Notification';\n var 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 var 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 (var i = 0; i < clientList.length; i++) {\n var 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";
2154
+ declare const PUSH_SERVICE_WORKER_SCRIPT = "\n// BuildBase Push Notification Service Worker\n// Place this file in your app's public directory (e.g. public/push-sw.js)\n\nself.addEventListener('push', function(event) {\n if (!event.data) return;\n\n 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";
2152
2155
 
2153
2156
  interface BetaFormData {
2154
2157
  name?: string;
@@ -2159,6 +2162,35 @@ interface BetaFormResponse {
2159
2162
  message: string;
2160
2163
  }
2161
2164
 
2165
+ /** Props passed to the custom loadingComponent render function. */
2166
+ interface LoadingProps {
2167
+ /** Human-readable, locale-aware message describing what's happening */
2168
+ message: string;
2169
+ }
2170
+ interface FullScreenLoaderContextValue {
2171
+ /** Show the full-screen loader with a message */
2172
+ show: (message: string) => void;
2173
+ /** Hide the full-screen loader */
2174
+ hide: () => void;
2175
+ /** Whether the loader is currently visible */
2176
+ visible: boolean;
2177
+ /** Current loader message */
2178
+ message: string;
2179
+ }
2180
+ /**
2181
+ * Hook to control the full-screen loader from anywhere in the SDK.
2182
+ *
2183
+ * @example
2184
+ * ```tsx
2185
+ * const { show, hide } = useFullScreenLoader();
2186
+ *
2187
+ * show('Processing payment...');
2188
+ * await processPayment();
2189
+ * hide();
2190
+ * ```
2191
+ */
2192
+ declare function useFullScreenLoader(): FullScreenLoaderContextValue;
2193
+
2162
2194
  /**
2163
2195
  * Type-safe translation keys for the BuildBase SDK.
2164
2196
  * All user-facing strings are defined here.
@@ -2206,6 +2238,9 @@ interface SDKMessages {
2206
2238
  error: string;
2207
2239
  refreshAction: string;
2208
2240
  retryAction: string;
2241
+ noPermissionTitle: string;
2242
+ noPermissionDescription: string;
2243
+ billingManageOnly: string;
2209
2244
  };
2210
2245
  };
2211
2246
  subscription: {
@@ -2706,6 +2741,13 @@ interface SDKMessages {
2706
2741
  errorLoading: string;
2707
2742
  insufficientCredits: string;
2708
2743
  };
2744
+ loading: {
2745
+ restoringSession: string;
2746
+ redirecting: string;
2747
+ signingIn: string;
2748
+ verifyingAccount: string;
2749
+ almostThere: string;
2750
+ };
2709
2751
  errors: {
2710
2752
  networkError: string;
2711
2753
  unauthorized: string;
@@ -2836,6 +2878,41 @@ interface SaaSOSProviderProps extends IOsState {
2836
2878
  * ```
2837
2879
  */
2838
2880
  getCheckoutStripeParams?: GetCheckoutStripeParams;
2881
+ /**
2882
+ * Custom content or render function for the full-screen loading overlay.
2883
+ * Used during auth code exchange, and available to any SDK feature via `useFullScreenLoader()`.
2884
+ * The SDK handles the full-screen white backdrop, centering, and messages — you just render.
2885
+ *
2886
+ * - Pass a `ReactNode` for static content (logo, spinner).
2887
+ * - Pass a function to receive `{ message }` — the SDK manages which message to show.
2888
+ *
2889
+ * If not provided, a default spinner with status message is shown.
2890
+ *
2891
+ * @example Static content
2892
+ * ```tsx
2893
+ * <SaaSOSProvider
2894
+ * loadingComponent={
2895
+ * <>
2896
+ * <img src="/logo.svg" alt="Logo" />
2897
+ * <p>Signing you in...</p>
2898
+ * </>
2899
+ * }
2900
+ * >
2901
+ * ```
2902
+ *
2903
+ * @example Render function with message
2904
+ * ```tsx
2905
+ * <SaaSOSProvider
2906
+ * loadingComponent={({ message }) => (
2907
+ * <>
2908
+ * <img src="/logo.svg" alt="Logo" />
2909
+ * <p>{message}</p>
2910
+ * </>
2911
+ * )}
2912
+ * >
2913
+ * ```
2914
+ */
2915
+ loadingComponent?: react__default.ReactNode | ((props: LoadingProps) => react__default.ReactNode);
2839
2916
  }
2840
2917
  declare const SaaSOSProvider: react__default.FC<SaaSOSProviderProps>;
2841
2918
 
@@ -4473,7 +4550,7 @@ declare const useSubscriptionManagement: (workspaceId: string | null | undefined
4473
4550
  * return (
4474
4551
  * <div>
4475
4552
  * {invoices.map(invoice => (
4476
- * <InvoiceCard key={invoice._id} invoice={invoice} />
4553
+ * <InvoiceCard key={invoice.id} invoice={invoice} />
4477
4554
  * ))}
4478
4555
  * {hasMore && <button onClick={() => refetch()}>Load More</button>}
4479
4556
  * </div>
@@ -4501,7 +4578,7 @@ declare const useSubscriptionManagement: (workspaceId: string | null | undefined
4501
4578
  *
4502
4579
  * return (
4503
4580
  * <div>
4504
- * {invoices.map(invoice => <InvoiceCard key={invoice._id} invoice={invoice} />)}
4581
+ * {invoices.map(invoice => <InvoiceCard key={invoice.id} invoice={invoice} />)}
4505
4582
  * {hasMore && <button onClick={loadMore}>Load More</button>}
4506
4583
  * </div>
4507
4584
  * );
@@ -5154,6 +5231,37 @@ declare function useSeatStatus(workspace: {
5154
5231
  settingsMaxUsers?: number | null;
5155
5232
  }): SeatStatus;
5156
5233
 
5234
+ interface FullScreenLoaderProps {
5235
+ /** Content to display centered on screen. Falls back to a default spinner + message. */
5236
+ children?: react__default.ReactNode;
5237
+ /** Message shown below the default spinner (only used when no children are provided). Defaults to "Loading..." */
5238
+ message?: string;
5239
+ /** Background color of the overlay. Defaults to white (dark mode: near-black). */
5240
+ backgroundColor?: string;
5241
+ }
5242
+ /**
5243
+ * Full-screen overlay that centers its content.
5244
+ * Uses inline styles — works without any CSS imports.
5245
+ * Respects dark mode and reduced-motion preferences.
5246
+ *
5247
+ * @example Default spinner
5248
+ * ```tsx
5249
+ * <FullScreenLoader message="Signing you in..." />
5250
+ * ```
5251
+ *
5252
+ * @example Custom content
5253
+ * ```tsx
5254
+ * <FullScreenLoader>
5255
+ * <img src="/logo.svg" alt="Logo" />
5256
+ * <p>Loading your workspace...</p>
5257
+ * </FullScreenLoader>
5258
+ * ```
5259
+ */
5260
+ declare const FullScreenLoader: {
5261
+ ({ children, message, backgroundColor, }: FullScreenLoaderProps): react_jsx_runtime.JSX.Element;
5262
+ displayName: string;
5263
+ };
5264
+
5157
5265
  interface BetaFormProps {
5158
5266
  onSuccess?: () => void;
5159
5267
  onError?: (error: string) => void;
@@ -5274,5 +5382,5 @@ declare const PushNotificationProvider: react__default.FC<PushNotificationProvid
5274
5382
  */
5275
5383
  declare function usePushNotifications(): PushNotificationContextValue;
5276
5384
 
5277
- 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 };
5278
- 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 };
5385
+ 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 };
5386
+ 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, SubscriptionContextValue, SubscriptionItemTypeValue, SubscriptionStatusType, TrialStatus, UserCreatedEventData, UserUpdatedEventData, WorkspaceChangedEventData, WorkspaceCreatedEventData, WorkspaceDeletedEventData, WorkspaceSettingsSection, WorkspaceUpdatedEventData, WorkspaceUserAddedEventData, WorkspaceUserRemovedEventData, WorkspaceUserRoleChangedEventData };