@strivacity/sdk-core 2.1.1 → 2.1.2

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/flows/BaseFlow.cjs +1 -1
  3. package/dist/flows/BaseFlow.cjs.map +1 -1
  4. package/dist/flows/BaseFlow.mjs +1 -1
  5. package/dist/flows/BaseFlow.mjs.map +1 -1
  6. package/dist/flows/NativeFlow.cjs +1 -1
  7. package/dist/flows/NativeFlow.cjs.map +1 -1
  8. package/dist/flows/NativeFlow.mjs +1 -1
  9. package/dist/flows/NativeFlow.mjs.map +1 -1
  10. package/dist/flows/PopupFlow.cjs +1 -1
  11. package/dist/flows/PopupFlow.cjs.map +1 -1
  12. package/dist/flows/PopupFlow.mjs +1 -1
  13. package/dist/flows/PopupFlow.mjs.map +1 -1
  14. package/dist/flows/RedirectFlow.cjs +1 -1
  15. package/dist/flows/RedirectFlow.cjs.map +1 -1
  16. package/dist/flows/RedirectFlow.mjs +1 -1
  17. package/dist/flows/RedirectFlow.mjs.map +1 -1
  18. package/dist/storages/LocalStorage.cjs +1 -1
  19. package/dist/storages/LocalStorage.cjs.map +1 -1
  20. package/dist/storages/LocalStorage.mjs +1 -1
  21. package/dist/storages/LocalStorage.mjs.map +1 -1
  22. package/dist/storages/SessionStorage.cjs +1 -1
  23. package/dist/storages/SessionStorage.cjs.map +1 -1
  24. package/dist/storages/SessionStorage.mjs +1 -1
  25. package/dist/storages/SessionStorage.mjs.map +1 -1
  26. package/dist/utils/HttpClient.cjs.map +1 -1
  27. package/dist/utils/HttpClient.mjs.map +1 -1
  28. package/dist/utils/Metadata.cjs +1 -1
  29. package/dist/utils/Metadata.cjs.map +1 -1
  30. package/dist/utils/Metadata.mjs +1 -1
  31. package/dist/utils/Metadata.mjs.map +1 -1
  32. package/dist/utils/NativeFlowHandler.cjs +1 -1
  33. package/dist/utils/NativeFlowHandler.cjs.map +1 -1
  34. package/dist/utils/NativeFlowHandler.mjs +1 -1
  35. package/dist/utils/NativeFlowHandler.mjs.map +1 -1
  36. package/dist/utils/Session.cjs +1 -1
  37. package/dist/utils/Session.cjs.map +1 -1
  38. package/dist/utils/Session.mjs +1 -1
  39. package/dist/utils/Session.mjs.map +1 -1
  40. package/dist/utils/State.cjs +1 -1
  41. package/dist/utils/State.cjs.map +1 -1
  42. package/dist/utils/State.mjs +1 -1
  43. package/dist/utils/State.mjs.map +1 -1
  44. package/dist/utils/base64Url.cjs.map +1 -1
  45. package/dist/utils/base64Url.mjs.map +1 -1
  46. package/dist/utils/credentials.cjs +1 -1
  47. package/dist/utils/credentials.cjs.map +1 -1
  48. package/dist/utils/credentials.mjs +1 -1
  49. package/dist/utils/credentials.mjs.map +1 -1
  50. package/dist/utils/errors.cjs.map +1 -1
  51. package/dist/utils/errors.mjs.map +1 -1
  52. package/dist/utils/handlers.cjs +1 -1
  53. package/dist/utils/handlers.cjs.map +1 -1
  54. package/dist/utils/handlers.mjs +1 -1
  55. package/dist/utils/handlers.mjs.map +1 -1
  56. package/dist/utils/object.cjs.map +1 -1
  57. package/dist/utils/object.mjs.map +1 -1
  58. package/package.json +5 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,13 @@
1
+ ## 2.1.2 (2026-01-13)
2
+
3
+ ### 🩹 Fixes
4
+
5
+ - add authorization header to the finish endpoint ([f9a973f](https://github.com/Strivacity/sdk-js/commit/f9a973f))
6
+
7
+ ### 🧱 Updated Dependencies
8
+
9
+ - Updated testing to 2.1.1
10
+
1
11
  ## 2.1.1 (2025-11-19)
2
12
 
3
13
  ### 🩹 Fixes
@@ -1,2 +1,2 @@
1
- "use strict";var P=Object.defineProperty;var E=t=>{throw TypeError(t)};var q=(t,e,s)=>e in t?P(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var o=(t,e,s)=>q(t,typeof e!="symbol"?e+"":e,s),p=(t,e,s)=>e.has(t)||E("Cannot "+s);var r=(t,e,s)=>(p(t,e,"read from private field"),s?s.call(t):e.get(t)),d=(t,e,s)=>e.has(t)?E("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),a=(t,e,s,i)=>(p(t,e,"write to private field"),i?i.call(t,s):e.set(t,s),s),f=(t,e,s)=>(p(t,e,"access private method"),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("../utils/jwt.cjs"),j=require("../utils/date.cjs"),x=require("../utils/Metadata.cjs"),S=require("../utils/Session.cjs"),U=require("../utils/State.cjs");require("../utils/base64Url.cjs");require("../utils/crypto.cjs");const w={accessTokenExpired:new Set,init:new Set,loggedIn:new Set,loginInitiated:new Set,logoutInitiated:new Set,sessionLoaded:new Set,tokenRefreshed:new Set,tokenRefreshFailed:new Set,tokenRevoked:new Set,tokenRevokeFailed:new Set};var l,n,h,c,I,R;class z{constructor(e,s,i){d(this,c);d(this,l);d(this,n,null);d(this,h,!1);o(this,"httpClient");o(this,"storage");o(this,"metadata");o(this,"session",null);o(this,"options");if(!e.issuer)throw new Error("Missing option: issuer");if(!e.clientId)throw new Error("Missing option: clientId");if(!e.redirectUri)throw new Error("Missing option: redirectUri");if(!e.urlHandler)throw new Error("Missing option: urlHandler");if(!e.callbackHandler)throw new Error("Missing option: callbackHandler");if(e.scopes&&!Array.isArray(e.scopes))throw new Error("Invalid option: scopes");e.scopes||(e.scopes=["openid"]),e.responseType||(e.responseType="code"),e.responseMode||(e.responseMode="query"),e.storageTokenName||(e.storageTokenName="sty.session"),this.options=e,this.storage=s,this.httpClient=i,this.metadata=new x.Metadata(this,new URL("/.well-known/openid-configuration",e.issuer).toString()),a(this,l,f(this,c,I).call(this))}get idTokenClaims(){var e;return(e=this.session)==null?void 0:e.claims}get accessToken(){var e;return(e=this.session)==null?void 0:e.access_token}get refreshToken(){var e;return(e=this.session)==null?void 0:e.refresh_token}get refreshInProgress(){return r(this,h)}get accessTokenExpired(){var e,s;return!((e=this.session)!=null&&e.access_token)||!((s=this.session)!=null&&s.expires_at)||this.session.expires_at<=j.timestamp()}get accessTokenExpirationDate(){var e;return(e=this.session)==null?void 0:e.expires_at}get isAuthenticated(){return r(this,n)?r(this,n):(a(this,n,f(this,c,R).call(this)),r(this,n))}get isAuthenticatedSync(){var e;return!!((e=this.session)!=null&&e.access_token&&!this.accessTokenExpired)}async logout(e){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");await this.waitToInitialize();const s=this.session;if(!(s!=null&&s.id_token))return;await this.storage.delete(this.options.storageTokenName),this.session=null;const i=new URL(await this.metadata.endSessionEndpoint);i.searchParams.append("id_token_hint",s==null?void 0:s.id_token),e!=null&&e.postLogoutRedirectUri&&i.searchParams.append("post_logout_redirect_uri",e.postLogoutRedirectUri),this.dispatchEvent("logoutInitiated",[{idToken:s.id_token,claims:s.claims}]);try{await this.options.urlHandler(i.toString(),e)}catch{}}async refresh(){var s,i;if(await this.waitToInitialize(),typeof((s=this.session)==null?void 0:s.refresh_token)!="string")return;const e=this.session;try{const k=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"refresh_token",client_id:this.options.clientId,refresh_token:(i=this.session)==null?void 0:i.refresh_token});Object.assign(this.session,await k.json()),this.session.id_token&&(this.session.claims=v.jwt.decode(this.session.id_token)),await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.refreshToken&&this.idTokenClaims&&this.dispatchEvent("tokenRefreshed",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}])}catch{this.session=null,await this.storage.delete(this.options.storageTokenName),this.dispatchEvent("tokenRefreshFailed",[{refreshToken:e.refresh_token}])}}async revoke(){await this.waitToInitialize();const e=this.session;let s=!0;try{e!=null&&e.refresh_token?await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"refresh_token",token:e.refresh_token}):e!=null&&e.access_token&&await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"access_token",token:e.access_token})}catch{s=!1}finally{this.session=null,await this.storage.delete(this.options.storageTokenName),e!=null&&e.refresh_token?this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.refresh_token,tokenTypeHint:"refresh_token"}]):e!=null&&e.access_token&&this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.access_token,tokenTypeHint:"access_token"}])}}async tokenExchange(e={}){var k,u,g,T,_,m;if(await this.waitToInitialize(),this.session=new S.Session,Object.assign(this.session,e),this.session.error)throw new Error(`${this.session.error}: ${this.session.error_description}`);if(!this.session.code)throw new Error("Invalid or missing code");let s;try{const y=await this.storage.get(`sty.${this.session.state}`);if(!y)throw new Error;s=U.State.fromSerializedData(y),await this.storage.delete(`sty.${this.session.state}`)}catch{throw new Error("Invalid or missing state")}const i=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"authorization_code",client_id:this.options.clientId,redirect_uri:this.options.redirectUri,code_verifier:s.codeVerifier,code:this.session.code});if(Object.assign(this.session,await i.json()),this.session.id_token&&(this.session.claims=v.jwt.decode(this.session.id_token)),this.session.error)throw new Error(`${this.session.error}: ${this.session.error_description}`);if(this.session.scope!==((k=this.options.scopes)==null?void 0:k.join(" ")))throw new Error("Invalid scope");if(((u=this.session.claims)==null?void 0:u.nonce)!==s.nonce)throw new Error("Invalid nonce");if(((g=this.session.claims)==null?void 0:g.iss)!==await this.metadata.issuer)throw new Error("Invalid iss");if(Array.isArray((T=this.session.claims)==null?void 0:T.aud)?((_=this.session.claims)==null?void 0:_.aud[0])!==this.options.clientId:((m=this.session.claims)==null?void 0:m.aud)!==this.options.clientId)throw new Error("Invalid aud");await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.idTokenClaims&&this.dispatchEvent("loggedIn",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}])}async getAuthorizationUrl(e={}){var i;const s=new URL(await this.metadata.authorizationEndpoint);return s.searchParams.append("client_id",this.options.clientId),s.searchParams.append("redirect_uri",this.options.redirectUri),s.searchParams.append("response_type",this.options.responseType||"code"),s.searchParams.append("response_mode",this.options.responseMode||"fragment"),s.searchParams.append("scope",((i=this.options.scopes)==null?void 0:i.join(" "))||""),s.searchParams.append("code_challenge_method","S256"),e.prompt&&s.searchParams.append("prompt",e.prompt),e.acrValues&&s.searchParams.append("acr_values",e.acrValues.join(" ")),e.loginHint&&s.searchParams.append("login_hint",e.loginHint),e.uiLocales&&s.searchParams.append("ui_locales",e.uiLocales.join(" ")),s}async waitToInitialize(){await r(this,l)}async sendTokenRequest(e,s={}){return this.httpClient.request(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()})}subscribeToEvent(e,s){return w[e].add(s),{dispose:()=>{w[e].delete(s)}}}dispatchEvent(e,s){for(const i of w[e])i(...s)}}l=new WeakMap,n=new WeakMap,h=new WeakMap,c=new WeakSet,I=async function(){this.session=S.Session.load(await this.storage.get(this.options.storageTokenName)),this.dispatchEvent("init",[]),this.session&&this.accessToken&&this.idTokenClaims&&this.dispatchEvent("sessionLoaded",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.accessToken&&this.accessTokenExpired&&this.dispatchEvent("accessTokenExpired",[{accessToken:this.accessToken,refreshToken:this.refreshToken}])},R=async function(){let e=!1;try{await this.waitToInitialize()}catch{}if(this.accessTokenExpired&&this.refreshToken&&!this.refreshInProgress)try{a(this,h,!0),await this.refresh()}catch{}finally{a(this,h,!1)}return this.accessTokenExpired||(e=!0),a(this,n,null),e};exports.BaseFlow=z;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("../utils/jwt.cjs"),a=require("../utils/date.cjs"),h=require("../utils/Metadata.cjs"),r=require("../utils/Session.cjs"),c=require("../utils/State.cjs");require("../utils/base64Url.cjs");require("../utils/crypto.cjs");const i={accessTokenExpired:new Set,init:new Set,loggedIn:new Set,loginInitiated:new Set,logoutInitiated:new Set,sessionLoaded:new Set,tokenRefreshed:new Set,tokenRefreshFailed:new Set,tokenRevoked:new Set,tokenRevokeFailed:new Set};class d{#t;#e=null;#s=!1;httpClient;storage;metadata;session=null;options;get idTokenClaims(){return this.session?.claims}get accessToken(){return this.session?.access_token}get refreshToken(){return this.session?.refresh_token}get refreshInProgress(){return this.#s}get accessTokenExpired(){return!this.session?.access_token||!this.session?.expires_at||this.session.expires_at<=a.timestamp()}get accessTokenExpirationDate(){return this.session?.expires_at}get isAuthenticated(){return this.#e?this.#e:(this.#e=this.#n(),this.#e)}get isAuthenticatedSync(){return!!(this.session?.access_token&&!this.accessTokenExpired)}constructor(e,s,t){if(!e.issuer)throw new Error("Missing option: issuer");if(!e.clientId)throw new Error("Missing option: clientId");if(!e.redirectUri)throw new Error("Missing option: redirectUri");if(!e.urlHandler)throw new Error("Missing option: urlHandler");if(!e.callbackHandler)throw new Error("Missing option: callbackHandler");if(e.scopes&&!Array.isArray(e.scopes))throw new Error("Invalid option: scopes");e.scopes||(e.scopes=["openid"]),e.responseType||(e.responseType="code"),e.responseMode||(e.responseMode="query"),e.storageTokenName||(e.storageTokenName="sty.session"),this.options=e,this.storage=s,this.httpClient=t,this.metadata=new h.Metadata(this,new URL("/.well-known/openid-configuration",e.issuer).toString()),this.#t=this.#i()}async#i(){this.session=r.Session.load(await this.storage.get(this.options.storageTokenName)),this.dispatchEvent("init",[]),this.session&&this.accessToken&&this.idTokenClaims&&this.dispatchEvent("sessionLoaded",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.accessToken&&this.accessTokenExpired&&this.dispatchEvent("accessTokenExpired",[{accessToken:this.accessToken,refreshToken:this.refreshToken}])}async#n(){let e=!1;try{await this.waitToInitialize()}catch{}if(this.accessTokenExpired&&this.refreshToken&&!this.refreshInProgress)try{this.#s=!0,await this.refresh()}catch{}finally{this.#s=!1}return this.accessTokenExpired||(e=!0),this.#e=null,e}async logout(e){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");await this.waitToInitialize();const s=this.session;if(!s?.id_token)return;await this.storage.delete(this.options.storageTokenName),this.session=null;const t=new URL(await this.metadata.endSessionEndpoint);t.searchParams.append("id_token_hint",s?.id_token),e?.postLogoutRedirectUri&&t.searchParams.append("post_logout_redirect_uri",e.postLogoutRedirectUri),this.dispatchEvent("logoutInitiated",[{idToken:s.id_token,claims:s.claims}]);try{await this.options.urlHandler(t.toString(),e)}catch{}}async refresh(){if(await this.waitToInitialize(),typeof this.session?.refresh_token!="string")return;const e=this.session;try{const s=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"refresh_token",client_id:this.options.clientId,refresh_token:this.session?.refresh_token});Object.assign(this.session,await s.json()),this.session.id_token&&(this.session.claims=o.jwt.decode(this.session.id_token)),await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.refreshToken&&this.idTokenClaims&&this.dispatchEvent("tokenRefreshed",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}])}catch{this.session=null,await this.storage.delete(this.options.storageTokenName),this.dispatchEvent("tokenRefreshFailed",[{refreshToken:e.refresh_token}])}}async revoke(){await this.waitToInitialize();const e=this.session;let s=!0;try{e?.refresh_token?await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"refresh_token",token:e.refresh_token}):e?.access_token&&await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"access_token",token:e.access_token})}catch{s=!1}finally{this.session=null,await this.storage.delete(this.options.storageTokenName),e?.refresh_token?this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.refresh_token,tokenTypeHint:"refresh_token"}]):e?.access_token&&this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.access_token,tokenTypeHint:"access_token"}])}}async tokenExchange(e={}){if(await this.waitToInitialize(),this.session=new r.Session,Object.assign(this.session,e),this.session.error)throw new Error(`${this.session.error}: ${this.session.error_description}`);if(!this.session.code)throw new Error("Invalid or missing code");let s;try{const n=await this.storage.get(`sty.${this.session.state}`);if(!n)throw new Error;s=c.State.fromSerializedData(n),await this.storage.delete(`sty.${this.session.state}`)}catch{throw new Error("Invalid or missing state")}const t=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"authorization_code",client_id:this.options.clientId,redirect_uri:this.options.redirectUri,code_verifier:s.codeVerifier,code:this.session.code});if(Object.assign(this.session,await t.json()),this.session.id_token&&(this.session.claims=o.jwt.decode(this.session.id_token)),this.session.error)throw new Error(`${this.session.error}: ${this.session.error_description}`);if(this.session.scope!==this.options.scopes?.join(" "))throw new Error("Invalid scope");if(this.session.claims?.nonce!==s.nonce)throw new Error("Invalid nonce");if(this.session.claims?.iss!==await this.metadata.issuer)throw new Error("Invalid iss");if(Array.isArray(this.session.claims?.aud)?this.session.claims?.aud[0]!==this.options.clientId:this.session.claims?.aud!==this.options.clientId)throw new Error("Invalid aud");await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.idTokenClaims&&this.dispatchEvent("loggedIn",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}])}async getAuthorizationUrl(e={}){const s=new URL(await this.metadata.authorizationEndpoint);return s.searchParams.append("client_id",this.options.clientId),s.searchParams.append("redirect_uri",this.options.redirectUri),s.searchParams.append("response_type",this.options.responseType||"code"),s.searchParams.append("response_mode",this.options.responseMode||"fragment"),s.searchParams.append("scope",this.options.scopes?.join(" ")||""),s.searchParams.append("code_challenge_method","S256"),e.prompt&&s.searchParams.append("prompt",e.prompt),e.acrValues&&s.searchParams.append("acr_values",e.acrValues.join(" ")),e.loginHint&&s.searchParams.append("login_hint",e.loginHint),e.uiLocales&&s.searchParams.append("ui_locales",e.uiLocales.join(" ")),s}async waitToInitialize(){await this.#t}async sendTokenRequest(e,s={}){return this.httpClient.request(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()})}subscribeToEvent(e,s){return i[e].add(s),{dispose:()=>{i[e].delete(s)}}}dispatchEvent(e,s){for(const t of i[e])t(...s)}}exports.BaseFlow=d;
2
2
  //# sourceMappingURL=BaseFlow.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"BaseFlow.cjs","sources":["../../src/flows/BaseFlow.ts"],"sourcesContent":["import type { IdTokenClaims, SDKOptions, SDKStorage, EventFunctions, ExtraRequestArgs, LogoutParams, SDKHttpClient, HttpClientResponse } from '../types';\nimport { jwt } from '../utils/jwt';\nimport { timestamp } from '../utils/date';\nimport { Metadata } from '../utils/Metadata';\nimport { Session } from '../utils/Session';\nimport { State } from '../utils/State';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst eventCallbacks: Record<keyof EventFunctions, Set<(...args: Array<any>) => Promise<void> | void>> = {\n\taccessTokenExpired: new Set(),\n\tinit: new Set(),\n\tloggedIn: new Set(),\n\tloginInitiated: new Set(),\n\tlogoutInitiated: new Set(),\n\tsessionLoaded: new Set(),\n\ttokenRefreshed: new Set(),\n\ttokenRefreshFailed: new Set(),\n\ttokenRevoked: new Set(),\n\ttokenRevokeFailed: new Set(),\n};\n\n/**\n * An abstract base class that provides common functionality for different OIDC flows.\n *\n * @template Options - The options type extending `SDKOptions` used for configuring the flow.\n * @template URLHandlerParams - The options type extending `ExtraRequestArgs` used for URL handling.\n */\nexport abstract class BaseFlow<Options extends SDKOptions = SDKOptions, URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs> {\n\t/**\n\t * @ignore\n\t */\n\t#initializationPromise: Promise<void>;\n\n\t/**\n\t * @ignore\n\t */\n\t#isAuthenticatedPromise: Promise<boolean> | null = null;\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\t#refreshInProgressState = false;\n\n\t/**\n\t * An instance of the HTTP client used for making requests.\n\t *\n\t * @type {SDKHttpClient}\n\t */\n\thttpClient: SDKHttpClient;\n\n\t/**\n\t * The storage mechanism used to persist session data.\n\t *\n\t * @type {SDKStorage}\n\t */\n\tstorage: SDKStorage;\n\n\t/**\n\t * Metadata information about the authorization server.\n\t *\n\t * @type {Metadata}\n\t */\n\tmetadata: Metadata;\n\n\t/**\n\t * The current session data.\n\t *\n\t * @type {Session | null}\n\t */\n\tsession: Session | null = null;\n\n\t/**\n\t * The configuration options for the flow.\n\t *\n\t * @type {Options}\n\t */\n\toptions: Options;\n\n\t/**\n\t * Retrieves the ID token claims from the current session.\n\t *\n\t * @type {IdTokenClaims | null | undefined}\n\t */\n\tget idTokenClaims(): IdTokenClaims | null | undefined {\n\t\treturn this.session?.claims;\n\t}\n\n\t/**\n\t * Retrieves the access token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget accessToken(): string | null | undefined {\n\t\treturn this.session?.access_token;\n\t}\n\n\t/**\n\t * Retrieves the refresh token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget refreshToken(): string | null | undefined {\n\t\treturn this.session?.refresh_token;\n\t}\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\tget refreshInProgress(): boolean {\n\t\treturn this.#refreshInProgressState;\n\t}\n\n\t/**\n\t * Determines if the access token has expired.\n\t *\n\t * @type {boolean}\n\t */\n\tget accessTokenExpired(): boolean {\n\t\treturn !this.session?.access_token || !this.session?.expires_at || this.session.expires_at <= timestamp();\n\t}\n\n\t/**\n\t * Retrieves the access token expiration date.\n\t *\n\t * @type {number | null | undefined}\n\t */\n\tget accessTokenExpirationDate(): number | null | undefined {\n\t\treturn this.session?.expires_at;\n\t}\n\n\t/**\n\t * Checks if the user is authenticated by evaluating the presence of access or refresh tokens.\n\t *\n\t * @returns {Promise<boolean>} - A promise that resolves to `true` if the user is authenticated, otherwise `false`.\n\t */\n\tget isAuthenticated(): Promise<boolean> {\n\t\tif (this.#isAuthenticatedPromise) {\n\t\t\treturn this.#isAuthenticatedPromise;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = this.#checkAuthentication();\n\n\t\treturn this.#isAuthenticatedPromise;\n\t}\n\n\t/**\n\t * Checks authentication status without attempting token refresh.\n\t * Useful when you want to avoid side effects.\n\t *\n\t * @returns {boolean} - Returns `true` if the user has a valid, non-expired access token.\n\t */\n\tget isAuthenticatedSync(): boolean {\n\t\treturn Boolean(this.session?.access_token && !this.accessTokenExpired);\n\t}\n\n\t/**\n\t * Constructs a new instance of the `BaseFlow` class.\n\t *\n\t * @param {Options} options - Configuration options for the flow.\n\t * @param {SDKStorage} storage - Storage mechanism for session data.\n\t *\n\t * @throws {Error} Throws an error if required options are missing or invalid.\n\t */\n\tconstructor(options: Options, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.issuer) {\n\t\t\tthrow new Error('Missing option: issuer');\n\t\t}\n\t\tif (!options.clientId) {\n\t\t\tthrow new Error('Missing option: clientId');\n\t\t}\n\t\tif (!options.redirectUri) {\n\t\t\tthrow new Error('Missing option: redirectUri');\n\t\t}\n\t\tif (!options.urlHandler) {\n\t\t\tthrow new Error('Missing option: urlHandler');\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\tthrow new Error('Missing option: callbackHandler');\n\t\t}\n\t\tif (options.scopes && !Array.isArray(options.scopes)) {\n\t\t\tthrow new Error('Invalid option: scopes');\n\t\t}\n\n\t\tif (!options.scopes) {\n\t\t\toptions.scopes = ['openid'];\n\t\t}\n\t\tif (!options.responseType) {\n\t\t\toptions.responseType = 'code';\n\t\t}\n\t\tif (!options.responseMode) {\n\t\t\toptions.responseMode = 'query';\n\t\t}\n\t\tif (!options.storageTokenName) {\n\t\t\toptions.storageTokenName = 'sty.session';\n\t\t}\n\n\t\tthis.options = options;\n\t\tthis.storage = storage;\n\t\tthis.httpClient = httpClient;\n\t\tthis.metadata = new Metadata(this, new URL('/.well-known/openid-configuration', options.issuer).toString());\n\n\t\tthis.#initializationPromise = this.#init();\n\t}\n\n\t/**\n\t * Initializes the flow by loading the session from storage and setting up event listeners.\n\t * @ignore\n\t */\n\tasync #init() {\n\t\tthis.session = Session.load(await this.storage.get(this.options.storageTokenName!));\n\n\t\tthis.dispatchEvent('init', []);\n\n\t\tif (this.session && this.accessToken && this.idTokenClaims) {\n\t\t\tthis.dispatchEvent('sessionLoaded', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t}\n\n\t\tif (this.accessToken && this.accessTokenExpired) {\n\t\t\tthis.dispatchEvent('accessTokenExpired', [{ accessToken: this.accessToken, refreshToken: this.refreshToken }]);\n\t\t}\n\t}\n\n\t/**\n\t * Internal method to check authentication status with proper error handling.\n\t * @ignore\n\t */\n\tasync #checkAuthentication(): Promise<boolean> {\n\t\tlet isAuthenticated = false;\n\n\t\ttry {\n\t\t\tawait this.waitToInitialize();\n\t\t} catch {\n\t\t\t// Initialization failed\n\t\t}\n\n\t\t// Attempt to refresh the token if it has expired\n\t\tif (this.accessTokenExpired && this.refreshToken && !this.refreshInProgress) {\n\t\t\ttry {\n\t\t\t\tthis.#refreshInProgressState = true;\n\t\t\t\tawait this.refresh();\n\t\t\t} catch {\n\t\t\t\t// Token refresh failed - if you want to log errors use the tokenRefreshFailed event\n\t\t\t} finally {\n\t\t\t\tthis.#refreshInProgressState = false;\n\t\t\t}\n\t\t}\n\n\t\tif (!this.accessTokenExpired) {\n\t\t\tisAuthenticated = true;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = null;\n\n\t\treturn isAuthenticated;\n\t}\n\n\t/**\n\t * Initiates the login process. Subclasses should implement this method to handle the specific login flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during login.\n\t * @returns {Promise<void>} - A promise that resolves when the login process is complete.\n\t */\n\tabstract login(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Registers a new user. Subclasses should implement this method to handle the specific registration flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during registration.\n\t * @returns {Promise<void>} - A promise that resolves when the registration process is complete.\n\t */\n\tabstract register(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Initiates the entry process.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<void>} A promise that resolves when the entry process completes.\n\t */\n\tabstract entry(url?: string): unknown;\n\n\t/**\n\t * Logs out the current user and optionally redirects to a post-logout URI.\n\t *\n\t * @param {URLHandlerParams & LogoutParams} [params] - Additional params for handling URLs during logout.\n\t * @returns {Promise<void>} - A promise that resolves when the logout process is complete.\n\t */\n\tasync logout(params?: URLHandlerParams & LogoutParams): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tthrow new Error('URL handler is not defined. Please provide a valid URL handler function in the SDK options.');\n\t\t}\n\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\n\t\tif (!session?.id_token) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.storage.delete(this.options.storageTokenName!);\n\t\tthis.session = null;\n\n\t\tconst url = new URL(await this.metadata.endSessionEndpoint);\n\n\t\turl.searchParams.append('id_token_hint', session?.id_token);\n\n\t\tif (params?.postLogoutRedirectUri) {\n\t\t\turl.searchParams.append('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\t\t}\n\n\t\tthis.dispatchEvent('logoutInitiated', [{ idToken: session.id_token, claims: session.claims! }]);\n\n\t\ttry {\n\t\t\tawait this.options.urlHandler(url.toString(), params as URLHandlerParams);\n\t\t} catch {}\n\t}\n\n\t/**\n\t * Refreshes the access token using the refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token refresh is complete.\n\t *\n\t * @throws {Error} Throws an error if the refresh fails.\n\t */\n\tasync refresh(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tif (typeof this.session?.refresh_token !== 'string') {\n\t\t\treturn;\n\t\t}\n\n\t\tconst session = this.session;\n\n\t\ttry {\n\t\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\trefresh_token: this.session?.refresh_token,\n\t\t\t});\n\n\t\t\tObject.assign(this.session, await request.json());\n\n\t\t\tif (this.session.id_token) {\n\t\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t\t}\n\n\t\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\t\tif (this.accessToken && this.refreshToken && this.idTokenClaims) {\n\t\t\t\tthis.dispatchEvent('tokenRefreshed', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tthis.dispatchEvent('tokenRefreshFailed', [{ refreshToken: session.refresh_token! }]);\n\t\t}\n\t}\n\n\t/**\n\t * Revokes the current access or refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token revocation is complete.\n\t */\n\tasync revoke(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\t\tlet success = true;\n\n\t\ttry {\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'refresh_token',\n\t\t\t\t\ttoken: session.refresh_token,\n\t\t\t\t});\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'access_token',\n\t\t\t\t\ttoken: session.access_token,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch {\n\t\t\tsuccess = false;\n\t\t} finally {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.refresh_token, tokenTypeHint: 'refresh_token' }]);\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.access_token, tokenTypeHint: 'access_token' }]);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Exchanges an authorization code for access and refresh tokens.\n\t *\n\t * @param {Record<string, string>} [params={}] - Parameters containing the authorization code and other required values.\n\t * @returns {Promise<void>} - A promise that resolves when the token exchange is complete.\n\t *\n\t * @throws {Error} Throws an error if the authorization code is invalid or if there are issues with state, nonce, or tokens.\n\t */\n\tasync tokenExchange(params: Record<string, string> = {}): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tthis.session = new Session();\n\n\t\tObject.assign(this.session, params);\n\n\t\tif (this.session.error) {\n\t\t\tthrow new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t}\n\t\tif (!this.session.code) {\n\t\t\tthrow new Error('Invalid or missing code');\n\t\t}\n\n\t\tlet state: State;\n\n\t\ttry {\n\t\t\tconst serializedState = await this.storage.get(`sty.${this.session.state}`);\n\n\t\t\tif (!serializedState) {\n\t\t\t\tthrow new Error();\n\t\t\t}\n\n\t\t\tstate = State.fromSerializedData(serializedState);\n\n\t\t\tawait this.storage.delete(`sty.${this.session.state}`);\n\t\t} catch {\n\t\t\tthrow new Error('Invalid or missing state');\n\t\t}\n\n\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\tgrant_type: 'authorization_code',\n\t\t\tclient_id: this.options.clientId,\n\t\t\tredirect_uri: this.options.redirectUri,\n\t\t\tcode_verifier: state.codeVerifier,\n\t\t\tcode: this.session.code,\n\t\t});\n\n\t\tObject.assign(this.session, await request.json());\n\n\t\tif (this.session.id_token) {\n\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t}\n\n\t\tif (this.session.error) {\n\t\t\tthrow new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t}\n\t\tif (this.session.scope !== this.options.scopes?.join(' ')) {\n\t\t\tthrow new Error('Invalid scope');\n\t\t}\n\t\tif (this.session.claims?.nonce !== state.nonce) {\n\t\t\tthrow new Error('Invalid nonce');\n\t\t}\n\t\tif (this.session.claims?.iss !== (await this.metadata.issuer)) {\n\t\t\tthrow new Error('Invalid iss');\n\t\t}\n\t\tif (Array.isArray(this.session.claims?.aud) ? this.session.claims?.aud[0] !== this.options.clientId : this.session.claims?.aud !== this.options.clientId) {\n\t\t\tthrow new Error('Invalid aud');\n\t\t}\n\n\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\tif (this.accessToken && this.idTokenClaims) {\n\t\t\tthis.dispatchEvent('loggedIn', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t}\n\t}\n\n\t/**\n\t * Constructs the authorization URL for initiating the authorization flow.\n\t *\n\t * @param {ExtraRequestArgs} [params={}] - Additional params to include in the authorization URL.\n\t * @returns {Promise<URL>} - A promise that resolves to the constructed authorization URL.\n\t */\n\tasync getAuthorizationUrl(params: ExtraRequestArgs = {}): Promise<URL> {\n\t\tconst url = new URL(await this.metadata.authorizationEndpoint);\n\n\t\turl.searchParams.append('client_id', this.options.clientId);\n\t\turl.searchParams.append('redirect_uri', this.options.redirectUri);\n\t\turl.searchParams.append('response_type', this.options.responseType || 'code');\n\t\turl.searchParams.append('response_mode', this.options.responseMode || 'fragment');\n\t\turl.searchParams.append('scope', this.options.scopes?.join(' ') || '');\n\t\turl.searchParams.append('code_challenge_method', 'S256');\n\n\t\tif (params.prompt) {\n\t\t\turl.searchParams.append('prompt', params.prompt);\n\t\t}\n\t\tif (params.acrValues) {\n\t\t\turl.searchParams.append('acr_values', params.acrValues.join(' '));\n\t\t}\n\t\tif (params.loginHint) {\n\t\t\turl.searchParams.append('login_hint', params.loginHint);\n\t\t}\n\t\tif (params.uiLocales) {\n\t\t\turl.searchParams.append('ui_locales', params.uiLocales.join(' '));\n\t\t}\n\n\t\treturn url;\n\t}\n\n\tprotected async waitToInitialize(): Promise<void> {\n\t\tawait this.#initializationPromise;\n\t}\n\n\t/**\n\t * Sends a token request to the specified URL with the given data.\n\t *\n\t * @param {string} url - The URL to send the request to.\n\t * @param {Record<string, string>} [data={}] - The data to include in the request body.\n\t * @returns {Promise<HttpClientResponse<Session>>} - A promise that resolves to the response from the request.\n\t */\n\tasync sendTokenRequest(url: string, data: Record<string, string> = {}): Promise<HttpClientResponse<Session>> {\n\t\treturn this.httpClient.request<Session>(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded' },\n\t\t\tbody: new URLSearchParams(data).toString(),\n\t\t});\n\t}\n\n\t/**\n\t * Subscribes a callback function to an event.\n\t *\n\t * @param {T} eventName - The name of the event to subscribe to.\n\t * @param {(...params: Parameters<EventFunctions[T]>) => Promise<void> | void} callbackFn - The callback function to execute when the event is dispatched.\n\t * @returns {{ dispose: () => void }} - An object with a `dispose` method to remove the subscription.\n\t */\n\tsubscribeToEvent<T extends keyof EventFunctions>(\n\t\teventName: T,\n\t\tcallbackFn: (...params: Parameters<EventFunctions[T]>) => Promise<void> | void,\n\t): { dispose: () => void } {\n\t\teventCallbacks[eventName].add(callbackFn);\n\n\t\treturn {\n\t\t\tdispose: () => {\n\t\t\t\teventCallbacks[eventName].delete(callbackFn);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Dispatches an event to all subscribed callback functions.\n\t *\n\t * @param {T} eventName - The name of the event to dispatch.\n\t * @param {Parameters<EventFunctions[T]>} args - The arguments to pass to the callback functions.\n\t */\n\tprotected dispatchEvent<T extends keyof EventFunctions>(eventName: T, args: Parameters<EventFunctions[T]>): void {\n\t\tfor (const eventFn of eventCallbacks[eventName]) {\n\t\t\tvoid eventFn(...args);\n\t\t}\n\t}\n}\n"],"names":["eventCallbacks","BaseFlow","options","storage","httpClient","__privateAdd","_BaseFlow_instances","_initializationPromise","_isAuthenticatedPromise","_refreshInProgressState","__publicField","Metadata","__privateSet","__privateMethod","init_fn","_a","__privateGet","_b","timestamp","checkAuthentication_fn","params","session","url","request","jwt","success","Session","state","serializedState","State","_c","_d","_e","_f","data","eventName","callbackFn","args","eventFn","isAuthenticated"],"mappings":"k1BAQA,MAAMA,EAAmG,CACxG,uBAAwB,IACxB,SAAU,IACV,aAAc,IACd,mBAAoB,IACpB,oBAAqB,IACrB,kBAAmB,IACnB,mBAAoB,IACpB,uBAAwB,IACxB,iBAAkB,IAClB,sBAAuB,GACxB,kBAQO,MAAeC,CAAgH,CA4IrI,YAAYC,EAAkBC,EAAqBC,EAA2B,CA5IxEC,EAAA,KAAAC,GAIND,EAAA,KAAAE,GAKAF,EAAA,KAAAG,EAAmD,MAOnDH,EAAA,KAAAI,EAA0B,IAO1BC,EAAA,mBAOAA,EAAA,gBAOAA,EAAA,iBAOAA,EAAA,eAA0B,MAO1BA,EAAA,gBA0FC,GAAI,CAACR,EAAQ,OACZ,MAAM,IAAI,MAAM,wBAAwB,EAEzC,GAAI,CAACA,EAAQ,SACZ,MAAM,IAAI,MAAM,0BAA0B,EAE3C,GAAI,CAACA,EAAQ,YACZ,MAAM,IAAI,MAAM,6BAA6B,EAE9C,GAAI,CAACA,EAAQ,WACZ,MAAM,IAAI,MAAM,4BAA4B,EAE7C,GAAI,CAACA,EAAQ,gBACZ,MAAM,IAAI,MAAM,iCAAiC,EAElD,GAAIA,EAAQ,QAAU,CAAC,MAAM,QAAQA,EAAQ,MAAM,EAClD,MAAM,IAAI,MAAM,wBAAwB,EAGpCA,EAAQ,SACZA,EAAQ,OAAS,CAAC,QAAQ,GAEtBA,EAAQ,eACZA,EAAQ,aAAe,QAEnBA,EAAQ,eACZA,EAAQ,aAAe,SAEnBA,EAAQ,mBACZA,EAAQ,iBAAmB,eAG5B,KAAK,QAAUA,EACf,KAAK,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E,EAA2C,CAChH,UAAWC,KAAWtC,EAAemC,CAAS,EACxCG,EAAQ,GAAGD,CAAI,CACrB,CAEF,CA/gBC9B,EAAA,YAKAC,EAAA,YAOAC,EAAA,YAhBMH,EAAA,YAyLAQ,EAAA,gBAAQ,CACb,KAAK,QAAUY,UAAQ,KAAK,MAAM,KAAK,QAAQ,IAAI,KAAK,QAAQ,gBAAiB,CAAC,EAElF,KAAK,cAAc,OAAQ,EAAE,EAEzB,KAAK,SAAW,KAAK,aAAe,KAAK,eAC5C,KAAK,cAAc,gBAAiB,CAAC,CAAE,YAAa,KAAK,YAAa,aAAc,KAAK,aAAc,OAAQ,KAAK,aAAA,CAAe,CAAC,EAGjI,KAAK,aAAe,KAAK,oBAC5B,KAAK,cAAc,qBAAsB,CAAC,CAAE,YAAa,KAAK,YAAa,aAAc,KAAK,YAAA,CAAc,CAAC,CAC9G,EAOKP,EAAA,gBAAyC,CAC9C,IAAIoB,EAAkB,GAEtB,GAAI,CACH,MAAM,KAAK,iBAAA,CAAiB,MACrB,CAAA,CAKR,GAAI,KAAK,oBAAsB,KAAK,cAAgB,CAAC,KAAK,kBACzD,GAAI,CACH3B,EAAA,KAAKH,EAA0B,IAC/B,MAAM,KAAK,QAAA,CAAQ,MACZ,CAAA,QAER,CACCG,EAAA,KAAKH,EAA0B,GAAA,CAIjC,OAAK,KAAK,qBACT8B,EAAkB,IAGnB3B,EAAA,KAAKJ,EAA0B,MAExB+B,CAAA"}
1
+ {"version":3,"file":"BaseFlow.cjs","sources":["../../src/flows/BaseFlow.ts"],"sourcesContent":["import type { IdTokenClaims, SDKOptions, SDKStorage, EventFunctions, ExtraRequestArgs, LogoutParams, SDKHttpClient, HttpClientResponse } from '../types';\nimport { jwt } from '../utils/jwt';\nimport { timestamp } from '../utils/date';\nimport { Metadata } from '../utils/Metadata';\nimport { Session } from '../utils/Session';\nimport { State } from '../utils/State';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst eventCallbacks: Record<keyof EventFunctions, Set<(...args: Array<any>) => Promise<void> | void>> = {\n\taccessTokenExpired: new Set(),\n\tinit: new Set(),\n\tloggedIn: new Set(),\n\tloginInitiated: new Set(),\n\tlogoutInitiated: new Set(),\n\tsessionLoaded: new Set(),\n\ttokenRefreshed: new Set(),\n\ttokenRefreshFailed: new Set(),\n\ttokenRevoked: new Set(),\n\ttokenRevokeFailed: new Set(),\n};\n\n/**\n * An abstract base class that provides common functionality for different OIDC flows.\n *\n * @template Options - The options type extending `SDKOptions` used for configuring the flow.\n * @template URLHandlerParams - The options type extending `ExtraRequestArgs` used for URL handling.\n */\nexport abstract class BaseFlow<Options extends SDKOptions = SDKOptions, URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs> {\n\t/**\n\t * @ignore\n\t */\n\t#initializationPromise: Promise<void>;\n\n\t/**\n\t * @ignore\n\t */\n\t#isAuthenticatedPromise: Promise<boolean> | null = null;\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\t#refreshInProgressState = false;\n\n\t/**\n\t * An instance of the HTTP client used for making requests.\n\t *\n\t * @type {SDKHttpClient}\n\t */\n\thttpClient: SDKHttpClient;\n\n\t/**\n\t * The storage mechanism used to persist session data.\n\t *\n\t * @type {SDKStorage}\n\t */\n\tstorage: SDKStorage;\n\n\t/**\n\t * Metadata information about the authorization server.\n\t *\n\t * @type {Metadata}\n\t */\n\tmetadata: Metadata;\n\n\t/**\n\t * The current session data.\n\t *\n\t * @type {Session | null}\n\t */\n\tsession: Session | null = null;\n\n\t/**\n\t * The configuration options for the flow.\n\t *\n\t * @type {Options}\n\t */\n\toptions: Options;\n\n\t/**\n\t * Retrieves the ID token claims from the current session.\n\t *\n\t * @type {IdTokenClaims | null | undefined}\n\t */\n\tget idTokenClaims(): IdTokenClaims | null | undefined {\n\t\treturn this.session?.claims;\n\t}\n\n\t/**\n\t * Retrieves the access token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget accessToken(): string | null | undefined {\n\t\treturn this.session?.access_token;\n\t}\n\n\t/**\n\t * Retrieves the refresh token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget refreshToken(): string | null | undefined {\n\t\treturn this.session?.refresh_token;\n\t}\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\tget refreshInProgress(): boolean {\n\t\treturn this.#refreshInProgressState;\n\t}\n\n\t/**\n\t * Determines if the access token has expired.\n\t *\n\t * @type {boolean}\n\t */\n\tget accessTokenExpired(): boolean {\n\t\treturn !this.session?.access_token || !this.session?.expires_at || this.session.expires_at <= timestamp();\n\t}\n\n\t/**\n\t * Retrieves the access token expiration date.\n\t *\n\t * @type {number | null | undefined}\n\t */\n\tget accessTokenExpirationDate(): number | null | undefined {\n\t\treturn this.session?.expires_at;\n\t}\n\n\t/**\n\t * Checks if the user is authenticated by evaluating the presence of access or refresh tokens.\n\t *\n\t * @returns {Promise<boolean>} - A promise that resolves to `true` if the user is authenticated, otherwise `false`.\n\t */\n\tget isAuthenticated(): Promise<boolean> {\n\t\tif (this.#isAuthenticatedPromise) {\n\t\t\treturn this.#isAuthenticatedPromise;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = this.#checkAuthentication();\n\n\t\treturn this.#isAuthenticatedPromise;\n\t}\n\n\t/**\n\t * Checks authentication status without attempting token refresh.\n\t * Useful when you want to avoid side effects.\n\t *\n\t * @returns {boolean} - Returns `true` if the user has a valid, non-expired access token.\n\t */\n\tget isAuthenticatedSync(): boolean {\n\t\treturn Boolean(this.session?.access_token && !this.accessTokenExpired);\n\t}\n\n\t/**\n\t * Constructs a new instance of the `BaseFlow` class.\n\t *\n\t * @param {Options} options - Configuration options for the flow.\n\t * @param {SDKStorage} storage - Storage mechanism for session data.\n\t *\n\t * @throws {Error} Throws an error if required options are missing or invalid.\n\t */\n\tconstructor(options: Options, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.issuer) {\n\t\t\tthrow new Error('Missing option: issuer');\n\t\t}\n\t\tif (!options.clientId) {\n\t\t\tthrow new Error('Missing option: clientId');\n\t\t}\n\t\tif (!options.redirectUri) {\n\t\t\tthrow new Error('Missing option: redirectUri');\n\t\t}\n\t\tif (!options.urlHandler) {\n\t\t\tthrow new Error('Missing option: urlHandler');\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\tthrow new Error('Missing option: callbackHandler');\n\t\t}\n\t\tif (options.scopes && !Array.isArray(options.scopes)) {\n\t\t\tthrow new Error('Invalid option: scopes');\n\t\t}\n\n\t\tif (!options.scopes) {\n\t\t\toptions.scopes = ['openid'];\n\t\t}\n\t\tif (!options.responseType) {\n\t\t\toptions.responseType = 'code';\n\t\t}\n\t\tif (!options.responseMode) {\n\t\t\toptions.responseMode = 'query';\n\t\t}\n\t\tif (!options.storageTokenName) {\n\t\t\toptions.storageTokenName = 'sty.session';\n\t\t}\n\n\t\tthis.options = options;\n\t\tthis.storage = storage;\n\t\tthis.httpClient = httpClient;\n\t\tthis.metadata = new Metadata(this, new URL('/.well-known/openid-configuration', options.issuer).toString());\n\n\t\tthis.#initializationPromise = this.#init();\n\t}\n\n\t/**\n\t * Initializes the flow by loading the session from storage and setting up event listeners.\n\t * @ignore\n\t */\n\tasync #init() {\n\t\tthis.session = Session.load(await this.storage.get(this.options.storageTokenName!));\n\n\t\tthis.dispatchEvent('init', []);\n\n\t\tif (this.session && this.accessToken && this.idTokenClaims) {\n\t\t\tthis.dispatchEvent('sessionLoaded', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t}\n\n\t\tif (this.accessToken && this.accessTokenExpired) {\n\t\t\tthis.dispatchEvent('accessTokenExpired', [{ accessToken: this.accessToken, refreshToken: this.refreshToken }]);\n\t\t}\n\t}\n\n\t/**\n\t * Internal method to check authentication status with proper error handling.\n\t * @ignore\n\t */\n\tasync #checkAuthentication(): Promise<boolean> {\n\t\tlet isAuthenticated = false;\n\n\t\ttry {\n\t\t\tawait this.waitToInitialize();\n\t\t} catch {\n\t\t\t// Initialization failed\n\t\t}\n\n\t\t// Attempt to refresh the token if it has expired\n\t\tif (this.accessTokenExpired && this.refreshToken && !this.refreshInProgress) {\n\t\t\ttry {\n\t\t\t\tthis.#refreshInProgressState = true;\n\t\t\t\tawait this.refresh();\n\t\t\t} catch {\n\t\t\t\t// Token refresh failed - if you want to log errors use the tokenRefreshFailed event\n\t\t\t} finally {\n\t\t\t\tthis.#refreshInProgressState = false;\n\t\t\t}\n\t\t}\n\n\t\tif (!this.accessTokenExpired) {\n\t\t\tisAuthenticated = true;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = null;\n\n\t\treturn isAuthenticated;\n\t}\n\n\t/**\n\t * Initiates the login process. Subclasses should implement this method to handle the specific login flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during login.\n\t * @returns {Promise<void>} - A promise that resolves when the login process is complete.\n\t */\n\tabstract login(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Registers a new user. Subclasses should implement this method to handle the specific registration flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during registration.\n\t * @returns {Promise<void>} - A promise that resolves when the registration process is complete.\n\t */\n\tabstract register(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Initiates the entry process.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<void>} A promise that resolves when the entry process completes.\n\t */\n\tabstract entry(url?: string): unknown;\n\n\t/**\n\t * Logs out the current user and optionally redirects to a post-logout URI.\n\t *\n\t * @param {URLHandlerParams & LogoutParams} [params] - Additional params for handling URLs during logout.\n\t * @returns {Promise<void>} - A promise that resolves when the logout process is complete.\n\t */\n\tasync logout(params?: URLHandlerParams & LogoutParams): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tthrow new Error('URL handler is not defined. Please provide a valid URL handler function in the SDK options.');\n\t\t}\n\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\n\t\tif (!session?.id_token) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.storage.delete(this.options.storageTokenName!);\n\t\tthis.session = null;\n\n\t\tconst url = new URL(await this.metadata.endSessionEndpoint);\n\n\t\turl.searchParams.append('id_token_hint', session?.id_token);\n\n\t\tif (params?.postLogoutRedirectUri) {\n\t\t\turl.searchParams.append('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\t\t}\n\n\t\tthis.dispatchEvent('logoutInitiated', [{ idToken: session.id_token, claims: session.claims! }]);\n\n\t\ttry {\n\t\t\tawait this.options.urlHandler(url.toString(), params as URLHandlerParams);\n\t\t} catch {}\n\t}\n\n\t/**\n\t * Refreshes the access token using the refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token refresh is complete.\n\t *\n\t * @throws {Error} Throws an error if the refresh fails.\n\t */\n\tasync refresh(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tif (typeof this.session?.refresh_token !== 'string') {\n\t\t\treturn;\n\t\t}\n\n\t\tconst session = this.session;\n\n\t\ttry {\n\t\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\trefresh_token: this.session?.refresh_token,\n\t\t\t});\n\n\t\t\tObject.assign(this.session, await request.json());\n\n\t\t\tif (this.session.id_token) {\n\t\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t\t}\n\n\t\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\t\tif (this.accessToken && this.refreshToken && this.idTokenClaims) {\n\t\t\t\tthis.dispatchEvent('tokenRefreshed', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tthis.dispatchEvent('tokenRefreshFailed', [{ refreshToken: session.refresh_token! }]);\n\t\t}\n\t}\n\n\t/**\n\t * Revokes the current access or refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token revocation is complete.\n\t */\n\tasync revoke(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\t\tlet success = true;\n\n\t\ttry {\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'refresh_token',\n\t\t\t\t\ttoken: session.refresh_token,\n\t\t\t\t});\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'access_token',\n\t\t\t\t\ttoken: session.access_token,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch {\n\t\t\tsuccess = false;\n\t\t} finally {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.refresh_token, tokenTypeHint: 'refresh_token' }]);\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.access_token, tokenTypeHint: 'access_token' }]);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Exchanges an authorization code for access and refresh tokens.\n\t *\n\t * @param {Record<string, string>} [params={}] - Parameters containing the authorization code and other required values.\n\t * @returns {Promise<void>} - A promise that resolves when the token exchange is complete.\n\t *\n\t * @throws {Error} Throws an error if the authorization code is invalid or if there are issues with state, nonce, or tokens.\n\t */\n\tasync tokenExchange(params: Record<string, string> = {}): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tthis.session = new Session();\n\n\t\tObject.assign(this.session, params);\n\n\t\tif (this.session.error) {\n\t\t\tthrow new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t}\n\t\tif (!this.session.code) {\n\t\t\tthrow new Error('Invalid or missing code');\n\t\t}\n\n\t\tlet state: State;\n\n\t\ttry {\n\t\t\tconst serializedState = await this.storage.get(`sty.${this.session.state}`);\n\n\t\t\tif (!serializedState) {\n\t\t\t\tthrow new Error();\n\t\t\t}\n\n\t\t\tstate = State.fromSerializedData(serializedState);\n\n\t\t\tawait this.storage.delete(`sty.${this.session.state}`);\n\t\t} catch {\n\t\t\tthrow new Error('Invalid or missing state');\n\t\t}\n\n\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\tgrant_type: 'authorization_code',\n\t\t\tclient_id: this.options.clientId,\n\t\t\tredirect_uri: this.options.redirectUri,\n\t\t\tcode_verifier: state.codeVerifier,\n\t\t\tcode: this.session.code,\n\t\t});\n\n\t\tObject.assign(this.session, await request.json());\n\n\t\tif (this.session.id_token) {\n\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t}\n\n\t\tif (this.session.error) {\n\t\t\tthrow new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t}\n\t\tif (this.session.scope !== this.options.scopes?.join(' ')) {\n\t\t\tthrow new Error('Invalid scope');\n\t\t}\n\t\tif (this.session.claims?.nonce !== state.nonce) {\n\t\t\tthrow new Error('Invalid nonce');\n\t\t}\n\t\tif (this.session.claims?.iss !== (await this.metadata.issuer)) {\n\t\t\tthrow new Error('Invalid iss');\n\t\t}\n\t\tif (Array.isArray(this.session.claims?.aud) ? this.session.claims?.aud[0] !== this.options.clientId : this.session.claims?.aud !== this.options.clientId) {\n\t\t\tthrow new Error('Invalid aud');\n\t\t}\n\n\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\tif (this.accessToken && this.idTokenClaims) {\n\t\t\tthis.dispatchEvent('loggedIn', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t}\n\t}\n\n\t/**\n\t * Constructs the authorization URL for initiating the authorization flow.\n\t *\n\t * @param {ExtraRequestArgs} [params={}] - Additional params to include in the authorization URL.\n\t * @returns {Promise<URL>} - A promise that resolves to the constructed authorization URL.\n\t */\n\tasync getAuthorizationUrl(params: ExtraRequestArgs = {}): Promise<URL> {\n\t\tconst url = new URL(await this.metadata.authorizationEndpoint);\n\n\t\turl.searchParams.append('client_id', this.options.clientId);\n\t\turl.searchParams.append('redirect_uri', this.options.redirectUri);\n\t\turl.searchParams.append('response_type', this.options.responseType || 'code');\n\t\turl.searchParams.append('response_mode', this.options.responseMode || 'fragment');\n\t\turl.searchParams.append('scope', this.options.scopes?.join(' ') || '');\n\t\turl.searchParams.append('code_challenge_method', 'S256');\n\n\t\tif (params.prompt) {\n\t\t\turl.searchParams.append('prompt', params.prompt);\n\t\t}\n\t\tif (params.acrValues) {\n\t\t\turl.searchParams.append('acr_values', params.acrValues.join(' '));\n\t\t}\n\t\tif (params.loginHint) {\n\t\t\turl.searchParams.append('login_hint', params.loginHint);\n\t\t}\n\t\tif (params.uiLocales) {\n\t\t\turl.searchParams.append('ui_locales', params.uiLocales.join(' '));\n\t\t}\n\n\t\treturn url;\n\t}\n\n\tprotected async waitToInitialize(): Promise<void> {\n\t\tawait this.#initializationPromise;\n\t}\n\n\t/**\n\t * Sends a token request to the specified URL with the given data.\n\t *\n\t * @param {string} url - The URL to send the request to.\n\t * @param {Record<string, string>} [data={}] - The data to include in the request body.\n\t * @returns {Promise<HttpClientResponse<Session>>} - A promise that resolves to the response from the request.\n\t */\n\tasync sendTokenRequest(url: string, data: Record<string, string> = {}): Promise<HttpClientResponse<Session>> {\n\t\treturn this.httpClient.request<Session>(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded' },\n\t\t\tbody: new URLSearchParams(data).toString(),\n\t\t});\n\t}\n\n\t/**\n\t * Subscribes a callback function to an event.\n\t *\n\t * @param {T} eventName - The name of the event to subscribe to.\n\t * @param {(...params: Parameters<EventFunctions[T]>) => Promise<void> | void} callbackFn - The callback function to execute when the event is dispatched.\n\t * @returns {{ dispose: () => void }} - An object with a `dispose` method to remove the subscription.\n\t */\n\tsubscribeToEvent<T extends keyof EventFunctions>(\n\t\teventName: T,\n\t\tcallbackFn: (...params: Parameters<EventFunctions[T]>) => Promise<void> | void,\n\t): { dispose: () => void } {\n\t\teventCallbacks[eventName].add(callbackFn);\n\n\t\treturn {\n\t\t\tdispose: () => {\n\t\t\t\teventCallbacks[eventName].delete(callbackFn);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Dispatches an event to all subscribed callback functions.\n\t *\n\t * @param {T} eventName - The name of the event to dispatch.\n\t * @param {Parameters<EventFunctions[T]>} args - The arguments to pass to the callback functions.\n\t */\n\tprotected dispatchEvent<T extends keyof EventFunctions>(eventName: T, args: Parameters<EventFunctions[T]>): void {\n\t\tfor (const eventFn of eventCallbacks[eventName]) {\n\t\t\tvoid eventFn(...args);\n\t\t}\n\t}\n}\n"],"names":["eventCallbacks","BaseFlow","#initializationPromise","#isAuthenticatedPromise","#refreshInProgressState","timestamp","#checkAuthentication","options","storage","httpClient","Metadata","#init","Session","isAuthenticated","params","session","url","request","jwt","success","state","serializedState","State","data","eventName","callbackFn","args","eventFn"],"mappings":"yTAQA,MAAMA,EAAmG,CACxG,uBAAwB,IACxB,SAAU,IACV,aAAc,IACd,mBAAoB,IACpB,oBAAqB,IACrB,kBAAmB,IACnB,mBAAoB,IACpB,uBAAwB,IACxB,iBAAkB,IAClB,sBAAuB,GACxB,EAQO,MAAeC,CAAgH,CAIrIC,GAKAC,GAAmD,KAOnDC,GAA0B,GAO1B,WAOA,QAOA,SAOA,QAA0B,KAO1B,QAOA,IAAI,eAAkD,CACrD,OAAO,KAAK,SAAS,MACtB,CAOA,IAAI,aAAyC,CAC5C,OAAO,KAAK,S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Q,KAAK,GAAG,GAAK,EAAE,EACrEA,EAAI,aAAa,OAAO,wBAAyB,MAAM,EAEnDF,EAAO,QACVE,EAAI,aAAa,OAAO,SAAUF,EAAO,MAAM,EAE5CA,EAAO,WACVE,EAAI,aAAa,OAAO,aAAcF,EAAO,UAAU,KAAK,GAAG,CAAC,EAE7DA,EAAO,WACVE,EAAI,aAAa,OAAO,aAAcF,EAAO,SAAS,EAEnDA,EAAO,WACVE,EAAI,aAAa,OAAO,aAAcF,EAAO,UAAU,KAAK,GAAG,CAAC,EAG1DE,CACR,CAEA,MAAgB,kBAAkC,CACjD,MAAM,KAAKd,EACZ,CASA,MAAM,iBAAiBc,EAAaO,EAA+B,GAA0C,CAC5G,OAAO,KAAK,WAAW,QAAiBP,EAAK,CAC5C,OAAQ,OACR,QAAS,CAAE,eAAgB,mCAAA,EAC3B,KAAM,IAAI,gBAAgBO,CAAI,EAAE,SAAA,CAAS,CACzC,CACF,CASA,iBACCC,EACAC,EAC0B,CAC1B,OAAAzB,EAAewB,CAAS,EAAE,IAAIC,CAAU,EAEjC,CACN,QAAS,IAAM,CACdzB,EAAewB,CAAS,EAAE,OAAOC,CAAU,CAC5C,CAAA,CAEF,CAQU,cAA8CD,EAAcE,EAA2C,CAChH,UAAWC,KAAW3B,EAAewB,CAAS,EACxCG,EAAQ,GAAGD,CAAI,CAEtB,CACD"}
@@ -1,2 +1,2 @@
1
- var P=Object.defineProperty;var E=t=>{throw TypeError(t)};var x=(t,e,s)=>e in t?P(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var o=(t,e,s)=>x(t,typeof e!="symbol"?e+"":e,s),p=(t,e,s)=>e.has(t)||E("Cannot "+s);var r=(t,e,s)=>(p(t,e,"read from private field"),s?s.call(t):e.get(t)),d=(t,e,s)=>e.has(t)?E("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),a=(t,e,s,i)=>(p(t,e,"write to private field"),i?i.call(t,s):e.set(t,s),s),f=(t,e,s)=>(p(t,e,"access private method"),s);import{jwt as v}from"../utils/jwt.mjs";import{timestamp as U}from"../utils/date.mjs";import{Metadata as z}from"../utils/Metadata.mjs";import{Session as I}from"../utils/Session.mjs";import{State as C}from"../utils/State.mjs";import"../utils/base64Url.mjs";import"../utils/crypto.mjs";const w={accessTokenExpired:new Set,init:new Set,loggedIn:new Set,loginInitiated:new Set,logoutInitiated:new Set,sessionLoaded:new Set,tokenRefreshed:new Set,tokenRefreshFailed:new Set,tokenRevoked:new Set,tokenRevokeFailed:new Set};var l,n,h,c,S,R;class F{constructor(e,s,i){d(this,c);d(this,l);d(this,n,null);d(this,h,!1);o(this,"httpClient");o(this,"storage");o(this,"metadata");o(this,"session",null);o(this,"options");if(!e.issuer)throw new Error("Missing option: issuer");if(!e.clientId)throw new Error("Missing option: clientId");if(!e.redirectUri)throw new Error("Missing option: redirectUri");if(!e.urlHandler)throw new Error("Missing option: urlHandler");if(!e.callbackHandler)throw new Error("Missing option: callbackHandler");if(e.scopes&&!Array.isArray(e.scopes))throw new Error("Invalid option: scopes");e.scopes||(e.scopes=["openid"]),e.responseType||(e.responseType="code"),e.responseMode||(e.responseMode="query"),e.storageTokenName||(e.storageTokenName="sty.session"),this.options=e,this.storage=s,this.httpClient=i,this.metadata=new z(this,new URL("/.well-known/openid-configuration",e.issuer).toString()),a(this,l,f(this,c,S).call(this))}get idTokenClaims(){var e;return(e=this.session)==null?void 0:e.claims}get accessToken(){var e;return(e=this.session)==null?void 0:e.access_token}get refreshToken(){var e;return(e=this.session)==null?void 0:e.refresh_token}get refreshInProgress(){return r(this,h)}get accessTokenExpired(){var e,s;return!((e=this.session)!=null&&e.access_token)||!((s=this.session)!=null&&s.expires_at)||this.session.expires_at<=U()}get accessTokenExpirationDate(){var e;return(e=this.session)==null?void 0:e.expires_at}get isAuthenticated(){return r(this,n)?r(this,n):(a(this,n,f(this,c,R).call(this)),r(this,n))}get isAuthenticatedSync(){var e;return!!((e=this.session)!=null&&e.access_token&&!this.accessTokenExpired)}async logout(e){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");await this.waitToInitialize();const s=this.session;if(!(s!=null&&s.id_token))return;await this.storage.delete(this.options.storageTokenName),this.session=null;const i=new URL(await this.metadata.endSessionEndpoint);i.searchParams.append("id_token_hint",s==null?void 0:s.id_token),e!=null&&e.postLogoutRedirectUri&&i.searchParams.append("post_logout_redirect_uri",e.postLogoutRedirectUri),this.dispatchEvent("logoutInitiated",[{idToken:s.id_token,claims:s.claims}]);try{await this.options.urlHandler(i.toString(),e)}catch{}}async refresh(){var s,i;if(await this.waitToInitialize(),typeof((s=this.session)==null?void 0:s.refresh_token)!="string")return;const e=this.session;try{const k=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"refresh_token",client_id:this.options.clientId,refresh_token:(i=this.session)==null?void 0:i.refresh_token});Object.assign(this.session,await k.json()),this.session.id_token&&(this.session.claims=v.decode(this.session.id_token)),await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.refreshToken&&this.idTokenClaims&&this.dispatchEvent("tokenRefreshed",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}])}catch{this.session=null,await this.storage.delete(this.options.storageTokenName),this.dispatchEvent("tokenRefreshFailed",[{refreshToken:e.refresh_token}])}}async revoke(){await this.waitToInitialize();const e=this.session;let s=!0;try{e!=null&&e.refresh_token?await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"refresh_token",token:e.refresh_token}):e!=null&&e.access_token&&await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"access_token",token:e.access_token})}catch{s=!1}finally{this.session=null,await this.storage.delete(this.options.storageTokenName),e!=null&&e.refresh_token?this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.refresh_token,tokenTypeHint:"refresh_token"}]):e!=null&&e.access_token&&this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.access_token,tokenTypeHint:"access_token"}])}}async tokenExchange(e={}){var k,u,g,T,m,_;if(await this.waitToInitialize(),this.session=new I,Object.assign(this.session,e),this.session.error)throw new Error(`${this.session.error}: ${this.session.error_description}`);if(!this.session.code)throw new Error("Invalid or missing code");let s;try{const y=await this.storage.get(`sty.${this.session.state}`);if(!y)throw new Error;s=C.fromSerializedData(y),await this.storage.delete(`sty.${this.session.state}`)}catch{throw new Error("Invalid or missing state")}const i=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"authorization_code",client_id:this.options.clientId,redirect_uri:this.options.redirectUri,code_verifier:s.codeVerifier,code:this.session.code});if(Object.assign(this.session,await i.json()),this.session.id_token&&(this.session.claims=v.decode(this.session.id_token)),this.session.error)throw new Error(`${this.session.error}: ${this.session.error_description}`);if(this.session.scope!==((k=this.options.scopes)==null?void 0:k.join(" ")))throw new Error("Invalid scope");if(((u=this.session.claims)==null?void 0:u.nonce)!==s.nonce)throw new Error("Invalid nonce");if(((g=this.session.claims)==null?void 0:g.iss)!==await this.metadata.issuer)throw new Error("Invalid iss");if(Array.isArray((T=this.session.claims)==null?void 0:T.aud)?((m=this.session.claims)==null?void 0:m.aud[0])!==this.options.clientId:((_=this.session.claims)==null?void 0:_.aud)!==this.options.clientId)throw new Error("Invalid aud");await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.idTokenClaims&&this.dispatchEvent("loggedIn",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}])}async getAuthorizationUrl(e={}){var i;const s=new URL(await this.metadata.authorizationEndpoint);return s.searchParams.append("client_id",this.options.clientId),s.searchParams.append("redirect_uri",this.options.redirectUri),s.searchParams.append("response_type",this.options.responseType||"code"),s.searchParams.append("response_mode",this.options.responseMode||"fragment"),s.searchParams.append("scope",((i=this.options.scopes)==null?void 0:i.join(" "))||""),s.searchParams.append("code_challenge_method","S256"),e.prompt&&s.searchParams.append("prompt",e.prompt),e.acrValues&&s.searchParams.append("acr_values",e.acrValues.join(" ")),e.loginHint&&s.searchParams.append("login_hint",e.loginHint),e.uiLocales&&s.searchParams.append("ui_locales",e.uiLocales.join(" ")),s}async waitToInitialize(){await r(this,l)}async sendTokenRequest(e,s={}){return this.httpClient.request(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()})}subscribeToEvent(e,s){return w[e].add(s),{dispose:()=>{w[e].delete(s)}}}dispatchEvent(e,s){for(const i of w[e])i(...s)}}l=new WeakMap,n=new WeakMap,h=new WeakMap,c=new WeakSet,S=async function(){this.session=I.load(await this.storage.get(this.options.storageTokenName)),this.dispatchEvent("init",[]),this.session&&this.accessToken&&this.idTokenClaims&&this.dispatchEvent("sessionLoaded",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.accessToken&&this.accessTokenExpired&&this.dispatchEvent("accessTokenExpired",[{accessToken:this.accessToken,refreshToken:this.refreshToken}])},R=async function(){let e=!1;try{await this.waitToInitialize()}catch{}if(this.accessTokenExpired&&this.refreshToken&&!this.refreshInProgress)try{a(this,h,!0),await this.refresh()}catch{}finally{a(this,h,!1)}return this.accessTokenExpired||(e=!0),a(this,n,null),e};export{F as BaseFlow};
1
+ import{jwt as o}from"../utils/jwt.mjs";import{timestamp as a}from"../utils/date.mjs";import{Metadata as h}from"../utils/Metadata.mjs";import{Session as r}from"../utils/Session.mjs";import{State as c}from"../utils/State.mjs";import"../utils/base64Url.mjs";import"../utils/crypto.mjs";const i={accessTokenExpired:new Set,init:new Set,loggedIn:new Set,loginInitiated:new Set,logoutInitiated:new Set,sessionLoaded:new Set,tokenRefreshed:new Set,tokenRefreshFailed:new Set,tokenRevoked:new Set,tokenRevokeFailed:new Set};class T{#t;#e=null;#s=!1;httpClient;storage;metadata;session=null;options;get idTokenClaims(){return this.session?.claims}get accessToken(){return this.session?.access_token}get refreshToken(){return this.session?.refresh_token}get refreshInProgress(){return this.#s}get accessTokenExpired(){return!this.session?.access_token||!this.session?.expires_at||this.session.expires_at<=a()}get accessTokenExpirationDate(){return this.session?.expires_at}get isAuthenticated(){return this.#e?this.#e:(this.#e=this.#n(),this.#e)}get isAuthenticatedSync(){return!!(this.session?.access_token&&!this.accessTokenExpired)}constructor(e,s,t){if(!e.issuer)throw new Error("Missing option: issuer");if(!e.clientId)throw new Error("Missing option: clientId");if(!e.redirectUri)throw new Error("Missing option: redirectUri");if(!e.urlHandler)throw new Error("Missing option: urlHandler");if(!e.callbackHandler)throw new Error("Missing option: callbackHandler");if(e.scopes&&!Array.isArray(e.scopes))throw new Error("Invalid option: scopes");e.scopes||(e.scopes=["openid"]),e.responseType||(e.responseType="code"),e.responseMode||(e.responseMode="query"),e.storageTokenName||(e.storageTokenName="sty.session"),this.options=e,this.storage=s,this.httpClient=t,this.metadata=new h(this,new URL("/.well-known/openid-configuration",e.issuer).toString()),this.#t=this.#i()}async#i(){this.session=r.load(await this.storage.get(this.options.storageTokenName)),this.dispatchEvent("init",[]),this.session&&this.accessToken&&this.idTokenClaims&&this.dispatchEvent("sessionLoaded",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.accessToken&&this.accessTokenExpired&&this.dispatchEvent("accessTokenExpired",[{accessToken:this.accessToken,refreshToken:this.refreshToken}])}async#n(){let e=!1;try{await this.waitToInitialize()}catch{}if(this.accessTokenExpired&&this.refreshToken&&!this.refreshInProgress)try{this.#s=!0,await this.refresh()}catch{}finally{this.#s=!1}return this.accessTokenExpired||(e=!0),this.#e=null,e}async logout(e){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");await this.waitToInitialize();const s=this.session;if(!s?.id_token)return;await this.storage.delete(this.options.storageTokenName),this.session=null;const t=new URL(await this.metadata.endSessionEndpoint);t.searchParams.append("id_token_hint",s?.id_token),e?.postLogoutRedirectUri&&t.searchParams.append("post_logout_redirect_uri",e.postLogoutRedirectUri),this.dispatchEvent("logoutInitiated",[{idToken:s.id_token,claims:s.claims}]);try{await this.options.urlHandler(t.toString(),e)}catch{}}async refresh(){if(await this.waitToInitialize(),typeof this.session?.refresh_token!="string")return;const e=this.session;try{const s=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"refresh_token",client_id:this.options.clientId,refresh_token:this.session?.refresh_token});Object.assign(this.session,await s.json()),this.session.id_token&&(this.session.claims=o.decode(this.session.id_token)),await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.refreshToken&&this.idTokenClaims&&this.dispatchEvent("tokenRefreshed",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}])}catch{this.session=null,await this.storage.delete(this.options.storageTokenName),this.dispatchEvent("tokenRefreshFailed",[{refreshToken:e.refresh_token}])}}async revoke(){await this.waitToInitialize();const e=this.session;let s=!0;try{e?.refresh_token?await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"refresh_token",token:e.refresh_token}):e?.access_token&&await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"access_token",token:e.access_token})}catch{s=!1}finally{this.session=null,await this.storage.delete(this.options.storageTokenName),e?.refresh_token?this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.refresh_token,tokenTypeHint:"refresh_token"}]):e?.access_token&&this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.access_token,tokenTypeHint:"access_token"}])}}async tokenExchange(e={}){if(await this.waitToInitialize(),this.session=new r,Object.assign(this.session,e),this.session.error)throw new Error(`${this.session.error}: ${this.session.error_description}`);if(!this.session.code)throw new Error("Invalid or missing code");let s;try{const n=await this.storage.get(`sty.${this.session.state}`);if(!n)throw new Error;s=c.fromSerializedData(n),await this.storage.delete(`sty.${this.session.state}`)}catch{throw new Error("Invalid or missing state")}const t=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"authorization_code",client_id:this.options.clientId,redirect_uri:this.options.redirectUri,code_verifier:s.codeVerifier,code:this.session.code});if(Object.assign(this.session,await t.json()),this.session.id_token&&(this.session.claims=o.decode(this.session.id_token)),this.session.error)throw new Error(`${this.session.error}: ${this.session.error_description}`);if(this.session.scope!==this.options.scopes?.join(" "))throw new Error("Invalid scope");if(this.session.claims?.nonce!==s.nonce)throw new Error("Invalid nonce");if(this.session.claims?.iss!==await this.metadata.issuer)throw new Error("Invalid iss");if(Array.isArray(this.session.claims?.aud)?this.session.claims?.aud[0]!==this.options.clientId:this.session.claims?.aud!==this.options.clientId)throw new Error("Invalid aud");await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.idTokenClaims&&this.dispatchEvent("loggedIn",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}])}async getAuthorizationUrl(e={}){const s=new URL(await this.metadata.authorizationEndpoint);return s.searchParams.append("client_id",this.options.clientId),s.searchParams.append("redirect_uri",this.options.redirectUri),s.searchParams.append("response_type",this.options.responseType||"code"),s.searchParams.append("response_mode",this.options.responseMode||"fragment"),s.searchParams.append("scope",this.options.scopes?.join(" ")||""),s.searchParams.append("code_challenge_method","S256"),e.prompt&&s.searchParams.append("prompt",e.prompt),e.acrValues&&s.searchParams.append("acr_values",e.acrValues.join(" ")),e.loginHint&&s.searchParams.append("login_hint",e.loginHint),e.uiLocales&&s.searchParams.append("ui_locales",e.uiLocales.join(" ")),s}async waitToInitialize(){await this.#t}async sendTokenRequest(e,s={}){return this.httpClient.request(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()})}subscribeToEvent(e,s){return i[e].add(s),{dispose:()=>{i[e].delete(s)}}}dispatchEvent(e,s){for(const t of i[e])t(...s)}}export{T as BaseFlow};
2
2
  //# sourceMappingURL=BaseFlow.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"BaseFlow.mjs","sources":["../../src/flows/BaseFlow.ts"],"sourcesContent":["import type { IdTokenClaims, SDKOptions, SDKStorage, EventFunctions, ExtraRequestArgs, LogoutParams, SDKHttpClient, HttpClientResponse } from '../types';\nimport { jwt } from '../utils/jwt';\nimport { timestamp } from '../utils/date';\nimport { Metadata } from '../utils/Metadata';\nimport { Session } from '../utils/Session';\nimport { State } from '../utils/State';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst eventCallbacks: Record<keyof EventFunctions, Set<(...args: Array<any>) => Promise<void> | void>> = {\n\taccessTokenExpired: new Set(),\n\tinit: new Set(),\n\tloggedIn: new Set(),\n\tloginInitiated: new Set(),\n\tlogoutInitiated: new Set(),\n\tsessionLoaded: new Set(),\n\ttokenRefreshed: new Set(),\n\ttokenRefreshFailed: new Set(),\n\ttokenRevoked: new Set(),\n\ttokenRevokeFailed: new Set(),\n};\n\n/**\n * An abstract base class that provides common functionality for different OIDC flows.\n *\n * @template Options - The options type extending `SDKOptions` used for configuring the flow.\n * @template URLHandlerParams - The options type extending `ExtraRequestArgs` used for URL handling.\n */\nexport abstract class BaseFlow<Options extends SDKOptions = SDKOptions, URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs> {\n\t/**\n\t * @ignore\n\t */\n\t#initializationPromise: Promise<void>;\n\n\t/**\n\t * @ignore\n\t */\n\t#isAuthenticatedPromise: Promise<boolean> | null = null;\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\t#refreshInProgressState = false;\n\n\t/**\n\t * An instance of the HTTP client used for making requests.\n\t *\n\t * @type {SDKHttpClient}\n\t */\n\thttpClient: SDKHttpClient;\n\n\t/**\n\t * The storage mechanism used to persist session data.\n\t *\n\t * @type {SDKStorage}\n\t */\n\tstorage: SDKStorage;\n\n\t/**\n\t * Metadata information about the authorization server.\n\t *\n\t * @type {Metadata}\n\t */\n\tmetadata: Metadata;\n\n\t/**\n\t * The current session data.\n\t *\n\t * @type {Session | null}\n\t */\n\tsession: Session | null = null;\n\n\t/**\n\t * The configuration options for the flow.\n\t *\n\t * @type {Options}\n\t */\n\toptions: Options;\n\n\t/**\n\t * Retrieves the ID token claims from the current session.\n\t *\n\t * @type {IdTokenClaims | null | undefined}\n\t */\n\tget idTokenClaims(): IdTokenClaims | null | undefined {\n\t\treturn this.session?.claims;\n\t}\n\n\t/**\n\t * Retrieves the access token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget accessToken(): string | null | undefined {\n\t\treturn this.session?.access_token;\n\t}\n\n\t/**\n\t * Retrieves the refresh token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget refreshToken(): string | null | undefined {\n\t\treturn this.session?.refresh_token;\n\t}\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\tget refreshInProgress(): boolean {\n\t\treturn this.#refreshInProgressState;\n\t}\n\n\t/**\n\t * Determines if the access token has expired.\n\t *\n\t * @type {boolean}\n\t */\n\tget accessTokenExpired(): boolean {\n\t\treturn !this.session?.access_token || !this.session?.expires_at || this.session.expires_at <= timestamp();\n\t}\n\n\t/**\n\t * Retrieves the access token expiration date.\n\t *\n\t * @type {number | null | undefined}\n\t */\n\tget accessTokenExpirationDate(): number | null | undefined {\n\t\treturn this.session?.expires_at;\n\t}\n\n\t/**\n\t * Checks if the user is authenticated by evaluating the presence of access or refresh tokens.\n\t *\n\t * @returns {Promise<boolean>} - A promise that resolves to `true` if the user is authenticated, otherwise `false`.\n\t */\n\tget isAuthenticated(): Promise<boolean> {\n\t\tif (this.#isAuthenticatedPromise) {\n\t\t\treturn this.#isAuthenticatedPromise;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = this.#checkAuthentication();\n\n\t\treturn this.#isAuthenticatedPromise;\n\t}\n\n\t/**\n\t * Checks authentication status without attempting token refresh.\n\t * Useful when you want to avoid side effects.\n\t *\n\t * @returns {boolean} - Returns `true` if the user has a valid, non-expired access token.\n\t */\n\tget isAuthenticatedSync(): boolean {\n\t\treturn Boolean(this.session?.access_token && !this.accessTokenExpired);\n\t}\n\n\t/**\n\t * Constructs a new instance of the `BaseFlow` class.\n\t *\n\t * @param {Options} options - Configuration options for the flow.\n\t * @param {SDKStorage} storage - Storage mechanism for session data.\n\t *\n\t * @throws {Error} Throws an error if required options are missing or invalid.\n\t */\n\tconstructor(options: Options, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.issuer) {\n\t\t\tthrow new Error('Missing option: issuer');\n\t\t}\n\t\tif (!options.clientId) {\n\t\t\tthrow new Error('Missing option: clientId');\n\t\t}\n\t\tif (!options.redirectUri) {\n\t\t\tthrow new Error('Missing option: redirectUri');\n\t\t}\n\t\tif (!options.urlHandler) {\n\t\t\tthrow new Error('Missing option: urlHandler');\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\tthrow new Error('Missing option: callbackHandler');\n\t\t}\n\t\tif (options.scopes && !Array.isArray(options.scopes)) {\n\t\t\tthrow new Error('Invalid option: scopes');\n\t\t}\n\n\t\tif (!options.scopes) {\n\t\t\toptions.scopes = ['openid'];\n\t\t}\n\t\tif (!options.responseType) {\n\t\t\toptions.responseType = 'code';\n\t\t}\n\t\tif (!options.responseMode) {\n\t\t\toptions.responseMode = 'query';\n\t\t}\n\t\tif (!options.storageTokenName) {\n\t\t\toptions.storageTokenName = 'sty.session';\n\t\t}\n\n\t\tthis.options = options;\n\t\tthis.storage = storage;\n\t\tthis.httpClient = httpClient;\n\t\tthis.metadata = new Metadata(this, new URL('/.well-known/openid-configuration', options.issuer).toString());\n\n\t\tthis.#initializationPromise = this.#init();\n\t}\n\n\t/**\n\t * Initializes the flow by loading the session from storage and setting up event listeners.\n\t * @ignore\n\t */\n\tasync #init() {\n\t\tthis.session = Session.load(await this.storage.get(this.options.storageTokenName!));\n\n\t\tthis.dispatchEvent('init', []);\n\n\t\tif (this.session && this.accessToken && this.idTokenClaims) {\n\t\t\tthis.dispatchEvent('sessionLoaded', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t}\n\n\t\tif (this.accessToken && this.accessTokenExpired) {\n\t\t\tthis.dispatchEvent('accessTokenExpired', [{ accessToken: this.accessToken, refreshToken: this.refreshToken }]);\n\t\t}\n\t}\n\n\t/**\n\t * Internal method to check authentication status with proper error handling.\n\t * @ignore\n\t */\n\tasync #checkAuthentication(): Promise<boolean> {\n\t\tlet isAuthenticated = false;\n\n\t\ttry {\n\t\t\tawait this.waitToInitialize();\n\t\t} catch {\n\t\t\t// Initialization failed\n\t\t}\n\n\t\t// Attempt to refresh the token if it has expired\n\t\tif (this.accessTokenExpired && this.refreshToken && !this.refreshInProgress) {\n\t\t\ttry {\n\t\t\t\tthis.#refreshInProgressState = true;\n\t\t\t\tawait this.refresh();\n\t\t\t} catch {\n\t\t\t\t// Token refresh failed - if you want to log errors use the tokenRefreshFailed event\n\t\t\t} finally {\n\t\t\t\tthis.#refreshInProgressState = false;\n\t\t\t}\n\t\t}\n\n\t\tif (!this.accessTokenExpired) {\n\t\t\tisAuthenticated = true;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = null;\n\n\t\treturn isAuthenticated;\n\t}\n\n\t/**\n\t * Initiates the login process. Subclasses should implement this method to handle the specific login flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during login.\n\t * @returns {Promise<void>} - A promise that resolves when the login process is complete.\n\t */\n\tabstract login(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Registers a new user. Subclasses should implement this method to handle the specific registration flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during registration.\n\t * @returns {Promise<void>} - A promise that resolves when the registration process is complete.\n\t */\n\tabstract register(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Initiates the entry process.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<void>} A promise that resolves when the entry process completes.\n\t */\n\tabstract entry(url?: string): unknown;\n\n\t/**\n\t * Logs out the current user and optionally redirects to a post-logout URI.\n\t *\n\t * @param {URLHandlerParams & LogoutParams} [params] - Additional params for handling URLs during logout.\n\t * @returns {Promise<void>} - A promise that resolves when the logout process is complete.\n\t */\n\tasync logout(params?: URLHandlerParams & LogoutParams): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tthrow new Error('URL handler is not defined. Please provide a valid URL handler function in the SDK options.');\n\t\t}\n\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\n\t\tif (!session?.id_token) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.storage.delete(this.options.storageTokenName!);\n\t\tthis.session = null;\n\n\t\tconst url = new URL(await this.metadata.endSessionEndpoint);\n\n\t\turl.searchParams.append('id_token_hint', session?.id_token);\n\n\t\tif (params?.postLogoutRedirectUri) {\n\t\t\turl.searchParams.append('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\t\t}\n\n\t\tthis.dispatchEvent('logoutInitiated', [{ idToken: session.id_token, claims: session.claims! }]);\n\n\t\ttry {\n\t\t\tawait this.options.urlHandler(url.toString(), params as URLHandlerParams);\n\t\t} catch {}\n\t}\n\n\t/**\n\t * Refreshes the access token using the refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token refresh is complete.\n\t *\n\t * @throws {Error} Throws an error if the refresh fails.\n\t */\n\tasync refresh(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tif (typeof this.session?.refresh_token !== 'string') {\n\t\t\treturn;\n\t\t}\n\n\t\tconst session = this.session;\n\n\t\ttry {\n\t\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\trefresh_token: this.session?.refresh_token,\n\t\t\t});\n\n\t\t\tObject.assign(this.session, await request.json());\n\n\t\t\tif (this.session.id_token) {\n\t\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t\t}\n\n\t\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\t\tif (this.accessToken && this.refreshToken && this.idTokenClaims) {\n\t\t\t\tthis.dispatchEvent('tokenRefreshed', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tthis.dispatchEvent('tokenRefreshFailed', [{ refreshToken: session.refresh_token! }]);\n\t\t}\n\t}\n\n\t/**\n\t * Revokes the current access or refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token revocation is complete.\n\t */\n\tasync revoke(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\t\tlet success = true;\n\n\t\ttry {\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'refresh_token',\n\t\t\t\t\ttoken: session.refresh_token,\n\t\t\t\t});\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'access_token',\n\t\t\t\t\ttoken: session.access_token,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch {\n\t\t\tsuccess = false;\n\t\t} finally {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.refresh_token, tokenTypeHint: 'refresh_token' }]);\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.access_token, tokenTypeHint: 'access_token' }]);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Exchanges an authorization code for access and refresh tokens.\n\t *\n\t * @param {Record<string, string>} [params={}] - Parameters containing the authorization code and other required values.\n\t * @returns {Promise<void>} - A promise that resolves when the token exchange is complete.\n\t *\n\t * @throws {Error} Throws an error if the authorization code is invalid or if there are issues with state, nonce, or tokens.\n\t */\n\tasync tokenExchange(params: Record<string, string> = {}): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tthis.session = new Session();\n\n\t\tObject.assign(this.session, params);\n\n\t\tif (this.session.error) {\n\t\t\tthrow new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t}\n\t\tif (!this.session.code) {\n\t\t\tthrow new Error('Invalid or missing code');\n\t\t}\n\n\t\tlet state: State;\n\n\t\ttry {\n\t\t\tconst serializedState = await this.storage.get(`sty.${this.session.state}`);\n\n\t\t\tif (!serializedState) {\n\t\t\t\tthrow new Error();\n\t\t\t}\n\n\t\t\tstate = State.fromSerializedData(serializedState);\n\n\t\t\tawait this.storage.delete(`sty.${this.session.state}`);\n\t\t} catch {\n\t\t\tthrow new Error('Invalid or missing state');\n\t\t}\n\n\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\tgrant_type: 'authorization_code',\n\t\t\tclient_id: this.options.clientId,\n\t\t\tredirect_uri: this.options.redirectUri,\n\t\t\tcode_verifier: state.codeVerifier,\n\t\t\tcode: this.session.code,\n\t\t});\n\n\t\tObject.assign(this.session, await request.json());\n\n\t\tif (this.session.id_token) {\n\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t}\n\n\t\tif (this.session.error) {\n\t\t\tthrow new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t}\n\t\tif (this.session.scope !== this.options.scopes?.join(' ')) {\n\t\t\tthrow new Error('Invalid scope');\n\t\t}\n\t\tif (this.session.claims?.nonce !== state.nonce) {\n\t\t\tthrow new Error('Invalid nonce');\n\t\t}\n\t\tif (this.session.claims?.iss !== (await this.metadata.issuer)) {\n\t\t\tthrow new Error('Invalid iss');\n\t\t}\n\t\tif (Array.isArray(this.session.claims?.aud) ? this.session.claims?.aud[0] !== this.options.clientId : this.session.claims?.aud !== this.options.clientId) {\n\t\t\tthrow new Error('Invalid aud');\n\t\t}\n\n\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\tif (this.accessToken && this.idTokenClaims) {\n\t\t\tthis.dispatchEvent('loggedIn', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t}\n\t}\n\n\t/**\n\t * Constructs the authorization URL for initiating the authorization flow.\n\t *\n\t * @param {ExtraRequestArgs} [params={}] - Additional params to include in the authorization URL.\n\t * @returns {Promise<URL>} - A promise that resolves to the constructed authorization URL.\n\t */\n\tasync getAuthorizationUrl(params: ExtraRequestArgs = {}): Promise<URL> {\n\t\tconst url = new URL(await this.metadata.authorizationEndpoint);\n\n\t\turl.searchParams.append('client_id', this.options.clientId);\n\t\turl.searchParams.append('redirect_uri', this.options.redirectUri);\n\t\turl.searchParams.append('response_type', this.options.responseType || 'code');\n\t\turl.searchParams.append('response_mode', this.options.responseMode || 'fragment');\n\t\turl.searchParams.append('scope', this.options.scopes?.join(' ') || '');\n\t\turl.searchParams.append('code_challenge_method', 'S256');\n\n\t\tif (params.prompt) {\n\t\t\turl.searchParams.append('prompt', params.prompt);\n\t\t}\n\t\tif (params.acrValues) {\n\t\t\turl.searchParams.append('acr_values', params.acrValues.join(' '));\n\t\t}\n\t\tif (params.loginHint) {\n\t\t\turl.searchParams.append('login_hint', params.loginHint);\n\t\t}\n\t\tif (params.uiLocales) {\n\t\t\turl.searchParams.append('ui_locales', params.uiLocales.join(' '));\n\t\t}\n\n\t\treturn url;\n\t}\n\n\tprotected async waitToInitialize(): Promise<void> {\n\t\tawait this.#initializationPromise;\n\t}\n\n\t/**\n\t * Sends a token request to the specified URL with the given data.\n\t *\n\t * @param {string} url - The URL to send the request to.\n\t * @param {Record<string, string>} [data={}] - The data to include in the request body.\n\t * @returns {Promise<HttpClientResponse<Session>>} - A promise that resolves to the response from the request.\n\t */\n\tasync sendTokenRequest(url: string, data: Record<string, string> = {}): Promise<HttpClientResponse<Session>> {\n\t\treturn this.httpClient.request<Session>(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded' },\n\t\t\tbody: new URLSearchParams(data).toString(),\n\t\t});\n\t}\n\n\t/**\n\t * Subscribes a callback function to an event.\n\t *\n\t * @param {T} eventName - The name of the event to subscribe to.\n\t * @param {(...params: Parameters<EventFunctions[T]>) => Promise<void> | void} callbackFn - The callback function to execute when the event is dispatched.\n\t * @returns {{ dispose: () => void }} - An object with a `dispose` method to remove the subscription.\n\t */\n\tsubscribeToEvent<T extends keyof EventFunctions>(\n\t\teventName: T,\n\t\tcallbackFn: (...params: Parameters<EventFunctions[T]>) => Promise<void> | void,\n\t): { dispose: () => void } {\n\t\teventCallbacks[eventName].add(callbackFn);\n\n\t\treturn {\n\t\t\tdispose: () => {\n\t\t\t\teventCallbacks[eventName].delete(callbackFn);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Dispatches an event to all subscribed callback functions.\n\t *\n\t * @param {T} eventName - The name of the event to dispatch.\n\t * @param {Parameters<EventFunctions[T]>} args - The arguments to pass to the callback functions.\n\t */\n\tprotected dispatchEvent<T extends keyof EventFunctions>(eventName: T, args: Parameters<EventFunctions[T]>): void {\n\t\tfor (const eventFn of eventCallbacks[eventName]) {\n\t\t\tvoid eventFn(...args);\n\t\t}\n\t}\n}\n"],"names":["eventCallbacks","BaseFlow","options","storage","httpClient","__privateAdd","_BaseFlow_instances","_initializationPromise","_isAuthenticatedPromise","_refreshInProgressState","__publicField","Metadata","__privateSet","__privateMethod","init_fn","_a","__privateGet","_b","timestamp","checkAuthentication_fn","params","session","url","request","jwt","success","Session","state","serializedState","State","_c","_d","_e","_f","data","eventName","callbackFn","args","eventFn","isAuthenticated"],"mappings":"ozBAQA,MAA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W,KAAK,aAAe,KAAK,eAC5C,KAAK,cAAc,gBAAiB,CAAC,CAAE,YAAa,KAAK,YAAa,aAAc,KAAK,aAAc,OAAQ,KAAK,aAAA,CAAe,CAAC,EAGjI,KAAK,aAAe,KAAK,oBAC5B,KAAK,cAAc,qBAAsB,CAAC,CAAE,YAAa,KAAK,YAAa,aAAc,KAAK,YAAA,CAAc,CAAC,CAC9G,EAOKP,EAAA,gBAAyC,CAC9C,IAAIoB,EAAkB,GAEtB,GAAI,CACH,MAAM,KAAK,iBAAA,CAAiB,MACrB,CAAA,CAKR,GAAI,KAAK,oBAAsB,KAAK,cAAgB,CAAC,KAAK,kBACzD,GAAI,CACH3B,EAAA,KAAKH,EAA0B,IAC/B,MAAM,KAAK,QAAA,CAAQ,MACZ,CAAA,QAER,CACCG,EAAA,KAAKH,EAA0B,GAAA,CAIjC,OAAK,KAAK,qBACT8B,EAAkB,IAGnB3B,EAAA,KAAKJ,EAA0B,MAExB+B,CAAA"}
1
+ {"version":3,"file":"BaseFlow.mjs","sources":["../../src/flows/BaseFlow.ts"],"sourcesContent":["import type { IdTokenClaims, SDKOptions, SDKStorage, EventFunctions, ExtraRequestArgs, LogoutParams, SDKHttpClient, HttpClientResponse } from '../types';\nimport { jwt } from '../utils/jwt';\nimport { timestamp } from '../utils/date';\nimport { Metadata } from '../utils/Metadata';\nimport { Session } from '../utils/Session';\nimport { State } from '../utils/State';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst eventCallbacks: Record<keyof EventFunctions, Set<(...args: Array<any>) => Promise<void> | void>> = {\n\taccessTokenExpired: new Set(),\n\tinit: new Set(),\n\tloggedIn: new Set(),\n\tloginInitiated: new Set(),\n\tlogoutInitiated: new Set(),\n\tsessionLoaded: new Set(),\n\ttokenRefreshed: new Set(),\n\ttokenRefreshFailed: new Set(),\n\ttokenRevoked: new Set(),\n\ttokenRevokeFailed: new Set(),\n};\n\n/**\n * An abstract base class that provides common functionality for different OIDC flows.\n *\n * @template Options - The options type extending `SDKOptions` used for configuring the flow.\n * @template URLHandlerParams - The options type extending `ExtraRequestArgs` used for URL handling.\n */\nexport abstract class BaseFlow<Options extends SDKOptions = SDKOptions, URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs> {\n\t/**\n\t * @ignore\n\t */\n\t#initializationPromise: Promise<void>;\n\n\t/**\n\t * @ignore\n\t */\n\t#isAuthenticatedPromise: Promise<boolean> | null = null;\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\t#refreshInProgressState = false;\n\n\t/**\n\t * An instance of the HTTP client used for making requests.\n\t *\n\t * @type {SDKHttpClient}\n\t */\n\thttpClient: SDKHttpClient;\n\n\t/**\n\t * The storage mechanism used to persist session data.\n\t *\n\t * @type {SDKStorage}\n\t */\n\tstorage: SDKStorage;\n\n\t/**\n\t * Metadata information about the authorization server.\n\t *\n\t * @type {Metadata}\n\t */\n\tmetadata: Metadata;\n\n\t/**\n\t * The current session data.\n\t *\n\t * @type {Session | null}\n\t */\n\tsession: Session | null = null;\n\n\t/**\n\t * The configuration options for the flow.\n\t *\n\t * @type {Options}\n\t */\n\toptions: Options;\n\n\t/**\n\t * Retrieves the ID token claims from the current session.\n\t *\n\t * @type {IdTokenClaims | null | undefined}\n\t */\n\tget idTokenClaims(): IdTokenClaims | null | undefined {\n\t\treturn this.session?.claims;\n\t}\n\n\t/**\n\t * Retrieves the access token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget accessToken(): string | null | undefined {\n\t\treturn this.session?.access_token;\n\t}\n\n\t/**\n\t * Retrieves the refresh token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget refreshToken(): string | null | undefined {\n\t\treturn this.session?.refresh_token;\n\t}\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\tget refreshInProgress(): boolean {\n\t\treturn this.#refreshInProgressState;\n\t}\n\n\t/**\n\t * Determines if the access token has expired.\n\t *\n\t * @type {boolean}\n\t */\n\tget accessTokenExpired(): boolean {\n\t\treturn !this.session?.access_token || !this.session?.expires_at || this.session.expires_at <= timestamp();\n\t}\n\n\t/**\n\t * Retrieves the access token expiration date.\n\t *\n\t * @type {number | null | undefined}\n\t */\n\tget accessTokenExpirationDate(): number | null | undefined {\n\t\treturn this.session?.expires_at;\n\t}\n\n\t/**\n\t * Checks if the user is authenticated by evaluating the presence of access or refresh tokens.\n\t *\n\t * @returns {Promise<boolean>} - A promise that resolves to `true` if the user is authenticated, otherwise `false`.\n\t */\n\tget isAuthenticated(): Promise<boolean> {\n\t\tif (this.#isAuthenticatedPromise) {\n\t\t\treturn this.#isAuthenticatedPromise;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = this.#checkAuthentication();\n\n\t\treturn this.#isAuthenticatedPromise;\n\t}\n\n\t/**\n\t * Checks authentication status without attempting token refresh.\n\t * Useful when you want to avoid side effects.\n\t *\n\t * @returns {boolean} - Returns `true` if the user has a valid, non-expired access token.\n\t */\n\tget isAuthenticatedSync(): boolean {\n\t\treturn Boolean(this.session?.access_token && !this.accessTokenExpired);\n\t}\n\n\t/**\n\t * Constructs a new instance of the `BaseFlow` class.\n\t *\n\t * @param {Options} options - Configuration options for the flow.\n\t * @param {SDKStorage} storage - Storage mechanism for session data.\n\t *\n\t * @throws {Error} Throws an error if required options are missing or invalid.\n\t */\n\tconstructor(options: Options, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.issuer) {\n\t\t\tthrow new Error('Missing option: issuer');\n\t\t}\n\t\tif (!options.clientId) {\n\t\t\tthrow new Error('Missing option: clientId');\n\t\t}\n\t\tif (!options.redirectUri) {\n\t\t\tthrow new Error('Missing option: redirectUri');\n\t\t}\n\t\tif (!options.urlHandler) {\n\t\t\tthrow new Error('Missing option: urlHandler');\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\tthrow new Error('Missing option: callbackHandler');\n\t\t}\n\t\tif (options.scopes && !Array.isArray(options.scopes)) {\n\t\t\tthrow new Error('Invalid option: scopes');\n\t\t}\n\n\t\tif (!options.scopes) {\n\t\t\toptions.scopes = ['openid'];\n\t\t}\n\t\tif (!options.responseType) {\n\t\t\toptions.responseType = 'code';\n\t\t}\n\t\tif (!options.responseMode) {\n\t\t\toptions.responseMode = 'query';\n\t\t}\n\t\tif (!options.storageTokenName) {\n\t\t\toptions.storageTokenName = 'sty.session';\n\t\t}\n\n\t\tthis.options = options;\n\t\tthis.storage = storage;\n\t\tthis.httpClient = httpClient;\n\t\tthis.metadata = new Metadata(this, new URL('/.well-known/openid-configuration', options.issuer).toString());\n\n\t\tthis.#initializationPromise = this.#init();\n\t}\n\n\t/**\n\t * Initializes the flow by loading the session from storage and setting up event listeners.\n\t * @ignore\n\t */\n\tasync #init() {\n\t\tthis.session = Session.load(await this.storage.get(this.options.storageTokenName!));\n\n\t\tthis.dispatchEvent('init', []);\n\n\t\tif (this.session && this.accessToken && this.idTokenClaims) {\n\t\t\tthis.dispatchEvent('sessionLoaded', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t}\n\n\t\tif (this.accessToken && this.accessTokenExpired) {\n\t\t\tthis.dispatchEvent('accessTokenExpired', [{ accessToken: this.accessToken, refreshToken: this.refreshToken }]);\n\t\t}\n\t}\n\n\t/**\n\t * Internal method to check authentication status with proper error handling.\n\t * @ignore\n\t */\n\tasync #checkAuthentication(): Promise<boolean> {\n\t\tlet isAuthenticated = false;\n\n\t\ttry {\n\t\t\tawait this.waitToInitialize();\n\t\t} catch {\n\t\t\t// Initialization failed\n\t\t}\n\n\t\t// Attempt to refresh the token if it has expired\n\t\tif (this.accessTokenExpired && this.refreshToken && !this.refreshInProgress) {\n\t\t\ttry {\n\t\t\t\tthis.#refreshInProgressState = true;\n\t\t\t\tawait this.refresh();\n\t\t\t} catch {\n\t\t\t\t// Token refresh failed - if you want to log errors use the tokenRefreshFailed event\n\t\t\t} finally {\n\t\t\t\tthis.#refreshInProgressState = false;\n\t\t\t}\n\t\t}\n\n\t\tif (!this.accessTokenExpired) {\n\t\t\tisAuthenticated = true;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = null;\n\n\t\treturn isAuthenticated;\n\t}\n\n\t/**\n\t * Initiates the login process. Subclasses should implement this method to handle the specific login flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during login.\n\t * @returns {Promise<void>} - A promise that resolves when the login process is complete.\n\t */\n\tabstract login(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Registers a new user. Subclasses should implement this method to handle the specific registration flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during registration.\n\t * @returns {Promise<void>} - A promise that resolves when the registration process is complete.\n\t */\n\tabstract register(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Initiates the entry process.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<void>} A promise that resolves when the entry process completes.\n\t */\n\tabstract entry(url?: string): unknown;\n\n\t/**\n\t * Logs out the current user and optionally redirects to a post-logout URI.\n\t *\n\t * @param {URLHandlerParams & LogoutParams} [params] - Additional params for handling URLs during logout.\n\t * @returns {Promise<void>} - A promise that resolves when the logout process is complete.\n\t */\n\tasync logout(params?: URLHandlerParams & LogoutParams): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tthrow new Error('URL handler is not defined. Please provide a valid URL handler function in the SDK options.');\n\t\t}\n\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\n\t\tif (!session?.id_token) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.storage.delete(this.options.storageTokenName!);\n\t\tthis.session = null;\n\n\t\tconst url = new URL(await this.metadata.endSessionEndpoint);\n\n\t\turl.searchParams.append('id_token_hint', session?.id_token);\n\n\t\tif (params?.postLogoutRedirectUri) {\n\t\t\turl.searchParams.append('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\t\t}\n\n\t\tthis.dispatchEvent('logoutInitiated', [{ idToken: session.id_token, claims: session.claims! }]);\n\n\t\ttry {\n\t\t\tawait this.options.urlHandler(url.toString(), params as URLHandlerParams);\n\t\t} catch {}\n\t}\n\n\t/**\n\t * Refreshes the access token using the refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token refresh is complete.\n\t *\n\t * @throws {Error} Throws an error if the refresh fails.\n\t */\n\tasync refresh(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tif (typeof this.session?.refresh_token !== 'string') {\n\t\t\treturn;\n\t\t}\n\n\t\tconst session = this.session;\n\n\t\ttry {\n\t\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\trefresh_token: this.session?.refresh_token,\n\t\t\t});\n\n\t\t\tObject.assign(this.session, await request.json());\n\n\t\t\tif (this.session.id_token) {\n\t\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t\t}\n\n\t\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\t\tif (this.accessToken && this.refreshToken && this.idTokenClaims) {\n\t\t\t\tthis.dispatchEvent('tokenRefreshed', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tthis.dispatchEvent('tokenRefreshFailed', [{ refreshToken: session.refresh_token! }]);\n\t\t}\n\t}\n\n\t/**\n\t * Revokes the current access or refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token revocation is complete.\n\t */\n\tasync revoke(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\t\tlet success = true;\n\n\t\ttry {\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'refresh_token',\n\t\t\t\t\ttoken: session.refresh_token,\n\t\t\t\t});\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'access_token',\n\t\t\t\t\ttoken: session.access_token,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch {\n\t\t\tsuccess = false;\n\t\t} finally {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.refresh_token, tokenTypeHint: 'refresh_token' }]);\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.access_token, tokenTypeHint: 'access_token' }]);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Exchanges an authorization code for access and refresh tokens.\n\t *\n\t * @param {Record<string, string>} [params={}] - Parameters containing the authorization code and other required values.\n\t * @returns {Promise<void>} - A promise that resolves when the token exchange is complete.\n\t *\n\t * @throws {Error} Throws an error if the authorization code is invalid or if there are issues with state, nonce, or tokens.\n\t */\n\tasync tokenExchange(params: Record<string, string> = {}): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tthis.session = new Session();\n\n\t\tObject.assign(this.session, params);\n\n\t\tif (this.session.error) {\n\t\t\tthrow new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t}\n\t\tif (!this.session.code) {\n\t\t\tthrow new Error('Invalid or missing code');\n\t\t}\n\n\t\tlet state: State;\n\n\t\ttry {\n\t\t\tconst serializedState = await this.storage.get(`sty.${this.session.state}`);\n\n\t\t\tif (!serializedState) {\n\t\t\t\tthrow new Error();\n\t\t\t}\n\n\t\t\tstate = State.fromSerializedData(serializedState);\n\n\t\t\tawait this.storage.delete(`sty.${this.session.state}`);\n\t\t} catch {\n\t\t\tthrow new Error('Invalid or missing state');\n\t\t}\n\n\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\tgrant_type: 'authorization_code',\n\t\t\tclient_id: this.options.clientId,\n\t\t\tredirect_uri: this.options.redirectUri,\n\t\t\tcode_verifier: state.codeVerifier,\n\t\t\tcode: this.session.code,\n\t\t});\n\n\t\tObject.assign(this.session, await request.json());\n\n\t\tif (this.session.id_token) {\n\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t}\n\n\t\tif (this.session.error) {\n\t\t\tthrow new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t}\n\t\tif (this.session.scope !== this.options.scopes?.join(' ')) {\n\t\t\tthrow new Error('Invalid scope');\n\t\t}\n\t\tif (this.session.claims?.nonce !== state.nonce) {\n\t\t\tthrow new Error('Invalid nonce');\n\t\t}\n\t\tif (this.session.claims?.iss !== (await this.metadata.issuer)) {\n\t\t\tthrow new Error('Invalid iss');\n\t\t}\n\t\tif (Array.isArray(this.session.claims?.aud) ? this.session.claims?.aud[0] !== this.options.clientId : this.session.claims?.aud !== this.options.clientId) {\n\t\t\tthrow new Error('Invalid aud');\n\t\t}\n\n\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\tif (this.accessToken && this.idTokenClaims) {\n\t\t\tthis.dispatchEvent('loggedIn', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t}\n\t}\n\n\t/**\n\t * Constructs the authorization URL for initiating the authorization flow.\n\t *\n\t * @param {ExtraRequestArgs} [params={}] - Additional params to include in the authorization URL.\n\t * @returns {Promise<URL>} - A promise that resolves to the constructed authorization URL.\n\t */\n\tasync getAuthorizationUrl(params: ExtraRequestArgs = {}): Promise<URL> {\n\t\tconst url = new URL(await this.metadata.authorizationEndpoint);\n\n\t\turl.searchParams.append('client_id', this.options.clientId);\n\t\turl.searchParams.append('redirect_uri', this.options.redirectUri);\n\t\turl.searchParams.append('response_type', this.options.responseType || 'code');\n\t\turl.searchParams.append('response_mode', this.options.responseMode || 'fragment');\n\t\turl.searchParams.append('scope', this.options.scopes?.join(' ') || '');\n\t\turl.searchParams.append('code_challenge_method', 'S256');\n\n\t\tif (params.prompt) {\n\t\t\turl.searchParams.append('prompt', params.prompt);\n\t\t}\n\t\tif (params.acrValues) {\n\t\t\turl.searchParams.append('acr_values', params.acrValues.join(' '));\n\t\t}\n\t\tif (params.loginHint) {\n\t\t\turl.searchParams.append('login_hint', params.loginHint);\n\t\t}\n\t\tif (params.uiLocales) {\n\t\t\turl.searchParams.append('ui_locales', params.uiLocales.join(' '));\n\t\t}\n\n\t\treturn url;\n\t}\n\n\tprotected async waitToInitialize(): Promise<void> {\n\t\tawait this.#initializationPromise;\n\t}\n\n\t/**\n\t * Sends a token request to the specified URL with the given data.\n\t *\n\t * @param {string} url - The URL to send the request to.\n\t * @param {Record<string, string>} [data={}] - The data to include in the request body.\n\t * @returns {Promise<HttpClientResponse<Session>>} - A promise that resolves to the response from the request.\n\t */\n\tasync sendTokenRequest(url: string, data: Record<string, string> = {}): Promise<HttpClientResponse<Session>> {\n\t\treturn this.httpClient.request<Session>(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded' },\n\t\t\tbody: new URLSearchParams(data).toString(),\n\t\t});\n\t}\n\n\t/**\n\t * Subscribes a callback function to an event.\n\t *\n\t * @param {T} eventName - The name of the event to subscribe to.\n\t * @param {(...params: Parameters<EventFunctions[T]>) => Promise<void> | void} callbackFn - The callback function to execute when the event is dispatched.\n\t * @returns {{ dispose: () => void }} - An object with a `dispose` method to remove the subscription.\n\t */\n\tsubscribeToEvent<T extends keyof EventFunctions>(\n\t\teventName: T,\n\t\tcallbackFn: (...params: Parameters<EventFunctions[T]>) => Promise<void> | void,\n\t): { dispose: () => void } {\n\t\teventCallbacks[eventName].add(callbackFn);\n\n\t\treturn {\n\t\t\tdispose: () => {\n\t\t\t\teventCallbacks[eventName].delete(callbackFn);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Dispatches an event to all subscribed callback functions.\n\t *\n\t * @param {T} eventName - The name of the event to dispatch.\n\t * @param {Parameters<EventFunctions[T]>} args - The arguments to pass to the callback functions.\n\t */\n\tprotected dispatchEvent<T extends keyof EventFunctions>(eventName: T, args: Parameters<EventFunctions[T]>): void {\n\t\tfor (const eventFn of eventCallbacks[eventName]) {\n\t\t\tvoid eventFn(...args);\n\t\t}\n\t}\n}\n"],"names":["eventCallbacks","BaseFlow","#initializationPromise","#isAuthenticatedPromise","#refreshInProgressState","timestamp","#checkAuthentication","options","storage","httpClient","Metadata","#init","Session","isAuthenticated","params","session","url","request","jwt","success","state","serializedState","State","data","eventName","callbackFn","args","eventFn"],"mappings":"2RAQA,MAAMA,EAAmG,CACxG,uBAAwB,IACxB,SAAU,IACV,aAAc,IACd,mBAAoB,IACpB,oBAAqB,IACrB,kBAAmB,IACnB,mBAAoB,IACpB,uBAAwB,IACxB,iBAAkB,IAClB,sBAAuB,GACxB,EAQO,MAAeC,CAAgH,CAIrIC,GAKAC,GAAmD,KAOnDC,GAA0B,GAO1B,WAOA,QAOA,SAOA,QAA0B,KAO1B,QAOA,IAAI,eAAkD,CACrD,OAAO,KAAK,SAAS,MACtB,CAOA,IAAI,aAAyC,CAC5C,OAAO,KAAK,SAAS,YACtB,CAOA,IAAI,cAA0C,CAC7C,OAAO,KAAK,SAAS,aACtB,CAOA,IAAI,mBAA6B,CAChC,OAAO,KAAKA,EACb,CAOA,IAAI,oBAA8B,CACjC,MAAO,CAAC,KAAK,SAAS,cAAgB,CAAC,KAAK,SAAS,YAAc,KAAK,QAAQ,YAAcC,EAAA,CAC/F,CAOA,IAAI,2BAAuD,CAC1D,OAAO,KAAK,SAAS,UACtB,CAOA,IAAI,iBAAoC,CACvC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EAG1DE,CACR,CAEA,MAAgB,kBAAkC,CACjD,MAAM,KAAKd,EACZ,CASA,MAAM,iBAAiBc,EAAaO,EAA+B,GAA0C,CAC5G,OAAO,KAAK,WAAW,QAAiBP,EAAK,CAC5C,OAAQ,OACR,QAAS,CAAE,eAAgB,mCAAA,EAC3B,KAAM,IAAI,gBAAgBO,CAAI,EAAE,SAAA,CAAS,CACzC,CACF,CASA,iBACCC,EACAC,EAC0B,CAC1B,OAAAzB,EAAewB,CAAS,EAAE,IAAIC,CAAU,EAEjC,CACN,QAAS,IAAM,CACdzB,EAAewB,CAAS,EAAE,OAAOC,CAAU,CAC5C,CAAA,CAEF,CAQU,cAA8CD,EAAcE,EAA2C,CAChH,UAAWC,KAAW3B,EAAewB,CAAS,EACxCG,EAAQ,GAAGD,CAAI,CAEtB,CACD"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("../utils/handlers.cjs"),l=require("../utils/NativeFlowHandler.cjs"),c=require("./BaseFlow.cjs");require("../utils/State.cjs");require("../utils/crypto.cjs");require("../utils/base64Url.cjs");require("../utils/date.cjs");require("../utils/errors.cjs");require("../utils/jwt.cjs");require("../utils/Metadata.cjs");require("../utils/Session.cjs");class d extends c.BaseFlow{constructor(e,r,t){e.urlHandler||(e.urlHandler=o.redirectUrlHandler),e.callbackHandler||(e.callbackHandler=o.redirectCallbackHandler),super(e,r,t)}login(e={}){return this.dispatchEvent("loginInitiated",[]),new l.NativeFlowHandler(this,e)}register(e={}){return e.prompt="create",this.login(e)}async entry(e){var n;e||(e=(n=globalThis.window)==null?void 0:n.location.href);const r=new URL(e);r.searchParams.append("sdk","web"),r.searchParams.append("client_id",this.options.clientId),r.searchParams.append("redirect_uri",this.options.redirectUri);const t=await this.httpClient.request(`${this.options.issuer}/provider/flow/entry?${r.searchParams.toString()}`);if(!t.ok){if(t.status===400){const i=await t.json();let a="Entry request failed with status 400";throw typeof i=="object"&&(i.error?a=`${i.error}: ${i.error_description}`:i.errorKey&&(a=i.errorKey)),new Error(a)}throw new Error(`Entry request failed with status ${t.status}`)}const s=new URL(await t.text()).searchParams.get("session_id");if(!s)throw new Error("Session ID not found in entry response");return s}async handleCallback(e){var r;if(typeof this.options.callbackHandler!="function")throw new Error("Callback handler is not defined. Please provide a valid callback handler function in the SDK options.");e||(e=(r=globalThis.window)==null?void 0:r.location.href),await this.tokenExchange(await this.options.callbackHandler(e,this.options.responseMode||"fragment"))}}exports.NativeFlow=d;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("../utils/handlers.cjs"),o=require("../utils/NativeFlowHandler.cjs"),l=require("./BaseFlow.cjs");require("../utils/State.cjs");require("../utils/crypto.cjs");require("../utils/base64Url.cjs");require("../utils/date.cjs");require("../utils/errors.cjs");require("../utils/jwt.cjs");require("../utils/Metadata.cjs");require("../utils/Session.cjs");class c extends l.BaseFlow{constructor(e,t,r){e.urlHandler||(e.urlHandler=n.redirectUrlHandler),e.callbackHandler||(e.callbackHandler=n.redirectCallbackHandler),super(e,t,r)}login(e={}){return this.dispatchEvent("loginInitiated",[]),new o.NativeFlowHandler(this,e)}register(e={}){return e.prompt="create",this.login(e)}async entry(e){e||(e=globalThis.window?.location.href);const t=new URL(e);t.searchParams.append("sdk","web"),t.searchParams.append("client_id",this.options.clientId),t.searchParams.append("redirect_uri",this.options.redirectUri);const r=await this.httpClient.request(`${this.options.issuer}/provider/flow/entry?${t.searchParams.toString()}`);if(!r.ok){if(r.status===400){const i=await r.json();let a="Entry request failed with status 400";throw typeof i=="object"&&(i.error?a=`${i.error}: ${i.error_description}`:i.errorKey&&(a=i.errorKey)),new Error(a)}throw new Error(`Entry request failed with status ${r.status}`)}const s=new URL(await r.text()).searchParams.get("session_id");if(!s)throw new Error("Session ID not found in entry response");return s}async handleCallback(e){if(typeof this.options.callbackHandler!="function")throw new Error("Callback handler is not defined. Please provide a valid callback handler function in the SDK options.");e||(e=globalThis.window?.location.href),await this.tokenExchange(await this.options.callbackHandler(e,this.options.responseMode||"fragment"))}}exports.NativeFlow=c;
2
2
  //# sourceMappingURL=NativeFlow.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"NativeFlow.cjs","sources":["../../src/flows/NativeFlow.ts"],"sourcesContent":["import type { SDKOptions, NativeParams, SDKStorage, SDKHttpClient } from '../types';\nimport { redirectUrlHandler, redirectCallbackHandler } from '../utils/handlers';\nimport { NativeFlowHandler } from '../utils/NativeFlowHandler';\nimport { BaseFlow } from './BaseFlow';\n\nexport class NativeFlow extends BaseFlow<SDKOptions, NativeParams> {\n\tconstructor(options: SDKOptions, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.urlHandler) {\n\t\t\toptions.urlHandler = redirectUrlHandler;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\toptions.callbackHandler = redirectCallbackHandler;\n\t\t}\n\n\t\tsuper(options, storage, httpClient);\n\t}\n\n\t/**\n\t * Initiates the login process via native UI.\n\t * @param {NativeParams} [params={}] Optional parameters for native configuration.\n\t * @returns {NativeFlowHandler} Returns with a native login handler.\n\t */\n\tlogin(params: NativeParams = {}): NativeFlowHandler {\n\t\tthis.dispatchEvent('loginInitiated', []);\n\n\t\treturn new NativeFlowHandler(this, params);\n\t}\n\n\t/**\n\t * Initiates the registration process via native UI.\n\t * @param {NativeParams} [params={}] Optional parameters for native configuration.\n\t * @returns {NativeFlowHandler} Returns with a native login handler.\n\t */\n\tregister(params: NativeParams = {}): NativeFlowHandler {\n\t\tparams.prompt = 'create';\n\n\t\treturn this.login(params);\n\t}\n\n\t/**\n\t * Initiates the entry process via a redirect.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<string>} A promise that resolves to the session ID.\n\t */\n\tasync entry(url?: string): Promise<string> {\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tconst entryUrl = new URL(url);\n\t\tentryUrl.searchParams.append('sdk', 'web');\n\t\tentryUrl.searchParams.append('client_id', this.options.clientId);\n\t\tentryUrl.searchParams.append('redirect_uri', this.options.redirectUri);\n\n\t\tconst response = await this.httpClient.request<string | Record<string, string>>(\n\t\t\t`${this.options.issuer}/provider/flow/entry?${entryUrl.searchParams.toString()}`,\n\t\t);\n\n\t\tif (!response.ok) {\n\t\t\tif (response.status === 400) {\n\t\t\t\tconst data = await response.json();\n\t\t\t\tlet message = 'Entry request failed with status 400';\n\n\t\t\t\tif (typeof data === 'object') {\n\t\t\t\t\tif (data.error) {\n\t\t\t\t\t\tmessage = `${data.error}: ${data.error_description}`;\n\t\t\t\t\t} else if (data.errorKey) {\n\t\t\t\t\t\tmessage = data.errorKey;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthrow new Error(message);\n\t\t\t}\n\n\t\t\tthrow new Error(`Entry request failed with status ${response.status}`);\n\t\t}\n\n\t\tconst sessionId = new URL(await response.text()).searchParams.get('session_id');\n\n\t\tif (!sessionId) {\n\t\t\tthrow new Error('Session ID not found in entry response');\n\t\t}\n\n\t\treturn sessionId;\n\t}\n\n\t/**\n\t * Handles the callback after login or registration via a redirect.\n\t * @param {string} [url] The URL to handle the callback from. Defaults to the current window location.\n\t * @returns {Promise<void>} A promise that resolves when the callback is handled.\n\t */\n\tasync handleCallback(url?: string): Promise<void> {\n\t\tif (typeof this.options.callbackHandler !== 'function') {\n\t\t\tthrow new Error('Callback handler is not defined. Please provide a valid callback handler function in the SDK options.');\n\t\t}\n\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tawait this.tokenExchange((await this.options.callbackHandler(url, this.options.responseMode || 'fragment')) as Record<string, string>);\n\t}\n}\n"],"names":["NativeFlow","BaseFlow","options","storage","httpClient","redirectUrlHandler","redirectCallbackHandler","params","NativeFlowHandler","url","_a","entryUrl","response","data","message","sessionId"],"mappings":"ybAKO,MAAMA,UAAmBC,EAAAA,QAAmC,CAClE,YAAYC,EAAqBC,EAA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,OAAO,KAAK,QAAQ,iBAAoB,WAC3C,MAAM,IAAI,MAAM,uGAAuG,EAGnHA,IACJA,GAAMC,EAAA,WAAW,SAAX,YAAAA,EAAmB,SAAS,MAGnC,MAAM,KAAK,cAAe,MAAM,KAAK,QAAQ,gBAAgBD,EAAK,KAAK,QAAQ,cAAgB,UAAU,CAA4B,CAAA,CAEvI"}
1
+ {"version":3,"file":"NativeFlow.cjs","sources":["../../src/flows/NativeFlow.ts"],"sourcesContent":["import type { SDKOptions, NativeParams, SDKStorage, SDKHttpClient } from '../types';\nimport { redirectUrlHandler, redirectCallbackHandler } from '../utils/handlers';\nimport { NativeFlowHandler } from '../utils/NativeFlowHandler';\nimport { BaseFlow } from './BaseFlow';\n\nexport class NativeFlow extends BaseFlow<SDKOptions, NativeParams> {\n\tconstructor(options: SDKOptions, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.urlHandler) {\n\t\t\toptions.urlHandler = redirectUrlHandler;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\toptions.callbackHandler = redirectCallbackHandler;\n\t\t}\n\n\t\tsuper(options, storage, httpClient);\n\t}\n\n\t/**\n\t * Initiates the login process via native UI.\n\t * @param {NativeParams} [params={}] Optional parameters for native configuration.\n\t * @returns {NativeFlowHandler} Returns with a native login handler.\n\t */\n\tlogin(params: NativeParams = {}): NativeFlowHandler {\n\t\tthis.dispatchEvent('loginInitiated', []);\n\n\t\treturn new NativeFlowHandler(this, params);\n\t}\n\n\t/**\n\t * Initiates the registration process via native UI.\n\t * @param {NativeParams} [params={}] Optional parameters for native configuration.\n\t * @returns {NativeFlowHandler} Returns with a native login handler.\n\t */\n\tregister(params: NativeParams = {}): NativeFlowHandler {\n\t\tparams.prompt = 'create';\n\n\t\treturn this.login(params);\n\t}\n\n\t/**\n\t * Initiates the entry process via a redirect.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<string>} A promise that resolves to the session ID.\n\t */\n\tasync entry(url?: string): Promise<string> {\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tconst entryUrl = new URL(url);\n\t\tentryUrl.searchParams.append('sdk', 'web');\n\t\tentryUrl.searchParams.append('client_id', this.options.clientId);\n\t\tentryUrl.searchParams.append('redirect_uri', this.options.redirectUri);\n\n\t\tconst response = await this.httpClient.request<string | Record<string, string>>(\n\t\t\t`${this.options.issuer}/provider/flow/entry?${entryUrl.searchParams.toString()}`,\n\t\t);\n\n\t\tif (!response.ok) {\n\t\t\tif (response.status === 400) {\n\t\t\t\tconst data = await response.json();\n\t\t\t\tlet message = 'Entry request failed with status 400';\n\n\t\t\t\tif (typeof data === 'object') {\n\t\t\t\t\tif (data.error) {\n\t\t\t\t\t\tmessage = `${data.error}: ${data.error_description}`;\n\t\t\t\t\t} else if (data.errorKey) {\n\t\t\t\t\t\tmessage = data.errorKey;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthrow new Error(message);\n\t\t\t}\n\n\t\t\tthrow new Error(`Entry request failed with status ${response.status}`);\n\t\t}\n\n\t\tconst sessionId = new URL(await response.text()).searchParams.get('session_id');\n\n\t\tif (!sessionId) {\n\t\t\tthrow new Error('Session ID not found in entry response');\n\t\t}\n\n\t\treturn sessionId;\n\t}\n\n\t/**\n\t * Handles the callback after login or registration via a redirect.\n\t * @param {string} [url] The URL to handle the callback from. Defaults to the current window location.\n\t * @returns {Promise<void>} A promise that resolves when the callback is handled.\n\t */\n\tasync handleCallback(url?: string): Promise<void> {\n\t\tif (typeof this.options.callbackHandler !== 'function') {\n\t\t\tthrow new Error('Callback handler is not defined. Please provide a valid callback handler function in the SDK options.');\n\t\t}\n\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tawait this.tokenExchange((await this.options.callbackHandler(url, this.options.responseMode || 'fragment')) as Record<string, string>);\n\t}\n}\n"],"names":["NativeFlow","BaseFlow","options","storage","httpClient","redirectUrlHandler","redirect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EACJ,MAAM,IAAI,MAAM,wCAAwC,EAGzD,OAAOA,CACR,CAOA,MAAM,eAAeL,EAA6B,CACjD,GAAI,OAAO,KAAK,QAAQ,iBAAoB,WAC3C,MAAM,IAAI,MAAM,uGAAuG,EAGnHA,IACJA,EAAM,WAAW,QAAQ,SAAS,MAGnC,MAAM,KAAK,cAAe,MAAM,KAAK,QAAQ,gBAAgBA,EAAK,KAAK,QAAQ,cAAgB,UAAU,CAA4B,CACtI,CACD"}
@@ -1,2 +1,2 @@
1
- import{redirectUrlHandler as s,redirectCallbackHandler as l}from"../utils/handlers.mjs";import{NativeFlowHandler as c}from"../utils/NativeFlowHandler.mjs";import{BaseFlow as d}from"./BaseFlow.mjs";import"../utils/State.mjs";import"../utils/crypto.mjs";import"../utils/base64Url.mjs";import"../utils/date.mjs";import"../utils/errors.mjs";import"../utils/jwt.mjs";import"../utils/Metadata.mjs";import"../utils/Session.mjs";class v extends d{constructor(r,e,t){r.urlHandler||(r.urlHandler=s),r.callbackHandler||(r.callbackHandler=l),super(r,e,t)}login(r={}){return this.dispatchEvent("loginInitiated",[]),new c(this,r)}register(r={}){return r.prompt="create",this.login(r)}async entry(r){var n;r||(r=(n=globalThis.window)==null?void 0:n.location.href);const e=new URL(r);e.searchParams.append("sdk","web"),e.searchParams.append("client_id",this.options.clientId),e.searchParams.append("redirect_uri",this.options.redirectUri);const t=await this.httpClient.request(`${this.options.issuer}/provider/flow/entry?${e.searchParams.toString()}`);if(!t.ok){if(t.status===400){const i=await t.json();let a="Entry request failed with status 400";throw typeof i=="object"&&(i.error?a=`${i.error}: ${i.error_description}`:i.errorKey&&(a=i.errorKey)),new Error(a)}throw new Error(`Entry request failed with status ${t.status}`)}const o=new URL(await t.text()).searchParams.get("session_id");if(!o)throw new Error("Session ID not found in entry response");return o}async handleCallback(r){var e;if(typeof this.options.callbackHandler!="function")throw new Error("Callback handler is not defined. Please provide a valid callback handler function in the SDK options.");r||(r=(e=globalThis.window)==null?void 0:e.location.href),await this.tokenExchange(await this.options.callbackHandler(r,this.options.responseMode||"fragment"))}}export{v as NativeFlow};
1
+ import{redirectUrlHandler as n,redirectCallbackHandler as s}from"../utils/handlers.mjs";import{NativeFlowHandler as l}from"../utils/NativeFlowHandler.mjs";import{BaseFlow as c}from"./BaseFlow.mjs";import"../utils/State.mjs";import"../utils/crypto.mjs";import"../utils/base64Url.mjs";import"../utils/date.mjs";import"../utils/errors.mjs";import"../utils/jwt.mjs";import"../utils/Metadata.mjs";import"../utils/Session.mjs";class E extends c{constructor(r,t,e){r.urlHandler||(r.urlHandler=n),r.callbackHandler||(r.callbackHandler=s),super(r,t,e)}login(r={}){return this.dispatchEvent("loginInitiated",[]),new l(this,r)}register(r={}){return r.prompt="create",this.login(r)}async entry(r){r||(r=globalThis.window?.location.href);const t=new URL(r);t.searchParams.append("sdk","web"),t.searchParams.append("client_id",this.options.clientId),t.searchParams.append("redirect_uri",this.options.redirectUri);const e=await this.httpClient.request(`${this.options.issuer}/provider/flow/entry?${t.searchParams.toString()}`);if(!e.ok){if(e.status===400){const i=await e.json();let a="Entry request failed with status 400";throw typeof i=="object"&&(i.error?a=`${i.error}: ${i.error_description}`:i.errorKey&&(a=i.errorKey)),new Error(a)}throw new Error(`Entry request failed with status ${e.status}`)}const o=new URL(await e.text()).searchParams.get("session_id");if(!o)throw new Error("Session ID not found in entry response");return o}async handleCallback(r){if(typeof this.options.callbackHandler!="function")throw new Error("Callback handler is not defined. Please provide a valid callback handler function in the SDK options.");r||(r=globalThis.window?.location.href),await this.tokenExchange(await this.options.callbackHandler(r,this.options.responseMode||"fragment"))}}export{E as NativeFlow};
2
2
  //# sourceMappingURL=NativeFlow.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"NativeFlow.mjs","sources":["../../src/flows/NativeFlow.ts"],"sourcesContent":["import type { SDKOptions, NativeParams, SDKStorage, SDKHttpClient } from '../types';\nimport { redirectUrlHandler, redirectCallbackHandler } from '../utils/handlers';\nimport { NativeFlowHandler } from '../utils/NativeFlowHandler';\nimport { BaseFlow } from './BaseFlow';\n\nexport class NativeFlow extends BaseFlow<SDKOptions, NativeParams> {\n\tconstructor(options: SDKOptions, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.urlHandler) {\n\t\t\toptions.urlHandler = redirectUrlHandler;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\toptions.callbackHandler = redirectCallbackHandler;\n\t\t}\n\n\t\tsuper(options, storage, httpClient);\n\t}\n\n\t/**\n\t * Initiates the login process via native UI.\n\t * @param {NativeParams} [params={}] Optional parameters for native configuration.\n\t * @returns {NativeFlowHandler} Returns with a native login handler.\n\t */\n\tlogin(params: NativeParams = {}): NativeFlowHandler {\n\t\tthis.dispatchEvent('loginInitiated', []);\n\n\t\treturn new NativeFlowHandler(this, params);\n\t}\n\n\t/**\n\t * Initiates the registration process via native UI.\n\t * @param {NativeParams} [params={}] Optional parameters for native configuration.\n\t * @returns {NativeFlowHandler} Returns with a native login handler.\n\t */\n\tregister(params: NativeParams = {}): NativeFlowHandler {\n\t\tparams.prompt = 'create';\n\n\t\treturn this.login(params);\n\t}\n\n\t/**\n\t * Initiates the entry process via a redirect.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<string>} A promise that resolves to the session ID.\n\t */\n\tasync entry(url?: string): Promise<string> {\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tconst entryUrl = new URL(url);\n\t\tentryUrl.searchParams.append('sdk', 'web');\n\t\tentryUrl.searchParams.append('client_id', this.options.clientId);\n\t\tentryUrl.searchParams.append('redirect_uri', this.options.redirectUri);\n\n\t\tconst response = await this.httpClient.request<string | Record<string, string>>(\n\t\t\t`${this.options.issuer}/provider/flow/entry?${entryUrl.searchParams.toString()}`,\n\t\t);\n\n\t\tif (!response.ok) {\n\t\t\tif (response.status === 400) {\n\t\t\t\tconst data = await response.json();\n\t\t\t\tlet message = 'Entry request failed with status 400';\n\n\t\t\t\tif (typeof data === 'object') {\n\t\t\t\t\tif (data.error) {\n\t\t\t\t\t\tmessage = `${data.error}: ${data.error_description}`;\n\t\t\t\t\t} else if (data.errorKey) {\n\t\t\t\t\t\tmessage = data.errorKey;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthrow new Error(message);\n\t\t\t}\n\n\t\t\tthrow new Error(`Entry request failed with status ${response.status}`);\n\t\t}\n\n\t\tconst sessionId = new URL(await response.text()).searchParams.get('session_id');\n\n\t\tif (!sessionId) {\n\t\t\tthrow new Error('Session ID not found in entry response');\n\t\t}\n\n\t\treturn sessionId;\n\t}\n\n\t/**\n\t * Handles the callback after login or registration via a redirect.\n\t * @param {string} [url] The URL to handle the callback from. Defaults to the current window location.\n\t * @returns {Promise<void>} A promise that resolves when the callback is handled.\n\t */\n\tasync handleCallback(url?: string): Promise<void> {\n\t\tif (typeof this.options.callbackHandler !== 'function') {\n\t\t\tthrow new Error('Callback handler is not defined. Please provide a valid callback handler function in the SDK options.');\n\t\t}\n\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tawait this.tokenExchange((await this.options.callbackHandler(url, this.options.responseMode || 'fragment')) as Record<string, string>);\n\t}\n}\n"],"names":["NativeFlow","BaseFlow","options","storage","httpClient","redirectUrlHandler","redirectCallbackHandler","params","NativeFlowHandler","url","_a","entryUrl","response","data","message","sessionId"],"mappings":"qaAKO,MAAMA,UAAmBC,CAAmC,CAClE,YAAYC,EAAqBC,EAAqBC,EAA2B,CAC3EF,EAAQ,aACZA,EAAQ,WAAaG,GAEjBH,EAAQ,kBACZA,EAAQ,gBAAkBI,GAG3B,MAAMJ,EAASC,EAASC,CAAU,CAAA,CAQnC,MAAMG,EAAuB,GAAuB,CACnD,YAAK,cAAc,iBAAkB,EAAE,EAEhC,IAAIC,EAAkB,KAAMD,CAAM,CAAA,CAQ1C,SAASA,EAAuB,GAAuB,CACtD,OAAAA,EAAO,OAAS,SAET,KAAK,MAAM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age, SDKHttpClient } from '../types';\nimport { redirectUrlHandler, redirectCallbackHandler } from '../utils/handlers';\nimport { NativeFlowHandler } from '../utils/NativeFlowHandler';\nimport { BaseFlow } from './BaseFlow';\n\nexport class NativeFlow extends BaseFlow<SDKOptions, NativeParams> {\n\tconstructor(options: SDKOptions, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.urlHandler) {\n\t\t\toptions.urlHandler = redirectUrlHandler;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\toptions.callbackHandler = redirectCallbackHandler;\n\t\t}\n\n\t\tsuper(options, storage, httpClient);\n\t}\n\n\t/**\n\t * Initiates the login process via native UI.\n\t * @param {NativeParams} [params={}] Optional parameters for native configuration.\n\t * @returns {NativeFlowHandler} Returns with a native login handler.\n\t */\n\tlogin(params: NativeParams = {}): NativeFlowHandler {\n\t\tthis.dispatchEvent('loginInitiated', []);\n\n\t\treturn new NativeFlowHandler(this, params);\n\t}\n\n\t/**\n\t * Initiates the registration process via native UI.\n\t * @param {NativeParams} [params={}] Optional parameters for native configuration.\n\t * @returns {NativeFlowHandler} Returns with a native login handler.\n\t */\n\tregister(params: NativeParams = {}): NativeFlowHandler {\n\t\tparams.prompt = 'create';\n\n\t\treturn this.login(params);\n\t}\n\n\t/**\n\t * Initiates the entry process via a redirect.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<string>} A promise that resolves to the session ID.\n\t */\n\tasync entry(url?: string): Promise<string> {\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tconst entryUrl = new URL(url);\n\t\tentryUrl.searchParams.append('sdk', 'web');\n\t\tentryUrl.searchParams.append('client_id', this.options.clientId);\n\t\tentryUrl.searchParams.append('redirect_uri', this.options.redirectUri);\n\n\t\tconst response = await this.httpClient.request<string | Record<string, string>>(\n\t\t\t`${this.options.issuer}/provider/flow/entry?${entryUrl.searchParams.toString()}`,\n\t\t);\n\n\t\tif (!response.ok) {\n\t\t\tif (response.status === 400) {\n\t\t\t\tconst data = await response.json();\n\t\t\t\tlet message = 'Entry request failed with status 400';\n\n\t\t\t\tif (typeof data === 'object') {\n\t\t\t\t\tif (data.error) {\n\t\t\t\t\t\tmessage = `${data.error}: ${data.error_description}`;\n\t\t\t\t\t} else if (data.errorKey) {\n\t\t\t\t\t\tmessage = data.errorKey;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthrow new Error(message);\n\t\t\t}\n\n\t\t\tthrow new Error(`Entry request failed with status ${response.status}`);\n\t\t}\n\n\t\tconst sessionId = new URL(await response.text()).searchParams.get('session_id');\n\n\t\tif (!sessionId) {\n\t\t\tthrow new Error('Session ID not found in entry response');\n\t\t}\n\n\t\treturn sessionId;\n\t}\n\n\t/**\n\t * Handles the callback after login or registration via a redirect.\n\t * @param {string} [url] The URL to handle the callback from. Defaults to the current window location.\n\t * @returns {Promise<void>} A promise that resolves when the callback is handled.\n\t */\n\tasync handleCallback(url?: string): Promise<void> {\n\t\tif (typeof this.options.callbackHandler !== 'function') {\n\t\t\tthrow new Error('Callback handler is not defined. Please provide a valid callback handler function in the SDK options.');\n\t\t}\n\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tawait this.tokenExchange((await this.options.callbackHandler(url, this.options.responseMode || 'fragment')) as Record<string, string>);\n\t}\n}\n"],"names":["NativeFlow","BaseFlow","options","storage","httpClient","redirectUrlHandler","redirectCallbackHandler","params","NativeFlowHandler","url","entryUrl","response","data","message","sessionId"],"mappings":"qaAKO,MAAMA,UAAmBC,CAAmC,CAClE,YAAYC,EAAqBC,EAAqBC,EAA2B,CAC3EF,EAAQ,aACZA,EAAQ,WAAaG,GAEjBH,EAAQ,kBACZA,EAAQ,gBAAkBI,GAG3B,MAAMJ,EAASC,EAASC,CAAU,CACnC,CAOA,MAAMG,EAAuB,GAAuB,CACnD,YAAK,cAAc,iBAAkB,EAAE,EAEhC,IAAIC,EAAkB,KAAM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:"Module"});const n=require("../utils/handlers.cjs"),i=require("../utils/State.cjs"),o=require("./BaseFlow.cjs");require("../utils/crypto.cjs");require("../utils/base64Url.cjs");require("../utils/date.cjs");require("../utils/jwt.cjs");require("../utils/Metadata.cjs");require("../utils/Session.cjs");class l extends o.BaseFlow{constructor(e,t,a){e.urlHandler||(e.urlHandler=n.popupUrlHandler),e.callbackHandler||(e.callbackHandler=n.popupCallbackHandler),super(e,t,a)}async login(e={}){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");const t=await i.State.create(),a=await this.getAuthorizationUrl(e);a.searchParams.append("state",t.id),a.searchParams.append("code_challenge",t.codeChallenge),a.searchParams.append("nonce",t.nonce),a.searchParams.append("display","popup"),await this.storage.set(`sty.${t.id}`,JSON.stringify(t)),this.dispatchEvent("loginInitiated",[]);const r=await this.options.urlHandler(a.toString(),e);await this.tokenExchange(r)}async register(e={}){e.prompt="create",await this.login(e)}async entry(e){var a;if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");e||(e=(a=globalThis.window)==null?void 0:a.location.href);const t=new URL(e);await this.options.urlHandler(`${this.options.issuer}/provider/entry?${t.searchParams.toString()}`)}async handleCallback(){if(typeof this.options.callbackHandler!="function")throw new Error("Callback handler is not defined. Please provide a valid callback handler function in the SDK options.");await this.options.callbackHandler(this.options.responseMode||"fragment")}}exports.PopupFlow=l;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("../utils/handlers.cjs"),i=require("../utils/State.cjs"),o=require("./BaseFlow.cjs");require("../utils/crypto.cjs");require("../utils/base64Url.cjs");require("../utils/date.cjs");require("../utils/jwt.cjs");require("../utils/Metadata.cjs");require("../utils/Session.cjs");class l extends o.BaseFlow{constructor(e,a,t){e.urlHandler||(e.urlHandler=n.popupUrlHandler),e.callbackHandler||(e.callbackHandler=n.popupCallbackHandler),super(e,a,t)}async login(e={}){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");const a=await i.State.create(),t=await this.getAuthorizationUrl(e);t.searchParams.append("state",a.id),t.searchParams.append("code_challenge",a.codeChallenge),t.searchParams.append("nonce",a.nonce),t.searchParams.append("display","popup"),await this.storage.set(`sty.${a.id}`,JSON.stringify(a)),this.dispatchEvent("loginInitiated",[]);const r=await this.options.urlHandler(t.toString(),e);await this.tokenExchange(r)}async register(e={}){e.prompt="create",await this.login(e)}async entry(e){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");e||(e=globalThis.window?.location.href);const a=new URL(e);await this.options.urlHandler(`${this.options.issuer}/provider/entry?${a.searchParams.toString()}`)}async handleCallback(){if(typeof this.options.callbackHandler!="function")throw new Error("Callback handler is not defined. Please provide a valid callback handler function in the SDK options.");await this.options.callbackHandler(this.options.responseMode||"fragment")}}exports.PopupFlow=l;
2
2
  //# sourceMappingURL=PopupFlow.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"PopupFlow.cjs","sources":["../../src/flows/PopupFlow.ts"],"sourcesContent":["import type { SDKOptions, PopupParams, SDKStorage, SDKHttpClient } from '../types';\nimport { popupCallbackHandler, popupUrlHandler } from '../utils/handlers';\nimport { State } from '../utils/State';\nimport { BaseFlow } from './BaseFlow';\n\n/**\n * Implements the Popup flow for authentication using a popup window.\n */\nexport class PopupFlow extends BaseFlow<SDKOptions, PopupParams> {\n\tconstructor(options: SDKOptions, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.urlHandler) {\n\t\t\toptions.urlHandler = popupUrlHandler;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\toptions.callbackHandler = popupCallbackHandler;\n\t\t}\n\n\t\tsuper(options, storage, httpClient);\n\t}\n\n\t/**\n\t * Initiates the login process via a popup window.\n\t * @param {PopupParams} [params={}] Optional parameters for popup window configuration.\n\t * @returns {Promise<void>} A promise that resolves when the login process completes.\n\t */\n\tasync login(params: PopupParams = {}): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tthrow new Error('URL handler is not defined. Please provide a valid URL handler function in the SDK options.');\n\t\t}\n\n\t\tconst state = await State.create();\n\t\tconst url = await this.getAuthorizationUrl(params);\n\n\t\turl.searchParams.append('state', state.id);\n\t\turl.searchParams.append('code_challenge', state.codeChallenge);\n\t\turl.searchParams.append('nonce', state.nonce);\n\t\turl.searchParams.append('display', 'popup');\n\n\t\tawait this.storage.set(`sty.${state.id}`, JSON.stringify(state));\n\n\t\tthis.dispatchEvent('loginInitiated', []);\n\n\t\tconst data = (await this.options.urlHandler(url.toString(), params)) as Record<string, string>;\n\n\t\tawait this.tokenExchange(data);\n\t}\n\n\t/**\n\t * Initiates the registration process via a popup window.\n\t * @param {PopupParams} [params={}] Optional parameters for popup window configuration.\n\t * @returns {Promise<void>} A promise that resolves when the registration process completes.\n\t */\n\tasync register(params: PopupParams = {}): Promise<void> {\n\t\tparams.prompt = 'create';\n\n\t\tawait this.login(params);\n\t}\n\n\t/**\n\t * Initiates the entry process via a popup window.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<void>} A promise that resolves when the entry process completes.\n\t */\n\tasync entry(url?: string): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tthrow new Error('URL handler is not defined. Please provide a valid URL handler function in the SDK options.');\n\t\t}\n\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tconst entryUrl = new URL(url);\n\n\t\tawait this.options.urlHandler(`${this.options.issuer}/provider/entry?${entryUrl.searchParams.toString()}`);\n\t}\n\n\t/**\n\t * Handles the callback after login or registration via a popup window.\n\t */\n\tasync handleCallback(): Promise<void> {\n\t\tif (typeof this.options.callbackHandler !== 'function') {\n\t\t\tthrow new Error('Callback handler is not defined. Please provide a valid callback handler function in the SDK options.');\n\t\t}\n\n\t\tawait this.options.callbackHandler(this.options.responseMode || 'fragment');\n\t}\n}\n"],"names":["PopupFlow","BaseFlow","options","storage","httpClient","popupUrlHandler","popupCallbackHandler","params","state","State","url","data","_a","entryUrl"],"mappings":"gXAQO,MAAMA,UAAkBC,EAAAA,QAAkC,CAChE,YAAYC,EAAqBC,EAAqBC,EAA2B,CAC3EF,EAAQ,aACZA,EAAQ,WAAaG,EAAAA,iBAEjBH,EAAQ,kBACZA,EAAQ,gBAAkBI,EAAAA,sBAG3B,MAAMJ,EAASC,EAASC,CAAU,CAAA,CAQnC,MAAM,MAAMG,EAAsB,GAAmB,CACpD,GAAI,OAAO,KAAK,QAAQ,YAAe,WACtC,MAAM,IAAI,MAAM,6FAA6F,EAG9G,MAAMC,EAAQ,MAAMC,EAAAA,MAAM,OAAA,EACpBC,EAAM,MAAM,KAAK,oBAAoBH,CAAM,EAEjDG,EAAI,aAAa,OAAO,QAASF,EAAM,EAAE,EACzCE,EAAI,aAAa,OAAO,iBAAkBF,EAAM,aAAa,EAC7DE,EAAI,aAAa,OAAO,QAASF,EAAM,KAAK,EAC5CE,EAAI,aAAa,OAAO,UAAW,OAAO,EAE1C,MAAM,KAAK,QAAQ,IAAI,OAAOF,EAAM,EAAE,GAAI,KAAK,UAAUA,CAAK,CAAC,EAE/D,KAAK,cAAc,iBAAkB,EAAE,EAEvC,MAAMG,EAAQ,MAAM,KAAK,QAAQ,WAAWD,EAAI,SAAA,EAAYH,CAAM,EAElE,MAAM,KAAK,cAAcI,CAAI,CAAA,CAQ9B,MAAM,SAASJ,EAAsB,GAAmB,CACvDA,EAAO,OAAS,SAEhB,MAAM,KAAK,MAAMA,CAAM,CAAA,CAQxB,MAAM,MAAMG,EAA6B,OACxC,GAAI,OAAO,KAAK,QAAQ,YAAe,WACtC,MAAM,IAAI,MAAM,6FAA6F,EAGzGA,IACJA,GAAME,EAAA,WAAW,SAAX,YAAAA,EAAmB,SAAS,MAGnC,MAAMC,EAAW,IAAI,IAAIH,CAAG,EAE5B,MAAM,KAAK,QAAQ,WAAW,GAAG,KAAK,QAAQ,MAAM,mBAAmBG,EAAS,aAAa,SAAA,CAAU,EAAE,CAAA,CAM1G,MAAM,gBAAgC,CACrC,GAAI,OAAO,KAAK,QAAQ,iBAAoB,WAC3C,MAAM,IAAI,MAAM,uGAAuG,EAGxH,MAAM,KAAK,QAAQ,gBAAgB,KAAK,QAAQ,cAAgB,UAAU,CAAA,CAE5E"}
1
+ {"version":3,"file":"PopupFlow.cjs","sources":["../../src/flows/PopupFlow.ts"],"sourcesContent":["import type { SDKOptions, PopupParams, SDKStorage, SDKHttpClient } from '../types';\nimport { popupCallbackHandler, popupUrlHandler } from '../utils/handlers';\nimport { State } from '../utils/State';\nimport { BaseFlow } from './BaseFlow';\n\n/**\n * Implements the Popup flow for authentication using a popup window.\n */\nexport class PopupFlow extends BaseFlow<SDKOptions, PopupParams> {\n\tconstructor(options: SDKOptions, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.urlHandler) {\n\t\t\toptions.urlHandler = popupUrlHandler;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\toptions.callbackHandler = popupCallbackHandler;\n\t\t}\n\n\t\tsuper(options, storage, httpClient);\n\t}\n\n\t/**\n\t * Initiates the login process via a popup window.\n\t * @param {PopupParams} [params={}] Optional parameters for popup window configuration.\n\t * @returns {Promise<void>} A promise that resolves when the login process completes.\n\t */\n\tasync login(params: PopupParams = {}): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tthrow new Error('URL handler is not defined. Please provide a valid URL handler function in the SDK options.');\n\t\t}\n\n\t\tconst state = await State.create();\n\t\tconst url = await this.getAuthorizationUrl(params);\n\n\t\turl.searchParams.append('state', state.id);\n\t\turl.searchParams.append('code_challenge', state.codeChallenge);\n\t\turl.searchParams.append('nonce', state.nonce);\n\t\turl.searchParams.append('display', 'popup');\n\n\t\tawait this.storage.set(`sty.${state.id}`, JSON.stringify(state));\n\n\t\tthis.dispatchEvent('loginInitiated', []);\n\n\t\tconst data = (await this.options.urlHandler(url.toString(), params)) as Record<string, string>;\n\n\t\tawait this.tokenExchange(data);\n\t}\n\n\t/**\n\t * Initiates the registration process via a popup window.\n\t * @param {PopupParams} [params={}] Optional parameters for popup window configuration.\n\t * @returns {Promise<void>} A promise that resolves when the registration process completes.\n\t */\n\tasync register(params: PopupParams = {}): Promise<void> {\n\t\tparams.prompt = 'create';\n\n\t\tawait this.login(params);\n\t}\n\n\t/**\n\t * Initiates the entry process via a popup window.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<void>} A promise that resolves when the entry process completes.\n\t */\n\tasync entry(url?: string): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tthrow new Error('URL handler is not defined. Please provide a valid URL handler function in the SDK options.');\n\t\t}\n\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tconst entryUrl = new URL(url);\n\n\t\tawait this.options.urlHandler(`${this.options.issuer}/provider/entry?${entryUrl.searchParams.toString()}`);\n\t}\n\n\t/**\n\t * Handles the callback after login or registration via a popup window.\n\t */\n\tasync handleCallback(): Promise<void> {\n\t\tif (typeof this.options.callbackHandler !== 'function') {\n\t\t\tthrow new Error('Callback handler is not defined. Please provide a valid callback handler function in the SDK options.');\n\t\t}\n\n\t\tawait this.options.callbackHandler(this.options.responseMode || 'fragment');\n\t}\n}\n"],"names":["PopupFlow","BaseFlow","options","storage","httpClient","popupUrlHandler","popupCallbackHandler","params","state","State","url","data","entryUrl"],"mappings":"gXAQO,MAAMA,UAAkBC,EAAAA,QAAkC,CAChE,YAAYC,EAAqBC,EAAqBC,EAA2B,CAC3EF,EAAQ,aACZA,EAAQ,WAAaG,EAAAA,iBAEjBH,EAAQ,kBACZA,EAAQ,gBAAkBI,EAAAA,sBAG3B,MAAMJ,EAASC,EAASC,CAAU,CACnC,CAOA,MAAM,MAAMG,EAAsB,GAAmB,CACpD,GAAI,OAAO,KAAK,QAAQ,YAAe,WACtC,MAAM,IAAI,MAAM,6FAA6F,EAG9G,MAAMC,EAAQ,MAAMC,EAAAA,MAAM,OAAA,EACpBC,EAAM,MAAM,KAAK,oBAAoBH,CAAM,EAEjDG,EAAI,aAAa,OAAO,QAASF,EAAM,EAAE,EACzCE,EAAI,aAAa,OAAO,iBAAkBF,EAAM,aAAa,EAC7DE,EAAI,aAAa,OAAO,QAASF,EAAM,KAAK,EAC5CE,EAAI,aAAa,OAAO,UAAW,OAAO,EAE1C,MAAM,KAAK,QAAQ,IAAI,OAAOF,EAAM,EAAE,GAAI,KAAK,UAAUA,CAAK,CAAC,EAE/D,KAAK,cAAc,iBAAkB,EAAE,EAEvC,MAAMG,EAAQ,MAAM,KAAK,QAAQ,WAAWD,EAAI,SAAA,EAAYH,CAAM,EAElE,MAAM,KAAK,cAAcI,CAAI,CAC9B,CAOA,MAAM,SAASJ,EAAsB,GAAmB,CACvDA,EAAO,OAAS,SAEhB,MAAM,KAAK,MAAMA,CAAM,CACxB,CAOA,MAAM,MAAMG,EAA6B,CACxC,GAAI,OAAO,KAAK,QAAQ,YAAe,WACtC,MAAM,IAAI,MAAM,6FAA6F,EAGzGA,IACJA,EAAM,WAAW,QAAQ,SAAS,MAGnC,MAAME,EAAW,IAAI,IAAIF,CAAG,EAE5B,MAAM,KAAK,QAAQ,WAAW,GAAG,KAAK,QAAQ,MAAM,mBAAmBE,EAAS,aAAa,SAAA,CAAU,EAAE,CAC1G,CAKA,MAAM,gBAAgC,CACrC,GAAI,OAAO,KAAK,QAAQ,iBAAoB,WAC3C,MAAM,IAAI,MAAM,uGAAuG,EAGxH,MAAM,KAAK,QAAQ,gBAAgB,KAAK,QAAQ,cAAgB,UAAU,CAC3E,CACD"}
@@ -1,2 +1,2 @@
1
- import{popupUrlHandler as i,popupCallbackHandler as r}from"../utils/handlers.mjs";import{State as o}from"../utils/State.mjs";import{BaseFlow as l}from"./BaseFlow.mjs";import"../utils/crypto.mjs";import"../utils/base64Url.mjs";import"../utils/date.mjs";import"../utils/jwt.mjs";import"../utils/Metadata.mjs";import"../utils/Session.mjs";class y extends l{constructor(a,e,t){a.urlHandler||(a.urlHandler=i),a.callbackHandler||(a.callbackHandler=r),super(a,e,t)}async login(a={}){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");const e=await o.create(),t=await this.getAuthorizationUrl(a);t.searchParams.append("state",e.id),t.searchParams.append("code_challenge",e.codeChallenge),t.searchParams.append("nonce",e.nonce),t.searchParams.append("display","popup"),await this.storage.set(`sty.${e.id}`,JSON.stringify(e)),this.dispatchEvent("loginInitiated",[]);const n=await this.options.urlHandler(t.toString(),a);await this.tokenExchange(n)}async register(a={}){a.prompt="create",await this.login(a)}async entry(a){var t;if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");a||(a=(t=globalThis.window)==null?void 0:t.location.href);const e=new URL(a);await this.options.urlHandler(`${this.options.issuer}/provider/entry?${e.searchParams.toString()}`)}async handleCallback(){if(typeof this.options.callbackHandler!="function")throw new Error("Callback handler is not defined. Please provide a valid callback handler function in the SDK options.");await this.options.callbackHandler(this.options.responseMode||"fragment")}}export{y as PopupFlow};
1
+ import{popupUrlHandler as i,popupCallbackHandler as r}from"../utils/handlers.mjs";import{State as o}from"../utils/State.mjs";import{BaseFlow as l}from"./BaseFlow.mjs";import"../utils/crypto.mjs";import"../utils/base64Url.mjs";import"../utils/date.mjs";import"../utils/jwt.mjs";import"../utils/Metadata.mjs";import"../utils/Session.mjs";class y extends l{constructor(a,t,e){a.urlHandler||(a.urlHandler=i),a.callbackHandler||(a.callbackHandler=r),super(a,t,e)}async login(a={}){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");const t=await o.create(),e=await this.getAuthorizationUrl(a);e.searchParams.append("state",t.id),e.searchParams.append("code_challenge",t.codeChallenge),e.searchParams.append("nonce",t.nonce),e.searchParams.append("display","popup"),await this.storage.set(`sty.${t.id}`,JSON.stringify(t)),this.dispatchEvent("loginInitiated",[]);const n=await this.options.urlHandler(e.toString(),a);await this.tokenExchange(n)}async register(a={}){a.prompt="create",await this.login(a)}async entry(a){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");a||(a=globalThis.window?.location.href);const t=new URL(a);await this.options.urlHandler(`${this.options.issuer}/provider/entry?${t.searchParams.toString()}`)}async handleCallback(){if(typeof this.options.callbackHandler!="function")throw new Error("Callback handler is not defined. Please provide a valid callback handler function in the SDK options.");await this.options.callbackHandler(this.options.responseMode||"fragment")}}export{y as PopupFlow};
2
2
  //# sourceMappingURL=PopupFlow.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"PopupFlow.mjs","sources":["../../src/flows/PopupFlow.ts"],"sourcesContent":["import type { SDKOptions, PopupParams, SDKStorage, SDKHttpClient } from '../types';\nimport { popupCallbackHandler, popupUrlHandler } from '../utils/handlers';\nimport { State } from '../utils/State';\nimport { BaseFlow } from './BaseFlow';\n\n/**\n * Implements the Popup flow for authentication using a popup window.\n */\nexport class PopupFlow extends BaseFlow<SDKOptions, PopupParams> {\n\tconstructor(options: SDKOptions, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.urlHandler) {\n\t\t\toptions.urlHandler = popupUrlHandler;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\toptions.callbackHandler = popupCallbackHandler;\n\t\t}\n\n\t\tsuper(options, storage, httpClient);\n\t}\n\n\t/**\n\t * Initiates the login process via a popup window.\n\t * @param {PopupParams} [params={}] Optional parameters for popup window configuration.\n\t * @returns {Promise<void>} A promise that resolves when the login process completes.\n\t */\n\tasync login(params: PopupParams = {}): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tthrow new Error('URL handler is not defined. Please provide a valid URL handler function in the SDK options.');\n\t\t}\n\n\t\tconst state = await State.create();\n\t\tconst url = await this.getAuthorizationUrl(params);\n\n\t\turl.searchParams.append('state', state.id);\n\t\turl.searchParams.append('code_challenge', state.codeChallenge);\n\t\turl.searchParams.append('nonce', state.nonce);\n\t\turl.searchParams.append('display', 'popup');\n\n\t\tawait this.storage.set(`sty.${state.id}`, JSON.stringify(state));\n\n\t\tthis.dispatchEvent('loginInitiated', []);\n\n\t\tconst data = (await this.options.urlHandler(url.toString(), params)) as Record<string, string>;\n\n\t\tawait this.tokenExchange(data);\n\t}\n\n\t/**\n\t * Initiates the registration process via a popup window.\n\t * @param {PopupParams} [params={}] Optional parameters for popup window configuration.\n\t * @returns {Promise<void>} A promise that resolves when the registration process completes.\n\t */\n\tasync register(params: PopupParams = {}): Promise<void> {\n\t\tparams.prompt = 'create';\n\n\t\tawait this.login(params);\n\t}\n\n\t/**\n\t * Initiates the entry process via a popup window.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<void>} A promise that resolves when the entry process completes.\n\t */\n\tasync entry(url?: string): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tthrow new Error('URL handler is not defined. Please provide a valid URL handler function in the SDK options.');\n\t\t}\n\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tconst entryUrl = new URL(url);\n\n\t\tawait this.options.urlHandler(`${this.options.issuer}/provider/entry?${entryUrl.searchParams.toString()}`);\n\t}\n\n\t/**\n\t * Handles the callback after login or registration via a popup window.\n\t */\n\tasync handleCallback(): Promise<void> {\n\t\tif (typeof this.options.callbackHandler !== 'function') {\n\t\t\tthrow new Error('Callback handler is not defined. Please provide a valid callback handler function in the SDK options.');\n\t\t}\n\n\t\tawait this.options.callbackHandler(this.options.responseMode || 'fragment');\n\t}\n}\n"],"names":["PopupFlow","BaseFlow","options","storage","httpClient","popupUrlHandler","popupCallbackHandler","params","state","State","url","data","_a","entryUrl"],"mappings":"gVAQO,MAAMA,UAAkBC,CAAkC,CAChE,YAAYC,EAAqBC,EAAqBC,E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,KAAK,QAAQ,cAAgB,UAAU,CAAA,CAE5E"}
1
+ {"version":3,"file":"PopupFlow.mjs","sources":["../../src/flows/PopupFlow.ts"],"sourcesContent":["import type { SDKOptions, PopupParams, SDKStorage, SDKHttpClient } from '../types';\nimport { popupCallbackHandler, popupUrlHandler } from '../utils/handlers';\nimport { State } from '../utils/State';\nimport { BaseFlow } from './BaseFlow';\n\n/**\n * Implements the Popup flow for authentication using a popup window.\n */\nexport class PopupFlow extends BaseFlow<SDKOptions, PopupParams> {\n\tconstructor(options: SDKOptions, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.urlHandler) {\n\t\t\toptions.urlHandler = popupUrlHandler;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\toptions.callbackHandler = popupCallbackHandler;\n\t\t}\n\n\t\tsuper(options, storage, httpClient);\n\t}\n\n\t/**\n\t * Initiates the login process via a popup window.\n\t * @param {PopupParams} [params={}] Optional parameters for popup window configuration.\n\t * @returns {Promise<void>} A promise that resolves when the login process completes.\n\t */\n\tasync login(params: PopupParams = {}): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tthrow new Error('URL handler is not defined. Please provide a valid URL handler function in the SDK options.');\n\t\t}\n\n\t\tconst state = await State.create();\n\t\tconst url = await this.getAuthorizationUrl(params);\n\n\t\turl.searchParams.append('state', state.id);\n\t\turl.searchParams.append('code_challenge', state.codeChallenge);\n\t\turl.searchParams.append('nonce', state.nonce);\n\t\turl.searchParams.append('display', 'popup');\n\n\t\tawait this.storage.set(`sty.${state.id}`, JSON.stringify(state));\n\n\t\tthis.dispatchEvent('loginInitiated', []);\n\n\t\tconst data = (await this.options.urlHandler(url.toString(), params)) as Record<string, string>;\n\n\t\tawait this.tokenExchange(data);\n\t}\n\n\t/**\n\t * Initiates the registration process via a popup window.\n\t * @param {PopupParams} [params={}] Optional parameters for popup window configuration.\n\t * @returns {Promise<void>} A promise that resolves when the registration process completes.\n\t */\n\tasync register(params: PopupParams = {}): Promise<void> {\n\t\tparams.prompt = 'create';\n\n\t\tawait this.login(params);\n\t}\n\n\t/**\n\t * Initiates the entry process via a popup window.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<void>} A promise that resolves when the entry process completes.\n\t */\n\tasync entry(url?: string): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tthrow new Error('URL handler is not defined. Please provide a valid URL handler function in the SDK options.');\n\t\t}\n\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tconst entryUrl = new URL(url);\n\n\t\tawait this.options.urlHandler(`${this.options.issuer}/provider/entry?${entryUrl.searchParams.toString()}`);\n\t}\n\n\t/**\n\t * Handles the callback after login or registration via a popup window.\n\t */\n\tasync handleCallback(): Promise<void> {\n\t\tif (typeof this.options.callbackHandler !== 'function') {\n\t\t\tthrow new Error('Callback handler is not defined. Please provide a valid callback handler function in the SDK options.');\n\t\t}\n\n\t\tawait this.options.callbackHandler(this.options.responseMode || 'fragment');\n\t}\n}\n"],"names":["PopupFlow","BaseFlow","options","storage","httpClient","popupUrlHandler","popupCallbackHandler","params","state","State","url","data","entryUrl"],"mappings":"gVAQO,MAAMA,UAAkBC,CAAkC,CAChE,YAAYC,EAAqBC,EAAqBC,EAA2B,CAC3EF,EAAQ,aACZA,EAAQ,WAAaG,GAEjBH,EAAQ,kBACZA,EAAQ,gBAAkBI,GAG3B,MAAMJ,EAASC,EAASC,CAAU,CACnC,CAOA,MAAM,MAAMG,EAAsB,GAAmB,CACpD,GAAI,OAAO,KAAK,QAAQ,YAAe,WACtC,MAAM,IAAI,MAAM,6FAA6F,EAG9G,MAAMC,EAAQ,MAAMC,EAAM,OAAA,EACpBC,EAAM,MAAM,KAAK,oBAAoBH,CAAM,EAEjDG,EAAI,aAAa,OAAO,QAASF,EAAM,EAAE,EACzCE,EAAI,aAAa,OAAO,iBAAkBF,EAAM,aAAa,EAC7DE,EAAI,aAAa,OAAO,QAASF,EAAM,KAAK,EAC5CE,EAAI,aAAa,OAAO,UAAW,OAAO,EAE1C,MAAM,KAAK,QAAQ,IAAI,OAAOF,EAAM,EAAE,GAAI,KAAK,UAAUA,CAAK,CAAC,EAE/D,KAAK,cAAc,iBAAkB,EAAE,EAEvC,MAAMG,EAAQ,MAAM,KAAK,QAAQ,WAAWD,EAAI,SAAA,EAAYH,CAAM,EAElE,MAAM,KAAK,cAAcI,CAAI,CAC9B,CAOA,MAAM,SAASJ,EAAsB,GAAmB,CACvDA,EAAO,OAAS,SAEhB,MAAM,KAAK,MAAMA,CAAM,CACxB,CAOA,MAAM,MAAMG,EAA6B,CACxC,GAAI,OAAO,KAAK,QAAQ,YAAe,WACtC,MAAM,IAAI,MAAM,6FAA6F,EAGzGA,IACJA,EAAM,WAAW,QAAQ,SAAS,MAGnC,MAAME,EAAW,IAAI,IAAIF,CAAG,EAE5B,MAAM,KAAK,QAAQ,WAAW,GAAG,KAAK,QAAQ,MAAM,mBAAmBE,EAAS,aAAa,SAAA,CAAU,EAAE,CAC1G,CAKA,MAAM,gBAAgC,CACrC,GAAI,OAAO,KAAK,QAAQ,iBAAoB,WAC3C,MAAM,IAAI,MAAM,uGAAuG,EAGxH,MAAM,KAAK,QAAQ,gBAAgB,KAAK,QAAQ,cAAgB,UAAU,CAC3E,CACD"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("../utils/handlers.cjs"),r=require("../utils/State.cjs"),n=require("./BaseFlow.cjs");require("../utils/crypto.cjs");require("../utils/base64Url.cjs");require("../utils/date.cjs");require("../utils/jwt.cjs");require("../utils/Metadata.cjs");require("../utils/Session.cjs");class o extends n.BaseFlow{constructor(e,t,a){e.urlHandler||(e.urlHandler=i.redirectUrlHandler),e.callbackHandler||(e.callbackHandler=i.redirectCallbackHandler),super(e,t,a)}async login(e={}){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");const t=await r.State.create(),a=await this.getAuthorizationUrl(e);a.searchParams.append("state",t.id),a.searchParams.append("code_challenge",t.codeChallenge),a.searchParams.append("nonce",t.nonce),await this.storage.set(`sty.${t.id}`,JSON.stringify(t)),this.dispatchEvent("loginInitiated",[]),await this.options.urlHandler(a.toString(),e)}async register(e={}){e.prompt="create",await this.login(e)}async entry(e){var a;if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");e||(e=(a=globalThis.window)==null?void 0:a.location.href);const t=new URL(e);await this.options.urlHandler(`${this.options.issuer}/provider/entry?${t.searchParams.toString()}`)}async handleCallback(e){var t;if(typeof this.options.callbackHandler!="function")throw new Error("Callback handler is not defined. Please provide a valid callback handler function in the SDK options.");e||(e=(t=globalThis.window)==null?void 0:t.location.href),await this.tokenExchange(await this.options.callbackHandler(e,this.options.responseMode||"fragment"))}}exports.RedirectFlow=o;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("../utils/handlers.cjs"),r=require("../utils/State.cjs"),n=require("./BaseFlow.cjs");require("../utils/crypto.cjs");require("../utils/base64Url.cjs");require("../utils/date.cjs");require("../utils/jwt.cjs");require("../utils/Metadata.cjs");require("../utils/Session.cjs");class o extends n.BaseFlow{constructor(e,t,a){e.urlHandler||(e.urlHandler=i.redirectUrlHandler),e.callbackHandler||(e.callbackHandler=i.redirectCallbackHandler),super(e,t,a)}async login(e={}){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");const t=await r.State.create(),a=await this.getAuthorizationUrl(e);a.searchParams.append("state",t.id),a.searchParams.append("code_challenge",t.codeChallenge),a.searchParams.append("nonce",t.nonce),await this.storage.set(`sty.${t.id}`,JSON.stringify(t)),this.dispatchEvent("loginInitiated",[]),await this.options.urlHandler(a.toString(),e)}async register(e={}){e.prompt="create",await this.login(e)}async entry(e){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");e||(e=globalThis.window?.location.href);const t=new URL(e);await this.options.urlHandler(`${this.options.issuer}/provider/entry?${t.searchParams.toString()}`)}async handleCallback(e){if(typeof this.options.callbackHandler!="function")throw new Error("Callback handler is not defined. Please provide a valid callback handler function in the SDK options.");e||(e=globalThis.window?.location.href),await this.tokenExchange(await this.options.callbackHandler(e,this.options.responseMode||"fragment"))}}exports.RedirectFlow=o;
2
2
  //# sourceMappingURL=RedirectFlow.cjs.map