UNPKG

@nhost/nhost-js

Version:

Nhost JavaScript SDK

2 lines 2.63 kB
var e=e=>{const o=e.split(".");if(3!==o.length||!o[1])throw new Error("Invalid access token format");const r=JSON.parse((e=>{let t=e.replace(/-/g,"+").replace(/_/g,"/");const s=t.length%4;s&&(t+="=".repeat(4-s));const o=atob(t),r=Uint8Array.from(o,(e=>e.charCodeAt(0)));return(new TextDecoder).decode(r)})(o[1])),i="number"==typeof r.iat?1e3*r.iat:void 0,n="number"==typeof r.exp?1e3*r.exp:void 0,a=r["https://hasura.io/jwt/claims"],c=a?Object.entries(a).reduce(((e,[o,r])=>("string"==typeof r&&t(r)?e[o]=s(r):e[o]=r,e)),{}):void 0;return{...r,iat:i,exp:n,"https://hasura.io/jwt/claims":c}},t=e=>e.startsWith("{")&&e.endsWith("}"),s=e=>e&&"{}"!==e?e.slice(1,-1).split(",").map((e=>e.trim().replace(/^"(.*)"$/,"$1"))):[],o="nhostSession",r=class{storageKey;constructor(e){this.storageKey=e?.storageKey||"nhostSession"}get(){try{const e=window.localStorage.getItem(this.storageKey);return e?JSON.parse(e):null}catch{return this.remove(),null}}set(e){window.localStorage.setItem(this.storageKey,JSON.stringify(e))}remove(){window.localStorage.removeItem(this.storageKey)}},i=class{session=null;get(){return this.session}set(e){this.session=e}remove(){this.session=null}},n=class{cookieName;expirationDays;secure;sameSite;constructor(e){this.cookieName=e?.cookieName||"nhostSession",this.expirationDays=e?.expirationDays??30,this.secure=e?.secure??!0,this.sameSite=e?.sameSite||"lax"}get(){const e=document.cookie.split(";");for(const t of e){const[e,s]=t.trim().split("=");if(e===this.cookieName)try{return JSON.parse(decodeURIComponent(s||""))}catch{return this.remove(),null}}return null}set(e){const t=/* @__PURE__ */new Date;t.setTime(t.getTime()+24*this.expirationDays*60*60*1e3);const s=encodeURIComponent(JSON.stringify(e)),o=`${this.cookieName}=${s}; expires=${t.toUTCString()}; path=/; ${this.secure?"secure; ":""}SameSite=${this.sameSite}`;document.cookie=o}remove(){document.cookie=`${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; ${this.secure?"secure; ":""}SameSite=${this.sameSite}`}},a=class{storage;subscribers=/* @__PURE__ */new Set;constructor(e){this.storage=e}get(){return this.storage.get()}set(t){const s=e(t.accessToken),o={...t,decodedToken:s};this.storage.set(o),this.notifySubscribers(o)}remove(){this.storage.remove(),this.notifySubscribers(null)}onChange(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notifySubscribers(e){for(const s of this.subscribers)try{s(e)}catch(t){console.error("Error notifying subscriber:",t)}}},c=()=>"undefined"!=typeof window?new r:new i;export{r as a,o as i,c as n,i as o,n as r,a as t}; //# sourceMappingURL=session-BikXm4j-.js.map