@saas-support/react 0.5.0 → 0.6.0

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.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class c extends Error{constructor(t,e,s="unknown"){super(e),this.name="SaaSError",this.code=t,this.domain=s}get isNotFound(){return this.code===404}get isUnauthorized(){return this.code===401}get isForbidden(){return this.code===403}get isConflict(){return this.code===409}get isRateLimited(){return this.code===429}}class y{constructor(t,e){this.onUnauthorized=null,this.baseUrl=t,this.authMode=e}setUnauthorizedHandler(t){this.onUnauthorized=t}async request(t,e,s,r){try{return await this.doRequest(t,e,s,r)}catch(n){if(n instanceof c&&n.isUnauthorized&&this.onUnauthorized&&(r!=null&&r.Authorization)){const i=await this.onUnauthorized();if(i)return this.doRequest(t,e,s,{...r,Authorization:`Bearer ${i}`})}throw n}}async get(t,e){return this.request("GET",t,void 0,e)}async post(t,e,s){return this.request("POST",t,e,s)}async patch(t,e,s){return this.request("PATCH",t,e,s)}async del(t,e){return this.request("DELETE",t,void 0,e)}async uploadBinary(t,e,s){try{return await this.doUploadBinary(t,e,s)}catch(r){if(r instanceof c&&r.isUnauthorized&&this.onUnauthorized&&(s!=null&&s.Authorization)){const n=await this.onUnauthorized();if(n)return this.doUploadBinary(t,e,{...s,Authorization:`Bearer ${n}`})}throw r}}async doUploadBinary(t,e,s){const r={"Content-Type":"application/octet-stream",...this.getAuthHeaders(),...s},i=await(await fetch(`${this.baseUrl}${t}`,{method:"POST",headers:r,body:e})).json();if(i.code&&i.code>=400){const a=this.inferDomain(t);throw new c(i.code,i.message||"Upload failed",a)}return i.data}async doRequest(t,e,s,r){const n={"Content-Type":"application/json",...this.getAuthHeaders(),...r},a=await(await fetch(`${this.baseUrl}${e}`,{method:t,headers:n,body:s?JSON.stringify(s):void 0})).json();if(a.code&&a.code>=400){const p=this.inferDomain(e);throw new c(a.code,a.message||"Request failed",p)}return a.data}getAuthHeaders(){switch(this.authMode.type){case"publishableKey":case"apiKey":return{"X-API-Key":this.authMode.key};case"portalToken":case"embedToken":return{Authorization:`Bearer ${this.authMode.token}`}}}inferDomain(t){return t.startsWith("/auth")?"auth":t.startsWith("/billing")?"billing":t.startsWith("/report")?"report":"unknown"}}class ${constructor(t){this.accessToken=null,this.refreshToken=null,this.refreshTimer=null,this.refreshInFlight=null,this.onRefreshNeeded=null,this.onTokensChanged=null,this.boundHandleStorage=null,this.storageKey=`ss_rt_${t.slice(0,12)}`,this.refreshToken=this.loadRefreshToken(),typeof window<"u"&&(this.boundHandleStorage=this.handleStorageEvent.bind(this),window.addEventListener("storage",this.boundHandleStorage))}setRefreshCallback(t){this.onRefreshNeeded=t}setTokensChangedCallback(t){this.onTokensChanged=t}getAccessToken(){return this.accessToken}getRefreshToken(){return this.refreshToken}hasRefreshToken(){return this.refreshToken!==null}setTokens(t,e){this.accessToken=t,this.refreshToken=e,this.saveRefreshToken(e),this.scheduleRefresh(t)}clearTokens(){this.accessToken=null,this.refreshToken=null,this.removeRefreshToken(),this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null)}async refreshOnce(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.executeRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}destroy(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),typeof window<"u"&&this.boundHandleStorage&&(window.removeEventListener("storage",this.boundHandleStorage),this.boundHandleStorage=null)}async executeRefresh(){if(!this.onRefreshNeeded)throw new Error("No refresh callback configured");typeof navigator<"u"&&"locks"in navigator?await navigator.locks.request(`ss_refresh_lock_${this.storageKey}`,async()=>{const t=this.loadRefreshToken();t&&t!==this.refreshToken&&(this.refreshToken=t),await this.onRefreshNeeded()}):await this.onRefreshNeeded()}scheduleRefresh(t){this.refreshTimer&&clearTimeout(this.refreshTimer);const e=this.getTokenExpiry(t);if(!e)return;const s=e*1e3-Date.now()-6e4;if(s<=0){this.refreshOnce().catch(()=>{});return}this.refreshTimer=setTimeout(()=>{this.refreshOnce().catch(()=>{})},s)}handleStorageEvent(t){var e;if(t.key===this.storageKey){if(t.newValue===null){this.accessToken=null,this.refreshToken=null,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),(e=this.onTokensChanged)==null||e.call(this);return}t.newValue!==this.refreshToken&&(this.refreshToken=t.newValue,this.accessToken=null,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null))}}getTokenExpiry(t){try{const e=t.split(".")[1];return JSON.parse(atob(e)).exp??null}catch{return null}}loadRefreshToken(){try{return localStorage.getItem(this.storageKey)}catch{return null}}saveRefreshToken(t){try{localStorage.setItem(this.storageKey,t)}catch{}}removeRefreshToken(){try{localStorage.removeItem(this.storageKey)}catch{}}}class R{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>{var s;(s=this.listeners.get(t))==null||s.delete(e)}}emit(t,e){var s;(s=this.listeners.get(t))==null||s.forEach(r=>r(e))}removeAll(){this.listeners.clear()}}const w=500,T=600,v=5*60*1e3;class b{constructor(t,e,s,r){this.cachedUser=null,this.cachedSettings=null,this.loaded=!1,this.transport=t,this.tokenManager=e,this.emitter=s,this.baseUrl=r}async load(){var t,e;if(!this.loaded){try{this.cachedSettings=await this.transport.get("/auth/settings")}catch(s){console.warn("[SaaS Support] Failed to load project settings:",s)}if((t=this.tokenManager)!=null&&t.hasRefreshToken())try{await this.performRefresh()}catch{(e=this.tokenManager)==null||e.clearTokens()}this.loaded=!0}}async signIn(t,e){const s=await this.transport.post("/auth/login",{email:t,password:e});if("mfaRequired"in s&&s.mfaRequired)return s;const r=s;return this.setSession(r),r}async signUp(t,e){const s=await this.transport.post("/auth/register",{email:t,password:e});return this.setSession(s),s}async signOut(){var e;const t=(e=this.tokenManager)==null?void 0:e.getRefreshToken();if(t)try{await this.transport.post("/auth/logout",{refreshToken:t})}catch{}this.clearSession()}async signInWithOAuth(t){const e=`${this.baseUrl}/auth/oauth/${t}/popup-callback`,{authUrl:s,state:r}=await this.transport.get(`/auth/oauth/${t}?redirect_uri=${encodeURIComponent(e)}`),n=window.screenX+(window.innerWidth-w)/2,i=window.screenY+(window.innerHeight-T)/2,a=window.open(s,"saas-support-oauth",`width=${w},height=${T},left=${n},top=${i},toolbar=no,menubar=no`);return new Promise((p,l)=>{let h=!1;const d=async u=>{var k;if(((k=u.data)==null?void 0:k.type)==="saas-support:oauth-callback"&&!h){if(h=!0,window.removeEventListener("message",d),clearTimeout(m),clearInterval(f),a==null||a.close(),u.data.error){l(new Error(`OAuth error: ${u.data.error}`));return}try{const g=await this.transport.post(`/auth/oauth/${t}/callback`,{code:u.data.code,state:u.data.state||r});this.setSession(g),p(g)}catch(g){l(g)}}};window.addEventListener("message",d);const m=setTimeout(()=>{h||(h=!0,window.removeEventListener("message",d),clearInterval(f),a==null||a.close(),l(new Error("OAuth popup timed out")))},v),f=setInterval(()=>{a!=null&&a.closed&&!h&&(h=!0,clearInterval(f),clearTimeout(m),window.removeEventListener("message",d),l(new Error("OAuth popup was closed")))},500)})}async submitMfaCode(t,e){const s=await this.transport.post("/auth/login/mfa",{mfaToken:t,code:e});return this.setSession(s),s}async sendMagicLink(t,e){await this.transport.post("/auth/magic-link/send",{email:t,redirectUrl:e})}async verifyMagicLink(t){const e=await this.transport.post("/auth/magic-link/verify",{token:t});return this.setSession(e),e}async sendPasswordReset(t,e){await this.transport.post("/auth/password-reset/send",{email:t,redirectUrl:e})}async resetPassword(t,e){await this.transport.post("/auth/password-reset/verify",{token:t,newPassword:e})}async setupMfa(){return this.transport.post("/auth/mfa/setup",void 0,this.authHeaders())}async verifyMfa(t){return this.transport.post("/auth/mfa/verify",{code:t},this.authHeaders())}async disableMfa(t){await this.transport.post("/auth/mfa/disable",{code:t},this.authHeaders())}async getToken(){var e,s,r;const t=((e=this.tokenManager)==null?void 0:e.getAccessToken())??null;if(t)return t;if((s=this.tokenManager)!=null&&s.hasRefreshToken())try{return await this.tokenManager.refreshOnce(),((r=this.tokenManager)==null?void 0:r.getAccessToken())??null}catch{return this.clearSession(),null}return null}async getUser(){if(this.cachedUser)return this.cachedUser;const t=await this.getToken();if(!t)return null;try{return this.cachedUser=await this.transport.get("/auth/me",{Authorization:`Bearer ${t}`}),this.cachedUser}catch{return null}}getUserSync(){return this.cachedUser}isLoaded(){return this.loaded}async getSettings(){if(this.cachedSettings)return this.cachedSettings;try{return this.cachedSettings=await this.transport.get("/auth/settings"),this.cachedSettings}catch{return null}}onAuthStateChange(t){return this.emitter.on("authStateChange",t)}async updateProfile(t){const e=await this.transport.patch("/auth/me",t,this.authHeaders());return this.cachedUser=e,this.emitter.emit("authStateChange",e),e}async uploadAvatar(t){const e=await this.transport.uploadBinary("/auth/avatar",t,this.authHeaders());return this.cachedUser&&(this.cachedUser={...this.cachedUser,avatarUrl:e.avatarUrl},this.emitter.emit("authStateChange",this.cachedUser)),e}async changePassword(t,e){await this.transport.post("/auth/change-password",{currentPassword:t,newPassword:e},this.authHeaders())}async listOrgs(){return this.transport.get("/auth/orgs",this.authHeaders())}async createOrg(t,e){return this.transport.post("/auth/orgs",{name:t,slug:e},this.authHeaders())}async getOrg(t){return this.transport.get(`/auth/orgs/${t}`,this.authHeaders())}async updateOrg(t,e){return this.transport.patch(`/auth/orgs/${t}`,e,this.authHeaders())}async deleteOrg(t){await this.transport.del(`/auth/orgs/${t}`,this.authHeaders())}async listMembers(t){return this.transport.get(`/auth/orgs/${t}/members`,this.authHeaders())}async sendInvite(t,e,s){return this.transport.post(`/auth/orgs/${t}/invites`,{email:e,role:s},this.authHeaders())}async updateMemberRole(t,e,s){await this.transport.patch(`/auth/orgs/${t}/members/${e}`,{role:s},this.authHeaders())}async removeMember(t,e){await this.transport.del(`/auth/orgs/${t}/members/${e}`,this.authHeaders())}async acceptInvite(t){return this.transport.post(`/auth/invites/${t}/accept`,void 0,this.authHeaders())}async listInvites(t){return this.transport.get(`/auth/orgs/${t}/invites`,this.authHeaders())}async revokeInvite(t,e){await this.transport.del(`/auth/orgs/${t}/invites/${e}`,this.authHeaders())}async deleteAccount(){await this.transport.del("/auth/account",this.authHeaders()),this.clearSession()}handleExternalLogout(){this.cachedUser=null,this.emitter.emit("authStateChange",null)}async performRefresh(){var s;const t=(s=this.tokenManager)==null?void 0:s.getRefreshToken();if(!t)throw new Error("No refresh token");const e=await this.transport.post("/auth/refresh",{refreshToken:t});if(this.tokenManager.setTokens(e.accessToken,e.refreshToken),!this.cachedUser)try{this.cachedUser=await this.transport.get("/auth/me",{Authorization:`Bearer ${e.accessToken}`}),this.emitter.emit("authStateChange",this.cachedUser)}catch{}}setSession(t){var e;(e=this.tokenManager)==null||e.setTokens(t.accessToken,t.refreshToken),this.cachedUser=t.user,this.emitter.emit("authStateChange",t.user)}clearSession(){var t;(t=this.tokenManager)==null||t.clearTokens(),this.cachedUser=null,this.emitter.emit("authStateChange",null)}authHeaders(){var e;const t=(e=this.tokenManager)==null?void 0:e.getAccessToken();return t?{Authorization:`Bearer ${t}`}:{}}}class S{constructor(t){this.transport=t}async createCustomer(t){return this.transport.post("/billing/customers",t)}async getCustomer(t){return this.transport.get(`/billing/customers/${t}`)}async updateCustomer(t,e){return this.transport.patch(`/billing/customers/${t}`,e)}async subscribe(t,e){return this.transport.post(`/billing/customers/${t}/subscribe`,{planId:e})}async changePlan(t,e){return this.transport.patch(`/billing/customers/${t}/subscription`,{planId:e})}async cancelSubscription(t){return this.transport.del(`/billing/customers/${t}/subscription`)}async getInvoices(t){return this.transport.get(`/billing/customers/${t}/invoices`)}async ingestUsageEvent(t){return this.transport.post("/billing/events",t)}async getCurrentUsage(t){return this.transport.get(`/billing/customers/${t}/usage`)}async createPortalToken(t,e){return this.transport.post("/billing/portal-tokens",{customerId:t,expiresIn:e})}async applyCoupon(t,e){return this.transport.post(`/billing/customers/${t}/coupon`,{code:e})}}class U{constructor(t){this.transport=t}async executeQuery(t){return this.transport.post("/report/query",t)}async listQueries(t){const e=t?this.toQueryString(t):"";return this.transport.get(`/report/queries${e}`)}async saveQuery(t){return this.transport.post("/report/queries",t)}async updateQuery(t,e){return this.transport.patch(`/report/queries/${t}`,e)}async deleteQuery(t){await this.transport.del(`/report/queries/${t}`)}async listDashboards(t){const e=t?this.toQueryString(t):"";return this.transport.get(`/report/dashboards${e}`)}async createDashboard(t){return this.transport.post("/report/dashboards",t)}async getDashboard(t){return this.transport.get(`/report/dashboards/${t}`)}async updateDashboard(t,e){return this.transport.patch(`/report/dashboards/${t}`,e)}async deleteDashboard(t){await this.transport.del(`/report/dashboards/${t}`)}async createEmbedToken(t){return this.transport.post("/report/embed-tokens",t)}async listEmbedTokens(){return this.transport.get("/report/embed-tokens")}async revokeEmbedToken(t){await this.transport.del(`/report/embed-tokens/${t}`)}toQueryString(t){const e=Object.entries(t).filter(([,s])=>s!=null&&s!=="");return e.length===0?"":"?"+e.map(([s,r])=>`${s}=${encodeURIComponent(String(r))}`).join("&")}}const M="https://api.saas-support.com/v1";class H{constructor(t){if(this.tokenManager=null,this.loaded=!1,!t.publishableKey&&!t.apiKey)throw new Error("SaaSSupport: either publishableKey or apiKey is required");const e=t.baseUrl??M;this.emitter=new R;const s=t.publishableKey?new y(e,{type:"publishableKey",key:t.publishableKey}):null,r=t.apiKey?new y(e,{type:"apiKey",key:t.apiKey}):null;t.publishableKey&&(this.tokenManager=new $(t.publishableKey)),this.auth=new b(s??r,this.tokenManager,this.emitter,e),this.billing=new S(r??s),this.report=new U(r??s),this.tokenManager&&(this.tokenManager.setRefreshCallback(()=>this.auth.performRefresh()),this.tokenManager.setTokensChangedCallback(()=>{this.tokenManager.hasRefreshToken()||this.auth.handleExternalLogout()})),this.tokenManager&&s&&s.setUnauthorizedHandler(async()=>{try{return await this.tokenManager.refreshOnce(),this.tokenManager.getAccessToken()}catch{return null}})}async load(){this.loaded||(await this.auth.load(),this.loaded=!0)}isLoaded(){return this.loaded}onError(t){return this.emitter.on("error",t)}destroy(){var t;(t=this.tokenManager)==null||t.destroy(),this.emitter.removeAll()}}function E(o){return"mfaRequired"in o&&o.mfaRequired===!0}exports.AuthClient=b;exports.BillingClient=S;exports.ReportClient=U;exports.SaaSError=c;exports.SaaSSupport=H;exports.Transport=y;exports.isMfaRequired=E;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class d extends Error{constructor(t,e,s="unknown"){super(e),this.name="SaaSError",this.code=t,this.domain=s}get isNotFound(){return this.code===404}get isUnauthorized(){return this.code===401}get isForbidden(){return this.code===403}get isConflict(){return this.code===409}get isRateLimited(){return this.code===429}}class y{constructor(t,e){this.onUnauthorized=null,this.baseUrl=t,this.authMode=e}setUnauthorizedHandler(t){this.onUnauthorized=t}async request(t,e,s,r){try{return await this.doRequest(t,e,s,r)}catch(i){if(i instanceof d&&i.isUnauthorized&&this.onUnauthorized&&(r!=null&&r.Authorization)){const n=await this.onUnauthorized();if(n)return this.doRequest(t,e,s,{...r,Authorization:`Bearer ${n}`})}throw i}}async get(t,e){return this.request("GET",t,void 0,e)}async post(t,e,s){return this.request("POST",t,e,s)}async patch(t,e,s){return this.request("PATCH",t,e,s)}async del(t,e){return this.request("DELETE",t,void 0,e)}async uploadBinary(t,e,s){try{return await this.doUploadBinary(t,e,s)}catch(r){if(r instanceof d&&r.isUnauthorized&&this.onUnauthorized&&(s!=null&&s.Authorization)){const i=await this.onUnauthorized();if(i)return this.doUploadBinary(t,e,{...s,Authorization:`Bearer ${i}`})}throw r}}async doUploadBinary(t,e,s){const r={"Content-Type":"application/octet-stream",...this.getAuthHeaders(),...s},i=await fetch(`${this.baseUrl}${t}`,{method:"POST",headers:r,body:e}),n=await i.json();if(!i.ok||n.isOk===!1||n.code&&n.code>=400){const a=this.inferDomain(t),c=n.code||i.status;throw new d(c,n.message||"Upload failed",a)}return n.data}async doRequest(t,e,s,r){const i={"Content-Type":"application/json",...this.getAuthHeaders(),...r},n=await fetch(`${this.baseUrl}${e}`,{method:t,headers:i,body:s?JSON.stringify(s):void 0}),a=await n.json();if(!n.ok||a.isOk===!1||a.code&&a.code>=400){const c=this.inferDomain(e),h=a.code||n.status;throw new d(h,a.message||"Request failed",c)}return a.data}getAuthHeaders(){switch(this.authMode.type){case"publishableKey":case"apiKey":return{"X-API-Key":this.authMode.key};case"portalToken":case"embedToken":return{Authorization:`Bearer ${this.authMode.token}`}}}inferDomain(t){return t.startsWith("/auth")?"auth":t.startsWith("/billing")?"billing":t.startsWith("/report")?"report":"unknown"}}class ${constructor(t){this.accessToken=null,this.refreshToken=null,this.refreshTimer=null,this.refreshInFlight=null,this.onRefreshNeeded=null,this.onTokensChanged=null,this.boundHandleStorage=null,this.storageKey=`ss_rt_${t.slice(0,12)}`,this.refreshToken=this.loadRefreshToken(),typeof window<"u"&&(this.boundHandleStorage=this.handleStorageEvent.bind(this),window.addEventListener("storage",this.boundHandleStorage))}setRefreshCallback(t){this.onRefreshNeeded=t}setTokensChangedCallback(t){this.onTokensChanged=t}getAccessToken(){return this.accessToken}getRefreshToken(){return this.refreshToken}hasRefreshToken(){return this.refreshToken!==null}setTokens(t,e){this.accessToken=t,this.refreshToken=e,this.saveRefreshToken(e),this.scheduleRefresh(t)}clearTokens(){this.accessToken=null,this.refreshToken=null,this.removeRefreshToken(),this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null)}async refreshOnce(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.executeRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}destroy(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),typeof window<"u"&&this.boundHandleStorage&&(window.removeEventListener("storage",this.boundHandleStorage),this.boundHandleStorage=null)}async executeRefresh(){if(!this.onRefreshNeeded)throw new Error("No refresh callback configured");typeof navigator<"u"&&"locks"in navigator?await navigator.locks.request(`ss_refresh_lock_${this.storageKey}`,async()=>{const t=this.loadRefreshToken();t&&t!==this.refreshToken&&(this.refreshToken=t),await this.onRefreshNeeded()}):await this.onRefreshNeeded()}scheduleRefresh(t){this.refreshTimer&&clearTimeout(this.refreshTimer);const e=this.getTokenExpiry(t);if(!e)return;const s=e*1e3-Date.now()-6e4;if(s<=0){this.refreshOnce().catch(()=>{});return}this.refreshTimer=setTimeout(()=>{this.refreshOnce().catch(()=>{})},s)}handleStorageEvent(t){var e;if(t.key===this.storageKey){if(t.newValue===null){this.accessToken=null,this.refreshToken=null,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),(e=this.onTokensChanged)==null||e.call(this);return}t.newValue!==this.refreshToken&&(this.refreshToken=t.newValue,this.accessToken=null,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null))}}getTokenExpiry(t){try{const e=t.split(".")[1];return JSON.parse(atob(e)).exp??null}catch{return null}}loadRefreshToken(){try{return localStorage.getItem(this.storageKey)}catch{return null}}saveRefreshToken(t){try{localStorage.setItem(this.storageKey,t)}catch{}}removeRefreshToken(){try{localStorage.removeItem(this.storageKey)}catch{}}}class R{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>{var s;(s=this.listeners.get(t))==null||s.delete(e)}}emit(t,e){var s;(s=this.listeners.get(t))==null||s.forEach(r=>r(e))}removeAll(){this.listeners.clear()}}const w=500,T=600,v=5*60*1e3;class b{constructor(t,e,s,r){this.cachedUser=null,this.cachedSettings=null,this.loaded=!1,this.transport=t,this.tokenManager=e,this.emitter=s,this.baseUrl=r}async load(){var t,e;if(!this.loaded){try{this.cachedSettings=await this.transport.get("/auth/settings")}catch(s){console.warn("[SaaS Support] Failed to load project settings:",s)}if((t=this.tokenManager)!=null&&t.hasRefreshToken())try{await this.performRefresh()}catch{(e=this.tokenManager)==null||e.clearTokens()}this.loaded=!0}}async signIn(t,e){const s=await this.transport.post("/auth/login",{email:t,password:e});if("mfaRequired"in s&&s.mfaRequired)return s;const r=s;return this.setSession(r),r}async signUp(t,e){const s=await this.transport.post("/auth/register",{email:t,password:e});return this.setSession(s),s}async signOut(){var e;const t=(e=this.tokenManager)==null?void 0:e.getRefreshToken();if(t)try{await this.transport.post("/auth/logout",{refreshToken:t})}catch{}this.clearSession()}async signInWithOAuth(t){const e=`${this.baseUrl}/auth/oauth/${t}/popup-callback`,{authUrl:s,state:r}=await this.transport.get(`/auth/oauth/${t}?redirect_uri=${encodeURIComponent(e)}`),i=window.screenX+(window.innerWidth-w)/2,n=window.screenY+(window.innerHeight-T)/2,a=window.open(s,"saas-support-oauth",`width=${w},height=${T},left=${i},top=${n},toolbar=no,menubar=no`);return new Promise((c,h)=>{let u=!1;const g=async l=>{var k;if(((k=l.data)==null?void 0:k.type)==="saas-support:oauth-callback"&&!u){if(u=!0,window.removeEventListener("message",g),clearTimeout(m),clearInterval(f),a==null||a.close(),l.data.error){h(new Error(`OAuth error: ${l.data.error}`));return}try{const p=await this.transport.post(`/auth/oauth/${t}/callback`,{code:l.data.code,state:l.data.state||r});this.setSession(p),c(p)}catch(p){h(p)}}};window.addEventListener("message",g);const m=setTimeout(()=>{u||(u=!0,window.removeEventListener("message",g),clearInterval(f),a==null||a.close(),h(new Error("OAuth popup timed out")))},v),f=setInterval(()=>{a!=null&&a.closed&&!u&&(u=!0,clearInterval(f),clearTimeout(m),window.removeEventListener("message",g),h(new Error("OAuth popup was closed")))},500)})}async submitMfaCode(t,e){const s=await this.transport.post("/auth/login/mfa",{mfaToken:t,code:e});return this.setSession(s),s}async sendMagicLink(t,e){await this.transport.post("/auth/magic-link/send",{email:t,redirectUrl:e})}async verifyMagicLink(t){const e=await this.transport.post("/auth/magic-link/verify",{token:t});return this.setSession(e),e}async sendPasswordReset(t,e){await this.transport.post("/auth/password-reset/send",{email:t,redirectUrl:e})}async resetPassword(t,e){await this.transport.post("/auth/password-reset/verify",{token:t,newPassword:e})}async setupMfa(){return this.transport.post("/auth/mfa/setup",void 0,this.authHeaders())}async verifyMfa(t){return this.transport.post("/auth/mfa/verify",{code:t},this.authHeaders())}async disableMfa(t){await this.transport.post("/auth/mfa/disable",{code:t},this.authHeaders())}async getToken(){var e,s,r;const t=((e=this.tokenManager)==null?void 0:e.getAccessToken())??null;if(t)return t;if((s=this.tokenManager)!=null&&s.hasRefreshToken())try{return await this.tokenManager.refreshOnce(),((r=this.tokenManager)==null?void 0:r.getAccessToken())??null}catch{return this.clearSession(),null}return null}async getUser(){if(this.cachedUser)return this.cachedUser;const t=await this.getToken();if(!t)return null;try{return this.cachedUser=await this.transport.get("/auth/me",{Authorization:`Bearer ${t}`}),this.cachedUser}catch{return null}}getUserSync(){return this.cachedUser}isLoaded(){return this.loaded}async getSettings(){if(this.cachedSettings)return this.cachedSettings;try{return this.cachedSettings=await this.transport.get("/auth/settings"),this.cachedSettings}catch{return null}}onAuthStateChange(t){return this.emitter.on("authStateChange",t)}async updateProfile(t){const e=await this.transport.patch("/auth/me",t,this.authHeaders());return this.cachedUser=e,this.emitter.emit("authStateChange",e),e}async uploadAvatar(t){const e=await this.transport.uploadBinary("/auth/avatar",t,this.authHeaders());return this.cachedUser&&(this.cachedUser={...this.cachedUser,avatarUrl:e.avatarUrl},this.emitter.emit("authStateChange",this.cachedUser)),e}async changePassword(t,e){await this.transport.post("/auth/change-password",{currentPassword:t,newPassword:e},this.authHeaders())}async listOrgs(){return this.transport.get("/auth/orgs",this.authHeaders())}async createOrg(t,e){return this.transport.post("/auth/orgs",{name:t,slug:e},this.authHeaders())}async getOrg(t){return this.transport.get(`/auth/orgs/${t}`,this.authHeaders())}async updateOrg(t,e){return this.transport.patch(`/auth/orgs/${t}`,e,this.authHeaders())}async deleteOrg(t){await this.transport.del(`/auth/orgs/${t}`,this.authHeaders())}async listMembers(t){return this.transport.get(`/auth/orgs/${t}/members`,this.authHeaders())}async sendInvite(t,e,s){return this.transport.post(`/auth/orgs/${t}/invites`,{email:e,role:s},this.authHeaders())}async updateMemberRole(t,e,s){await this.transport.patch(`/auth/orgs/${t}/members/${e}`,{role:s},this.authHeaders())}async removeMember(t,e){await this.transport.del(`/auth/orgs/${t}/members/${e}`,this.authHeaders())}async acceptInvite(t){return this.transport.post(`/auth/invites/${t}/accept`,void 0,this.authHeaders())}async listInvites(t){return this.transport.get(`/auth/orgs/${t}/invites`,this.authHeaders())}async revokeInvite(t,e){await this.transport.del(`/auth/orgs/${t}/invites/${e}`,this.authHeaders())}async deleteAccount(){await this.transport.del("/auth/account",this.authHeaders()),this.clearSession()}handleExternalLogout(){this.cachedUser=null,this.emitter.emit("authStateChange",null)}async performRefresh(){var s;const t=(s=this.tokenManager)==null?void 0:s.getRefreshToken();if(!t)throw new Error("No refresh token");const e=await this.transport.post("/auth/refresh",{refreshToken:t});if(this.tokenManager.setTokens(e.accessToken,e.refreshToken),!this.cachedUser)try{this.cachedUser=await this.transport.get("/auth/me",{Authorization:`Bearer ${e.accessToken}`}),this.emitter.emit("authStateChange",this.cachedUser)}catch{}}setSession(t){var e;(e=this.tokenManager)==null||e.setTokens(t.accessToken,t.refreshToken),this.cachedUser=t.user,this.emitter.emit("authStateChange",t.user)}clearSession(){var t;(t=this.tokenManager)==null||t.clearTokens(),this.cachedUser=null,this.emitter.emit("authStateChange",null)}authHeaders(){var e;const t=(e=this.tokenManager)==null?void 0:e.getAccessToken();return t?{Authorization:`Bearer ${t}`}:{}}}class S{constructor(t){this.transport=t}async createCustomer(t){return this.transport.post("/billing/customers",t)}async getCustomer(t){return this.transport.get(`/billing/customers/${t}`)}async updateCustomer(t,e){return this.transport.patch(`/billing/customers/${t}`,e)}async subscribe(t,e){return this.transport.post(`/billing/customers/${t}/subscribe`,{planId:e})}async changePlan(t,e){return this.transport.patch(`/billing/customers/${t}/subscription`,{planId:e})}async cancelSubscription(t){return this.transport.del(`/billing/customers/${t}/subscription`)}async getInvoices(t){return this.transport.get(`/billing/customers/${t}/invoices`)}async ingestUsageEvent(t){return this.transport.post("/billing/events",t)}async getCurrentUsage(t){return this.transport.get(`/billing/customers/${t}/usage`)}async createPortalToken(t,e){return this.transport.post("/billing/portal-tokens",{customerId:t,expiresIn:e})}async applyCoupon(t,e){return this.transport.post(`/billing/customers/${t}/coupon`,{code:e})}}class U{constructor(t){this.transport=t}async executeQuery(t){return this.transport.post("/report/query",t)}async listQueries(t){const e=t?this.toQueryString(t):"";return this.transport.get(`/report/queries${e}`)}async saveQuery(t){return this.transport.post("/report/queries",t)}async updateQuery(t,e){return this.transport.patch(`/report/queries/${t}`,e)}async deleteQuery(t){await this.transport.del(`/report/queries/${t}`)}async listDashboards(t){const e=t?this.toQueryString(t):"";return this.transport.get(`/report/dashboards${e}`)}async createDashboard(t){return this.transport.post("/report/dashboards",t)}async getDashboard(t){return this.transport.get(`/report/dashboards/${t}`)}async updateDashboard(t,e){return this.transport.patch(`/report/dashboards/${t}`,e)}async deleteDashboard(t){await this.transport.del(`/report/dashboards/${t}`)}async createEmbedToken(t){return this.transport.post("/report/embed-tokens",t)}async listEmbedTokens(){return this.transport.get("/report/embed-tokens")}async revokeEmbedToken(t){await this.transport.del(`/report/embed-tokens/${t}`)}toQueryString(t){const e=Object.entries(t).filter(([,s])=>s!=null&&s!=="");return e.length===0?"":"?"+e.map(([s,r])=>`${s}=${encodeURIComponent(String(r))}`).join("&")}}const M="https://api.saas-support.com/v1";class H{constructor(t){if(this.tokenManager=null,this.loaded=!1,!t.publishableKey&&!t.apiKey)throw new Error("SaaSSupport: either publishableKey or apiKey is required");const e=t.baseUrl??M;this.emitter=new R;const s=t.publishableKey?new y(e,{type:"publishableKey",key:t.publishableKey}):null,r=t.apiKey?new y(e,{type:"apiKey",key:t.apiKey}):null;t.publishableKey&&(this.tokenManager=new $(t.publishableKey)),this.auth=new b(s??r,this.tokenManager,this.emitter,e),this.billing=new S(r??s),this.report=new U(r??s),this.tokenManager&&(this.tokenManager.setRefreshCallback(()=>this.auth.performRefresh()),this.tokenManager.setTokensChangedCallback(()=>{this.tokenManager.hasRefreshToken()||this.auth.handleExternalLogout()})),this.tokenManager&&s&&s.setUnauthorizedHandler(async()=>{try{return await this.tokenManager.refreshOnce(),this.tokenManager.getAccessToken()}catch{return null}})}async load(){this.loaded||(await this.auth.load(),this.loaded=!0)}isLoaded(){return this.loaded}onError(t){return this.emitter.on("error",t)}destroy(){var t;(t=this.tokenManager)==null||t.destroy(),this.emitter.removeAll()}}function E(o){return"mfaRequired"in o&&o.mfaRequired===!0}exports.AuthClient=b;exports.BillingClient=S;exports.ReportClient=U;exports.SaaSError=d;exports.SaaSSupport=H;exports.Transport=y;exports.isMfaRequired=E;
package/dist/index.d.ts CHANGED
@@ -2,6 +2,8 @@ export declare interface Appearance {
2
2
  baseTheme?: 'light' | 'dark';
3
3
  variables?: ThemeVariables;
4
4
  elements?: ElementOverrides;
5
+ /** Custom font URL, or null to disable CDN font loading */
6
+ fontUrl?: string | null;
5
7
  }
6
8
 
7
9
  export declare interface ApplyCouponResult {
@@ -173,6 +175,12 @@ export declare interface ElementOverrides {
173
175
  chartContainer?: React.CSSProperties;
174
176
  queryInput?: React.CSSProperties;
175
177
  dashboardGrid?: React.CSSProperties;
178
+ brandIcon?: React.CSSProperties;
179
+ oauthGrid?: React.CSSProperties;
180
+ mfaDigitInput?: React.CSSProperties;
181
+ glassPanel?: React.CSSProperties;
182
+ avatarLarge?: React.CSSProperties;
183
+ profileHeader?: React.CSSProperties;
176
184
  }
177
185
 
178
186
  export declare interface EmbedToken {
@@ -461,6 +469,12 @@ export declare interface ThemeVariables {
461
469
  colorWarning?: string;
462
470
  fontFamily?: string;
463
471
  borderRadius?: string;
472
+ colorPrimaryContainer?: string;
473
+ colorSurface?: string;
474
+ colorOnSurface?: string;
475
+ colorOutline?: string;
476
+ fontFamilyHeadline?: string;
477
+ fontFamilyBody?: string;
464
478
  }
465
479
 
466
480
  declare class TokenManager {
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- class g extends Error {
1
+ class p extends Error {
2
2
  constructor(t, e, s = "unknown") {
3
3
  super(e), this.name = "SaaSError", this.code = t, this.domain = s;
4
4
  }
@@ -18,7 +18,7 @@ class g extends Error {
18
18
  return this.code === 429;
19
19
  }
20
20
  }
21
- class k {
21
+ class m {
22
22
  constructor(t, e) {
23
23
  this.onUnauthorized = null, this.baseUrl = t, this.authMode = e;
24
24
  }
@@ -29,16 +29,16 @@ class k {
29
29
  async request(t, e, s, r) {
30
30
  try {
31
31
  return await this.doRequest(t, e, s, r);
32
- } catch (n) {
33
- if (n instanceof g && n.isUnauthorized && this.onUnauthorized && (r != null && r.Authorization)) {
34
- const i = await this.onUnauthorized();
35
- if (i)
32
+ } catch (i) {
33
+ if (i instanceof p && i.isUnauthorized && this.onUnauthorized && (r != null && r.Authorization)) {
34
+ const n = await this.onUnauthorized();
35
+ if (n)
36
36
  return this.doRequest(t, e, s, {
37
37
  ...r,
38
- Authorization: `Bearer ${i}`
38
+ Authorization: `Bearer ${n}`
39
39
  });
40
40
  }
41
- throw n;
41
+ throw i;
42
42
  }
43
43
  }
44
44
  async get(t, e) {
@@ -57,12 +57,12 @@ class k {
57
57
  try {
58
58
  return await this.doUploadBinary(t, e, s);
59
59
  } catch (r) {
60
- if (r instanceof g && r.isUnauthorized && this.onUnauthorized && (s != null && s.Authorization)) {
61
- const n = await this.onUnauthorized();
62
- if (n)
60
+ if (r instanceof p && r.isUnauthorized && this.onUnauthorized && (s != null && s.Authorization)) {
61
+ const i = await this.onUnauthorized();
62
+ if (i)
63
63
  return this.doUploadBinary(t, e, {
64
64
  ...s,
65
- Authorization: `Bearer ${n}`
65
+ Authorization: `Bearer ${i}`
66
66
  });
67
67
  }
68
68
  throw r;
@@ -73,30 +73,30 @@ class k {
73
73
  "Content-Type": "application/octet-stream",
74
74
  ...this.getAuthHeaders(),
75
75
  ...s
76
- }, i = await (await fetch(`${this.baseUrl}${t}`, {
76
+ }, i = await fetch(`${this.baseUrl}${t}`, {
77
77
  method: "POST",
78
78
  headers: r,
79
79
  body: e
80
- })).json();
81
- if (i.code && i.code >= 400) {
82
- const a = this.inferDomain(t);
83
- throw new g(i.code, i.message || "Upload failed", a);
80
+ }), n = await i.json();
81
+ if (!i.ok || n.isOk === !1 || n.code && n.code >= 400) {
82
+ const a = this.inferDomain(t), c = n.code || i.status;
83
+ throw new p(c, n.message || "Upload failed", a);
84
84
  }
85
- return i.data;
85
+ return n.data;
86
86
  }
87
87
  async doRequest(t, e, s, r) {
88
- const n = {
88
+ const i = {
89
89
  "Content-Type": "application/json",
90
90
  ...this.getAuthHeaders(),
91
91
  ...r
92
- }, a = await (await fetch(`${this.baseUrl}${e}`, {
92
+ }, n = await fetch(`${this.baseUrl}${e}`, {
93
93
  method: t,
94
- headers: n,
94
+ headers: i,
95
95
  body: s ? JSON.stringify(s) : void 0
96
- })).json();
97
- if (a.code && a.code >= 400) {
98
- const p = this.inferDomain(e);
99
- throw new g(a.code, a.message || "Request failed", p);
96
+ }), a = await n.json();
97
+ if (!n.ok || a.isOk === !1 || a.code && a.code >= 400) {
98
+ const c = this.inferDomain(e), h = a.code || n.status;
99
+ throw new p(h, a.message || "Request failed", c);
100
100
  }
101
101
  return a.data;
102
102
  }
@@ -285,36 +285,36 @@ class $ {
285
285
  async signInWithOAuth(t) {
286
286
  const e = `${this.baseUrl}/auth/oauth/${t}/popup-callback`, { authUrl: s, state: r } = await this.transport.get(
287
287
  `/auth/oauth/${t}?redirect_uri=${encodeURIComponent(e)}`
288
- ), n = window.screenX + (window.innerWidth - w) / 2, i = window.screenY + (window.innerHeight - T) / 2, a = window.open(
288
+ ), i = window.screenX + (window.innerWidth - w) / 2, n = window.screenY + (window.innerHeight - T) / 2, a = window.open(
289
289
  s,
290
290
  "saas-support-oauth",
291
- `width=${w},height=${T},left=${n},top=${i},toolbar=no,menubar=no`
291
+ `width=${w},height=${T},left=${i},top=${n},toolbar=no,menubar=no`
292
292
  );
293
- return new Promise((p, c) => {
294
- let h = !1;
295
- const l = async (u) => {
296
- var m;
297
- if (((m = u.data) == null ? void 0 : m.type) === "saas-support:oauth-callback" && !h) {
298
- if (h = !0, window.removeEventListener("message", l), clearTimeout(y), clearInterval(f), a == null || a.close(), u.data.error) {
299
- c(new Error(`OAuth error: ${u.data.error}`));
293
+ return new Promise((c, h) => {
294
+ let u = !1;
295
+ const d = async (l) => {
296
+ var k;
297
+ if (((k = l.data) == null ? void 0 : k.type) === "saas-support:oauth-callback" && !u) {
298
+ if (u = !0, window.removeEventListener("message", d), clearTimeout(y), clearInterval(f), a == null || a.close(), l.data.error) {
299
+ h(new Error(`OAuth error: ${l.data.error}`));
300
300
  return;
301
301
  }
302
302
  try {
303
- const d = await this.transport.post(
303
+ const g = await this.transport.post(
304
304
  `/auth/oauth/${t}/callback`,
305
- { code: u.data.code, state: u.data.state || r }
305
+ { code: l.data.code, state: l.data.state || r }
306
306
  );
307
- this.setSession(d), p(d);
308
- } catch (d) {
309
- c(d);
307
+ this.setSession(g), c(g);
308
+ } catch (g) {
309
+ h(g);
310
310
  }
311
311
  }
312
312
  };
313
- window.addEventListener("message", l);
313
+ window.addEventListener("message", d);
314
314
  const y = setTimeout(() => {
315
- h || (h = !0, window.removeEventListener("message", l), clearInterval(f), a == null || a.close(), c(new Error("OAuth popup timed out")));
315
+ u || (u = !0, window.removeEventListener("message", d), clearInterval(f), a == null || a.close(), h(new Error("OAuth popup timed out")));
316
316
  }, U), f = setInterval(() => {
317
- a != null && a.closed && !h && (h = !0, clearInterval(f), clearTimeout(y), window.removeEventListener("message", l), c(new Error("OAuth popup was closed")));
317
+ a != null && a.closed && !u && (u = !0, clearInterval(f), clearTimeout(y), window.removeEventListener("message", d), h(new Error("OAuth popup was closed")));
318
318
  }, 500);
319
319
  });
320
320
  }
@@ -592,7 +592,7 @@ class H {
592
592
  throw new Error("SaaSSupport: either publishableKey or apiKey is required");
593
593
  const e = t.baseUrl ?? M;
594
594
  this.emitter = new S();
595
- const s = t.publishableKey ? new k(e, { type: "publishableKey", key: t.publishableKey }) : null, r = t.apiKey ? new k(e, { type: "apiKey", key: t.apiKey }) : null;
595
+ const s = t.publishableKey ? new m(e, { type: "publishableKey", key: t.publishableKey }) : null, r = t.apiKey ? new m(e, { type: "apiKey", key: t.apiKey }) : null;
596
596
  t.publishableKey && (this.tokenManager = new b(t.publishableKey)), this.auth = new $(
597
597
  s ?? r,
598
598
  this.tokenManager,
@@ -629,8 +629,8 @@ export {
629
629
  $ as AuthClient,
630
630
  R as BillingClient,
631
631
  v as ReportClient,
632
- g as SaaSError,
632
+ p as SaaSError,
633
633
  H as SaaSSupport,
634
- k as Transport,
634
+ m as Transport,
635
635
  E as isMfaRequired
636
636
  };