@genation/sdk 0.2.9 → 0.2.11

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.
@@ -1,2 +1,2 @@
1
- (function(s,d){typeof exports=="object"&&typeof module<"u"?d(exports):typeof define=="function"&&define.amd?define(["exports"],d):(s=typeof globalThis<"u"?globalThis:s||self,d(s.Genation={}))})(this,(function(s){"use strict";class d extends Error{code;cause;constructor(e,t,n){super(e),this.name="GenationError",this.code=t,this.cause=n}}class c extends d{constructor(e,t,n){super(e,t,n),this.name="AuthError"}static invalidGrant(e="Invalid authorization code or refresh token"){return new c(e,"invalid_grant")}static accessDenied(e="User denied access"){return new c(e,"access_denied")}static expiredToken(e="Token has expired"){return new c(e,"expired_token")}static invalidState(e="State mismatch, possible CSRF attack"){return new c(e,"invalid_state")}static pkceVerificationFailed(e="PKCE verification failed"){return new c(e,"pkce_verification_failed")}}class h extends d{status;constructor(e,t,n){super(e,"network_error",n),this.name="NetworkError",this.status=t}static fromResponse(e){return new h(`HTTP ${e.status}: ${e.statusText}`,e.status)}}class f extends d{constructor(e){super(e,"config_error"),this.name="ConfigError"}static missingField(e){return new f(`Missing required config field: ${e}`)}}class g{baseUrl;timeout;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout??3e4}async request(e,t={}){const{method:n="GET",headers:i={},body:o,params:u}=t;let l=`${this.baseUrl}${e}`;if(u){const a=new URLSearchParams(u);l+=`?${a.toString()}`}const C=new AbortController,E=setTimeout(()=>C.abort(),this.timeout);try{const a=await fetch(l,{method:n,headers:{"Content-Type":"application/json",...i},body:o?JSON.stringify(o):void 0,signal:C.signal});if(clearTimeout(E),!a.ok)throw h.fromResponse(a);return await a.json()}catch(a){throw clearTimeout(E),a instanceof h?a:a instanceof Error&&a.name==="AbortError"?new h("Request timeout",void 0,a):new h("Network request failed",void 0,a)}}async postForm(e,t,n={}){const i=`${this.baseUrl}${e}`,o=new AbortController,u=setTimeout(()=>o.abort(),this.timeout);try{const l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...n},body:new URLSearchParams(t).toString(),signal:o.signal});if(clearTimeout(u),!l.ok)throw h.fromResponse(l);return await l.json()}catch(l){throw clearTimeout(u),l instanceof h?l:new h("Network request failed",void 0,l)}}}function p(r){return btoa(String.fromCharCode(...r)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function I(){const r=new Uint8Array(32);return crypto.getRandomValues(r),p(r)}async function U(r){const t=new TextEncoder().encode(r),n=await crypto.subtle.digest("SHA-256",t);return p(new Uint8Array(n))}async function A(){const r=I(),e=await U(r);return{codeVerifier:r,codeChallenge:e,codeChallengeMethod:"S256"}}function x(){const r=new Uint8Array(16);return crypto.getRandomValues(r),p(r)}const w="tokens",m="pkce",y="state";class M{storage;constructor(e){this.storage=e}async setTokens(e){await this.storage.set(w,JSON.stringify(e))}async getTokens(){const e=await this.storage.get(w);if(!e)return null;try{return JSON.parse(e)}catch{return null}}async clearTokens(){await this.storage.remove(w)}async isTokenExpired(){const e=await this.getTokens();if(!e)return!0;const t=e.issuedAt+e.expiresIn*1e3;return Date.now()>t-6e4}async setPKCE(e){await this.storage.set(m,e)}async consumePKCE(){const e=await this.storage.get(m);return e&&await this.storage.remove(m),e}async setState(e){await this.storage.set(y,e)}async consumeState(){const e=await this.storage.get(y);return e&&await this.storage.remove(y),e}async clearAll(){await this.storage.clear()}}const K="https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";class ${config;http;tokenManager;constructor(e,t){this.config={clientId:e.clientId,clientSecret:e.clientSecret,redirectUri:e.redirectUri,scopes:e.scopes,authUrl:e.authUrl??K},this.http=new g({baseUrl:this.config.authUrl}),this.tokenManager=t}async getAuthorizationUrl(){const e=await A(),t=x();await this.tokenManager.setPKCE(e.codeVerifier),await this.tokenManager.setState(t);const n=new URLSearchParams({response_type:"code",client_id:this.config.clientId,redirect_uri:this.config.redirectUri,state:t,code_challenge:e.codeChallenge,code_challenge_method:e.codeChallengeMethod});return this.config.scopes&&this.config.scopes.length>0&&n.append("scope",this.config.scopes.join(" ")),`${this.config.authUrl}/oauth/authorize?${n.toString()}`}async exchangeCode(e,t){const n=await this.tokenManager.consumeState();if(!n||n!==t)throw c.invalidState();const i=await this.tokenManager.consumePKCE();if(!i)throw c.pkceVerificationFailed("Missing code verifier");const o=await this.http.postForm("/oauth/token",{grant_type:"authorization_code",code:e,redirect_uri:this.config.redirectUri,client_id:this.config.clientId,client_secret:this.config.clientSecret,code_verifier:i}),u=this.mapTokenResponse(o);return await this.tokenManager.setTokens(u),u}async refreshToken(){const e=await this.tokenManager.getTokens();if(!e?.refreshToken)throw c.invalidGrant("No refresh token available");const t=await this.http.postForm("/oauth/token",{grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:this.config.clientId,client_secret:this.config.clientSecret}),n=this.mapTokenResponse(t);return await this.tokenManager.setTokens(n),n}async revokeToken(){const e=await this.tokenManager.getTokens();if(e)try{await this.http.postForm("/oauth/revoke",{token:e.accessToken,client_id:this.config.clientId,client_secret:this.config.clientSecret})}finally{await this.tokenManager.clearTokens()}}mapTokenResponse(e){return{accessToken:e.access_token,refreshToken:e.refresh_token,tokenType:e.token_type,expiresIn:e.expires_in,issuedAt:Date.now(),scope:e.scope}}}class T{store=new Map;async get(e){return this.store.get(e)??null}async set(e,t){this.store.set(e,t)}async remove(e){this.store.delete(e)}async clear(){this.store.clear()}}class k{prefix;constructor(e="genation"){this.prefix=e}getKey(e){return`${this.prefix}:${e}`}async get(e){return typeof window>"u"?null:localStorage.getItem(this.getKey(e))}async set(e,t){typeof window>"u"||localStorage.setItem(this.getKey(e),t)}async remove(e){typeof window>"u"||localStorage.removeItem(this.getKey(e))}async clear(){if(typeof window>"u")return;Object.keys(localStorage).filter(t=>t.startsWith(`${this.prefix}:`)).forEach(t=>localStorage.removeItem(t))}}class b{prefix;constructor(e="genation"){this.prefix=e}getKey(e){return`${this.prefix}:${e}`}async get(e){return typeof window>"u"?null:sessionStorage.getItem(this.getKey(e))}async set(e,t){typeof window>"u"||sessionStorage.setItem(this.getKey(e),t)}async remove(e){typeof window>"u"||sessionStorage.removeItem(this.getKey(e))}async clear(){if(typeof window>"u")return;Object.keys(sessionStorage).filter(t=>t.startsWith(`${this.prefix}:`)).forEach(t=>sessionStorage.removeItem(t))}}function _(r="localStorage"){switch(r){case"memory":return new T;case"localStorage":return new k;case"sessionStorage":return new b;default:return new k}}function S(r){return Array.isArray(r)?r.map(S):typeof r=="object"&&r!==null?Object.fromEntries(Object.entries(r).map(([e,t])=>[e.replace(/_([a-z])/g,(n,i)=>i.toUpperCase()),S(t)])):r}class v{oauth;tokenManager;http;httpServer;listeners=new Set;initialized=!1;constructor(e){this.validateConfig(e);const t=typeof e.storage=="object"?e.storage:_(e.storage);this.tokenManager=new M(t),this.oauth=new $(e,this.tokenManager),this.http=new g({baseUrl:e.authUrl??"https://mnnoheowoowbtpuoguul.supabase.co/auth/v1"}),this.httpServer=new g({baseUrl:"https://ff-api.genation.ai/api/v2/client"})}validateConfig(e){if(!e.clientId)throw f.missingField("clientId");if(!e.clientSecret)throw f.missingField("clientSecret");if(!e.redirectUri)throw f.missingField("redirectUri")}async emitAuthStateChange(e){const t=await this.getSession();this.listeners.forEach(n=>{try{n(e,t)}catch(i){console.error("Error in auth state change callback:",i)}})}onAuthStateChange(e){return this.listeners.add(e),this.initialized?setTimeout(()=>{this.emitAuthStateChange("INITIAL_SESSION")},0):(this.initialized=!0,setTimeout(()=>{this.emitAuthStateChange("INITIAL_SESSION")},0)),{subscription:{unsubscribe:()=>{this.listeners.delete(e)}}}}async signIn(){return this.oauth.getAuthorizationUrl()}async handleCallback(e){const t=new URL(e),n=t.searchParams.get("code"),i=t.searchParams.get("state");if(!n||!i)throw new Error("Missing code or state");const o=await this.oauth.exchangeCode(n,i);return await this.emitAuthStateChange("SIGNED_IN"),o}async getSession(){if(await this.tokenManager.isTokenExpired())try{await this.oauth.refreshToken()}catch{return null}const t=await this.tokenManager.getTokens();if(!t)return null;const n=await this.fetchUser(t.accessToken);return{accessToken:t.accessToken,refreshToken:t.refreshToken,expiresIn:t.expiresIn,expiresAt:t.issuedAt+t.expiresIn*1e3,user:n}}async getLicenses(e={}){const t=await this.getSession();if(!t)return null;const n=t.accessToken,{expiresAfter:i=new Date}=e,o=await this.httpServer.request("/licenses",{headers:{Authorization:`Bearer ${n}`},params:{expiresAfter:i.toISOString()}});return o.ok?S(o.data):(console.error("GenationClient: Error fetching licenses:",o.error),null)}async fetchUser(e){try{const t=await this.http.request("/oauth/userinfo",{headers:{Authorization:`Bearer ${e}`}});return{sub:t.sub,name:t.name,picture:t.picture,email:t.email,email_verified:t.email_verified,phone_number:t.phone_number,phone_number_verified:t.phone_number_verified}}catch(t){return console.error("GenationClient: Error fetching user:",t),null}}}function P(r){return new v(r)}s.AuthError=c,s.ConfigError=f,s.GenationClient=v,s.GenationError=d,s.LocalStorage=k,s.MemoryStorage=T,s.NetworkError=h,s.SessionStorage=b,s.createClient=P,s.createStorage=_,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(d,E){typeof exports=="object"&&typeof module<"u"?E(exports):typeof define=="function"&&define.amd?define(["exports"],E):(d=typeof globalThis<"u"?globalThis:d||self,E(d.Genation={}))})(this,(function(d){"use strict";class E extends Error{code;cause;constructor(t,r,n){super(t),this.name="GenationError",this.code=r,this.cause=n}}class m extends E{constructor(t,r,n){super(t,r,n),this.name="AuthError"}static invalidGrant(t="Invalid authorization code or refresh token"){return new m(t,"invalid_grant")}static accessDenied(t="User denied access"){return new m(t,"access_denied")}static expiredToken(t="Token has expired"){return new m(t,"expired_token")}static invalidState(t="State mismatch, possible CSRF attack"){return new m(t,"invalid_state")}static pkceVerificationFailed(t="PKCE verification failed"){return new m(t,"pkce_verification_failed")}}class w extends E{status;constructor(t,r,n){super(t,"network_error",n),this.name="NetworkError",this.status=r}static fromResponse(t){return new w(`HTTP ${t.status}: ${t.statusText}`,t.status)}}class K extends E{constructor(t){super(t,"config_error"),this.name="ConfigError"}static missingField(t){return new K(`Missing required config field: ${t}`)}}class W{baseUrl;timeout;constructor(t){this.baseUrl=t.baseUrl.replace(/\/$/,""),this.timeout=t.timeout??3e4}async request(t,r={}){const{method:n="GET",headers:s={},body:a,params:i}=r;let c=`${this.baseUrl}${t}`;if(i){const o=new URLSearchParams(i);c+=`?${o.toString()}`}const f=new AbortController,u=setTimeout(()=>f.abort(),this.timeout);try{const o=await fetch(c,{method:n,headers:{"Content-Type":"application/json",...s},body:a?JSON.stringify(a):void 0,signal:f.signal});if(clearTimeout(u),!o.ok)throw w.fromResponse(o);return await o.json()}catch(o){throw clearTimeout(u),o instanceof w?o:o instanceof Error&&o.name==="AbortError"?new w("Request timeout",void 0,o):new w("Network request failed",void 0,o)}}async postForm(t,r,n={}){const s=`${this.baseUrl}${t}`,a=new AbortController,i=setTimeout(()=>a.abort(),this.timeout);try{const c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...n},body:new URLSearchParams(r).toString(),signal:a.signal});if(clearTimeout(i),!c.ok)throw w.fromResponse(c);return await c.json()}catch(c){throw clearTimeout(i),c instanceof w?c:new w("Network request failed",void 0,c)}}}function I(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function we(){const e=new Uint8Array(32);return crypto.getRandomValues(e),I(e)}async function Se(e){const r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r);return I(new Uint8Array(n))}async function ge(){const e=we(),t=await Se(e);return{codeVerifier:e,codeChallenge:t,codeChallengeMethod:"S256"}}function be(){const e=new Uint8Array(16);return crypto.getRandomValues(e),I(e)}const J="tokens",U="pkce",D="state";class Ee{storage;constructor(t){this.storage=t}async setTokens(t){await this.storage.set(J,JSON.stringify(t))}async getTokens(){const t=await this.storage.get(J);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async clearTokens(){await this.storage.remove(J)}async isTokenExpired(){const t=await this.getTokens();if(!t)return!0;const r=t.issuedAt+t.expiresIn*1e3;return Date.now()>r-6e4}async setPKCE(t){await this.storage.set(U,t)}async consumePKCE(){const t=await this.storage.get(U);return t&&await this.storage.remove(U),t}async setState(t){await this.storage.set(D,t)}async consumeState(){const t=await this.storage.get(D);return t&&await this.storage.remove(D),t}async clearAll(){await this.storage.clear()}}const z="https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";class Ae{config;http;tokenManager;constructor(t,r){this.config={clientId:t.clientId,clientSecret:t.clientSecret,redirectUri:t.redirectUri,scopes:t.scopes,authUrl:t.authUrl??z},this.http=new W({baseUrl:this.config.authUrl}),this.tokenManager=r}async getAuthorizationUrl(){const t=await ge(),r=be();await this.tokenManager.setPKCE(t.codeVerifier),await this.tokenManager.setState(r);const n=new URLSearchParams({response_type:"code",client_id:this.config.clientId,redirect_uri:this.config.redirectUri,state:r,code_challenge:t.codeChallenge,code_challenge_method:t.codeChallengeMethod});return this.config.scopes&&this.config.scopes.length>0&&n.append("scope",this.config.scopes.join(" ")),`${this.config.authUrl}/oauth/authorize?${n.toString()}`}async exchangeCode(t,r){const n=await this.tokenManager.consumeState();if(!n||n!==r)throw m.invalidState();const s=await this.tokenManager.consumePKCE();if(!s)throw m.pkceVerificationFailed("Missing code verifier");const a=await this.http.postForm("/oauth/token",{grant_type:"authorization_code",code:t,redirect_uri:this.config.redirectUri,client_id:this.config.clientId,client_secret:this.config.clientSecret,code_verifier:s}),i=this.mapTokenResponse(a);return await this.tokenManager.setTokens(i),i}async refreshToken(){const t=await this.tokenManager.getTokens();if(!t?.refreshToken)throw m.invalidGrant("No refresh token available");const r=await this.http.postForm("/oauth/token",{grant_type:"refresh_token",refresh_token:t.refreshToken,client_id:this.config.clientId,client_secret:this.config.clientSecret}),n=this.mapTokenResponse(r);return await this.tokenManager.setTokens(n),n}async revokeToken(){const t=await this.tokenManager.getTokens();if(t)try{await this.http.postForm("/oauth/revoke",{token:t.accessToken,client_id:this.config.clientId,client_secret:this.config.clientSecret})}finally{await this.tokenManager.clearTokens()}}mapTokenResponse(t){return{accessToken:t.access_token,refreshToken:t.refresh_token,tokenType:t.token_type,expiresIn:t.expires_in,issuedAt:Date.now(),scope:t.scope}}}const B=new TextEncoder,R=new TextDecoder;function Te(...e){const t=e.reduce((s,{length:a})=>s+a,0),r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.length;return r}function M(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){const n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function Ke(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function P(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:R.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=R.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return Ke(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}class l extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class S extends l{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,r,n="unspecified",s="unspecified"){super(t,{cause:{claim:n,reason:s,payload:r}}),this.claim=n,this.reason=s,this.payload=r}}class q extends l{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,r,n="unspecified",s="unspecified"){super(t,{cause:{claim:n,reason:s,payload:r}}),this.claim=n,this.reason=s,this.payload=r}}class g extends l{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class h extends l{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class Y extends l{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class X extends l{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class Q extends l{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r)}}class ve extends l{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r)}}class Ce extends l{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(t="request timed out",r){super(t,r)}}class _e extends l{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}}const b=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),v=(e,t)=>e.name===t;function O(e){return parseInt(e.name.slice(4),10)}function Re(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Pe(e,t){if(!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function ke(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!v(e.algorithm,"HMAC"))throw b("HMAC");const n=parseInt(t.slice(2),10);if(O(e.algorithm.hash)!==n)throw b(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!v(e.algorithm,"RSASSA-PKCS1-v1_5"))throw b("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(O(e.algorithm.hash)!==n)throw b(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!v(e.algorithm,"RSA-PSS"))throw b("RSA-PSS");const n=parseInt(t.slice(2),10);if(O(e.algorithm.hash)!==n)throw b(`SHA-${n}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":{if(!v(e.algorithm,"Ed25519"))throw b("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!v(e.algorithm,t))throw b(t);break}case"ES256":case"ES384":case"ES512":{if(!v(e.algorithm,"ECDSA"))throw b("ECDSA");const n=Re(t);if(e.algorithm.namedCurve!==n)throw b(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Pe(e,r)}function Z(e,t,...r){if(r=r.filter(Boolean),r.length>2){const n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const We=(e,...t)=>Z("Key must be ",e,...t),j=(e,t,...r)=>Z(`Key for the ${e} algorithm must be `,t,...r),ee=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},te=e=>e?.[Symbol.toStringTag]==="KeyObject",re=e=>ee(e)||te(e);function Ie(...e){const t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(const n of t){const s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(const a of s){if(r.has(a))return!1;r.add(a)}}return!0}const Je=e=>typeof e=="object"&&e!==null;function A(e){if(!Je(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Ue(e,t){if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function De(e){let t,r;switch(e.kty){case"AKP":{switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new g('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function k(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=De(e),n={...e};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!(e.d||e.priv),e.key_ops??r)}async function Me(e,t,r){if(!A(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return P(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new g('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return k({...e,alg:t,ext:n});case"AKP":{if(typeof e.alg!="string"||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==void 0&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return k({...e,ext:n})}case"EC":case"OKP":return k({...e,alg:t,ext:n});default:throw new g('Unsupported "kty" (Key Type) Parameter value')}}function Oe(e,t,r,n,s){if(s.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;a=t;for(const i of n.crit){if(!a.has(i))throw new g(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(a.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}const x=e=>A(e)&&typeof e.kty=="string",xe=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),He=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,Ne=e=>e.kty==="oct"&&typeof e.k=="string";let C;const ne=async(e,t,r,n=!1)=>{C||=new WeakMap;let s=C.get(e);if(s?.[r])return s[r];const a=await k({...t,alg:r});return n&&Object.freeze(e),s?s[r]=a:C.set(e,{[r]:a}),a},$e=(e,t)=>{C||=new WeakMap;let r=C.get(e);if(r?.[t])return r[t];const n=e.type==="public",s=!!n;let a;if(e.asymmetricKeyType==="x25519"){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}a=e.toCryptoKey(e.asymmetricKeyType,s,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError("given KeyObject instance cannot be used for this algorithm");a=e.toCryptoKey(e.asymmetricKeyType,s,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");a=e.toCryptoKey(e.asymmetricKeyType,s,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let i;switch(t){case"RSA-OAEP":i="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":i="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":i="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":i="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:i},s,n?["encrypt"]:["decrypt"]);a=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:i},s,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){const c=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!c)throw new TypeError("given KeyObject instance cannot be used for this algorithm");t==="ES256"&&c==="P-256"&&(a=e.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),t==="ES384"&&c==="P-384"&&(a=e.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),t==="ES512"&&c==="P-521"&&(a=e.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(a=e.toCryptoKey({name:"ECDH",namedCurve:c},s,n?[]:["deriveBits"]))}if(!a)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return r?r[t]=a:C.set(e,{[t]:a}),a};async function Le(e,t){if(e instanceof Uint8Array||ee(e))return e;if(te(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return $e(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return ne(e,r,t)}if(x(e))return e.k?P(e.k):ne(e,e,t,!0);throw new Error("unreachable")}const _=e=>e?.[Symbol.toStringTag],H=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case r==="verify":case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n="unwrapKey":n=r;break;case r==="encrypt":n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Fe=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(x(t)){if(Ne(t)&&H(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!re(t))throw new TypeError(j(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${_(t)} instances for symmetric algorithms must be of type "secret"`)}},Ve=(e,t,r)=>{if(x(t))switch(r){case"decrypt":case"sign":if(xe(t)&&H(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(He(t)&&H(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!re(t))throw new TypeError(j(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${_(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${_(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${_(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${_(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${_(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Ge(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Fe(e,t,r);break;default:Ve(e,t,r)}}function ze(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new g(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Be(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(We(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return ke(t,e,r),t}async function qe(e,t,r,n){const s=await Be(e,t,"verify");Ue(e,s);const a=ze(e,s.algorithm);try{return await crypto.subtle.verify(a,s,r,n)}catch{return!1}}async function Ye(e,t,r){if(!A(e))throw new h("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new h('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new h("JWS Protected Header incorrect type");if(e.payload===void 0)throw new h("JWS Payload missing");if(typeof e.signature!="string")throw new h("JWS Signature missing or incorrect type");if(e.header!==void 0&&!A(e.header))throw new h("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const G=P(e.protected);n=JSON.parse(R.decode(G))}catch{throw new h("JWS Protected Header is invalid")}if(!Ie(n,e.header))throw new h("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...n,...e.header},a=Oe(h,new Map([["b64",!0]]),r?.crit,n,s);let i=!0;if(a.has("b64")&&(i=n.b64,typeof i!="boolean"))throw new h('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:c}=s;if(typeof c!="string"||!c)throw new h('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(i){if(typeof e.payload!="string")throw new h("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new h("JWS Payload must be a string or an Uint8Array instance");let f=!1;typeof t=="function"&&(t=await t(n,e),f=!0),Ge(c,t,"verify");const u=Te(e.protected!==void 0?M(e.protected):new Uint8Array,M("."),typeof e.payload=="string"?i?M(e.payload):B.encode(e.payload):e.payload);let o;try{o=P(e.signature)}catch{throw new h("Failed to base64url decode the signature")}const p=await Le(t,c);if(!await qe(c,p,o,u))throw new _e;let T;if(i)try{T=P(e.payload)}catch{throw new h("Failed to base64url decode the payload")}else typeof e.payload=="string"?T=B.encode(e.payload):T=e.payload;const y={payload:T};return e.protected!==void 0&&(y.protectedHeader=n),e.header!==void 0&&(y.unprotectedHeader=e.header),f?{...y,key:p}:y}async function Xe(e,t,r){if(e instanceof Uint8Array&&(e=R.decode(e)),typeof e!="string")throw new h("Compact JWS must be a string or Uint8Array");const{0:n,1:s,2:a,length:i}=e.split(".");if(i!==3)throw new h("Invalid Compact JWS");const c=await Ye({payload:s,protected:n,signature:a},t,r),f={payload:c.payload,protectedHeader:c.protectedHeader};return typeof t=="function"?{...f,key:c.key}:f}const Qe=e=>Math.floor(e.getTime()/1e3),se=60,ae=se*60,N=ae*24,Ze=N*7,je=N*365.25,et=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function ie(e){const t=et.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]),n=t[3].toLowerCase();let s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*se);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*ae);break;case"day":case"days":case"d":s=Math.round(r*N);break;case"week":case"weeks":case"w":s=Math.round(r*Ze);break;default:s=Math.round(r*je);break}return t[1]==="-"||t[4]==="ago"?-s:s}const oe=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,tt=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function rt(e,t,r={}){let n;try{n=JSON.parse(R.decode(t))}catch{}if(!A(n))throw new Y("JWT Claims Set must be a top-level JSON object");const{typ:s}=r;if(s&&(typeof e.typ!="string"||oe(e.typ)!==oe(s)))throw new S('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:a=[],issuer:i,subject:c,audience:f,maxTokenAge:u}=r,o=[...a];u!==void 0&&o.push("iat"),f!==void 0&&o.push("aud"),c!==void 0&&o.push("sub"),i!==void 0&&o.push("iss");for(const y of new Set(o.reverse()))if(!(y in n))throw new S(`missing required "${y}" claim`,n,y,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new S('unexpected "iss" claim value',n,"iss","check_failed");if(c&&n.sub!==c)throw new S('unexpected "sub" claim value',n,"sub","check_failed");if(f&&!tt(n.aud,typeof f=="string"?[f]:f))throw new S('unexpected "aud" claim value',n,"aud","check_failed");let p;switch(typeof r.clockTolerance){case"string":p=ie(r.clockTolerance);break;case"number":p=r.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:me}=r,T=Qe(me||new Date);if((n.iat!==void 0||u)&&typeof n.iat!="number")throw new S('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new S('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>T+p)throw new S('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new S('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=T-p)throw new q('"exp" claim timestamp check failed',n,"exp","check_failed")}if(u){const y=T-n.iat,G=typeof u=="number"?u:ie(u);if(y-p>G)throw new q('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(y<0-p)throw new S('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}async function nt(e,t,r){const n=await Xe(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new Y("JWTs MUST NOT use unencoded payload");const a={payload:rt(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...a,key:n.key}:a}function st(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new g('Unsupported "alg" value for a JSON Web Key Set')}}function at(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(it)}function it(e){return A(e)}class ot{#r;#i=new WeakMap;constructor(t){if(!at(t))throw new X("JSON Web Key Set malformed");this.#r=structuredClone(t)}jwks(){return this.#r}async getKey(t,r){const{alg:n,kid:s}={...t,...r?.header},a=st(n),i=this.#r.keys.filter(u=>{let o=a===u.kty;if(o&&typeof s=="string"&&(o=s===u.kid),o&&(typeof u.alg=="string"||a==="AKP")&&(o=n===u.alg),o&&typeof u.use=="string"&&(o=u.use==="sig"),o&&Array.isArray(u.key_ops)&&(o=u.key_ops.includes("verify")),o)switch(n){case"ES256":o=u.crv==="P-256";break;case"ES384":o=u.crv==="P-384";break;case"ES512":o=u.crv==="P-521";break;case"Ed25519":case"EdDSA":o=u.crv==="Ed25519";break}return o}),{0:c,length:f}=i;if(f===0)throw new Q;if(f!==1){const u=new ve,o=this.#i;throw u[Symbol.asyncIterator]=async function*(){for(const p of i)try{yield await ce(o,p,n)}catch{}},u}return ce(this.#i,c,n)}}async function ce(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){const s=await Me({...t,ext:!0},r);if(s instanceof Uint8Array||s.type!=="public")throw new X("JSON Web Key Set members must be public keys");n[r]=s}return n[r]}function ue(e){const t=new ot(e),r=async(n,s)=>t.getKey(n,s);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}function ct(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let $;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&($="jose/v6.1.3");const ut=Symbol();async function ht(e,t,r,n=fetch){const s=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(a=>{throw a.name==="TimeoutError"?new Ce:a});if(s.status!==200)throw new l("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await s.json()}catch{throw new l("Failed to parse the JSON Web Key Set HTTP response as JSON")}}const L=Symbol();function ft(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!A(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,A))}class dt{#r;#i;#c;#o;#n;#e;#t;#u;#s;#a;constructor(t,r){if(!(t instanceof URL))throw new TypeError("url must be an instance of URL");this.#r=new URL(t.href),this.#i=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.#c=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.#o=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,this.#t=new Headers(r?.headers),$&&!this.#t.has("User-Agent")&&this.#t.set("User-Agent",$),this.#t.has("accept")||(this.#t.set("accept","application/json"),this.#t.append("accept","application/jwk-set+json")),this.#u=r?.[ut],r?.[L]!==void 0&&(this.#a=r?.[L],ft(r?.[L],this.#o)&&(this.#n=this.#a.uat,this.#s=ue(this.#a.jwks)))}pendingFetch(){return!!this.#e}coolingDown(){return typeof this.#n=="number"?Date.now()<this.#n+this.#c:!1}fresh(){return typeof this.#n=="number"?Date.now()<this.#n+this.#o:!1}jwks(){return this.#s?.jwks()}async getKey(t,r){(!this.#s||!this.fresh())&&await this.reload();try{return await this.#s(t,r)}catch(n){if(n instanceof Q&&this.coolingDown()===!1)return await this.reload(),this.#s(t,r);throw n}}async reload(){this.#e&&ct()&&(this.#e=void 0),this.#e||=ht(this.#r.href,this.#t,AbortSignal.timeout(this.#i),this.#u).then(t=>{this.#s=ue(t),this.#a&&(this.#a.uat=Date.now(),this.#a.jwks=t),this.#n=Date.now(),this.#e=void 0}).catch(t=>{throw this.#e=void 0,t}),await this.#e}}function lt(e,t){const r=new dt(e,t),n=async(s,a)=>r.getKey(s,a);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>r.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>r.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}const he=new Map;async function fe(e,t=`${z}/.well-known/jwks.json`){let r=he.get(t);return r||(r=lt(new URL(t)),he.set(t,r)),nt(e,r)}class de{store=new Map;async get(t){return this.store.get(t)??null}async set(t,r){this.store.set(t,r)}async remove(t){this.store.delete(t)}async clear(){this.store.clear()}}class F{prefix;constructor(t="genation"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}async get(t){return typeof window>"u"?null:localStorage.getItem(this.getKey(t))}async set(t,r){typeof window>"u"||localStorage.setItem(this.getKey(t),r)}async remove(t){typeof window>"u"||localStorage.removeItem(this.getKey(t))}async clear(){if(typeof window>"u")return;Object.keys(localStorage).filter(r=>r.startsWith(`${this.prefix}:`)).forEach(r=>localStorage.removeItem(r))}}class le{prefix;constructor(t="genation"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}async get(t){return typeof window>"u"?null:sessionStorage.getItem(this.getKey(t))}async set(t,r){typeof window>"u"||sessionStorage.setItem(this.getKey(t),r)}async remove(t){typeof window>"u"||sessionStorage.removeItem(this.getKey(t))}async clear(){if(typeof window>"u")return;Object.keys(sessionStorage).filter(r=>r.startsWith(`${this.prefix}:`)).forEach(r=>sessionStorage.removeItem(r))}}function pe(e="localStorage"){switch(e){case"memory":return new de;case"localStorage":return new F;case"sessionStorage":return new le;default:return new F}}function V(e){return Array.isArray(e)?e.map(V):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([t,r])=>[t.replace(/_([a-z])/g,(n,s)=>s.toUpperCase()),V(r)])):e}class ye{oauth;tokenManager;jwksUrl;http;httpServer;listeners=new Set;initialized=!1;constructor(t){this.validateConfig(t);const r=typeof t.storage=="object"?t.storage:pe(t.storage),n=t.authUrl??"https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";this.tokenManager=new Ee(r),this.oauth=new Ae(t,this.tokenManager),this.jwksUrl=`${n}/.well-known/jwks.json`,this.http=new W({baseUrl:n}),this.httpServer=new W({baseUrl:"https://ff-api.genation.ai/api/v2/client"})}validateConfig(t){if(!t.clientId)throw K.missingField("clientId");if(!t.clientSecret)throw K.missingField("clientSecret");if(!t.redirectUri)throw K.missingField("redirectUri")}async emitAuthStateChange(t){const r=await this.getSession();this.listeners.forEach(n=>{try{n(t,r)}catch(s){console.error("Error in auth state change callback:",s)}})}onAuthStateChange(t){return this.listeners.add(t),this.initialized?setTimeout(()=>{this.emitAuthStateChange("INITIAL_SESSION")},0):(this.initialized=!0,setTimeout(()=>{this.emitAuthStateChange("INITIAL_SESSION")},0)),{subscription:{unsubscribe:()=>{this.listeners.delete(t)}}}}async signIn(){return this.oauth.getAuthorizationUrl()}async handleCallback(t){const r=new URL(t),n=r.searchParams.get("code"),s=r.searchParams.get("state");if(!n||!s)throw new Error("Missing code or state");const a=await this.oauth.exchangeCode(n,s);return await this.emitAuthStateChange("SIGNED_IN"),a}async signOut(){await this.tokenManager.clearTokens(),await this.emitAuthStateChange("SIGNED_OUT")}async getSession(){if(await this.tokenManager.isTokenExpired())try{await this.oauth.refreshToken()}catch{return null}const r=await this.tokenManager.getTokens();if(!r)return null;const n=await this.fetchUser(r.accessToken);return{accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:r.expiresIn,expiresAt:r.issuedAt+r.expiresIn*1e3,user:n}}async verifyToken(t){const{payload:r}=await fe(t,this.jwksUrl);return r}async getLicenses(t={}){const r=await this.getSession();if(!r)return null;const n=r.accessToken,{expiresAfter:s=new Date}=t,a=await this.httpServer.request("/licenses",{headers:{Authorization:`Bearer ${n}`},params:{expiresAfter:s.toISOString()}});return a.ok?V(a.data):(console.error("GenationClient: Error fetching licenses:",a.error),null)}async fetchUser(t){try{const r=await this.http.request("/oauth/userinfo",{headers:{Authorization:`Bearer ${t}`}});return{sub:r.sub,name:r.name,picture:r.picture,email:r.email,email_verified:r.email_verified,phone_number:r.phone_number,phone_number_verified:r.phone_number_verified}}catch(r){return console.error("GenationClient: Error fetching user:",r),null}}}function pt(e){return new ye(e)}d.AuthError=m,d.ConfigError=K,d.GenationClient=ye,d.GenationError=E,d.LocalStorage=F,d.MemoryStorage=de,d.NetworkError=w,d.SessionStorage=le,d.createClient=pt,d.createStorage=pe,d.verifyToken=fe,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})}));
2
2
  //# sourceMappingURL=genation.umd.js.map