@asgardeo/javascript 0.0.1 → 0.1.1

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 (73) hide show
  1. package/README.md +3 -3
  2. package/dist/AsgardeoJavaScriptClient.d.ts +17 -50
  3. package/dist/IsomorphicCrypto.d.ts +4 -4
  4. package/dist/{__legacy__/data/data-layer.d.ts → StorageManager.d.ts} +27 -26
  5. package/dist/__legacy__/client.d.ts +82 -98
  6. package/dist/__legacy__/helpers/authentication-helper.d.ts +9 -9
  7. package/dist/__legacy__/models/client-config.d.ts +6 -6
  8. package/dist/__legacy__/models/index.d.ts +0 -5
  9. package/dist/api/createOrganization.d.ts +129 -0
  10. package/dist/api/executeEmbeddedSignInFlow.d.ts +21 -0
  11. package/dist/api/executeEmbeddedSignUpFlow.d.ts +44 -0
  12. package/dist/api/getAllOrganizations.d.ts +112 -0
  13. package/dist/api/getMeOrganizations.d.ts +119 -0
  14. package/dist/api/getOrganization.d.ts +109 -0
  15. package/dist/api/getSchemas.d.ts +89 -0
  16. package/dist/api/getScim2Me.d.ts +89 -0
  17. package/dist/api/{oidc/getUserInfo.d.ts → getUserInfo.d.ts} +1 -1
  18. package/dist/api/initializeEmbeddedSignInFlow.d.ts +51 -0
  19. package/dist/api/updateMeProfile.d.ts +82 -0
  20. package/dist/api/updateOrganization.d.ts +118 -0
  21. package/dist/cjs/index.js +2437 -1224
  22. package/dist/cjs/index.js.map +4 -4
  23. package/dist/constants/ApplicationNativeAuthenticationConstants.d.ts +39 -0
  24. package/dist/constants/OIDCRequestConstants.d.ts +14 -0
  25. package/dist/constants/PKCEConstants.d.ts +1 -0
  26. package/dist/constants/ScopeConstants.d.ts +3 -6
  27. package/dist/constants/TokenExchangeConstants.d.ts +3 -3
  28. package/dist/constants/VendorConstants.d.ts +31 -0
  29. package/dist/{__legacy__/exception → errors}/exception.d.ts +3 -0
  30. package/dist/{__legacy__/data/index.d.ts → i18n/en-US.d.ts} +4 -2
  31. package/dist/{__legacy__/exception → i18n}/index.d.ts +2 -2
  32. package/dist/index.d.ts +44 -11
  33. package/dist/index.js +2399 -1219
  34. package/dist/index.js.map +4 -4
  35. package/dist/models/client.d.ts +60 -5
  36. package/dist/models/config.d.ts +51 -2
  37. package/dist/models/crypto.d.ts +2 -2
  38. package/dist/models/embedded-flow.d.ts +66 -0
  39. package/dist/models/embedded-signin-flow.d.ts +99 -0
  40. package/dist/{__legacy__/models/custom-grant.d.ts → models/field.d.ts} +13 -9
  41. package/dist/models/flow.d.ts +30 -0
  42. package/dist/models/i18n.d.ts +90 -0
  43. package/dist/{__legacy__/models/authorization-url.d.ts → models/oauth-request.d.ts} +3 -3
  44. package/dist/models/oauth-response.d.ts +1 -17
  45. package/dist/models/organization.d.ts +24 -0
  46. package/dist/models/scim2-schema.d.ts +3 -0
  47. package/dist/{__legacy__/models/data.d.ts → models/session.d.ts} +4 -0
  48. package/dist/models/store.d.ts +1 -1
  49. package/dist/models/token.d.ts +79 -20
  50. package/dist/models/user.d.ts +11 -84
  51. package/dist/theme/createTheme.d.ts +1 -1
  52. package/dist/theme/types.d.ts +29 -17
  53. package/dist/utils/deepMerge.d.ts +44 -0
  54. package/dist/utils/extractTenantDomainFromIdTokenPayload.d.ts +2 -2
  55. package/dist/utils/extractUserClaimsFromIdToken.d.ts +2 -2
  56. package/dist/utils/flattenUserSchema.d.ts +64 -0
  57. package/dist/utils/generateFlattenedUserProfile.d.ts +53 -0
  58. package/dist/utils/generateUserProfile.d.ts +55 -0
  59. package/dist/utils/get.d.ts +29 -0
  60. package/dist/utils/getAuthorizeRequestUrlParams.d.ts +59 -0
  61. package/dist/utils/getI18nBundles.d.ts +26 -0
  62. package/dist/utils/getLatestStateParam.d.ts +40 -0
  63. package/dist/utils/isEmpty.d.ts +48 -0
  64. package/dist/utils/processOpenIDScopes.d.ts +36 -0
  65. package/dist/{__legacy__/core/index.d.ts → utils/resolveFieldName.d.ts} +3 -2
  66. package/dist/utils/resolveFieldType.d.ts +20 -0
  67. package/dist/utils/set.d.ts +30 -0
  68. package/dist/utils/withVendorCSSClassPrefix.d.ts +32 -0
  69. package/package.json +4 -4
  70. package/dist/__legacy__/core/authentication-core.d.ts +0 -51
  71. package/dist/__legacy__/models/fetch.d.ts +0 -55
  72. package/dist/__legacy__/models/user.d.ts +0 -85
  73. package/dist/models/id-token.d.ts +0 -55
package/dist/cjs/index.js CHANGED
@@ -21,132 +21,201 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
21
21
  // src/index.ts
22
22
  var index_exports = {};
23
23
  __export(index_exports, {
24
- ASGARDEO_SESSION_ACTIVE: () => ASGARDEO_SESSION_ACTIVE,
24
+ ApplicationNativeAuthenticationConstants: () => ApplicationNativeAuthenticationConstants_default,
25
25
  AsgardeoAPIError: () => AsgardeoAPIError,
26
26
  AsgardeoAuthClient: () => AsgardeoAuthClient,
27
27
  AsgardeoAuthException: () => AsgardeoAuthException,
28
28
  AsgardeoError: () => AsgardeoError,
29
29
  AsgardeoJavaScriptClient: () => AsgardeoJavaScriptClient_default,
30
30
  AsgardeoRuntimeError: () => AsgardeoRuntimeError,
31
- DataLayer: () => DataLayer,
31
+ EmbeddedFlowComponentType: () => EmbeddedFlowComponentType,
32
+ EmbeddedFlowResponseType: () => EmbeddedFlowResponseType,
33
+ EmbeddedFlowStatus: () => EmbeddedFlowStatus,
34
+ EmbeddedFlowType: () => EmbeddedFlowType,
35
+ EmbeddedSignInFlowAuthenticatorKnownIdPType: () => EmbeddedSignInFlowAuthenticatorKnownIdPType,
36
+ EmbeddedSignInFlowAuthenticatorParamType: () => EmbeddedSignInFlowAuthenticatorParamType,
37
+ EmbeddedSignInFlowAuthenticatorPromptType: () => EmbeddedSignInFlowAuthenticatorPromptType,
38
+ EmbeddedSignInFlowStatus: () => EmbeddedSignInFlowStatus,
39
+ EmbeddedSignInFlowStepType: () => EmbeddedSignInFlowStepType,
40
+ EmbeddedSignInFlowType: () => EmbeddedSignInFlowType,
41
+ FieldType: () => FieldType,
42
+ FlowMode: () => FlowMode,
32
43
  IsomorphicCrypto: () => IsomorphicCrypto,
33
44
  OIDCRequestConstants: () => OIDCRequestConstants_default,
34
- ResponseMode: () => ResponseMode,
45
+ StorageManager: () => StorageManager_default,
35
46
  TokenConstants: () => TokenConstants_default,
47
+ VendorConstants: () => VendorConstants_default,
36
48
  WellKnownSchemaIds: () => WellKnownSchemaIds,
49
+ createOrganization: () => createOrganization_default,
50
+ createPatchOperations: () => createPatchOperations,
37
51
  createTheme: () => createTheme_default,
52
+ deepMerge: () => deepMerge_default,
53
+ executeEmbeddedSignInFlow: () => executeEmbeddedSignInFlow_default,
54
+ executeEmbeddedSignUpFlow: () => executeEmbeddedSignUpFlow_default,
38
55
  extractPkceStorageKeyFromState: () => extractPkceStorageKeyFromState_default,
39
56
  extractUserClaimsFromIdToken: () => extractUserClaimsFromIdToken_default,
57
+ flattenUserSchema: () => flattenUserSchema_default,
58
+ generateFlattenedUserProfile: () => generateFlattenedUserProfile_default,
59
+ generateUserProfile: () => generateUserProfile_default,
60
+ get: () => get_default,
61
+ getAllOrganizations: () => getAllOrganizations_default,
62
+ getI18nBundles: () => getI18nBundles_default,
63
+ getLatestStateParam: () => getLatestStateParam_default,
64
+ getMeOrganizations: () => getMeOrganizations_default,
65
+ getOrganization: () => getOrganization_default,
66
+ getSchemas: () => getSchemas_default,
67
+ getScim2Me: () => getScim2Me_default,
40
68
  getUserInfo: () => getUserInfo_default,
41
- removeTrailingSlash: () => removeTrailingSlash_default
69
+ initializeEmbeddedSignInFlow: () => initializeEmbeddedSignInFlow_default,
70
+ isEmpty: () => isEmpty_default,
71
+ processOpenIDScopes: () => processOpenIDScopes_default,
72
+ removeTrailingSlash: () => removeTrailingSlash_default,
73
+ resolveFieldName: () => resolveFieldName_default,
74
+ resolveFieldType: () => resolveFieldType_default,
75
+ set: () => set_default,
76
+ updateMeProfile: () => updateMeProfile_default,
77
+ updateOrganization: () => updateOrganization_default,
78
+ withVendorCSSClassPrefix: () => withVendorCSSClassPrefix_default
42
79
  });
43
80
  module.exports = __toCommonJS(index_exports);
44
81
 
45
- // src/constants/PKCEConstants.ts
46
- var PKCEConstants = {
47
- /**
48
- * Storage-related constants for managing PKCE state
49
- */
50
- Storage: {
51
- /**
52
- * Collection of storage keys used in PKCE implementation
53
- */
54
- StorageKeys: {
55
- /**
56
- * Key used to store the PKCE code verifier in temporary storage.
57
- * The code verifier is a cryptographically random string that is
58
- * used to generate the code challenge.
59
- */
60
- CODE_VERIFIER: "pkce_code_verifier",
61
- /**
62
- * Separator used in storage keys to create unique identifiers
63
- * by combining different parts of the key.
64
- */
65
- SEPARATOR: "#"
82
+ // src/StorageManager.ts
83
+ var ASGARDEO_SESSION_ACTIVE = "asgardeo-session-active";
84
+ var StorageManager = class {
85
+ constructor(instanceID, store) {
86
+ __publicField(this, "_id");
87
+ __publicField(this, "_store");
88
+ this._id = instanceID;
89
+ this._store = store;
90
+ }
91
+ async setDataInBulk(key, data) {
92
+ const existingDataJSON = await this._store.getData(key) ?? null;
93
+ const existingData = existingDataJSON && JSON.parse(existingDataJSON);
94
+ const dataToBeSaved = { ...existingData, ...data };
95
+ const dataToBeSavedJSON = JSON.stringify(dataToBeSaved);
96
+ await this._store.setData(key, dataToBeSavedJSON);
97
+ }
98
+ async setValue(key, attribute, value) {
99
+ const existingDataJSON = await this._store.getData(key) ?? null;
100
+ const existingData = existingDataJSON && JSON.parse(existingDataJSON);
101
+ const dataToBeSaved = { ...existingData, [attribute]: value };
102
+ const dataToBeSavedJSON = JSON.stringify(dataToBeSaved);
103
+ await this._store.setData(key, dataToBeSavedJSON);
104
+ }
105
+ async removeValue(key, attribute) {
106
+ const existingDataJSON = await this._store.getData(key) ?? null;
107
+ const existingData = existingDataJSON && JSON.parse(existingDataJSON);
108
+ const dataToBeSaved = { ...existingData };
109
+ delete dataToBeSaved[attribute];
110
+ const dataToBeSavedJSON = JSON.stringify(dataToBeSaved);
111
+ await this._store.setData(key, dataToBeSavedJSON);
112
+ }
113
+ _resolveKey(store, userId) {
114
+ return userId ? `${store}-${this._id}-${userId}` : `${store}-${this._id}`;
115
+ }
116
+ isLocalStorageAvailable() {
117
+ try {
118
+ const testValue = "__ASGARDEO_AUTH_CORE_LOCAL_STORAGE_TEST__";
119
+ localStorage.setItem(testValue, testValue);
120
+ localStorage.removeItem(testValue);
121
+ return true;
122
+ } catch (error) {
123
+ return false;
66
124
  }
67
125
  }
68
- };
69
- var PKCEConstants_default = PKCEConstants;
70
-
71
- // src/utils/extractPkceStorageKeyFromState.ts
72
- var extractPkceStorageKeyFromState = (state) => {
73
- const index = parseInt(state.split("request_")[1]);
74
- return `${PKCEConstants_default.Storage.StorageKeys.CODE_VERIFIER}${PKCEConstants_default.Storage.StorageKeys.SEPARATOR}${index}`;
75
- };
76
- var extractPkceStorageKeyFromState_default = extractPkceStorageKeyFromState;
77
-
78
- // src/utils/generateStateParamForRequestCorrelation.ts
79
- var generateStateParamForRequestCorrelation = (pkceKey, state) => {
80
- const index = parseInt(pkceKey.split(PKCEConstants_default.Storage.StorageKeys.SEPARATOR)[1]);
81
- return state ? `${state}_request_${index}` : `request_${index}`;
82
- };
83
- var generateStateParamForRequestCorrelation_default = generateStateParamForRequestCorrelation;
84
-
85
- // src/__legacy__/exception/exception.ts
86
- var AsgardeoAuthException = class {
87
- constructor(code, name, message) {
88
- __publicField(this, "name");
89
- __publicField(this, "code");
90
- __publicField(this, "message");
91
- this.message = message;
92
- this.name = name;
93
- this.code = code;
94
- Object.setPrototypeOf(this, new.target.prototype);
126
+ async setConfigData(config) {
127
+ await this.setDataInBulk(this._resolveKey("config_data" /* ConfigData */), config);
128
+ }
129
+ async setOIDCProviderMetaData(oidcProviderMetaData) {
130
+ this.setDataInBulk(this._resolveKey("oidc_provider_meta_data" /* OIDCProviderMetaData */), oidcProviderMetaData);
131
+ }
132
+ async setTemporaryData(temporaryData, userId) {
133
+ this.setDataInBulk(this._resolveKey("temporary_data" /* TemporaryData */, userId), temporaryData);
134
+ }
135
+ async setSessionData(sessionData, userId) {
136
+ this.setDataInBulk(this._resolveKey("session_data" /* SessionData */, userId), sessionData);
137
+ }
138
+ async setCustomData(key, customData, userId) {
139
+ this.setDataInBulk(this._resolveKey(key, userId), customData);
140
+ }
141
+ async getConfigData(userId) {
142
+ return JSON.parse(await this._store.getData(this._resolveKey("config_data" /* ConfigData */, userId)) ?? null);
143
+ }
144
+ async loadOpenIDProviderConfiguration() {
145
+ return JSON.parse(await this._store.getData(this._resolveKey("oidc_provider_meta_data" /* OIDCProviderMetaData */)) ?? null);
146
+ }
147
+ async getTemporaryData(userId) {
148
+ return JSON.parse(await this._store.getData(this._resolveKey("temporary_data" /* TemporaryData */, userId)) ?? null);
149
+ }
150
+ async getSessionData(userId) {
151
+ return JSON.parse(await this._store.getData(this._resolveKey("session_data" /* SessionData */, userId)) ?? null);
152
+ }
153
+ async getCustomData(key, userId) {
154
+ return JSON.parse(await this._store.getData(this._resolveKey(key, userId)) ?? null);
155
+ }
156
+ setSessionStatus(status) {
157
+ this.isLocalStorageAvailable() && localStorage.setItem(`${ASGARDEO_SESSION_ACTIVE}`, status);
158
+ }
159
+ getSessionStatus() {
160
+ return this.isLocalStorageAvailable() ? localStorage.getItem(`${ASGARDEO_SESSION_ACTIVE}`) ?? "" : "";
161
+ }
162
+ removeSessionStatus() {
163
+ this.isLocalStorageAvailable() && localStorage.removeItem(`${ASGARDEO_SESSION_ACTIVE}`);
164
+ }
165
+ async removeConfigData() {
166
+ await this._store.removeData(this._resolveKey("config_data" /* ConfigData */));
167
+ }
168
+ async removeOIDCProviderMetaData() {
169
+ await this._store.removeData(this._resolveKey("oidc_provider_meta_data" /* OIDCProviderMetaData */));
170
+ }
171
+ async removeTemporaryData(userId) {
172
+ await this._store.removeData(this._resolveKey("temporary_data" /* TemporaryData */, userId));
173
+ }
174
+ async removeSessionData(userId) {
175
+ await this._store.removeData(this._resolveKey("session_data" /* SessionData */, userId));
176
+ }
177
+ async getConfigDataParameter(key) {
178
+ const data = await this._store.getData(this._resolveKey("config_data" /* ConfigData */));
179
+ return data && JSON.parse(data)[key];
180
+ }
181
+ async getOIDCProviderMetaDataParameter(key) {
182
+ const data = await this._store.getData(this._resolveKey("oidc_provider_meta_data" /* OIDCProviderMetaData */));
183
+ return data && JSON.parse(data)[key];
184
+ }
185
+ async getTemporaryDataParameter(key, userId) {
186
+ const data = await this._store.getData(this._resolveKey("temporary_data" /* TemporaryData */, userId));
187
+ return data && JSON.parse(data)[key];
188
+ }
189
+ async getSessionDataParameter(key, userId) {
190
+ const data = await this._store.getData(this._resolveKey("session_data" /* SessionData */, userId));
191
+ return data && JSON.parse(data)[key];
192
+ }
193
+ async setConfigDataParameter(key, value) {
194
+ await this.setValue(this._resolveKey("config_data" /* ConfigData */), key, value);
195
+ }
196
+ async setOIDCProviderMetaDataParameter(key, value) {
197
+ await this.setValue(this._resolveKey("oidc_provider_meta_data" /* OIDCProviderMetaData */), key, value);
198
+ }
199
+ async setTemporaryDataParameter(key, value, userId) {
200
+ await this.setValue(this._resolveKey("temporary_data" /* TemporaryData */, userId), key, value);
201
+ }
202
+ async setSessionDataParameter(key, value, userId) {
203
+ await this.setValue(this._resolveKey("session_data" /* SessionData */, userId), key, value);
204
+ }
205
+ async removeConfigDataParameter(key) {
206
+ await this.removeValue(this._resolveKey("config_data" /* ConfigData */), key);
207
+ }
208
+ async removeOIDCProviderMetaDataParameter(key) {
209
+ await this.removeValue(this._resolveKey("oidc_provider_meta_data" /* OIDCProviderMetaData */), key);
210
+ }
211
+ async removeTemporaryDataParameter(key, userId) {
212
+ await this.removeValue(this._resolveKey("temporary_data" /* TemporaryData */, userId), key);
213
+ }
214
+ async removeSessionDataParameter(key, userId) {
215
+ await this.removeValue(this._resolveKey("session_data" /* SessionData */, userId), key);
95
216
  }
96
217
  };
97
-
98
- // src/utils/extractTenantDomainFromIdTokenPayload.ts
99
- var extractTenantDomainFromIdTokenPayload = (payload, subjectSeparator = "@") => {
100
- const uid = payload.sub;
101
- if (!uid) return "";
102
- const tokens = uid.split(subjectSeparator);
103
- return tokens.length > 2 ? tokens[tokens.length - 1] : "";
104
- };
105
- var extractTenantDomainFromIdTokenPayload_default = extractTenantDomainFromIdTokenPayload;
106
-
107
- // src/utils/extractUserClaimsFromIdToken.ts
108
- var extractUserClaimsFromIdToken = (payload) => {
109
- const filteredPayload = { ...payload };
110
- const protocolClaims = [
111
- "iss",
112
- "aud",
113
- "exp",
114
- "iat",
115
- "acr",
116
- "amr",
117
- "azp",
118
- "auth_time",
119
- "nonce",
120
- "c_hash",
121
- "at_hash",
122
- "nbf",
123
- "isk",
124
- "sid",
125
- "jti",
126
- "sub"
127
- ];
128
- protocolClaims.forEach((claim) => {
129
- delete filteredPayload[claim];
130
- });
131
- const userClaims = {};
132
- Object.entries(filteredPayload).forEach(([key, value]) => {
133
- const camelCasedKey = key.split("_").map((part, i) => i === 0 ? part : part[0].toUpperCase() + part.slice(1)).join("");
134
- userClaims[camelCasedKey] = value;
135
- });
136
- return userClaims;
137
- };
138
- var extractUserClaimsFromIdToken_default = extractUserClaimsFromIdToken;
139
-
140
- // src/constants/ScopeConstants.ts
141
- var ScopeConstants = {
142
- /**
143
- * The base OpenID Connect scope.
144
- * Required for all OpenID Connect flows. Indicates that the client
145
- * is initiating an OpenID Connect authentication request.
146
- */
147
- OPENID: "openid"
148
- };
149
- var ScopeConstants_default = ScopeConstants;
218
+ var StorageManager_default = StorageManager;
150
219
 
151
220
  // src/constants/OIDCDiscoveryConstants.ts
152
221
  var OIDCDiscoveryConstants = {
@@ -267,279 +336,65 @@ var OIDCDiscoveryConstants = {
267
336
  };
268
337
  var OIDCDiscoveryConstants_default = OIDCDiscoveryConstants;
269
338
 
270
- // src/constants/TokenExchangeConstants.ts
271
- var TokenExchangeConstants = {
339
+ // src/constants/ScopeConstants.ts
340
+ var ScopeConstants = {
272
341
  /**
273
- * Collection of placeholder strings used in token exchange operations.
274
- * These placeholders are replaced with actual values when processing
275
- * token exchange requests.
342
+ * The scope for accessing the user's profile information from SCIM.
343
+ * This scope allows the client to retrieve basic user information such as
344
+ * name, email, profile picture, etc.
276
345
  */
277
- Placeholders: {
346
+ INTERNAL_LOGIN: "internal_login",
347
+ /**
348
+ * The base OpenID Connect scope.
349
+ * Required for all OpenID Connect flows. Indicates that the client
350
+ * is initiating an OpenID Connect authentication request.
351
+ */
352
+ OPENID: "openid",
353
+ /**
354
+ * The OpenID Connect profile scope.
355
+ * This scope allows the client to access the user's profile information.
356
+ * It includes details such as the user's name, email, and other profile attributes.
357
+ */
358
+ PROFILE: "profile"
359
+ };
360
+ var ScopeConstants_default = ScopeConstants;
361
+
362
+ // src/constants/OIDCRequestConstants.ts
363
+ var OIDCRequestConstants = {
364
+ Params: {
278
365
  /**
279
- * Placeholder for the token value in exchange requests.
280
- * Usually replaced with an access token or refresh token.
366
+ * The authorization code returned from the authorization endpoint.
367
+ * Used in the authorization code flow.
281
368
  */
282
- TOKEN: "{{token}}",
369
+ AUTHORIZATION_CODE: "code",
283
370
  /**
284
- * Placeholder for the username in token exchange operations.
285
- * Used when user identity needs to be included in the exchange.
371
+ * Session state parameter used for session management between the client and the OP.
286
372
  */
287
- USERNAME: "{{username}}",
373
+ SESSION_STATE: "session_state",
288
374
  /**
289
- * Placeholder for OAuth scopes in token exchange requests.
290
- * Replaced with space-separated scope strings.
375
+ * State parameter used to maintain state between the request and the callback.
376
+ * Helps in preventing CSRF attacks.
291
377
  */
292
- SCOPE: "{{scope}}",
378
+ STATE: "state",
293
379
  /**
294
- * Placeholder for client ID in token exchange operations.
295
- * Required for client authentication.
380
+ * Indicates whether sign-out was successful during the end-session flow.
381
+ * May be returned by the OP after a logout request.
296
382
  */
297
- CLIENT_ID: "{{clientID}}",
383
+ SIGN_OUT_SUCCESS: "sign_out_success"
384
+ },
385
+ /**
386
+ * Constants related to the OpenID Connect (OIDC) sign-in flow.
387
+ */
388
+ SignIn: {
298
389
  /**
299
- * Placeholder for client secret in token exchange operations.
300
- * Used for client authentication in confidential client flows.
390
+ * Constants related to the payload of the OIDC sign-in request.
301
391
  */
302
- CLIENT_SECRET: "{{clientSecret}}"
303
- }
304
- };
305
- var TokenExchangeConstants_default = TokenExchangeConstants;
306
-
307
- // src/__legacy__/helpers/authentication-helper.ts
308
- var AuthenticationHelper = class {
309
- constructor(dataLayer, cryptoHelper) {
310
- __publicField(this, "_dataLayer");
311
- __publicField(this, "_config");
312
- __publicField(this, "_oidcProviderMetaData");
313
- __publicField(this, "_cryptoHelper");
314
- this._dataLayer = dataLayer;
315
- this._config = async () => await this._dataLayer.getConfigData();
316
- this._oidcProviderMetaData = async () => await this._dataLayer.getOIDCProviderMetaData();
317
- this._cryptoHelper = cryptoHelper;
318
- }
319
- async resolveEndpoints(response) {
320
- const oidcProviderMetaData = {};
321
- const configData = await this._config();
322
- configData.endpoints && Object.keys(configData.endpoints).forEach((endpointName) => {
323
- const snakeCasedName = endpointName.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
324
- oidcProviderMetaData[snakeCasedName] = configData?.endpoints ? configData.endpoints[endpointName] : "";
325
- });
326
- return { ...response, ...oidcProviderMetaData };
327
- }
328
- async resolveEndpointsExplicitly() {
329
- const oidcProviderMetaData = {};
330
- const configData = await this._config();
331
- const requiredEndpoints = [
332
- OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.AUTHORIZATION,
333
- OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.END_SESSION,
334
- OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.JWKS,
335
- OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.SESSION_IFRAME,
336
- OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.REVOCATION,
337
- OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.TOKEN,
338
- OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.ISSUER,
339
- OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.USERINFO
340
- ];
341
- const isRequiredEndpointsContains = configData.endpoints ? requiredEndpoints.every((reqEndpointName) => {
342
- return configData.endpoints ? Object.keys(configData.endpoints).some((endpointName) => {
343
- const snakeCasedName = endpointName.replace(
344
- /[A-Z]/g,
345
- (letter) => `_${letter.toLowerCase()}`
346
- );
347
- return snakeCasedName === reqEndpointName;
348
- }) : false;
349
- }) : false;
350
- if (!isRequiredEndpointsContains) {
351
- throw new AsgardeoAuthException(
352
- "JS-AUTH_HELPER-REE-NF01",
353
- "Required endpoints missing",
354
- "Some or all of the required endpoints are missing in the object passed to the `endpoints` attribute of the`AuthConfig` object."
355
- );
356
- }
357
- configData.endpoints && Object.keys(configData.endpoints).forEach((endpointName) => {
358
- const snakeCasedName = endpointName.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
359
- oidcProviderMetaData[snakeCasedName] = configData?.endpoints ? configData.endpoints[endpointName] : "";
360
- });
361
- return { ...oidcProviderMetaData };
362
- }
363
- async resolveEndpointsByBaseURL() {
364
- const oidcProviderMetaData = {};
365
- const configData = await this._config();
366
- const baseUrl = configData.baseUrl;
367
- if (!baseUrl) {
368
- throw new AsgardeoAuthException(
369
- "JS-AUTH_HELPER_REBO-NF01",
370
- "Base URL not defined.",
371
- "Base URL is not defined in AuthClient config."
372
- );
373
- }
374
- configData.endpoints && Object.keys(configData.endpoints).forEach((endpointName) => {
375
- const snakeCasedName = endpointName.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
376
- oidcProviderMetaData[snakeCasedName] = configData?.endpoints ? configData.endpoints[endpointName] : "";
377
- });
378
- const defaultEndpoints = {
379
- [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.AUTHORIZATION]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.AUTHORIZATION}`,
380
- [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.END_SESSION]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.END_SESSION}`,
381
- [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.ISSUER]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.ISSUER}`,
382
- [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.JWKS]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.JWKS}`,
383
- [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.SESSION_IFRAME]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.SESSION_IFRAME}`,
384
- [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.REVOCATION]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.REVOCATION}`,
385
- [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.TOKEN]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.TOKEN}`,
386
- [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.USERINFO]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.USERINFO}`
387
- };
388
- return { ...defaultEndpoints, ...oidcProviderMetaData };
389
- }
390
- async validateIdToken(idToken) {
391
- const jwksEndpoint = (await this._dataLayer.getOIDCProviderMetaData()).jwks_uri;
392
- const configData = await this._config();
393
- if (!jwksEndpoint || jwksEndpoint.trim().length === 0) {
394
- throw new AsgardeoAuthException(
395
- "JS_AUTH_HELPER-VIT-NF01",
396
- "JWKS endpoint not found.",
397
- "No JWKS endpoint was found in the OIDC provider meta data returned by the well-known endpoint or the JWKS endpoint passed to the SDK is empty."
398
- );
399
- }
400
- let response;
401
- try {
402
- response = await fetch(jwksEndpoint, {
403
- credentials: configData.sendCookiesInRequests ? "include" : "same-origin"
404
- });
405
- } catch (error) {
406
- throw new AsgardeoAuthException(
407
- "JS-AUTH_HELPER-VIT-NE02",
408
- "Request to jwks endpoint failed.",
409
- error ?? "The request sent to get the jwks from the server failed."
410
- );
411
- }
412
- if (response.status !== 200 || !response.ok) {
413
- throw new AsgardeoAuthException(
414
- "JS-AUTH_HELPER-VIT-HE03",
415
- `Invalid response status received for jwks request (${response.statusText}).`,
416
- await response.json()
417
- );
418
- }
419
- const issuer = (await this._oidcProviderMetaData()).issuer;
420
- const { keys } = await response.json();
421
- const jwk = await this._cryptoHelper.getJWKForTheIdToken(idToken.split(".")[0], keys);
422
- return this._cryptoHelper.isValidIdToken(
423
- idToken,
424
- jwk,
425
- (await this._config()).clientID,
426
- issuer ?? "",
427
- this._cryptoHelper.decodeIDToken(idToken).sub,
428
- (await this._config()).clockTolerance,
429
- (await this._config()).validateIDTokenIssuer ?? true
430
- );
431
- }
432
- getAuthenticatedUserInfo(idToken) {
433
- const payload = this._cryptoHelper.decodeIDToken(idToken);
434
- const tenantDomain = extractTenantDomainFromIdTokenPayload_default(payload);
435
- const username = payload?.["username"] ?? "";
436
- const givenName = payload?.["given_name"] ?? "";
437
- const familyName = payload?.["family_name"] ?? "";
438
- const fullName = givenName && familyName ? `${givenName} ${familyName}` : givenName ? givenName : familyName ? familyName : "";
439
- const displayName = payload.preferred_username ?? fullName;
440
- return {
441
- displayName,
442
- tenantDomain,
443
- username,
444
- ...extractUserClaimsFromIdToken_default(payload)
445
- };
446
- }
447
- async replaceCustomGrantTemplateTags(text, userID) {
448
- let scope = ScopeConstants_default.OPENID;
449
- const configData = await this._config();
450
- const sessionData = await this._dataLayer.getSessionData(userID);
451
- if (configData.scope && configData.scope.length > 0) {
452
- if (!configData.scope.includes(ScopeConstants_default.OPENID)) {
453
- configData.scope.push(ScopeConstants_default.OPENID);
454
- }
455
- scope = configData.scope.join(" ");
456
- }
457
- return text.replace(TokenExchangeConstants_default.Placeholders.TOKEN, sessionData.access_token).replace(
458
- TokenExchangeConstants_default.Placeholders.USERNAME,
459
- this.getAuthenticatedUserInfo(sessionData.id_token).username
460
- ).replace(TokenExchangeConstants_default.Placeholders.SCOPE, scope).replace(TokenExchangeConstants_default.Placeholders.CLIENT_ID, configData.clientID).replace(TokenExchangeConstants_default.Placeholders.CLIENT_SECRET, configData.clientSecret ?? "");
461
- }
462
- async clearUserSessionData(userID) {
463
- await this._dataLayer.removeTemporaryData(userID);
464
- await this._dataLayer.removeSessionData(userID);
465
- }
466
- async handleTokenResponse(response, userID) {
467
- if (response.status !== 200 || !response.ok) {
468
- throw new AsgardeoAuthException(
469
- "JS-AUTH_HELPER-HTR-NE01",
470
- `Invalid response status received for token request (${response.statusText}).`,
471
- await response.json()
472
- );
473
- }
474
- const parsedResponse = await response.json();
475
- parsedResponse.created_at = (/* @__PURE__ */ new Date()).getTime();
476
- const shouldValidateIdToken = (await this._config()).validateIDToken;
477
- if (shouldValidateIdToken) {
478
- return this.validateIdToken(parsedResponse.id_token).then(async () => {
479
- await this._dataLayer.setSessionData(parsedResponse, userID);
480
- const tokenResponse = {
481
- accessToken: parsedResponse.access_token,
482
- createdAt: parsedResponse.created_at,
483
- expiresIn: parsedResponse.expires_in,
484
- idToken: parsedResponse.id_token,
485
- refreshToken: parsedResponse.refresh_token,
486
- scope: parsedResponse.scope,
487
- tokenType: parsedResponse.token_type
488
- };
489
- return Promise.resolve(tokenResponse);
490
- });
491
- } else {
492
- const tokenResponse = {
493
- accessToken: parsedResponse.access_token,
494
- createdAt: parsedResponse.created_at,
495
- expiresIn: parsedResponse.expires_in,
496
- idToken: parsedResponse.id_token,
497
- refreshToken: parsedResponse.refresh_token,
498
- scope: parsedResponse.scope,
499
- tokenType: parsedResponse.token_type
500
- };
501
- await this._dataLayer.setSessionData(parsedResponse, userID);
502
- return Promise.resolve(tokenResponse);
503
- }
504
- }
505
- };
506
-
507
- // src/utils/generatePkceStorageKey.ts
508
- var generatePkceStorageKey = (tempStore) => {
509
- const keys = [];
510
- Object.keys(tempStore).forEach((key) => {
511
- if (key.startsWith(PKCEConstants_default.Storage.StorageKeys.CODE_VERIFIER)) {
512
- keys.push(key);
392
+ Payload: {
393
+ /**
394
+ * The default scopes used in OIDC sign-in requests.
395
+ */
396
+ DEFAULT_SCOPES: [ScopeConstants_default.OPENID, ScopeConstants_default.PROFILE, ScopeConstants_default.INTERNAL_LOGIN]
513
397
  }
514
- });
515
- const lastKey = keys.sort().pop();
516
- const index = parseInt(lastKey?.split(PKCEConstants_default.Storage.StorageKeys.SEPARATOR)[1] ?? "-1");
517
- return `${PKCEConstants_default.Storage.StorageKeys.CODE_VERIFIER}${PKCEConstants_default.Storage.StorageKeys.SEPARATOR}${index + 1}`;
518
- };
519
- var generatePkceStorageKey_default = generatePkceStorageKey;
520
-
521
- // src/constants/OIDCRequestConstants.ts
522
- var OIDCRequestConstants = {
523
- Params: {
524
- /**
525
- * The authorization code returned from the authorization endpoint.
526
- * Used in the authorization code flow.
527
- */
528
- AUTHORIZATION_CODE: "code",
529
- /**
530
- * Session state parameter used for session management between the client and the OP.
531
- */
532
- SESSION_STATE: "session_state",
533
- /**
534
- * State parameter used to maintain state between the request and the callback.
535
- * Helps in preventing CSRF attacks.
536
- */
537
- STATE: "state",
538
- /**
539
- * Indicates whether sign-out was successful during the end-session flow.
540
- * May be returned by the OP after a logout request.
541
- */
542
- SIGN_OUT_SUCCESS: "sign_out_success"
543
398
  },
544
399
  /**
545
400
  * Sign-out related constants for managing the end-session flow in OIDC.
@@ -565,6 +420,19 @@ var OIDCRequestConstants = {
565
420
  };
566
421
  var OIDCRequestConstants_default = OIDCRequestConstants;
567
422
 
423
+ // src/errors/exception.ts
424
+ var AsgardeoAuthException = class {
425
+ constructor(code, name, message) {
426
+ __publicField(this, "name");
427
+ __publicField(this, "code");
428
+ __publicField(this, "message");
429
+ this.message = message;
430
+ this.name = name;
431
+ this.code = code;
432
+ Object.setPrototypeOf(this, new.target.prototype);
433
+ }
434
+ };
435
+
568
436
  // src/constants/TokenConstants.ts
569
437
  var TokenConstants = {
570
438
  /**
@@ -660,7 +528,7 @@ var IsomorphicCrypto = class {
660
528
  *
661
529
  * @param idToken - id_token received from the IdP.
662
530
  * @param jwk - public key used for signing.
663
- * @param clientID - app identification.
531
+ * @param clientId - app identification.
664
532
  * @param issuer - id_token issuer.
665
533
  * @param username - Username.
666
534
  * @param clockTolerance - Allowed leeway for id_tokens (in seconds).
@@ -669,12 +537,12 @@ var IsomorphicCrypto = class {
669
537
  *
670
538
  * @throws
671
539
  */
672
- isValidIdToken(idToken, jwk, clientID, issuer, username, clockTolerance, validateJwtIssuer) {
540
+ isValidIdToken(idToken, jwk, clientId, issuer, username, clockTolerance, validateJwtIssuer) {
673
541
  return this._cryptoUtils.verifyJwt(
674
542
  idToken,
675
543
  jwk,
676
544
  TokenConstants_default.SignatureValidation.SUPPORTED_ALGORITHMS,
677
- clientID,
545
+ clientId,
678
546
  issuer,
679
547
  username,
680
548
  clockTolerance,
@@ -701,9 +569,9 @@ var IsomorphicCrypto = class {
701
569
  *
702
570
  * @throws
703
571
  */
704
- decodeIDToken(idToken) {
572
+ decodeIdToken(idToken) {
705
573
  try {
706
- const utf8String = this._cryptoUtils.base64URLDecode(idToken.split(".")[1]);
574
+ const utf8String = this._cryptoUtils.base64URLDecode(idToken?.split(".")[1]);
707
575
  const payload = JSON.parse(utf8String);
708
576
  return payload;
709
577
  } catch (error) {
@@ -712,644 +580,467 @@ var IsomorphicCrypto = class {
712
580
  }
713
581
  };
714
582
 
715
- // src/__legacy__/core/authentication-core.ts
716
- var AuthenticationCore = class {
717
- constructor(dataLayer, cryptoUtils) {
718
- __publicField(this, "_dataLayer");
719
- __publicField(this, "_config");
720
- __publicField(this, "_oidcProviderMetaData");
721
- __publicField(this, "_authenticationHelper");
722
- __publicField(this, "_cryptoUtils");
723
- __publicField(this, "_cryptoHelper");
724
- this._cryptoUtils = cryptoUtils;
725
- this._cryptoHelper = new IsomorphicCrypto(cryptoUtils);
726
- this._authenticationHelper = new AuthenticationHelper(dataLayer, this._cryptoHelper);
727
- this._dataLayer = dataLayer;
728
- this._config = async () => await this._dataLayer.getConfigData();
729
- this._oidcProviderMetaData = async () => await this._dataLayer.getOIDCProviderMetaData();
730
- }
731
- async getAuthorizationURLParams(config, userID) {
732
- const configData = await this._config();
733
- const authorizeRequestParams = /* @__PURE__ */ new Map();
734
- authorizeRequestParams.set("response_type", "code");
735
- authorizeRequestParams.set("client_id", configData.clientID);
736
- let scope = ScopeConstants_default.OPENID;
737
- if (configData.scope && configData.scope.length > 0) {
738
- if (!configData.scope.includes(ScopeConstants_default.OPENID)) {
739
- configData.scope.push(ScopeConstants_default.OPENID);
740
- }
741
- scope = configData.scope.join(" ");
742
- }
743
- authorizeRequestParams.set("scope", scope);
744
- authorizeRequestParams.set("redirect_uri", configData.signInRedirectURL);
745
- if (configData.responseMode) {
746
- authorizeRequestParams.set("response_mode", configData.responseMode);
747
- }
748
- const tempStore = await this._dataLayer.getTemporaryData(userID);
749
- const pkceKey = await generatePkceStorageKey_default(tempStore);
750
- if (configData.enablePKCE) {
751
- const codeVerifier = this._cryptoHelper?.getCodeVerifier();
752
- const codeChallenge = this._cryptoHelper?.getCodeChallenge(codeVerifier);
753
- await this._dataLayer.setTemporaryDataParameter(pkceKey, codeVerifier, userID);
754
- authorizeRequestParams.set("code_challenge_method", "S256");
755
- authorizeRequestParams.set("code_challenge", codeChallenge);
756
- }
757
- if (configData.prompt) {
758
- authorizeRequestParams.set("prompt", configData.prompt);
759
- }
760
- const customParams = config;
761
- if (customParams) {
762
- for (const [key, value] of Object.entries(customParams)) {
763
- if (key != "" && value != "" && key !== OIDCRequestConstants_default.Params.STATE) {
764
- authorizeRequestParams.set(key, value.toString());
765
- }
766
- }
767
- }
768
- authorizeRequestParams.set(
769
- OIDCRequestConstants_default.Params.STATE,
770
- generateStateParamForRequestCorrelation_default(
771
- pkceKey,
772
- customParams ? customParams[OIDCRequestConstants_default.Params.STATE]?.toString() : ""
773
- )
774
- );
775
- return authorizeRequestParams;
776
- }
777
- async getAuthorizationURL(config, userID) {
778
- const authorizeEndpoint = await this._dataLayer.getOIDCProviderMetaDataParameter(
779
- OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.AUTHORIZATION
780
- );
781
- if (!authorizeEndpoint || authorizeEndpoint.trim().length === 0) {
782
- throw new AsgardeoAuthException(
783
- "JS-AUTH_CORE-GAU-NF01",
784
- "No authorization endpoint found.",
785
- "No authorization endpoint was found in the OIDC provider meta data from the well-known endpoint or the authorization endpoint passed to the SDK is empty."
786
- );
787
- }
788
- const authorizeRequest = new URL(authorizeEndpoint);
789
- const authorizeRequestParams = await this.getAuthorizationURLParams(config, userID);
790
- for (const [key, value] of authorizeRequestParams.entries()) {
791
- authorizeRequest.searchParams.append(key, value);
583
+ // src/constants/PKCEConstants.ts
584
+ var PKCEConstants = {
585
+ DEFAULT_CODE_CHALLENGE_METHOD: "S256",
586
+ /**
587
+ * Storage-related constants for managing PKCE state
588
+ */
589
+ Storage: {
590
+ /**
591
+ * Collection of storage keys used in PKCE implementation
592
+ */
593
+ StorageKeys: {
594
+ /**
595
+ * Key used to store the PKCE code verifier in temporary storage.
596
+ * The code verifier is a cryptographically random string that is
597
+ * used to generate the code challenge.
598
+ */
599
+ CODE_VERIFIER: "pkce_code_verifier",
600
+ /**
601
+ * Separator used in storage keys to create unique identifiers
602
+ * by combining different parts of the key.
603
+ */
604
+ SEPARATOR: "#"
792
605
  }
793
- return authorizeRequest.toString();
794
606
  }
795
- async requestAccessToken(authorizationCode, sessionState, state, userID, tokenRequestConfig) {
796
- const tokenEndpoint = (await this._oidcProviderMetaData()).token_endpoint;
797
- const configData = await this._config();
798
- if (!tokenEndpoint || tokenEndpoint.trim().length === 0) {
799
- throw new AsgardeoAuthException(
800
- "JS-AUTH_CORE-RAT1-NF01",
801
- "Token endpoint not found.",
802
- "No token endpoint was found in the OIDC provider meta data returned by the well-known endpoint or the token endpoint passed to the SDK is empty."
803
- );
804
- }
805
- sessionState && await this._dataLayer.setSessionDataParameter(
806
- OIDCRequestConstants_default.Params.SESSION_STATE,
807
- sessionState,
808
- userID
809
- );
810
- const body = new URLSearchParams();
811
- body.set("client_id", configData.clientID);
812
- if (configData.clientSecret && configData.clientSecret.trim().length > 0) {
813
- body.set("client_secret", configData.clientSecret);
814
- }
815
- const code = authorizationCode;
816
- body.set("code", code);
817
- body.set("grant_type", "authorization_code");
818
- body.set("redirect_uri", configData.signInRedirectURL);
819
- if (tokenRequestConfig?.params) {
820
- Object.entries(tokenRequestConfig.params).forEach(([key, value]) => {
821
- body.append(key, value);
822
- });
823
- }
824
- if (configData.enablePKCE) {
825
- body.set(
826
- "code_verifier",
827
- `${await this._dataLayer.getTemporaryDataParameter(extractPkceStorageKeyFromState_default(state), userID)}`
828
- );
829
- await this._dataLayer.removeTemporaryDataParameter(extractPkceStorageKeyFromState_default(state), userID);
830
- }
831
- let tokenResponse;
832
- try {
833
- tokenResponse = await fetch(tokenEndpoint, {
834
- body,
835
- credentials: configData.sendCookiesInRequests ? "include" : "same-origin",
836
- headers: {
837
- Accept: "application/json",
838
- "Content-Type": "application/x-www-form-urlencoded"
839
- },
840
- method: "POST"
841
- });
842
- } catch (error) {
843
- throw new AsgardeoAuthException(
844
- "JS-AUTH_CORE-RAT1-NE02",
845
- "Requesting access token failed",
846
- error ?? "The request to get the access token from the server failed."
847
- );
607
+ };
608
+ var PKCEConstants_default = PKCEConstants;
609
+
610
+ // src/utils/extractPkceStorageKeyFromState.ts
611
+ var extractPkceStorageKeyFromState = (state) => {
612
+ const index = parseInt(state.split("request_")[1]);
613
+ return `${PKCEConstants_default.Storage.StorageKeys.CODE_VERIFIER}${PKCEConstants_default.Storage.StorageKeys.SEPARATOR}${index}`;
614
+ };
615
+ var extractPkceStorageKeyFromState_default = extractPkceStorageKeyFromState;
616
+
617
+ // src/constants/TokenExchangeConstants.ts
618
+ var TokenExchangeConstants = {
619
+ /**
620
+ * Collection of placeholder strings used in token exchange operations.
621
+ * These placeholders are replaced with actual values when processing
622
+ * token exchange requests.
623
+ */
624
+ Placeholders: {
625
+ /**
626
+ * Placeholder for the token value in exchange requests.
627
+ * Usually replaced with an access token or refresh token.
628
+ */
629
+ ACCESS_TOKEN: "{{accessToken}}",
630
+ /**
631
+ * Placeholder for the username in token exchange operations.
632
+ * Used when user identity needs to be included in the exchange.
633
+ */
634
+ USERNAME: "{{username}}",
635
+ /**
636
+ * Placeholder for OAuth scopes in token exchange requests.
637
+ * Replaced with space-separated scope strings.
638
+ */
639
+ SCOPES: "{{scopes}}",
640
+ /**
641
+ * Placeholder for client ID in token exchange operations.
642
+ * Required for client authentication.
643
+ */
644
+ CLIENT_ID: "{{clientId}}",
645
+ /**
646
+ * Placeholder for client secret in token exchange operations.
647
+ * Used for client authentication in confidential client flows.
648
+ */
649
+ CLIENT_SECRET: "{{clientSecret}}"
650
+ }
651
+ };
652
+ var TokenExchangeConstants_default = TokenExchangeConstants;
653
+
654
+ // src/utils/extractUserClaimsFromIdToken.ts
655
+ var extractUserClaimsFromIdToken = (payload) => {
656
+ const filteredPayload = { ...payload };
657
+ const protocolClaims = [
658
+ "iss",
659
+ "aud",
660
+ "exp",
661
+ "iat",
662
+ "acr",
663
+ "amr",
664
+ "azp",
665
+ "auth_time",
666
+ "nonce",
667
+ "c_hash",
668
+ "at_hash",
669
+ "nbf",
670
+ "isk",
671
+ "sid",
672
+ "jti",
673
+ "sub"
674
+ ];
675
+ protocolClaims.forEach((claim) => {
676
+ delete filteredPayload[claim];
677
+ });
678
+ const userClaims = {};
679
+ Object.entries(filteredPayload).forEach(([key, value]) => {
680
+ const camelCasedKey = key.split("_").map((part, i) => i === 0 ? part : part[0].toUpperCase() + part.slice(1)).join("");
681
+ userClaims[camelCasedKey] = value;
682
+ });
683
+ return userClaims;
684
+ };
685
+ var extractUserClaimsFromIdToken_default = extractUserClaimsFromIdToken;
686
+
687
+ // src/errors/AsgardeoError.ts
688
+ var AsgardeoError = class _AsgardeoError extends Error {
689
+ constructor(message, code, origin) {
690
+ const _origin = _AsgardeoError.resolveOrigin(origin);
691
+ const prefix = `\u{1F6E1}\uFE0F Asgardeo - ${_origin}:`;
692
+ const regex = new RegExp(`\u{1F6E1}\uFE0F\\s*Asgardeo\\s*-\\s*${_origin}:`, "i");
693
+ const sanitized = message.replace(regex, "");
694
+ const _message = `${prefix} ${sanitized.trim()}
695
+
696
+ (code="${code}")
697
+ `;
698
+ super(_message);
699
+ __publicField(this, "code");
700
+ __publicField(this, "origin");
701
+ this.name = new.target.name;
702
+ this.code = code;
703
+ this.origin = _origin;
704
+ if (Error.captureStackTrace) {
705
+ Error.captureStackTrace(this, new.target);
848
706
  }
849
- if (!tokenResponse.ok) {
850
- throw new AsgardeoAuthException(
851
- "JS-AUTH_CORE-RAT1-HE03",
852
- `Requesting access token failed with ${tokenResponse.statusText}`,
853
- await tokenResponse.json()
707
+ }
708
+ static resolveOrigin(origin) {
709
+ if (!origin) {
710
+ return "@asgardeo/javascript";
711
+ }
712
+ return `@asgardeo/${origin}`;
713
+ }
714
+ toString() {
715
+ return `[${this.name}]
716
+ Message: ${this.message}`;
717
+ }
718
+ };
719
+
720
+ // src/errors/AsgardeoRuntimeError.ts
721
+ var AsgardeoRuntimeError = class extends AsgardeoError {
722
+ /**
723
+ * Creates an instance of AsgardeoRuntimeError.
724
+ *
725
+ * @param message - Human-readable description of the error
726
+ * @param code - A unique error code that identifies the error type
727
+ * @param details - Additional details about the error that might be helpful for debugging
728
+ * @param origin - Optional. The SDK origin (e.g. 'react', 'vue'). Defaults to generic 'Asgardeo'
729
+ * @constructor
730
+ */
731
+ constructor(message, code, origin, details) {
732
+ super(message, code, origin);
733
+ this.details = details;
734
+ Object.defineProperty(this, "name", {
735
+ value: "AsgardeoRuntimeError",
736
+ configurable: true,
737
+ writable: true
738
+ });
739
+ }
740
+ /**
741
+ * Returns a string representation of the runtime error
742
+ * @returns Formatted error string with name, code, details, and message
743
+ */
744
+ toString() {
745
+ const details = this.details ? `
746
+ Details: ${JSON.stringify(this.details, null, 2)}` : "";
747
+ return `[${this.name}] (code="${this.code}")${details}
748
+ Message: ${this.message}`;
749
+ }
750
+ };
751
+
752
+ // src/utils/processOpenIDScopes.ts
753
+ var processOpenIDScopes = (scopes) => {
754
+ let processedScopes = [];
755
+ if (scopes) {
756
+ if (Array.isArray(scopes)) {
757
+ processedScopes = scopes;
758
+ } else if (typeof scopes === "string") {
759
+ processedScopes = scopes.split(" ");
760
+ } else {
761
+ throw new AsgardeoRuntimeError(
762
+ "Scopes must be a string or an array of strings.",
763
+ "processOpenIDScopes-Invalid-001",
764
+ "javascript",
765
+ "The provided scopes are not in the expected format. Please provide a string or an array of strings."
854
766
  );
855
767
  }
856
- return await this._authenticationHelper.handleTokenResponse(tokenResponse, userID);
857
768
  }
858
- async refreshAccessToken(userID) {
859
- const tokenEndpoint = (await this._oidcProviderMetaData()).token_endpoint;
769
+ OIDCRequestConstants_default.SignIn.Payload.DEFAULT_SCOPES.forEach((defaultScope) => {
770
+ if (!processedScopes.includes(defaultScope)) {
771
+ processedScopes.push(defaultScope);
772
+ }
773
+ });
774
+ return processedScopes.join(" ");
775
+ };
776
+ var processOpenIDScopes_default = processOpenIDScopes;
777
+
778
+ // src/__legacy__/helpers/authentication-helper.ts
779
+ var AuthenticationHelper = class {
780
+ constructor(storageManager, cryptoHelper) {
781
+ __publicField(this, "_storageManager");
782
+ __publicField(this, "_config");
783
+ __publicField(this, "_oidcProviderMetaData");
784
+ __publicField(this, "_cryptoHelper");
785
+ this._storageManager = storageManager;
786
+ this._config = async () => this._storageManager.getConfigData();
787
+ this._oidcProviderMetaData = async () => this._storageManager.loadOpenIDProviderConfiguration();
788
+ this._cryptoHelper = cryptoHelper;
789
+ }
790
+ async resolveEndpoints(response) {
791
+ const oidcProviderMetaData = {};
860
792
  const configData = await this._config();
861
- const sessionData = await this._dataLayer.getSessionData(userID);
862
- if (!sessionData.refresh_token) {
793
+ configData.endpoints && Object.keys(configData.endpoints).forEach((endpointName) => {
794
+ const snakeCasedName = endpointName.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
795
+ oidcProviderMetaData[snakeCasedName] = configData?.endpoints ? configData.endpoints[endpointName] : "";
796
+ });
797
+ return { ...response, ...oidcProviderMetaData };
798
+ }
799
+ async resolveEndpointsExplicitly() {
800
+ const oidcProviderMetaData = {};
801
+ const configData = await this._config();
802
+ const requiredEndpoints = [
803
+ OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.AUTHORIZATION,
804
+ OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.END_SESSION,
805
+ OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.JWKS,
806
+ OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.SESSION_IFRAME,
807
+ OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.REVOCATION,
808
+ OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.TOKEN,
809
+ OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.ISSUER,
810
+ OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.USERINFO
811
+ ];
812
+ const isRequiredEndpointsContains = configData.endpoints ? requiredEndpoints.every(
813
+ (reqEndpointName) => configData.endpoints ? Object.keys(configData.endpoints).some((endpointName) => {
814
+ const snakeCasedName = endpointName.replace(
815
+ /[A-Z]/g,
816
+ (letter) => `_${letter.toLowerCase()}`
817
+ );
818
+ return snakeCasedName === reqEndpointName;
819
+ }) : false
820
+ ) : false;
821
+ if (!isRequiredEndpointsContains) {
863
822
  throw new AsgardeoAuthException(
864
- "JS-AUTH_CORE-RAT2-NF01",
865
- "No refresh token found.",
866
- "There was no refresh token found. Asgardeo doesn't return a refresh token if the refresh token grant is not enabled."
823
+ "JS-AUTH_HELPER-REE-NF01",
824
+ "Required endpoints missing",
825
+ "Some or all of the required endpoints are missing in the object passed to the `endpoints` attribute of the`AuthConfig` object."
867
826
  );
868
827
  }
869
- if (!tokenEndpoint || tokenEndpoint.trim().length === 0) {
828
+ configData.endpoints && Object.keys(configData.endpoints).forEach((endpointName) => {
829
+ const snakeCasedName = endpointName.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
830
+ oidcProviderMetaData[snakeCasedName] = configData?.endpoints ? configData.endpoints[endpointName] : "";
831
+ });
832
+ return { ...oidcProviderMetaData };
833
+ }
834
+ async resolveEndpointsByBaseURL() {
835
+ const oidcProviderMetaData = {};
836
+ const configData = await this._config();
837
+ const { baseUrl } = configData;
838
+ if (!baseUrl) {
870
839
  throw new AsgardeoAuthException(
871
- "JS-AUTH_CORE-RAT2-NF02",
872
- "No refresh token endpoint found.",
873
- "No refresh token endpoint was in the OIDC provider meta data returned by the well-known endpoint or the refresh token endpoint passed to the SDK is empty."
840
+ "JS-AUTH_HELPER_REBO-NF01",
841
+ "Base URL not defined.",
842
+ "Base URL is not defined in AuthClient config."
874
843
  );
875
844
  }
876
- const body = [];
877
- body.push(`client_id=${configData.clientID}`);
878
- body.push(`refresh_token=${sessionData.refresh_token}`);
879
- body.push("grant_type=refresh_token");
880
- if (configData.clientSecret && configData.clientSecret.trim().length > 0) {
881
- body.push(`client_secret=${configData.clientSecret}`);
845
+ configData.endpoints && Object.keys(configData.endpoints).forEach((endpointName) => {
846
+ const snakeCasedName = endpointName.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
847
+ oidcProviderMetaData[snakeCasedName] = configData?.endpoints ? configData.endpoints[endpointName] : "";
848
+ });
849
+ const defaultEndpoints = {
850
+ [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.AUTHORIZATION]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.AUTHORIZATION}`,
851
+ [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.END_SESSION]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.END_SESSION}`,
852
+ [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.ISSUER]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.ISSUER}`,
853
+ [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.JWKS]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.JWKS}`,
854
+ [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.SESSION_IFRAME]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.SESSION_IFRAME}`,
855
+ [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.REVOCATION]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.REVOCATION}`,
856
+ [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.TOKEN]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.TOKEN}`,
857
+ [OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.USERINFO]: `${baseUrl}${OIDCDiscoveryConstants_default.Endpoints.USERINFO}`
858
+ };
859
+ return { ...defaultEndpoints, ...oidcProviderMetaData };
860
+ }
861
+ async validateIdToken(idToken) {
862
+ const jwksEndpoint = (await this._storageManager.loadOpenIDProviderConfiguration()).jwks_uri;
863
+ const configData = await this._config();
864
+ if (!jwksEndpoint || jwksEndpoint.trim().length === 0) {
865
+ throw new AsgardeoAuthException(
866
+ "JS_AUTH_HELPER-VIT-NF01",
867
+ "JWKS endpoint not found.",
868
+ "No JWKS endpoint was found in the OIDC provider meta data returned by the well-known endpoint or the JWKS endpoint passed to the SDK is empty."
869
+ );
882
870
  }
883
- let tokenResponse;
871
+ let response;
884
872
  try {
885
- tokenResponse = await fetch(tokenEndpoint, {
886
- body: body.join("&"),
887
- credentials: configData.sendCookiesInRequests ? "include" : "same-origin",
888
- headers: {
889
- Accept: "application/json",
890
- "Content-Type": "application/x-www-form-urlencoded"
891
- },
892
- method: "POST"
873
+ response = await fetch(jwksEndpoint, {
874
+ credentials: configData.sendCookiesInRequests ? "include" : "same-origin"
893
875
  });
894
876
  } catch (error) {
895
877
  throw new AsgardeoAuthException(
896
- "JS-AUTH_CORE-RAT2-NR03",
897
- "Refresh access token request failed.",
898
- error ?? "The request to refresh the access token failed."
899
- );
900
- }
901
- if (!tokenResponse.ok) {
902
- throw new AsgardeoAuthException(
903
- "JS-AUTH_CORE-RAT2-HE04",
904
- `Refreshing access token failed with ${tokenResponse.statusText}`,
905
- await tokenResponse.json()
906
- );
907
- }
908
- return this._authenticationHelper.handleTokenResponse(tokenResponse, userID);
909
- }
910
- async revokeAccessToken(userID) {
911
- const revokeTokenEndpoint = (await this._oidcProviderMetaData()).revocation_endpoint;
912
- const configData = await this._config();
913
- if (!revokeTokenEndpoint || revokeTokenEndpoint.trim().length === 0) {
914
- throw new AsgardeoAuthException(
915
- "JS-AUTH_CORE-RAT3-NF01",
916
- "No revoke access token endpoint found.",
917
- "No revoke access token endpoint was found in the OIDC provider meta data returned by the well-known endpoint or the revoke access token endpoint passed to the SDK is empty."
918
- );
919
- }
920
- const body = [];
921
- body.push(`client_id=${configData.clientID}`);
922
- body.push(`token=${(await this._dataLayer.getSessionData(userID)).access_token}`);
923
- body.push("token_type_hint=access_token");
924
- if (configData.clientSecret && configData.clientSecret.trim().length > 0) {
925
- body.push(`client_secret=${configData.clientSecret}`);
926
- }
927
- let response;
928
- try {
929
- response = await fetch(revokeTokenEndpoint, {
930
- body: body.join("&"),
931
- credentials: configData.sendCookiesInRequests ? "include" : "same-origin",
932
- headers: {
933
- Accept: "application/json",
934
- "Content-Type": "application/x-www-form-urlencoded"
935
- },
936
- method: "POST"
937
- });
938
- } catch (error) {
939
- throw new AsgardeoAuthException(
940
- "JS-AUTH_CORE-RAT3-NE02",
941
- "The request to revoke access token failed.",
942
- error ?? "The request sent to revoke the access token failed."
878
+ "JS-AUTH_HELPER-VIT-NE02",
879
+ "Request to jwks endpoint failed.",
880
+ error ?? "The request sent to get the jwks from the server failed."
943
881
  );
944
882
  }
945
883
  if (response.status !== 200 || !response.ok) {
946
884
  throw new AsgardeoAuthException(
947
- "JS-AUTH_CORE-RAT3-HE03",
948
- `Invalid response status received for revoke access token request (${response.statusText}).`,
885
+ "JS-AUTH_HELPER-VIT-HE03",
886
+ `Invalid response status received for jwks request (${response.statusText}).`,
949
887
  await response.json()
950
888
  );
951
889
  }
952
- this._authenticationHelper.clearUserSessionData(userID);
953
- return Promise.resolve(response);
954
- }
955
- async requestCustomGrant(customGrantParams, userID) {
956
- const oidcProviderMetadata = await this._oidcProviderMetaData();
957
- const configData = await this._config();
958
- let tokenEndpoint;
959
- if (customGrantParams.tokenEndpoint && customGrantParams.tokenEndpoint.trim().length !== 0) {
960
- tokenEndpoint = customGrantParams.tokenEndpoint;
961
- } else {
962
- tokenEndpoint = oidcProviderMetadata.token_endpoint;
963
- }
964
- if (!tokenEndpoint || tokenEndpoint.trim().length === 0) {
965
- throw new AsgardeoAuthException(
966
- "JS-AUTH_CORE-RCG-NF01",
967
- "Token endpoint not found.",
968
- "No token endpoint was found in the OIDC provider meta data returned by the well-known endpoint or the token endpoint passed to the SDK is empty."
969
- );
970
- }
971
- const data = await Promise.all(
972
- Object.entries(customGrantParams.data).map(async ([key, value]) => {
973
- const newValue = await this._authenticationHelper.replaceCustomGrantTemplateTags(
974
- value,
975
- userID
976
- );
977
- return `${key}=${newValue}`;
978
- })
890
+ const { issuer } = await this._oidcProviderMetaData();
891
+ const { keys } = await response.json();
892
+ const jwk = await this._cryptoHelper.getJWKForTheIdToken(idToken.split(".")[0], keys);
893
+ return this._cryptoHelper.isValidIdToken(
894
+ idToken,
895
+ jwk,
896
+ (await this._config()).clientId,
897
+ issuer ?? "",
898
+ this._cryptoHelper.decodeIdToken(idToken).sub,
899
+ (await this._config()).clockTolerance,
900
+ (await this._config()).validateIDTokenIssuer ?? true
979
901
  );
980
- let requestHeaders = {
981
- Accept: "application/json",
982
- "Content-Type": "application/x-www-form-urlencoded"
983
- };
984
- if (customGrantParams.attachToken) {
985
- requestHeaders = {
986
- ...requestHeaders,
987
- Authorization: `Bearer ${(await this._dataLayer.getSessionData(userID)).access_token}`
988
- };
989
- }
990
- const requestConfig = {
991
- body: data.join("&"),
992
- credentials: configData.sendCookiesInRequests ? "include" : "same-origin",
993
- headers: new Headers(requestHeaders),
994
- method: "POST"
902
+ }
903
+ getAuthenticatedUserInfo(idToken) {
904
+ const payload = this._cryptoHelper.decodeIdToken(idToken);
905
+ const username = payload?.["username"] ?? "";
906
+ const givenName = payload?.["given_name"] ?? "";
907
+ const familyName = payload?.["family_name"] ?? "";
908
+ const fullName = givenName && familyName ? `${givenName} ${familyName}` : givenName || familyName || "";
909
+ const displayName = payload.preferred_username ?? fullName;
910
+ return {
911
+ displayName,
912
+ username,
913
+ ...extractUserClaimsFromIdToken_default(payload)
995
914
  };
996
- let response;
997
- try {
998
- response = await fetch(tokenEndpoint, requestConfig);
999
- } catch (error) {
1000
- throw new AsgardeoAuthException(
1001
- "JS-AUTH_CORE-RCG-NE02",
1002
- "The custom grant request failed.",
1003
- error ?? "The request sent to get the custom grant failed."
1004
- );
915
+ }
916
+ async replaceCustomGrantTemplateTags(text, userId) {
917
+ const configData = await this._config();
918
+ const sessionData = await this._storageManager.getSessionData(userId);
919
+ const scope = processOpenIDScopes_default(configData.scopes);
920
+ if (typeof text !== "string") {
921
+ return text;
1005
922
  }
923
+ return text.replace(TokenExchangeConstants_default.Placeholders.ACCESS_TOKEN, sessionData.access_token).replace(
924
+ TokenExchangeConstants_default.Placeholders.USERNAME,
925
+ this.getAuthenticatedUserInfo(sessionData.id_token).username
926
+ ).replace(TokenExchangeConstants_default.Placeholders.SCOPES, scope).replace(TokenExchangeConstants_default.Placeholders.CLIENT_ID, configData.clientId).replace(TokenExchangeConstants_default.Placeholders.CLIENT_SECRET, configData.clientSecret ?? "");
927
+ }
928
+ async clearSession(userId) {
929
+ await this._storageManager.removeTemporaryData(userId);
930
+ await this._storageManager.removeSessionData(userId);
931
+ }
932
+ async handleTokenResponse(response, userId) {
1006
933
  if (response.status !== 200 || !response.ok) {
1007
934
  throw new AsgardeoAuthException(
1008
- "JS-AUTH_CORE-RCG-HE03",
1009
- `Invalid response status received for the custom grant request. (${response.statusText})`,
935
+ "JS-AUTH_HELPER-HTR-NE01",
936
+ `Invalid response status received for token request (${response.statusText}).`,
1010
937
  await response.json()
1011
938
  );
1012
939
  }
1013
- if (customGrantParams.returnsSession) {
1014
- return this._authenticationHelper.handleTokenResponse(response, userID);
1015
- } else {
1016
- return Promise.resolve(await response.json());
940
+ const parsedResponse = await response.json();
941
+ parsedResponse.created_at = (/* @__PURE__ */ new Date()).getTime();
942
+ const shouldValidateIdToken = (await this._config()).validateIDToken;
943
+ if (shouldValidateIdToken) {
944
+ return this.validateIdToken(parsedResponse.id_token).then(async () => {
945
+ await this._storageManager.setSessionData(parsedResponse, userId);
946
+ const tokenResponse2 = {
947
+ accessToken: parsedResponse.access_token,
948
+ createdAt: parsedResponse.created_at,
949
+ expiresIn: parsedResponse.expires_in,
950
+ idToken: parsedResponse.id_token,
951
+ refreshToken: parsedResponse.refresh_token,
952
+ scope: parsedResponse.scope,
953
+ tokenType: parsedResponse.token_type
954
+ };
955
+ return Promise.resolve(tokenResponse2);
956
+ });
1017
957
  }
1018
- }
1019
- async getBasicUserInfo(userID) {
1020
- const sessionData = await this._dataLayer.getSessionData(userID);
1021
- const authenticatedUser = this._authenticationHelper.getAuthenticatedUserInfo(
1022
- sessionData?.id_token
1023
- );
1024
- let basicUserInfo = {
1025
- allowedScopes: sessionData.scope,
1026
- sessionState: sessionData.session_state
958
+ const tokenResponse = {
959
+ accessToken: parsedResponse.access_token,
960
+ createdAt: parsedResponse.created_at,
961
+ expiresIn: parsedResponse.expires_in,
962
+ idToken: parsedResponse.id_token,
963
+ refreshToken: parsedResponse.refresh_token,
964
+ scope: parsedResponse.scope,
965
+ tokenType: parsedResponse.token_type
1027
966
  };
1028
- Object.keys(authenticatedUser).forEach((key) => {
1029
- if (authenticatedUser[key] === void 0 || authenticatedUser[key] === "" || authenticatedUser[key] === null) {
1030
- delete authenticatedUser[key];
1031
- }
1032
- });
1033
- basicUserInfo = { ...basicUserInfo, ...authenticatedUser };
1034
- return basicUserInfo;
1035
- }
1036
- async getDecodedIDToken(userID) {
1037
- const idToken = (await this._dataLayer.getSessionData(userID)).id_token;
1038
- const payload = this._cryptoHelper.decodeIDToken(idToken);
1039
- return payload;
1040
- }
1041
- async getCryptoHelper() {
1042
- return this._cryptoHelper;
1043
- }
1044
- async getIDToken(userID) {
1045
- return (await this._dataLayer.getSessionData(userID)).id_token;
967
+ await this._storageManager.setSessionData(parsedResponse, userId);
968
+ return Promise.resolve(tokenResponse);
1046
969
  }
1047
- async getOIDCProviderMetaData(forceInit) {
1048
- const configData = await this._config();
1049
- if (!forceInit && await this._dataLayer.getTemporaryDataParameter(
1050
- OIDCDiscoveryConstants_default.Storage.StorageKeys.OPENID_PROVIDER_CONFIG_INITIATED
1051
- )) {
1052
- return Promise.resolve();
970
+ };
971
+
972
+ // src/utils/generatePkceStorageKey.ts
973
+ var generatePkceStorageKey = (tempStore) => {
974
+ const keys = [];
975
+ Object.keys(tempStore).forEach((key) => {
976
+ if (key.startsWith(PKCEConstants_default.Storage.StorageKeys.CODE_VERIFIER)) {
977
+ keys.push(key);
1053
978
  }
1054
- const wellKnownEndpoint = configData.wellKnownEndpoint;
1055
- if (wellKnownEndpoint) {
1056
- let response;
1057
- try {
1058
- response = await fetch(wellKnownEndpoint);
1059
- if (response.status !== 200 || !response.ok) {
1060
- throw new Error();
1061
- }
1062
- } catch {
1063
- throw new AsgardeoAuthException(
1064
- "JS-AUTH_CORE-GOPMD-HE01",
1065
- "Invalid well-known response",
1066
- "The well known endpoint response has been failed with an error."
1067
- );
1068
- }
1069
- await this._dataLayer.setOIDCProviderMetaData(
1070
- await this._authenticationHelper.resolveEndpoints(await response.json())
1071
- );
1072
- await this._dataLayer.setTemporaryDataParameter(
1073
- OIDCDiscoveryConstants_default.Storage.StorageKeys.OPENID_PROVIDER_CONFIG_INITIATED,
1074
- true
1075
- );
1076
- return Promise.resolve();
1077
- } else if (configData.baseUrl) {
1078
- try {
1079
- await this._dataLayer.setOIDCProviderMetaData(await this._authenticationHelper.resolveEndpointsByBaseURL());
1080
- } catch (error) {
1081
- throw new AsgardeoAuthException(
1082
- "JS-AUTH_CORE-GOPMD-IV02",
1083
- "Resolving endpoints failed.",
1084
- error ?? "Resolving endpoints by base url failed."
1085
- );
1086
- }
1087
- await this._dataLayer.setTemporaryDataParameter(
1088
- OIDCDiscoveryConstants_default.Storage.StorageKeys.OPENID_PROVIDER_CONFIG_INITIATED,
1089
- true
1090
- );
1091
- return Promise.resolve();
979
+ });
980
+ const lastKey = keys.sort().pop();
981
+ const index = parseInt(lastKey?.split(PKCEConstants_default.Storage.StorageKeys.SEPARATOR)[1] ?? "-1");
982
+ return `${PKCEConstants_default.Storage.StorageKeys.CODE_VERIFIER}${PKCEConstants_default.Storage.StorageKeys.SEPARATOR}${index + 1}`;
983
+ };
984
+ var generatePkceStorageKey_default = generatePkceStorageKey;
985
+
986
+ // src/utils/generateStateParamForRequestCorrelation.ts
987
+ var generateStateParamForRequestCorrelation = (pkceKey, state) => {
988
+ const index = parseInt(pkceKey.split(PKCEConstants_default.Storage.StorageKeys.SEPARATOR)[1]);
989
+ return state ? `${state}_request_${index}` : `request_${index}`;
990
+ };
991
+ var generateStateParamForRequestCorrelation_default = generateStateParamForRequestCorrelation;
992
+
993
+ // src/utils/getAuthorizeRequestUrlParams.ts
994
+ var getAuthorizeRequestUrlParams = (options, pkceOptions, customParams) => {
995
+ const { redirectUri, clientId, clientSecret, scopes, responseMode, codeChallenge, codeChallengeMethod, prompt } = options;
996
+ const authorizeRequestParams = /* @__PURE__ */ new Map();
997
+ authorizeRequestParams.set("response_type", "code");
998
+ authorizeRequestParams.set("client_id", clientId);
999
+ authorizeRequestParams.set("scope", scopes);
1000
+ authorizeRequestParams.set("redirect_uri", redirectUri);
1001
+ if (responseMode) {
1002
+ authorizeRequestParams.set("response_mode", responseMode);
1003
+ }
1004
+ const pkceKey = pkceOptions?.key;
1005
+ if (codeChallenge) {
1006
+ authorizeRequestParams.set("code_challenge", codeChallenge);
1007
+ if (codeChallengeMethod) {
1008
+ authorizeRequestParams.set("code_challenge_method", codeChallengeMethod);
1092
1009
  } else {
1093
- await this._dataLayer.setOIDCProviderMetaData(await this._authenticationHelper.resolveEndpointsExplicitly());
1094
- await this._dataLayer.setTemporaryDataParameter(
1095
- OIDCDiscoveryConstants_default.Storage.StorageKeys.OPENID_PROVIDER_CONFIG_INITIATED,
1096
- true
1010
+ throw new AsgardeoRuntimeError(
1011
+ "Code challenge method is required when code challenge is provided.",
1012
+ "getAuthorizeRequestUrlParams-ValidationError-001",
1013
+ "javascript",
1014
+ "When PKCE is enabled, the code challenge method must be provided along with the code challenge."
1097
1015
  );
1098
- return Promise.resolve();
1099
1016
  }
1100
1017
  }
1101
- // TODO: Remove `Partial<OIDCEndpoints>` once the refactoring is done.
1102
- async getOIDCServiceEndpoints() {
1103
- const oidcProviderMetaData = await this._oidcProviderMetaData();
1104
- return {
1105
- authorizationEndpoint: oidcProviderMetaData.authorization_endpoint ?? "",
1106
- checkSessionIframe: oidcProviderMetaData.check_session_iframe ?? "",
1107
- endSessionEndpoint: oidcProviderMetaData.end_session_endpoint ?? "",
1108
- introspectionEndpoint: oidcProviderMetaData.introspection_endpoint ?? "",
1109
- issuer: oidcProviderMetaData.issuer ?? "",
1110
- jwksUri: oidcProviderMetaData.jwks_uri ?? "",
1111
- registrationEndpoint: oidcProviderMetaData.registration_endpoint ?? "",
1112
- revocationEndpoint: oidcProviderMetaData.revocation_endpoint ?? "",
1113
- tokenEndpoint: oidcProviderMetaData.token_endpoint ?? "",
1114
- userinfoEndpoint: oidcProviderMetaData.userinfo_endpoint ?? ""
1115
- };
1018
+ if (prompt) {
1019
+ authorizeRequestParams.set("prompt", prompt);
1116
1020
  }
1117
- async getSignOutURL(userID) {
1118
- const logoutEndpoint = (await this._oidcProviderMetaData())?.end_session_endpoint;
1119
- const configData = await this._config();
1120
- if (!logoutEndpoint || logoutEndpoint.trim().length === 0) {
1121
- throw new AsgardeoAuthException(
1122
- "JS-AUTH_CORE-GSOU-NF01",
1123
- "Sign-out endpoint not found.",
1124
- "No sign-out endpoint was found in the OIDC provider meta data returned by the well-known endpoint or the sign-out endpoint passed to the SDK is empty."
1125
- );
1126
- }
1127
- const callbackURL = configData?.signOutRedirectURL ?? configData?.signInRedirectURL;
1128
- if (!callbackURL || callbackURL.trim().length === 0) {
1129
- throw new AsgardeoAuthException(
1130
- "JS-AUTH_CORE-GSOU-NF03",
1131
- "No sign-out redirect URL found.",
1132
- "The sign-out redirect URL cannot be found or the URL passed to the SDK is empty. No sign-in redirect URL has been found either. "
1133
- );
1134
- }
1135
- const queryParams = new URLSearchParams();
1136
- queryParams.set("post_logout_redirect_uri", callbackURL);
1137
- if (configData.sendIdTokenInLogoutRequest) {
1138
- const idToken = (await this._dataLayer.getSessionData(userID))?.id_token;
1139
- if (!idToken || idToken.trim().length === 0) {
1140
- throw new AsgardeoAuthException(
1141
- "JS-AUTH_CORE-GSOU-NF02",
1142
- "ID token not found.",
1143
- "No ID token could be found. Either the session information is lost or you have not signed in."
1144
- );
1021
+ if (customParams) {
1022
+ for (const [key, value] of Object.entries(customParams)) {
1023
+ if (key !== "" && value !== "" && key !== OIDCRequestConstants_default.Params.STATE) {
1024
+ authorizeRequestParams.set(key, value.toString());
1145
1025
  }
1146
- queryParams.set("id_token_hint", idToken);
1147
- } else {
1148
- queryParams.set("client_id", configData.clientID);
1149
1026
  }
1150
- queryParams.set("state", OIDCRequestConstants_default.Params.SIGN_OUT_SUCCESS);
1151
- return `${logoutEndpoint}?${queryParams.toString()}`;
1152
- }
1153
- async clearUserSessionData(userID) {
1154
- await this._authenticationHelper.clearUserSessionData(userID);
1155
- }
1156
- async getAccessToken(userID) {
1157
- return (await this._dataLayer.getSessionData(userID))?.access_token;
1158
- }
1159
- /**
1160
- * The created timestamp of the token response in milliseconds.
1161
- *
1162
- * @param userID - User ID
1163
- * @returns Created at timestamp of the token response in milliseconds.
1164
- */
1165
- async getCreatedAt(userID) {
1166
- return (await this._dataLayer.getSessionData(userID))?.created_at;
1167
- }
1168
- /**
1169
- * The expires timestamp of the token response in seconds.
1170
- *
1171
- * @param userID - User ID
1172
- * @returns Expires in timestamp of the token response in seconds.
1173
- */
1174
- async getExpiresIn(userID) {
1175
- return (await this._dataLayer.getSessionData(userID))?.expires_in;
1176
- }
1177
- async isAuthenticated(userID) {
1178
- const isAccessTokenAvailable = Boolean(await this.getAccessToken(userID));
1179
- const createdAt = await this.getCreatedAt(userID);
1180
- const expiresInString = await this.getExpiresIn(userID);
1181
- if (!expiresInString) {
1182
- return false;
1183
- }
1184
- const expiresIn = parseInt(expiresInString) * 1e3;
1185
- const currentTime = (/* @__PURE__ */ new Date()).getTime();
1186
- const isAccessTokenValid = createdAt + expiresIn > currentTime;
1187
- const isAuthenticated = isAccessTokenAvailable && isAccessTokenValid;
1188
- return isAuthenticated;
1189
- }
1190
- async getPKCECode(state, userID) {
1191
- return await this._dataLayer.getTemporaryDataParameter(extractPkceStorageKeyFromState_default(state), userID);
1192
- }
1193
- async setPKCECode(pkce, state, userID) {
1194
- return await this._dataLayer.setTemporaryDataParameter(extractPkceStorageKeyFromState_default(state), pkce, userID);
1195
- }
1196
- async updateConfig(config) {
1197
- await this._dataLayer.setConfigData(config);
1198
- await this.getOIDCProviderMetaData(true);
1199
- }
1200
- };
1201
-
1202
- // src/__legacy__/data/data-layer.ts
1203
- var ASGARDEO_SESSION_ACTIVE = "asgardeo-session-active";
1204
- var DataLayer = class {
1205
- constructor(instanceID, store) {
1206
- __publicField(this, "_id");
1207
- __publicField(this, "_store");
1208
- this._id = instanceID;
1209
- this._store = store;
1210
- }
1211
- async setDataInBulk(key, data) {
1212
- const existingDataJSON = await this._store.getData(key) ?? null;
1213
- const existingData = existingDataJSON && JSON.parse(existingDataJSON);
1214
- const dataToBeSaved = { ...existingData, ...data };
1215
- const dataToBeSavedJSON = JSON.stringify(dataToBeSaved);
1216
- await this._store.setData(key, dataToBeSavedJSON);
1217
- }
1218
- async setValue(key, attribute, value) {
1219
- const existingDataJSON = await this._store.getData(key) ?? null;
1220
- const existingData = existingDataJSON && JSON.parse(existingDataJSON);
1221
- const dataToBeSaved = { ...existingData, [attribute]: value };
1222
- const dataToBeSavedJSON = JSON.stringify(dataToBeSaved);
1223
- await this._store.setData(key, dataToBeSavedJSON);
1224
- }
1225
- async removeValue(key, attribute) {
1226
- const existingDataJSON = await this._store.getData(key) ?? null;
1227
- const existingData = existingDataJSON && JSON.parse(existingDataJSON);
1228
- const dataToBeSaved = { ...existingData };
1229
- delete dataToBeSaved[attribute];
1230
- const dataToBeSavedJSON = JSON.stringify(dataToBeSaved);
1231
- await this._store.setData(key, dataToBeSavedJSON);
1232
- }
1233
- _resolveKey(store, userID) {
1234
- return userID ? `${store}-${this._id}-${userID}` : `${store}-${this._id}`;
1235
- }
1236
- isLocalStorageAvailable() {
1237
- try {
1238
- const testValue = "__ASGARDEO_AUTH_CORE_LOCAL_STORAGE_TEST__";
1239
- localStorage.setItem(testValue, testValue);
1240
- localStorage.removeItem(testValue);
1241
- return true;
1242
- } catch (error) {
1243
- return false;
1244
- }
1245
- }
1246
- async setConfigData(config) {
1247
- await this.setDataInBulk(this._resolveKey("config_data" /* ConfigData */), config);
1248
- }
1249
- async setOIDCProviderMetaData(oidcProviderMetaData) {
1250
- this.setDataInBulk(this._resolveKey("oidc_provider_meta_data" /* OIDCProviderMetaData */), oidcProviderMetaData);
1251
- }
1252
- async setTemporaryData(temporaryData, userID) {
1253
- this.setDataInBulk(this._resolveKey("temporary_data" /* TemporaryData */, userID), temporaryData);
1254
- }
1255
- async setSessionData(sessionData, userID) {
1256
- this.setDataInBulk(this._resolveKey("session_data" /* SessionData */, userID), sessionData);
1257
- }
1258
- async setCustomData(key, customData, userID) {
1259
- this.setDataInBulk(this._resolveKey(key, userID), customData);
1260
- }
1261
- async getConfigData() {
1262
- return JSON.parse(await this._store.getData(this._resolveKey("config_data" /* ConfigData */)) ?? null);
1263
- }
1264
- async getOIDCProviderMetaData() {
1265
- return JSON.parse(await this._store.getData(this._resolveKey("oidc_provider_meta_data" /* OIDCProviderMetaData */)) ?? null);
1266
- }
1267
- async getTemporaryData(userID) {
1268
- return JSON.parse(await this._store.getData(this._resolveKey("temporary_data" /* TemporaryData */, userID)) ?? null);
1269
- }
1270
- async getSessionData(userID) {
1271
- return JSON.parse(await this._store.getData(this._resolveKey("session_data" /* SessionData */, userID)) ?? null);
1272
- }
1273
- async getCustomData(key, userID) {
1274
- return JSON.parse(await this._store.getData(this._resolveKey(key, userID)) ?? null);
1275
- }
1276
- setSessionStatus(status) {
1277
- this.isLocalStorageAvailable() && localStorage.setItem(`${ASGARDEO_SESSION_ACTIVE}`, status);
1278
- }
1279
- getSessionStatus() {
1280
- return this.isLocalStorageAvailable() ? localStorage.getItem(`${ASGARDEO_SESSION_ACTIVE}`) ?? "" : "";
1281
- }
1282
- removeSessionStatus() {
1283
- this.isLocalStorageAvailable() && localStorage.removeItem(`${ASGARDEO_SESSION_ACTIVE}`);
1284
- }
1285
- async removeConfigData() {
1286
- await this._store.removeData(this._resolveKey("config_data" /* ConfigData */));
1287
- }
1288
- async removeOIDCProviderMetaData() {
1289
- await this._store.removeData(this._resolveKey("oidc_provider_meta_data" /* OIDCProviderMetaData */));
1290
- }
1291
- async removeTemporaryData(userID) {
1292
- await this._store.removeData(this._resolveKey("temporary_data" /* TemporaryData */, userID));
1293
- }
1294
- async removeSessionData(userID) {
1295
- await this._store.removeData(this._resolveKey("session_data" /* SessionData */, userID));
1296
- }
1297
- async getConfigDataParameter(key) {
1298
- const data = await this._store.getData(this._resolveKey("config_data" /* ConfigData */));
1299
- return data && JSON.parse(data)[key];
1300
- }
1301
- async getOIDCProviderMetaDataParameter(key) {
1302
- const data = await this._store.getData(this._resolveKey("oidc_provider_meta_data" /* OIDCProviderMetaData */));
1303
- return data && JSON.parse(data)[key];
1304
- }
1305
- async getTemporaryDataParameter(key, userID) {
1306
- const data = await this._store.getData(this._resolveKey("temporary_data" /* TemporaryData */, userID));
1307
- return data && JSON.parse(data)[key];
1308
- }
1309
- async getSessionDataParameter(key, userID) {
1310
- const data = await this._store.getData(this._resolveKey("session_data" /* SessionData */, userID));
1311
- return data && JSON.parse(data)[key];
1312
- }
1313
- async setConfigDataParameter(key, value) {
1314
- await this.setValue(this._resolveKey("config_data" /* ConfigData */), key, value);
1315
- }
1316
- async setOIDCProviderMetaDataParameter(key, value) {
1317
- await this.setValue(this._resolveKey("oidc_provider_meta_data" /* OIDCProviderMetaData */), key, value);
1318
- }
1319
- async setTemporaryDataParameter(key, value, userID) {
1320
- await this.setValue(this._resolveKey("temporary_data" /* TemporaryData */, userID), key, value);
1321
- }
1322
- async setSessionDataParameter(key, value, userID) {
1323
- await this.setValue(this._resolveKey("session_data" /* SessionData */, userID), key, value);
1324
- }
1325
- async removeConfigDataParameter(key) {
1326
- await this.removeValue(this._resolveKey("config_data" /* ConfigData */), key);
1327
- }
1328
- async removeOIDCProviderMetaDataParameter(key) {
1329
- await this.removeValue(this._resolveKey("oidc_provider_meta_data" /* OIDCProviderMetaData */), key);
1330
- }
1331
- async removeTemporaryDataParameter(key, userID) {
1332
- await this.removeValue(this._resolveKey("temporary_data" /* TemporaryData */, userID), key);
1333
- }
1334
- async removeSessionDataParameter(key, userID) {
1335
- await this.removeValue(this._resolveKey("session_data" /* SessionData */, userID), key);
1336
1027
  }
1028
+ authorizeRequestParams.set(
1029
+ OIDCRequestConstants_default.Params.STATE,
1030
+ generateStateParamForRequestCorrelation_default(
1031
+ pkceKey,
1032
+ customParams ? customParams[OIDCRequestConstants_default.Params.STATE]?.toString() : ""
1033
+ )
1034
+ );
1035
+ return authorizeRequestParams;
1337
1036
  };
1338
-
1339
- // src/models/oauth-response.ts
1340
- var ResponseMode = /* @__PURE__ */ ((ResponseMode2) => {
1341
- ResponseMode2["FormPost"] = "form_post";
1342
- ResponseMode2["Query"] = "query";
1343
- ResponseMode2["Direct"] = "direct";
1344
- return ResponseMode2;
1345
- })(ResponseMode || {});
1037
+ var getAuthorizeRequestUrlParams_default = getAuthorizeRequestUrlParams;
1346
1038
 
1347
1039
  // src/__legacy__/client.ts
1348
1040
  var DefaultConfig = {
1349
1041
  clockTolerance: 300,
1350
1042
  enablePKCE: true,
1351
- responseMode: "query" /* Query */,
1352
- scope: [ScopeConstants_default.OPENID],
1043
+ responseMode: "query",
1353
1044
  sendCookiesInRequests: true,
1354
1045
  validateIDToken: true,
1355
1046
  validateIDTokenIssuer: true
@@ -1371,8 +1062,12 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1371
1062
  * @preserve
1372
1063
  */
1373
1064
  constructor() {
1374
- __publicField(this, "_dataLayer");
1375
- __publicField(this, "_authenticationCore");
1065
+ __publicField(this, "_storageManager");
1066
+ __publicField(this, "_config");
1067
+ __publicField(this, "_oidcProviderMetaData");
1068
+ __publicField(this, "_authenticationHelper");
1069
+ __publicField(this, "_cryptoUtils");
1070
+ __publicField(this, "_cryptoHelper");
1376
1071
  }
1377
1072
  /**
1378
1073
  *
@@ -1382,8 +1077,8 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1382
1077
  *
1383
1078
  * @example
1384
1079
  * const config = \{
1385
- * signInRedirectURL: "http://localhost:3000/sign-in",
1386
- * clientID: "client ID",
1080
+ * afterSignInUrl: "http://localhost:3000/sign-in",
1081
+ * clientId: "client ID",
1387
1082
  * baseUrl: "https://localhost:9443"
1388
1083
  * \}
1389
1084
  *
@@ -1394,7 +1089,7 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1394
1089
  * @preserve
1395
1090
  */
1396
1091
  async initialize(config, store, cryptoUtils, instanceID) {
1397
- const clientId = config.clientID;
1092
+ const clientId = config.clientId;
1398
1093
  if (!_AsgardeoAuthClient._instanceID) {
1399
1094
  _AsgardeoAuthClient._instanceID = 0;
1400
1095
  } else {
@@ -1404,37 +1099,38 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1404
1099
  _AsgardeoAuthClient._instanceID = instanceID;
1405
1100
  }
1406
1101
  if (!clientId) {
1407
- this._dataLayer = new DataLayer(`instance_${_AsgardeoAuthClient._instanceID}`, store);
1102
+ this._storageManager = new StorageManager_default(`instance_${_AsgardeoAuthClient._instanceID}`, store);
1408
1103
  } else {
1409
- this._dataLayer = new DataLayer(`instance_${_AsgardeoAuthClient._instanceID}-${clientId}`, store);
1104
+ this._storageManager = new StorageManager_default(`instance_${_AsgardeoAuthClient._instanceID}-${clientId}`, store);
1410
1105
  }
1411
- this._authenticationCore = new AuthenticationCore(this._dataLayer, cryptoUtils);
1412
- _AsgardeoAuthClient._authenticationCore = new AuthenticationCore(this._dataLayer, cryptoUtils);
1413
- await this._dataLayer.setConfigData({
1106
+ this._cryptoUtils = cryptoUtils;
1107
+ this._cryptoHelper = new IsomorphicCrypto(cryptoUtils);
1108
+ this._authenticationHelper = new AuthenticationHelper(this._storageManager, this._cryptoHelper);
1109
+ this._config = async () => await this._storageManager.getConfigData();
1110
+ this._oidcProviderMetaData = async () => await this._storageManager.loadOpenIDProviderConfiguration();
1111
+ _AsgardeoAuthClient._authenticationHelper = this._authenticationHelper;
1112
+ await this._storageManager.setConfigData({
1414
1113
  ...DefaultConfig,
1415
1114
  ...config,
1416
- scope: [
1417
- ...DefaultConfig.scope ?? [],
1418
- ...config.scope?.filter((scope) => !DefaultConfig?.scope?.includes(scope)) ?? []
1419
- ]
1115
+ scope: processOpenIDScopes_default(config.scopes)
1420
1116
  });
1421
1117
  }
1422
1118
  /**
1423
- * This method returns the `DataLayer` object that allows you to access authentication data.
1119
+ * This method returns the `StorageManager` object that allows you to access authentication data.
1424
1120
  *
1425
- * @returns - The `DataLayer` object.
1121
+ * @returns - The `StorageManager` object.
1426
1122
  *
1427
1123
  * @example
1428
1124
  * ```
1429
- * const data = auth.getDataLayer();
1125
+ * const data = auth.getStorageManager();
1430
1126
  * ```
1431
1127
  *
1432
- * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getDataLayer}
1128
+ * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getStorageManager}
1433
1129
  *
1434
1130
  * @preserve
1435
1131
  */
1436
- getDataLayer() {
1437
- return this._dataLayer;
1132
+ getStorageManager() {
1133
+ return this._storageManager;
1438
1134
  }
1439
1135
  /**
1440
1136
  * This method returns the `instanceID` variable of the given instance.
@@ -1443,82 +1139,90 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1443
1139
  *
1444
1140
  * @example
1445
1141
  * ```
1446
- * const instanceId = auth.getInstanceID();
1142
+ * const instanceId = auth.getInstanceId();
1447
1143
  * ```
1448
1144
  *
1449
1145
  * @preserve
1450
1146
  */
1451
- getInstanceID() {
1147
+ getInstanceId() {
1452
1148
  return _AsgardeoAuthClient._instanceID;
1453
1149
  }
1454
- /**
1455
- * This is an async method that returns a Promise that resolves with the authorization URL parameters.
1456
- *
1457
- * @param config - (Optional) A config object to force initialization and pass
1458
- * custom path parameters such as the `fidp` parameter.
1459
- * @param userID - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1460
- * scenarios where each user should be uniquely identified.
1461
- *
1462
- * @returns - A promise that resolves with the authorization URL parameters.
1463
- *
1464
- * @example
1465
- * ```
1466
- * auth.getAuthorizationURLParams().then((params)=>{
1467
- * // console.log(params);
1468
- * }).catch((error)=>{
1469
- * // console.error(error);
1470
- * });
1471
- * ```
1472
- *
1473
- * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getAuthorizationURLParams}
1474
- *
1475
- * @preserve
1476
- */
1477
- async getAuthorizationURLParams(config, userID) {
1478
- const authRequestConfig = { ...config };
1479
- delete authRequestConfig?.forceInit;
1480
- if (await this._dataLayer.getTemporaryDataParameter(
1481
- OIDCDiscoveryConstants_default.Storage.StorageKeys.OPENID_PROVIDER_CONFIG_INITIATED
1482
- )) {
1483
- return this._authenticationCore.getAuthorizationURLParams(authRequestConfig, userID);
1484
- }
1485
- return this._authenticationCore.getOIDCProviderMetaData(config?.forceInit).then(() => {
1486
- return this._authenticationCore.getAuthorizationURLParams(authRequestConfig, userID);
1487
- });
1488
- }
1489
1150
  /**
1490
1151
  * This is an async method that returns a Promise that resolves with the authorization URL.
1491
1152
  *
1492
1153
  * @param config - (Optional) A config object to force initialization and pass
1493
1154
  * custom path parameters such as the fidp parameter.
1494
- * @param userID - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1155
+ * @param userId - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1495
1156
  * scenarios where each user should be uniquely identified.
1496
1157
  *
1497
1158
  * @returns - A promise that resolves with the authorization URL.
1498
1159
  *
1499
1160
  * @example
1500
1161
  * ```
1501
- * auth.getAuthorizationURL().then((url)=>{
1162
+ * auth.getSignInUrl().then((url)=>{
1502
1163
  * // console.log(url);
1503
1164
  * }).catch((error)=>{
1504
1165
  * // console.error(error);
1505
1166
  * });
1506
1167
  * ```
1507
1168
  *
1508
- * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getAuthorizationURL}
1169
+ * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getSignInUrl}
1509
1170
  *
1510
1171
  * @preserve
1511
1172
  */
1512
- async getAuthorizationURL(config, userID) {
1513
- const authRequestConfig = { ...config };
1173
+ async getSignInUrl(requestConfig, userId) {
1174
+ const authRequestConfig = { ...requestConfig };
1514
1175
  delete authRequestConfig?.forceInit;
1515
- if (await this._dataLayer.getTemporaryDataParameter(
1176
+ const __TODO__ = async () => {
1177
+ const authorizeEndpoint = await this._storageManager.getOIDCProviderMetaDataParameter(
1178
+ OIDCDiscoveryConstants_default.Storage.StorageKeys.Endpoints.AUTHORIZATION
1179
+ );
1180
+ if (!authorizeEndpoint || authorizeEndpoint.trim().length === 0) {
1181
+ throw new AsgardeoAuthException(
1182
+ "JS-AUTH_CORE-GAU-NF01",
1183
+ "No authorization endpoint found.",
1184
+ "No authorization endpoint was found in the OIDC provider meta data from the well-known endpoint or the authorization endpoint passed to the SDK is empty."
1185
+ );
1186
+ }
1187
+ const authorizeRequest = new URL(authorizeEndpoint);
1188
+ const configData = await this._config();
1189
+ const tempStore = await this._storageManager.getTemporaryData(userId);
1190
+ const pkceKey = await generatePkceStorageKey_default(tempStore);
1191
+ let codeVerifier;
1192
+ let codeChallenge;
1193
+ if (configData.enablePKCE) {
1194
+ codeVerifier = this._cryptoHelper?.getCodeVerifier();
1195
+ codeChallenge = this._cryptoHelper?.getCodeChallenge(codeVerifier);
1196
+ await this._storageManager.setTemporaryDataParameter(pkceKey, codeVerifier, userId);
1197
+ }
1198
+ if (authRequestConfig["client_secret"]) {
1199
+ authRequestConfig["client_secret"] = configData.clientSecret;
1200
+ }
1201
+ const authorizeRequestParams = getAuthorizeRequestUrlParams_default(
1202
+ {
1203
+ redirectUri: configData.afterSignInUrl,
1204
+ clientId: configData.clientId,
1205
+ scopes: processOpenIDScopes_default(configData.scopes),
1206
+ responseMode: configData.responseMode,
1207
+ codeChallengeMethod: PKCEConstants_default.DEFAULT_CODE_CHALLENGE_METHOD,
1208
+ codeChallenge,
1209
+ prompt: configData.prompt
1210
+ },
1211
+ { key: pkceKey },
1212
+ authRequestConfig
1213
+ );
1214
+ for (const [key, value] of authorizeRequestParams.entries()) {
1215
+ authorizeRequest.searchParams.append(key, value);
1216
+ }
1217
+ return authorizeRequest.toString();
1218
+ };
1219
+ if (await this._storageManager.getTemporaryDataParameter(
1516
1220
  OIDCDiscoveryConstants_default.Storage.StorageKeys.OPENID_PROVIDER_CONFIG_INITIATED
1517
1221
  )) {
1518
- return this._authenticationCore.getAuthorizationURL(authRequestConfig, userID);
1222
+ return __TODO__();
1519
1223
  }
1520
- return this._authenticationCore.getOIDCProviderMetaData(config?.forceInit).then(() => {
1521
- return this._authenticationCore.getAuthorizationURL(authRequestConfig, userID);
1224
+ return this.loadOpenIDProviderConfiguration(requestConfig?.forceInit).then(() => {
1225
+ return __TODO__();
1522
1226
  });
1523
1227
  }
1524
1228
  /**
@@ -1527,7 +1231,7 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1527
1231
  *
1528
1232
  * @param authorizationCode - The authorization code.
1529
1233
  * @param sessionState - The session state.
1530
- * @param userID - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1234
+ * @param userId - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1531
1235
  * scenarios where each user should be uniquely identified.
1532
1236
  *
1533
1237
  * @returns - A Promise that resolves with the token response.
@@ -1546,32 +1250,139 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1546
1250
  *
1547
1251
  * @preserve
1548
1252
  */
1549
- async requestAccessToken(authorizationCode, sessionState, state, userID, tokenRequestConfig) {
1550
- if (await this._dataLayer.getTemporaryDataParameter(
1551
- OIDCDiscoveryConstants_default.Storage.StorageKeys.OPENID_PROVIDER_CONFIG_INITIATED
1552
- )) {
1553
- return this._authenticationCore.requestAccessToken(
1554
- authorizationCode,
1253
+ async requestAccessToken(authorizationCode, sessionState, state, userId, tokenRequestConfig) {
1254
+ const __TODO__ = async () => {
1255
+ const tokenEndpoint = (await this._oidcProviderMetaData()).token_endpoint;
1256
+ const configData = await this._config();
1257
+ if (!tokenEndpoint || tokenEndpoint.trim().length === 0) {
1258
+ throw new AsgardeoAuthException(
1259
+ "JS-AUTH_CORE-RAT1-NF01",
1260
+ "Token endpoint not found.",
1261
+ "No token endpoint was found in the OIDC provider meta data returned by the well-known endpoint or the token endpoint passed to the SDK is empty."
1262
+ );
1263
+ }
1264
+ sessionState && await this._storageManager.setSessionDataParameter(
1265
+ OIDCRequestConstants_default.Params.SESSION_STATE,
1555
1266
  sessionState,
1556
- state,
1557
- userID,
1558
- tokenRequestConfig
1267
+ userId
1559
1268
  );
1269
+ const body = new URLSearchParams();
1270
+ body.set("client_id", configData.clientId);
1271
+ if (configData.clientSecret && configData.clientSecret.trim().length > 0) {
1272
+ body.set("client_secret", configData.clientSecret);
1273
+ }
1274
+ const code = authorizationCode;
1275
+ body.set("code", code);
1276
+ body.set("grant_type", "authorization_code");
1277
+ body.set("redirect_uri", configData.afterSignInUrl);
1278
+ if (tokenRequestConfig?.params) {
1279
+ Object.entries(tokenRequestConfig.params).forEach(([key, value]) => {
1280
+ body.append(key, value);
1281
+ });
1282
+ }
1283
+ if (configData.enablePKCE) {
1284
+ body.set(
1285
+ "code_verifier",
1286
+ `${await this._storageManager.getTemporaryDataParameter(extractPkceStorageKeyFromState_default(state), userId)}`
1287
+ );
1288
+ await this._storageManager.removeTemporaryDataParameter(extractPkceStorageKeyFromState_default(state), userId);
1289
+ }
1290
+ let tokenResponse;
1291
+ try {
1292
+ tokenResponse = await fetch(tokenEndpoint, {
1293
+ body,
1294
+ credentials: configData.sendCookiesInRequests ? "include" : "same-origin",
1295
+ headers: {
1296
+ Accept: "application/json",
1297
+ "Content-Type": "application/x-www-form-urlencoded"
1298
+ },
1299
+ method: "POST"
1300
+ });
1301
+ } catch (error) {
1302
+ throw new AsgardeoAuthException(
1303
+ "JS-AUTH_CORE-RAT1-NE02",
1304
+ "Requesting access token failed",
1305
+ error ?? "The request to get the access token from the server failed."
1306
+ );
1307
+ }
1308
+ if (!tokenResponse.ok) {
1309
+ throw new AsgardeoAuthException(
1310
+ "JS-AUTH_CORE-RAT1-HE03",
1311
+ `Requesting access token failed with ${tokenResponse.statusText}`,
1312
+ await tokenResponse.json()
1313
+ );
1314
+ }
1315
+ return await this._authenticationHelper.handleTokenResponse(tokenResponse, userId);
1316
+ };
1317
+ if (await this._storageManager.getTemporaryDataParameter(
1318
+ OIDCDiscoveryConstants_default.Storage.StorageKeys.OPENID_PROVIDER_CONFIG_INITIATED
1319
+ )) {
1320
+ return __TODO__();
1560
1321
  }
1561
- return this._authenticationCore.getOIDCProviderMetaData(false).then(() => {
1562
- return this._authenticationCore.requestAccessToken(
1563
- authorizationCode,
1564
- sessionState,
1565
- state,
1566
- userID,
1567
- tokenRequestConfig
1568
- );
1322
+ return this.loadOpenIDProviderConfiguration(false).then(() => {
1323
+ return __TODO__();
1569
1324
  });
1570
1325
  }
1326
+ async loadOpenIDProviderConfiguration(forceInit) {
1327
+ const configData = await this._config();
1328
+ if (!forceInit && await this._storageManager.getTemporaryDataParameter(
1329
+ OIDCDiscoveryConstants_default.Storage.StorageKeys.OPENID_PROVIDER_CONFIG_INITIATED
1330
+ )) {
1331
+ return Promise.resolve();
1332
+ }
1333
+ const wellKnownEndpoint = configData.wellKnownEndpoint;
1334
+ if (wellKnownEndpoint) {
1335
+ let response;
1336
+ try {
1337
+ response = await fetch(wellKnownEndpoint);
1338
+ if (response.status !== 200 || !response.ok) {
1339
+ throw new Error();
1340
+ }
1341
+ } catch {
1342
+ throw new AsgardeoAuthException(
1343
+ "JS-AUTH_CORE-GOPMD-HE01",
1344
+ "Invalid well-known response",
1345
+ "The well known endpoint response has been failed with an error."
1346
+ );
1347
+ }
1348
+ await this._storageManager.setOIDCProviderMetaData(
1349
+ await this._authenticationHelper.resolveEndpoints(await response.json())
1350
+ );
1351
+ await this._storageManager.setTemporaryDataParameter(
1352
+ OIDCDiscoveryConstants_default.Storage.StorageKeys.OPENID_PROVIDER_CONFIG_INITIATED,
1353
+ true
1354
+ );
1355
+ return Promise.resolve();
1356
+ } else if (configData.baseUrl) {
1357
+ try {
1358
+ await this._storageManager.setOIDCProviderMetaData(
1359
+ await this._authenticationHelper.resolveEndpointsByBaseURL()
1360
+ );
1361
+ } catch (error) {
1362
+ throw new AsgardeoAuthException(
1363
+ "JS-AUTH_CORE-GOPMD-IV02",
1364
+ "Resolving endpoints failed.",
1365
+ error ?? "Resolving endpoints by base url failed."
1366
+ );
1367
+ }
1368
+ await this._storageManager.setTemporaryDataParameter(
1369
+ OIDCDiscoveryConstants_default.Storage.StorageKeys.OPENID_PROVIDER_CONFIG_INITIATED,
1370
+ true
1371
+ );
1372
+ return Promise.resolve();
1373
+ } else {
1374
+ await this._storageManager.setOIDCProviderMetaData(await this._authenticationHelper.resolveEndpointsExplicitly());
1375
+ await this._storageManager.setTemporaryDataParameter(
1376
+ OIDCDiscoveryConstants_default.Storage.StorageKeys.OPENID_PROVIDER_CONFIG_INITIATED,
1377
+ true
1378
+ );
1379
+ return Promise.resolve();
1380
+ }
1381
+ }
1571
1382
  /**
1572
1383
  * This method returns the sign-out URL.
1573
1384
  *
1574
- * @param userID - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1385
+ * @param userId - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1575
1386
  * scenarios where each user should be uniquely identified.
1576
1387
  *
1577
1388
  * **This doesn't clear the authentication data.**
@@ -1580,15 +1391,48 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1580
1391
  *
1581
1392
  * @example
1582
1393
  * ```
1583
- * const signOutUrl = await auth.getSignOutURL();
1394
+ * const signOutUrl = await auth.getSignOutUrl();
1584
1395
  * ```
1585
1396
  *
1586
- * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getSignOutURL}
1397
+ * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getSignOutUrl}
1587
1398
  *
1588
1399
  * @preserve
1589
1400
  */
1590
- async getSignOutURL(userID) {
1591
- return this._authenticationCore.getSignOutURL(userID);
1401
+ async getSignOutUrl(userId) {
1402
+ const logoutEndpoint = (await this._oidcProviderMetaData())?.end_session_endpoint;
1403
+ const configData = await this._config();
1404
+ if (!logoutEndpoint || logoutEndpoint.trim().length === 0) {
1405
+ throw new AsgardeoAuthException(
1406
+ "JS-AUTH_CORE-GSOU-NF01",
1407
+ "Sign-out endpoint not found.",
1408
+ "No sign-out endpoint was found in the OIDC provider meta data returned by the well-known endpoint or the sign-out endpoint passed to the SDK is empty."
1409
+ );
1410
+ }
1411
+ const callbackURL = configData?.afterSignOutUrl ?? configData?.afterSignInUrl;
1412
+ if (!callbackURL || callbackURL.trim().length === 0) {
1413
+ throw new AsgardeoAuthException(
1414
+ "JS-AUTH_CORE-GSOU-NF03",
1415
+ "No sign-out redirect URL found.",
1416
+ "The sign-out redirect URL cannot be found or the URL passed to the SDK is empty. No sign-in redirect URL has been found either. "
1417
+ );
1418
+ }
1419
+ const queryParams = new URLSearchParams();
1420
+ queryParams.set("post_logout_redirect_uri", callbackURL);
1421
+ if (configData.sendIdTokenInLogoutRequest) {
1422
+ const idToken = (await this._storageManager.getSessionData(userId))?.id_token;
1423
+ if (!idToken || idToken.trim().length === 0) {
1424
+ throw new AsgardeoAuthException(
1425
+ "JS-AUTH_CORE-GSOU-NF02",
1426
+ "ID token not found.",
1427
+ "No ID token could be found. Either the session information is lost or you have not signed in."
1428
+ );
1429
+ }
1430
+ queryParams.set("id_token_hint", idToken);
1431
+ } else {
1432
+ queryParams.set("client_id", configData.clientId);
1433
+ }
1434
+ queryParams.set("state", OIDCRequestConstants_default.Params.SIGN_OUT_SUCCESS);
1435
+ return `${logoutEndpoint}?${queryParams.toString()}`;
1592
1436
  }
1593
1437
  /**
1594
1438
  * This method returns OIDC service endpoints that are fetched from the `.well-known` endpoint.
@@ -1597,75 +1441,103 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1597
1441
  *
1598
1442
  * @example
1599
1443
  * ```
1600
- * const endpoints = await auth.getOIDCServiceEndpoints();
1444
+ * const endpoints = await auth.getOpenIDProviderEndpoints();
1601
1445
  * ```
1602
1446
  *
1603
- * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getOIDCServiceEndpoints}
1447
+ * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getOpenIDProviderEndpoints}
1604
1448
  *
1605
1449
  * @preserve
1606
1450
  */
1607
- async getOIDCServiceEndpoints() {
1608
- return this._authenticationCore.getOIDCServiceEndpoints();
1609
- }
1610
- /**
1611
- * This method decodes the payload of the ID token and returns it.
1451
+ async getOpenIDProviderEndpoints() {
1452
+ const oidcProviderMetaData = await this._oidcProviderMetaData();
1453
+ return {
1454
+ authorizationEndpoint: oidcProviderMetaData.authorization_endpoint ?? "",
1455
+ checkSessionIframe: oidcProviderMetaData.check_session_iframe ?? "",
1456
+ endSessionEndpoint: oidcProviderMetaData.end_session_endpoint ?? "",
1457
+ introspectionEndpoint: oidcProviderMetaData.introspection_endpoint ?? "",
1458
+ issuer: oidcProviderMetaData.issuer ?? "",
1459
+ jwksUri: oidcProviderMetaData.jwks_uri ?? "",
1460
+ registrationEndpoint: oidcProviderMetaData.registration_endpoint ?? "",
1461
+ revocationEndpoint: oidcProviderMetaData.revocation_endpoint ?? "",
1462
+ tokenEndpoint: oidcProviderMetaData.token_endpoint ?? "",
1463
+ userinfoEndpoint: oidcProviderMetaData.userinfo_endpoint ?? ""
1464
+ };
1465
+ }
1466
+ /**
1467
+ * This method decodes the payload of the ID token and returns it.
1612
1468
  *
1613
- * @param userID - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1469
+ * @param userId - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1614
1470
  * scenarios where each user should be uniquely identified.
1615
1471
  *
1616
1472
  * @returns - A Promise that resolves with the decoded ID token payload.
1617
1473
  *
1618
1474
  * @example
1619
1475
  * ```
1620
- * const decodedIdToken = await auth.getDecodedIDToken();
1476
+ * const decodedIdToken = await auth.getDecodedIdToken();
1621
1477
  * ```
1622
1478
  *
1623
- * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getDecodedIDToken}
1479
+ * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getDecodedIdToken}
1624
1480
  *
1625
1481
  * @preserve
1626
1482
  */
1627
- async getDecodedIDToken(userID) {
1628
- return this._authenticationCore.getDecodedIDToken(userID);
1483
+ async getDecodedIdToken(userId) {
1484
+ const idToken = (await this._storageManager.getSessionData(userId)).id_token;
1485
+ const payload = this._cryptoHelper.decodeIdToken(idToken);
1486
+ return payload;
1629
1487
  }
1630
1488
  /**
1631
1489
  * This method returns the ID token.
1632
1490
  *
1633
- * @param userID - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1491
+ * @param userId - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1634
1492
  * scenarios where each user should be uniquely identified.
1635
1493
  *
1636
1494
  * @returns - A Promise that resolves with the ID token.
1637
1495
  *
1638
1496
  * @example
1639
1497
  * ```
1640
- * const idToken = await auth.getIDToken();
1498
+ * const idToken = await auth.getIdToken();
1641
1499
  * ```
1642
1500
  *
1643
- * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getIDToken}
1501
+ * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getIdToken}
1644
1502
  *
1645
1503
  * @preserve
1646
1504
  */
1647
- async getIDToken(userID) {
1648
- return this._authenticationCore.getIDToken(userID);
1505
+ async getIdToken(userId) {
1506
+ return (await this._storageManager.getSessionData(userId)).id_token;
1649
1507
  }
1650
1508
  /**
1651
1509
  * This method returns the basic user information obtained from the ID token.
1652
1510
  *
1653
- * @param userID - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1511
+ * @param userId - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1654
1512
  * scenarios where each user should be uniquely identified.
1655
1513
  *
1656
1514
  * @returns - A Promise that resolves with an object containing the basic user information.
1657
1515
  *
1658
1516
  * @example
1659
1517
  * ```
1660
- * const userInfo = await auth.getBasicUserInfo();
1518
+ * const userInfo = await auth.getUser();
1661
1519
  * ```
1662
1520
  *
1663
- * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getBasicUserInfo}
1521
+ * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getUser}
1664
1522
  *
1665
1523
  * @preserve
1666
1524
  */
1667
- async getBasicUserInfo(userID) {
1668
- return this._authenticationCore.getBasicUserInfo(userID);
1525
+ async getUser(userId) {
1526
+ const sessionData = await this._storageManager.getSessionData(userId);
1527
+ const authenticatedUser = this._authenticationHelper.getAuthenticatedUserInfo(sessionData?.id_token);
1528
+ Object.keys(authenticatedUser).forEach((key) => {
1529
+ if (authenticatedUser[key] === void 0 || authenticatedUser[key] === "" || authenticatedUser[key] === null) {
1530
+ delete authenticatedUser[key];
1531
+ }
1532
+ });
1533
+ return authenticatedUser;
1534
+ }
1535
+ async getUserSession(userId) {
1536
+ const sessionData = await this._storageManager.getSessionData(userId);
1537
+ return {
1538
+ scopes: sessionData?.scope?.split(" "),
1539
+ sessionState: sessionData?.session_state ?? ""
1540
+ };
1669
1541
  }
1670
1542
  /**
1671
1543
  * This method returns the crypto helper object.
@@ -1677,17 +1549,17 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1677
1549
  * const cryptoHelper = await auth.IsomorphicCrypto();
1678
1550
  * ```
1679
1551
  *
1680
- * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getCryptoHelper}
1552
+ * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getCrypto}
1681
1553
  *
1682
1554
  * @preserve
1683
1555
  */
1684
- async getCryptoHelper() {
1685
- return this._authenticationCore.getCryptoHelper();
1556
+ async getCrypto() {
1557
+ return this._cryptoHelper;
1686
1558
  }
1687
1559
  /**
1688
1560
  * This method revokes the access token.
1689
1561
  *
1690
- * @param userID - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1562
+ * @param userId - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1691
1563
  * scenarios where each user should be uniquely identified.
1692
1564
  *
1693
1565
  * **This method also clears the authentication data.**
@@ -1707,14 +1579,56 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1707
1579
  *
1708
1580
  * @preserve
1709
1581
  */
1710
- revokeAccessToken(userID) {
1711
- return this._authenticationCore.revokeAccessToken(userID);
1582
+ async revokeAccessToken(userId) {
1583
+ const revokeTokenEndpoint = (await this._oidcProviderMetaData()).revocation_endpoint;
1584
+ const configData = await this._config();
1585
+ if (!revokeTokenEndpoint || revokeTokenEndpoint.trim().length === 0) {
1586
+ throw new AsgardeoAuthException(
1587
+ "JS-AUTH_CORE-RAT3-NF01",
1588
+ "No revoke access token endpoint found.",
1589
+ "No revoke access token endpoint was found in the OIDC provider meta data returned by the well-known endpoint or the revoke access token endpoint passed to the SDK is empty."
1590
+ );
1591
+ }
1592
+ const body = [];
1593
+ body.push(`client_id=${configData.clientId}`);
1594
+ body.push(`token=${(await this._storageManager.getSessionData(userId)).access_token}`);
1595
+ body.push("token_type_hint=access_token");
1596
+ if (configData.clientSecret && configData.clientSecret.trim().length > 0) {
1597
+ body.push(`client_secret=${configData.clientSecret}`);
1598
+ }
1599
+ let response;
1600
+ try {
1601
+ response = await fetch(revokeTokenEndpoint, {
1602
+ body: body.join("&"),
1603
+ credentials: configData.sendCookiesInRequests ? "include" : "same-origin",
1604
+ headers: {
1605
+ Accept: "application/json",
1606
+ "Content-Type": "application/x-www-form-urlencoded"
1607
+ },
1608
+ method: "POST"
1609
+ });
1610
+ } catch (error) {
1611
+ throw new AsgardeoAuthException(
1612
+ "JS-AUTH_CORE-RAT3-NE02",
1613
+ "The request to revoke access token failed.",
1614
+ error ?? "The request sent to revoke the access token failed."
1615
+ );
1616
+ }
1617
+ if (response.status !== 200 || !response.ok) {
1618
+ throw new AsgardeoAuthException(
1619
+ "JS-AUTH_CORE-RAT3-HE03",
1620
+ `Invalid response status received for revoke access token request (${response.statusText}).`,
1621
+ await response.json()
1622
+ );
1623
+ }
1624
+ this._authenticationHelper.clearSession(userId);
1625
+ return Promise.resolve(response);
1712
1626
  }
1713
1627
  /**
1714
1628
  * This method refreshes the access token and returns a Promise that resolves with the new access
1715
1629
  * token and other relevant data.
1716
1630
  *
1717
- * @param userID - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1631
+ * @param userId - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1718
1632
  * scenarios where each user should be uniquely identified.
1719
1633
  *
1720
1634
  * @returns - A Promise that resolves with the token response.
@@ -1732,13 +1646,62 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1732
1646
  *
1733
1647
  * @preserve
1734
1648
  */
1735
- refreshAccessToken(userID) {
1736
- return this._authenticationCore.refreshAccessToken(userID);
1649
+ async refreshAccessToken(userId) {
1650
+ const tokenEndpoint = (await this._oidcProviderMetaData()).token_endpoint;
1651
+ const configData = await this._config();
1652
+ const sessionData = await this._storageManager.getSessionData(userId);
1653
+ if (!sessionData.refresh_token) {
1654
+ throw new AsgardeoAuthException(
1655
+ "JS-AUTH_CORE-RAT2-NF01",
1656
+ "No refresh token found.",
1657
+ "There was no refresh token found. Asgardeo doesn't return a refresh token if the refresh token grant is not enabled."
1658
+ );
1659
+ }
1660
+ if (!tokenEndpoint || tokenEndpoint.trim().length === 0) {
1661
+ throw new AsgardeoAuthException(
1662
+ "JS-AUTH_CORE-RAT2-NF02",
1663
+ "No refresh token endpoint found.",
1664
+ "No refresh token endpoint was in the OIDC provider meta data returned by the well-known endpoint or the refresh token endpoint passed to the SDK is empty."
1665
+ );
1666
+ }
1667
+ const body = [];
1668
+ body.push(`client_id=${configData.clientId}`);
1669
+ body.push(`refresh_token=${sessionData.refresh_token}`);
1670
+ body.push("grant_type=refresh_token");
1671
+ if (configData.clientSecret && configData.clientSecret.trim().length > 0) {
1672
+ body.push(`client_secret=${configData.clientSecret}`);
1673
+ }
1674
+ let tokenResponse;
1675
+ try {
1676
+ tokenResponse = await fetch(tokenEndpoint, {
1677
+ body: body.join("&"),
1678
+ credentials: configData.sendCookiesInRequests ? "include" : "same-origin",
1679
+ headers: {
1680
+ Accept: "application/json",
1681
+ "Content-Type": "application/x-www-form-urlencoded"
1682
+ },
1683
+ method: "POST"
1684
+ });
1685
+ } catch (error) {
1686
+ throw new AsgardeoAuthException(
1687
+ "JS-AUTH_CORE-RAT2-NR03",
1688
+ "Refresh access token request failed.",
1689
+ error ?? "The request to refresh the access token failed."
1690
+ );
1691
+ }
1692
+ if (!tokenResponse.ok) {
1693
+ throw new AsgardeoAuthException(
1694
+ "JS-AUTH_CORE-RAT2-HE04",
1695
+ `Refreshing access token failed with ${tokenResponse.statusText}`,
1696
+ await tokenResponse.json()
1697
+ );
1698
+ }
1699
+ return this._authenticationHelper.handleTokenResponse(tokenResponse, userId);
1737
1700
  }
1738
1701
  /**
1739
1702
  * This method returns the access token.
1740
1703
  *
1741
- * @param userID - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1704
+ * @param userId - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1742
1705
  * scenarios where each user should be uniquely identified.
1743
1706
  *
1744
1707
  * @returns - A Promise that resolves with the access token.
@@ -1752,15 +1715,15 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1752
1715
  *
1753
1716
  * @preserve
1754
1717
  */
1755
- async getAccessToken(userID) {
1756
- return this._authenticationCore.getAccessToken(userID);
1718
+ async getAccessToken(userId) {
1719
+ return (await this._storageManager.getSessionData(userId))?.access_token;
1757
1720
  }
1758
1721
  /**
1759
1722
  * This method sends a custom-grant request and returns a Promise that resolves with the response
1760
1723
  * depending on the config passed.
1761
1724
  *
1762
1725
  * @param config - A config object containing the custom grant configurations.
1763
- * @param userID - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1726
+ * @param userId - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1764
1727
  * scenarios where each user should be uniquely identified.
1765
1728
  *
1766
1729
  * @returns - A Promise that resolves with the response depending
@@ -1771,7 +1734,7 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1771
1734
  * const config = {
1772
1735
  * attachToken: false,
1773
1736
  * data: {
1774
- * client_id: "{{clientID}}",
1737
+ * client_id: "{{clientId}}",
1775
1738
  * grant_type: "account_switch",
1776
1739
  * scope: "{{scope}}",
1777
1740
  * token: "{{token}}",
@@ -1782,44 +1745,115 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1782
1745
  * signInRequired: true
1783
1746
  * }
1784
1747
  *
1785
- * auth.requestCustomGrant(config).then((response)=>{
1748
+ * auth.exchangeToken(config).then((response)=>{
1786
1749
  * // console.log(response);
1787
1750
  * }).catch((error)=>{
1788
1751
  * // console.error(error);
1789
1752
  * });
1790
1753
  * ```
1791
1754
  *
1792
- * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#requestCustomGrant}
1755
+ * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#exchangeToken}
1793
1756
  *
1794
1757
  * @preserve
1795
1758
  */
1796
- requestCustomGrant(config, userID) {
1797
- return this._authenticationCore.requestCustomGrant(config, userID);
1759
+ async exchangeToken(config, userId) {
1760
+ const oidcProviderMetadata = await this._oidcProviderMetaData();
1761
+ const configData = await this._config();
1762
+ let tokenEndpoint;
1763
+ if (config.tokenEndpoint && config.tokenEndpoint.trim().length !== 0) {
1764
+ tokenEndpoint = config.tokenEndpoint;
1765
+ } else {
1766
+ tokenEndpoint = oidcProviderMetadata.token_endpoint;
1767
+ }
1768
+ if (!tokenEndpoint || tokenEndpoint.trim().length === 0) {
1769
+ throw new AsgardeoAuthException(
1770
+ "JS-AUTH_CORE-RCG-NF01",
1771
+ "Token endpoint not found.",
1772
+ "No token endpoint was found in the OIDC provider meta data returned by the well-known endpoint or the token endpoint passed to the SDK is empty."
1773
+ );
1774
+ }
1775
+ const data = await Promise.all(
1776
+ Object.entries(config.data).map(async ([key, value]) => {
1777
+ const newValue = await this._authenticationHelper.replaceCustomGrantTemplateTags(
1778
+ value,
1779
+ userId
1780
+ );
1781
+ return `${key}=${newValue}`;
1782
+ })
1783
+ );
1784
+ let requestHeaders = {
1785
+ Accept: "application/json",
1786
+ "Content-Type": "application/x-www-form-urlencoded"
1787
+ };
1788
+ if (config.attachToken) {
1789
+ requestHeaders = {
1790
+ ...requestHeaders,
1791
+ Authorization: `Bearer ${(await this._storageManager.getSessionData(userId)).access_token}`
1792
+ };
1793
+ }
1794
+ const requestConfig = {
1795
+ body: data.join("&"),
1796
+ credentials: configData.sendCookiesInRequests ? "include" : "same-origin",
1797
+ headers: new Headers(requestHeaders),
1798
+ method: "POST"
1799
+ };
1800
+ let response;
1801
+ try {
1802
+ response = await fetch(tokenEndpoint, requestConfig);
1803
+ } catch (error) {
1804
+ throw new AsgardeoAuthException(
1805
+ "JS-AUTH_CORE-RCG-NE02",
1806
+ "The custom grant request failed.",
1807
+ error ?? "The request sent to get the custom grant failed."
1808
+ );
1809
+ }
1810
+ if (response.status !== 200 || !response.ok) {
1811
+ throw new AsgardeoAuthException(
1812
+ "JS-AUTH_CORE-RCG-HE03",
1813
+ `Invalid response status received for the custom grant request. (${response.statusText})`,
1814
+ await response.json()
1815
+ );
1816
+ }
1817
+ if (config.returnsSession) {
1818
+ return this._authenticationHelper.handleTokenResponse(response, userId);
1819
+ } else {
1820
+ return Promise.resolve(await response.json());
1821
+ }
1798
1822
  }
1799
1823
  /**
1800
1824
  * This method returns if the user is authenticated or not.
1801
1825
  *
1802
- * @param userID - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1826
+ * @param userId - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1803
1827
  * scenarios where each user should be uniquely identified.
1804
1828
  *
1805
1829
  * @returns - A Promise that resolves with `true` if the user is authenticated, `false` otherwise.
1806
1830
  *
1807
1831
  * @example
1808
1832
  * ```
1809
- * await auth.isAuthenticated();
1833
+ * await auth.isSignedIn();
1810
1834
  * ```
1811
1835
  *
1812
- * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#isAuthenticated}
1836
+ * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#isSignedIn}
1813
1837
  *
1814
1838
  * @preserve
1815
1839
  */
1816
- async isAuthenticated(userID) {
1817
- return this._authenticationCore.isAuthenticated(userID);
1840
+ async isSignedIn(userId) {
1841
+ const isAccessTokenAvailable = Boolean(await this.getAccessToken(userId));
1842
+ const createdAt = (await this._storageManager.getSessionData(userId))?.created_at;
1843
+ const expiresInString = (await this._storageManager.getSessionData(userId))?.expires_in;
1844
+ if (!expiresInString) {
1845
+ return false;
1846
+ }
1847
+ const expiresIn = parseInt(expiresInString) * 1e3;
1848
+ const currentTime = (/* @__PURE__ */ new Date()).getTime();
1849
+ const isAccessTokenValid = createdAt + expiresIn > currentTime;
1850
+ const isSignedIn = isAccessTokenAvailable && isAccessTokenValid;
1851
+ return isSignedIn;
1818
1852
  }
1819
1853
  /**
1820
1854
  * This method returns the PKCE code generated during the generation of the authentication URL.
1821
1855
  *
1822
- * @param userID - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1856
+ * @param userId - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1823
1857
  * scenarios where each user should be uniquely identified.
1824
1858
  * @param state - The state parameter that was passed in the authentication URL.
1825
1859
  *
@@ -1834,15 +1868,18 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1834
1868
  *
1835
1869
  * @preserve
1836
1870
  */
1837
- async getPKCECode(state, userID) {
1838
- return this._authenticationCore.getPKCECode(state, userID);
1871
+ async getPKCECode(state, userId) {
1872
+ return await this._storageManager.getTemporaryDataParameter(
1873
+ extractPkceStorageKeyFromState_default(state),
1874
+ userId
1875
+ );
1839
1876
  }
1840
1877
  /**
1841
1878
  * This method sets the PKCE code to the data store.
1842
1879
  *
1843
1880
  * @param pkce - The PKCE code.
1844
1881
  * @param state - The state parameter that was passed in the authentication URL.
1845
- * @param userID - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1882
+ * @param userId - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user
1846
1883
  * scenarios where each user should be uniquely identified.
1847
1884
  *
1848
1885
  * @example
@@ -1854,15 +1891,15 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1854
1891
  *
1855
1892
  * @preserve
1856
1893
  */
1857
- async setPKCECode(pkce, state, userID) {
1858
- await this._authenticationCore.setPKCECode(pkce, state, userID);
1894
+ async setPKCECode(pkce, state, userId) {
1895
+ return await this._storageManager.setTemporaryDataParameter(extractPkceStorageKeyFromState_default(state), pkce, userId);
1859
1896
  }
1860
1897
  /**
1861
1898
  * This method returns if the sign-out is successful or not.
1862
1899
  *
1863
1900
  * @param signOutRedirectUrl - The URL to which the user has been redirected to after signing-out.
1864
1901
  *
1865
- * **The server appends path parameters to the `signOutRedirectURL` and these path parameters
1902
+ * **The server appends path parameters to the `afterSignOutUrl` and these path parameters
1866
1903
  * are required for this method to function.**
1867
1904
  *
1868
1905
  * @returns - `true` if successful, `false` otherwise.
@@ -1871,8 +1908,8 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1871
1908
  *
1872
1909
  * @preserve
1873
1910
  */
1874
- static isSignOutSuccessful(signOutRedirectURL) {
1875
- const url = new URL(signOutRedirectURL);
1911
+ static isSignOutSuccessful(afterSignOutUrl) {
1912
+ const url = new URL(afterSignOutUrl);
1876
1913
  const stateParam = url.searchParams.get(OIDCRequestConstants_default.Params.STATE);
1877
1914
  const error = Boolean(url.searchParams.get("error"));
1878
1915
  return stateParam ? stateParam === OIDCRequestConstants_default.Params.SIGN_OUT_SUCCESS && !error : false;
@@ -1882,7 +1919,7 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1882
1919
  *
1883
1920
  * @param signOutRedirectUrl - The URL to which the user has been redirected to after signing-out.
1884
1921
  *
1885
- * **The server appends path parameters to the `signOutRedirectURL` and these path parameters
1922
+ * **The server appends path parameters to the `afterSignOutUrl` and these path parameters
1886
1923
  * are required for this method to function.**
1887
1924
  *
1888
1925
  * @returns - `true` if successful, `false` otherwise.
@@ -1891,8 +1928,8 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1891
1928
  *
1892
1929
  * @preserve
1893
1930
  */
1894
- static didSignOutFail(signOutRedirectURL) {
1895
- const url = new URL(signOutRedirectURL);
1931
+ static didSignOutFail(afterSignOutUrl) {
1932
+ const url = new URL(afterSignOutUrl);
1896
1933
  const stateParam = url.searchParams.get(OIDCRequestConstants_default.Params.STATE);
1897
1934
  const error = Boolean(url.searchParams.get("error"));
1898
1935
  return stateParam ? stateParam === OIDCRequestConstants_default.Params.SIGN_OUT_SUCCESS && error : false;
@@ -1905,160 +1942,897 @@ var _AsgardeoAuthClient = class _AsgardeoAuthClient {
1905
1942
  * @example
1906
1943
  * ```
1907
1944
  * const config = {
1908
- * signInRedirectURL: "http://localhost:3000/sign-in",
1909
- * clientID: "client ID",
1945
+ * afterSignInUrl: "http://localhost:3000/sign-in",
1946
+ * clientId: "client ID",
1910
1947
  * baseUrl: "https://localhost:9443"
1911
1948
  * }
1912
1949
  *
1913
- * await auth.updateConfig(config);
1950
+ * await auth.reInitialize(config);
1914
1951
  * ```
1915
- * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#updateConfig}
1952
+ * {@link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#reInitialize}
1916
1953
  *
1917
1954
  * @preserve
1918
1955
  */
1919
- async updateConfig(config) {
1920
- await this._authenticationCore.updateConfig(config);
1956
+ async reInitialize(config) {
1957
+ await this._storageManager.setConfigData(config);
1958
+ await this.loadOpenIDProviderConfiguration(true);
1959
+ }
1960
+ static async clearSession(userId) {
1961
+ await this._authenticationHelper.clearSession(userId);
1962
+ }
1963
+ };
1964
+ __publicField(_AsgardeoAuthClient, "_instanceID");
1965
+ // FIXME: Validate this.
1966
+ // Ref: https://github.com/asgardeo/asgardeo-auth-js-core/pull/205
1967
+ __publicField(_AsgardeoAuthClient, "_authenticationHelper");
1968
+ var AsgardeoAuthClient = _AsgardeoAuthClient;
1969
+
1970
+ // src/errors/AsgardeoAPIError.ts
1971
+ var AsgardeoAPIError = class extends AsgardeoError {
1972
+ /**
1973
+ * Creates an instance of AsgardeoAPIError.
1974
+ *
1975
+ * @param message - Human-readable description of the error
1976
+ * @param code - A unique error code that identifies the error type
1977
+ * @param statusCode - HTTP status code of the failed request
1978
+ * @param statusText - HTTP status text of the failed request
1979
+ * @param origin - Optional. The SDK origin (e.g. 'react', 'vue'). Defaults to generic 'Asgardeo'
1980
+ * @constructor
1981
+ */
1982
+ constructor(message, code, origin, statusCode, statusText) {
1983
+ super(message, code, origin);
1984
+ this.statusCode = statusCode;
1985
+ this.statusText = statusText;
1986
+ Object.defineProperty(this, "name", {
1987
+ value: "AsgardeoAPIError",
1988
+ configurable: true,
1989
+ writable: true
1990
+ });
1991
+ }
1992
+ /**
1993
+ * Returns a string representation of the API error
1994
+ * @returns Formatted error string with name, code, status, and message
1995
+ */
1996
+ toString() {
1997
+ const status = this.statusCode ? ` (HTTP ${this.statusCode} - ${this.statusText})` : "";
1998
+ return `[${this.name}] (code="${this.code}")${status}
1999
+ Message: ${this.message}`;
2000
+ }
2001
+ };
2002
+
2003
+ // src/api/initializeEmbeddedSignInFlow.ts
2004
+ var initializeEmbeddedSignInFlow = async ({
2005
+ url,
2006
+ baseUrl,
2007
+ payload,
2008
+ ...requestConfig
2009
+ }) => {
2010
+ if (!payload) {
2011
+ throw new AsgardeoAPIError(
2012
+ "Authorization payload is required",
2013
+ "initializeEmbeddedSignInFlow-ValidationError-002",
2014
+ "javascript",
2015
+ 400,
2016
+ "If an authorization payload is not provided, the request cannot be constructed correctly."
2017
+ );
2018
+ }
2019
+ const searchParams = new URLSearchParams();
2020
+ Object.entries(payload).forEach(([key, value]) => {
2021
+ if (value !== void 0 && value !== null) {
2022
+ searchParams.append(key, String(value));
2023
+ }
2024
+ });
2025
+ const { headers: customHeaders, ...otherConfig } = requestConfig;
2026
+ const response = await fetch(url ?? `${baseUrl}/oauth2/authorize`, {
2027
+ method: requestConfig.method || "POST",
2028
+ headers: {
2029
+ "Content-Type": "application/x-www-form-urlencoded",
2030
+ Accept: "application/json",
2031
+ ...customHeaders
2032
+ },
2033
+ body: searchParams.toString(),
2034
+ ...otherConfig
2035
+ });
2036
+ if (!response.ok) {
2037
+ const errorText = await response.text();
2038
+ throw new AsgardeoAPIError(
2039
+ `Authorization request failed: ${errorText}`,
2040
+ "initializeEmbeddedSignInFlow-ResponseError-001",
2041
+ "javascript",
2042
+ response.status,
2043
+ response.statusText
2044
+ );
2045
+ }
2046
+ return await response.json();
2047
+ };
2048
+ var initializeEmbeddedSignInFlow_default = initializeEmbeddedSignInFlow;
2049
+
2050
+ // src/api/executeEmbeddedSignInFlow.ts
2051
+ var executeEmbeddedSignInFlow = async ({
2052
+ url,
2053
+ baseUrl,
2054
+ payload,
2055
+ ...requestConfig
2056
+ }) => {
2057
+ if (!payload) {
2058
+ throw new AsgardeoAPIError(
2059
+ "Authorization payload is required",
2060
+ "executeEmbeddedSignInFlow-ValidationError-002",
2061
+ "javascript",
2062
+ 400,
2063
+ "If an authorization payload is not provided, the request cannot be constructed correctly."
2064
+ );
2065
+ }
2066
+ const { headers: customHeaders, ...otherConfig } = requestConfig;
2067
+ const response = await fetch(url ?? `${baseUrl}/oauth2/authn`, {
2068
+ method: requestConfig.method || "POST",
2069
+ headers: {
2070
+ "Content-Type": "application/json",
2071
+ Accept: "application/json",
2072
+ ...customHeaders
2073
+ },
2074
+ body: JSON.stringify(payload),
2075
+ ...otherConfig
2076
+ });
2077
+ if (!response.ok) {
2078
+ const errorText = await response.text();
2079
+ throw new AsgardeoAPIError(
2080
+ `Authorization request failed: ${errorText}`,
2081
+ "initializeEmbeddedSignInFlow-ResponseError-001",
2082
+ "javascript",
2083
+ response.status,
2084
+ response.statusText
2085
+ );
2086
+ }
2087
+ return await response.json();
2088
+ };
2089
+ var executeEmbeddedSignInFlow_default = executeEmbeddedSignInFlow;
2090
+
2091
+ // src/models/embedded-flow.ts
2092
+ var EmbeddedFlowType = /* @__PURE__ */ ((EmbeddedFlowType2) => {
2093
+ EmbeddedFlowType2["Registration"] = "REGISTRATION";
2094
+ return EmbeddedFlowType2;
2095
+ })(EmbeddedFlowType || {});
2096
+ var EmbeddedFlowStatus = /* @__PURE__ */ ((EmbeddedFlowStatus2) => {
2097
+ EmbeddedFlowStatus2["Complete"] = "COMPLETE";
2098
+ EmbeddedFlowStatus2["Incomplete"] = "INCOMPLETE";
2099
+ return EmbeddedFlowStatus2;
2100
+ })(EmbeddedFlowStatus || {});
2101
+ var EmbeddedFlowResponseType = /* @__PURE__ */ ((EmbeddedFlowResponseType2) => {
2102
+ EmbeddedFlowResponseType2["Redirection"] = "REDIRECTION";
2103
+ EmbeddedFlowResponseType2["View"] = "VIEW";
2104
+ return EmbeddedFlowResponseType2;
2105
+ })(EmbeddedFlowResponseType || {});
2106
+ var EmbeddedFlowComponentType = /* @__PURE__ */ ((EmbeddedFlowComponentType2) => {
2107
+ EmbeddedFlowComponentType2["Button"] = "BUTTON";
2108
+ EmbeddedFlowComponentType2["Checkbox"] = "CHECKBOX";
2109
+ EmbeddedFlowComponentType2["Divider"] = "DIVIDER";
2110
+ EmbeddedFlowComponentType2["Form"] = "FORM";
2111
+ EmbeddedFlowComponentType2["Image"] = "IMAGE";
2112
+ EmbeddedFlowComponentType2["Input"] = "INPUT";
2113
+ EmbeddedFlowComponentType2["Radio"] = "RADIO";
2114
+ EmbeddedFlowComponentType2["Select"] = "SELECT";
2115
+ EmbeddedFlowComponentType2["Typography"] = "TYPOGRAPHY";
2116
+ return EmbeddedFlowComponentType2;
2117
+ })(EmbeddedFlowComponentType || {});
2118
+
2119
+ // src/api/executeEmbeddedSignUpFlow.ts
2120
+ var executeEmbeddedSignUpFlow = async ({
2121
+ url,
2122
+ baseUrl,
2123
+ payload,
2124
+ ...requestConfig
2125
+ }) => {
2126
+ if (!baseUrl && !url) {
2127
+ throw new AsgardeoAPIError(
2128
+ "Embedded SignUp flow execution failed: Base URL or URL is not provided.",
2129
+ "javascript-executeEmbeddedSignUpFlow-ValidationError-001",
2130
+ "javascript",
2131
+ 400,
2132
+ "At least one of the baseUrl or url must be provided to execute the embedded sign up flow."
2133
+ );
2134
+ }
2135
+ const { headers: customHeaders, ...otherConfig } = requestConfig;
2136
+ const response = await fetch(url ?? `${baseUrl}/api/server/v1/flow/execute`, {
2137
+ method: requestConfig.method || "POST",
2138
+ headers: {
2139
+ "Content-Type": "application/json",
2140
+ Accept: "application/json",
2141
+ ...customHeaders
2142
+ },
2143
+ body: JSON.stringify({
2144
+ ...payload ?? {},
2145
+ flowType: "REGISTRATION" /* Registration */
2146
+ }),
2147
+ ...otherConfig
2148
+ });
2149
+ if (!response.ok) {
2150
+ const errorText = await response.text();
2151
+ throw new AsgardeoAPIError(
2152
+ `Embedded SignUp flow execution failed: ${errorText}`,
2153
+ "javascript-executeEmbeddedSignUpFlow-ResponseError-100",
2154
+ "javascript",
2155
+ response.status,
2156
+ response.statusText
2157
+ );
2158
+ }
2159
+ return await response.json();
2160
+ };
2161
+ var executeEmbeddedSignUpFlow_default = executeEmbeddedSignUpFlow;
2162
+
2163
+ // src/api/getUserInfo.ts
2164
+ var getUserInfo = async ({ url, ...requestConfig }) => {
2165
+ try {
2166
+ new URL(url);
2167
+ } catch (error) {
2168
+ throw new AsgardeoAPIError(
2169
+ "Invalid endpoint URL provided",
2170
+ "getUserInfo-ValidationError-001",
2171
+ "javascript",
2172
+ 400,
2173
+ "Invalid Request"
2174
+ );
2175
+ }
2176
+ const response = await fetch(url, {
2177
+ method: "GET",
2178
+ headers: {
2179
+ "Content-Type": "application/json",
2180
+ Accept: "application/json"
2181
+ },
2182
+ ...requestConfig
2183
+ });
2184
+ if (!response.ok) {
2185
+ const errorText = await response.text();
2186
+ throw new AsgardeoAPIError(
2187
+ `Failed to fetch user info: ${errorText}`,
2188
+ "getUserInfo-ResponseError-001",
2189
+ "javascript",
2190
+ response.status,
2191
+ response.statusText
2192
+ );
2193
+ }
2194
+ return await response.json();
2195
+ };
2196
+ var getUserInfo_default = getUserInfo;
2197
+
2198
+ // src/api/getScim2Me.ts
2199
+ var getScim2Me = async ({ url, baseUrl, fetcher, ...requestConfig }) => {
2200
+ try {
2201
+ new URL(url ?? baseUrl);
2202
+ } catch (error) {
2203
+ throw new AsgardeoAPIError(
2204
+ `Invalid URL provided. ${error?.toString()}`,
2205
+ "getScim2Me-ValidationError-001",
2206
+ "javascript",
2207
+ 400,
2208
+ "The provided `url` or `baseUrl` path does not adhere to the URL schema."
2209
+ );
2210
+ }
2211
+ const fetchFn = fetcher || fetch;
2212
+ const resolvedUrl = url ?? `${baseUrl}/scim2/Me`;
2213
+ const requestInit = {
2214
+ method: "GET",
2215
+ headers: {
2216
+ "Content-Type": "application/scim+json",
2217
+ Accept: "application/json",
2218
+ ...requestConfig.headers
2219
+ },
2220
+ ...requestConfig
2221
+ };
2222
+ try {
2223
+ const response = await fetchFn(resolvedUrl, requestInit);
2224
+ if (!response?.ok) {
2225
+ const errorText = await response.text();
2226
+ throw new AsgardeoAPIError(
2227
+ `Failed to fetch user profile: ${errorText}`,
2228
+ "getScim2Me-ResponseError-001",
2229
+ "javascript",
2230
+ response.status,
2231
+ response.statusText
2232
+ );
2233
+ }
2234
+ return await response.json();
2235
+ } catch (error) {
2236
+ if (error instanceof AsgardeoAPIError) {
2237
+ throw error;
2238
+ }
2239
+ throw new AsgardeoAPIError(
2240
+ `Network or parsing error: ${error instanceof Error ? error.message : "Unknown error"}`,
2241
+ "getScim2Me-NetworkError-001",
2242
+ "javascript",
2243
+ 0,
2244
+ "Network Error"
2245
+ );
2246
+ }
2247
+ };
2248
+ var getScim2Me_default = getScim2Me;
2249
+
2250
+ // src/api/getSchemas.ts
2251
+ var getSchemas = async ({ url, baseUrl, fetcher, ...requestConfig }) => {
2252
+ try {
2253
+ new URL(url ?? baseUrl);
2254
+ } catch (error) {
2255
+ throw new AsgardeoAPIError(
2256
+ `Invalid URL provided. ${error?.toString()}`,
2257
+ "getSchemas-ValidationError-001",
2258
+ "javascript",
2259
+ 400,
2260
+ "The provided `url` or `baseUrl` path does not adhere to the URL schema."
2261
+ );
2262
+ }
2263
+ const fetchFn = fetcher || fetch;
2264
+ const resolvedUrl = url ?? `${baseUrl}/scim2/Schemas`;
2265
+ const requestInit = {
2266
+ method: "GET",
2267
+ headers: {
2268
+ "Content-Type": "application/json",
2269
+ Accept: "application/json",
2270
+ ...requestConfig.headers
2271
+ },
2272
+ ...requestConfig
2273
+ };
2274
+ try {
2275
+ const response = await fetchFn(resolvedUrl, requestInit);
2276
+ if (!response?.ok) {
2277
+ const errorText = await response.text();
2278
+ throw new AsgardeoAPIError(
2279
+ `Failed to fetch SCIM2 schemas: ${errorText}`,
2280
+ "getSchemas-ResponseError-001",
2281
+ "javascript",
2282
+ response.status,
2283
+ response.statusText
2284
+ );
2285
+ }
2286
+ return await response.json();
2287
+ } catch (error) {
2288
+ if (error instanceof AsgardeoAPIError) {
2289
+ throw error;
2290
+ }
2291
+ throw new AsgardeoAPIError(
2292
+ `Network or parsing error: ${error instanceof Error ? error.message : "Unknown error"}`,
2293
+ "getSchemas-NetworkError-001",
2294
+ "javascript",
2295
+ 0,
2296
+ "Network Error"
2297
+ );
2298
+ }
2299
+ };
2300
+ var getSchemas_default = getSchemas;
2301
+
2302
+ // src/api/getAllOrganizations.ts
2303
+ var getAllOrganizations = async ({
2304
+ baseUrl,
2305
+ filter = "",
2306
+ limit = 10,
2307
+ recursive = false,
2308
+ fetcher,
2309
+ ...requestConfig
2310
+ }) => {
2311
+ try {
2312
+ new URL(baseUrl);
2313
+ } catch (error) {
2314
+ throw new AsgardeoAPIError(
2315
+ `Invalid base URL provided. ${error?.toString()}`,
2316
+ "getAllOrganizations-ValidationError-001",
2317
+ "javascript",
2318
+ 400,
2319
+ "The provided `baseUrl` does not adhere to the URL schema."
2320
+ );
2321
+ }
2322
+ const queryParams = new URLSearchParams(
2323
+ Object.fromEntries(
2324
+ Object.entries({
2325
+ filter,
2326
+ limit: limit.toString(),
2327
+ recursive: recursive.toString()
2328
+ }).filter(([, value]) => Boolean(value))
2329
+ )
2330
+ );
2331
+ const fetchFn = fetcher || fetch;
2332
+ const resolvedUrl = `${baseUrl}/api/server/v1/organizations?${queryParams.toString()}`;
2333
+ const requestInit = {
2334
+ method: "GET",
2335
+ headers: {
2336
+ "Content-Type": "application/json",
2337
+ Accept: "application/json",
2338
+ ...requestConfig.headers
2339
+ },
2340
+ ...requestConfig
2341
+ };
2342
+ try {
2343
+ const response = await fetchFn(resolvedUrl, requestInit);
2344
+ if (!response?.ok) {
2345
+ const errorText = await response.text();
2346
+ throw new AsgardeoAPIError(
2347
+ `Failed to get organizations: ${errorText}`,
2348
+ "getAllOrganizations-ResponseError-001",
2349
+ "javascript",
2350
+ response.status,
2351
+ response.statusText
2352
+ );
2353
+ }
2354
+ const data = await response.json();
2355
+ return {
2356
+ hasMore: data.hasMore,
2357
+ nextCursor: data.nextCursor,
2358
+ organizations: data.organizations || [],
2359
+ totalCount: data.totalCount
2360
+ };
2361
+ } catch (error) {
2362
+ if (error instanceof AsgardeoAPIError) {
2363
+ throw error;
2364
+ }
2365
+ throw new AsgardeoAPIError(
2366
+ `Network or parsing error: ${error instanceof Error ? error.message : "Unknown error"}`,
2367
+ "getAllOrganizations-NetworkError-001",
2368
+ "javascript",
2369
+ 0,
2370
+ "Network Error"
2371
+ );
2372
+ }
2373
+ };
2374
+ var getAllOrganizations_default = getAllOrganizations;
2375
+
2376
+ // src/api/createOrganization.ts
2377
+ var createOrganization = async ({
2378
+ baseUrl,
2379
+ payload,
2380
+ fetcher,
2381
+ ...requestConfig
2382
+ }) => {
2383
+ try {
2384
+ new URL(baseUrl);
2385
+ } catch (error) {
2386
+ throw new AsgardeoAPIError(
2387
+ `Invalid base URL provided. ${error?.toString()}`,
2388
+ "createOrganization-ValidationError-001",
2389
+ "javascript",
2390
+ 400,
2391
+ "The provided `baseUrl` does not adhere to the URL schema."
2392
+ );
2393
+ }
2394
+ if (!payload) {
2395
+ throw new AsgardeoAPIError(
2396
+ "Organization payload is required",
2397
+ "createOrganization-ValidationError-002",
2398
+ "javascript",
2399
+ 400,
2400
+ "Invalid Request"
2401
+ );
2402
+ }
2403
+ const organizationPayload = {
2404
+ ...payload,
2405
+ type: "TENANT"
2406
+ };
2407
+ const fetchFn = fetcher || fetch;
2408
+ const resolvedUrl = `${baseUrl}/api/server/v1/organizations`;
2409
+ const requestInit = {
2410
+ method: "POST",
2411
+ headers: {
2412
+ "Content-Type": "application/json",
2413
+ Accept: "application/json",
2414
+ ...requestConfig.headers
2415
+ },
2416
+ body: JSON.stringify(organizationPayload),
2417
+ ...requestConfig
2418
+ };
2419
+ try {
2420
+ const response = await fetchFn(resolvedUrl, requestInit);
2421
+ if (!response?.ok) {
2422
+ const errorText = await response.text();
2423
+ throw new AsgardeoAPIError(
2424
+ `Failed to create organization: ${errorText}`,
2425
+ "createOrganization-ResponseError-001",
2426
+ "javascript",
2427
+ response.status,
2428
+ response.statusText
2429
+ );
2430
+ }
2431
+ return await response.json();
2432
+ } catch (error) {
2433
+ if (error instanceof AsgardeoAPIError) {
2434
+ throw error;
2435
+ }
2436
+ throw new AsgardeoAPIError(
2437
+ `Network or parsing error: ${error instanceof Error ? error.message : "Unknown error"}`,
2438
+ "createOrganization-NetworkError-001",
2439
+ "javascript",
2440
+ 0,
2441
+ "Network Error"
2442
+ );
2443
+ }
2444
+ };
2445
+ var createOrganization_default = createOrganization;
2446
+
2447
+ // src/api/getMeOrganizations.ts
2448
+ var getMeOrganizations = async ({
2449
+ baseUrl,
2450
+ after = "",
2451
+ authorizedAppName = "",
2452
+ before = "",
2453
+ filter = "",
2454
+ limit = 10,
2455
+ recursive = false,
2456
+ fetcher,
2457
+ ...requestConfig
2458
+ }) => {
2459
+ try {
2460
+ new URL(baseUrl);
2461
+ } catch (error) {
2462
+ throw new AsgardeoAPIError(
2463
+ `Invalid base URL provided. ${error?.toString()}`,
2464
+ "getMeOrganizations-ValidationError-001",
2465
+ "javascript",
2466
+ 400,
2467
+ "The provided `baseUrl` does not adhere to the URL schema."
2468
+ );
2469
+ }
2470
+ const queryParams = new URLSearchParams(
2471
+ Object.fromEntries(
2472
+ Object.entries({
2473
+ after,
2474
+ authorizedAppName,
2475
+ before,
2476
+ filter,
2477
+ limit: limit.toString(),
2478
+ recursive: recursive.toString()
2479
+ }).filter(([, value]) => Boolean(value))
2480
+ )
2481
+ );
2482
+ const fetchFn = fetcher || fetch;
2483
+ const resolvedUrl = `${baseUrl}/api/users/v1/me/organizations?${queryParams.toString()}`;
2484
+ const requestInit = {
2485
+ method: "GET",
2486
+ headers: {
2487
+ "Content-Type": "application/json",
2488
+ Accept: "application/json",
2489
+ ...requestConfig.headers
2490
+ },
2491
+ ...requestConfig
2492
+ };
2493
+ try {
2494
+ const response = await fetchFn(resolvedUrl, requestInit);
2495
+ if (!response?.ok) {
2496
+ const errorText = await response.text();
2497
+ throw new AsgardeoAPIError(
2498
+ `Failed to fetch associated organizations of the user: ${errorText}`,
2499
+ "getMeOrganizations-ResponseError-001",
2500
+ "javascript",
2501
+ response.status,
2502
+ response.statusText
2503
+ );
2504
+ }
2505
+ const data = await response.json();
2506
+ return data.organizations || [];
2507
+ } catch (error) {
2508
+ if (error instanceof AsgardeoAPIError) {
2509
+ throw error;
2510
+ }
2511
+ throw new AsgardeoAPIError(
2512
+ `Network or parsing error: ${error instanceof Error ? error.message : "Unknown error"}`,
2513
+ "getMeOrganizations-NetworkError-001",
2514
+ "javascript",
2515
+ 0,
2516
+ "Network Error"
2517
+ );
2518
+ }
2519
+ };
2520
+ var getMeOrganizations_default = getMeOrganizations;
2521
+
2522
+ // src/api/getOrganization.ts
2523
+ var getOrganization = async ({
2524
+ baseUrl,
2525
+ organizationId,
2526
+ fetcher,
2527
+ ...requestConfig
2528
+ }) => {
2529
+ try {
2530
+ new URL(baseUrl);
2531
+ } catch (error) {
2532
+ throw new AsgardeoAPIError(
2533
+ `Invalid base URL provided. ${error?.toString()}`,
2534
+ "getOrganization-ValidationError-001",
2535
+ "javascript",
2536
+ 400,
2537
+ "The provided `baseUrl` does not adhere to the URL schema."
2538
+ );
1921
2539
  }
1922
- static async clearUserSessionData(userID) {
1923
- await this._authenticationCore.clearUserSessionData(userID);
2540
+ if (!organizationId) {
2541
+ throw new AsgardeoAPIError(
2542
+ "Organization ID is required",
2543
+ "getOrganization-ValidationError-002",
2544
+ "javascript",
2545
+ 400,
2546
+ "Invalid Request"
2547
+ );
1924
2548
  }
1925
- };
1926
- __publicField(_AsgardeoAuthClient, "_instanceID");
1927
- __publicField(_AsgardeoAuthClient, "_authenticationCore");
1928
- var AsgardeoAuthClient = _AsgardeoAuthClient;
1929
-
1930
- // src/errors/AsgardeoError.ts
1931
- var AsgardeoError = class _AsgardeoError extends Error {
1932
- constructor(message, code, origin) {
1933
- const _origin = _AsgardeoError.resolveOrigin(origin);
1934
- const prefix = `\u{1F6E1}\uFE0F Asgardeo - ${_origin}:`;
1935
- const regex = new RegExp(`\u{1F6E1}\uFE0F\\s*Asgardeo\\s*-\\s*${_origin}:`, "i");
1936
- const sanitized = message.replace(regex, "");
1937
- const _message = `${prefix} ${sanitized.trim()}
1938
-
1939
- (code="${code}")
1940
- `;
1941
- super(_message);
1942
- __publicField(this, "code");
1943
- __publicField(this, "origin");
1944
- this.name = new.target.name;
1945
- this.code = code;
1946
- this.origin = _origin;
1947
- if (Error.captureStackTrace) {
1948
- Error.captureStackTrace(this, new.target);
2549
+ const fetchFn = fetcher || fetch;
2550
+ const resolvedUrl = `${baseUrl}/api/server/v1/organizations/${organizationId}`;
2551
+ const requestInit = {
2552
+ method: "GET",
2553
+ headers: {
2554
+ "Content-Type": "application/json",
2555
+ Accept: "application/json",
2556
+ ...requestConfig.headers
2557
+ },
2558
+ ...requestConfig
2559
+ };
2560
+ try {
2561
+ const response = await fetchFn(resolvedUrl, requestInit);
2562
+ if (!response?.ok) {
2563
+ const errorText = await response.text();
2564
+ throw new AsgardeoAPIError(
2565
+ `Failed to fetch organization details: ${errorText}`,
2566
+ "getOrganization-ResponseError-001",
2567
+ "javascript",
2568
+ response.status,
2569
+ response.statusText
2570
+ );
1949
2571
  }
1950
- }
1951
- static resolveOrigin(origin) {
1952
- if (!origin) {
1953
- return "@asgardeo/javascript";
2572
+ return await response.json();
2573
+ } catch (error) {
2574
+ if (error instanceof AsgardeoAPIError) {
2575
+ throw error;
1954
2576
  }
1955
- return `@asgardeo/${origin}`;
1956
- }
1957
- toString() {
1958
- return `[${this.name}]
1959
- Message: ${this.message}`;
2577
+ throw new AsgardeoAPIError(
2578
+ `Network or parsing error: ${error instanceof Error ? error.message : "Unknown error"}`,
2579
+ "getOrganization-NetworkError-001",
2580
+ "javascript",
2581
+ 0,
2582
+ "Network Error"
2583
+ );
1960
2584
  }
1961
2585
  };
2586
+ var getOrganization_default = getOrganization;
1962
2587
 
1963
- // src/errors/AsgardeoAPIError.ts
1964
- var AsgardeoAPIError = class extends AsgardeoError {
1965
- /**
1966
- * Creates an instance of AsgardeoAPIError.
1967
- *
1968
- * @param message - Human-readable description of the error
1969
- * @param code - A unique error code that identifies the error type
1970
- * @param statusCode - HTTP status code of the failed request
1971
- * @param statusText - HTTP status text of the failed request
1972
- * @param origin - Optional. The SDK origin (e.g. 'react', 'vue'). Defaults to generic 'Asgardeo'
1973
- * @constructor
1974
- */
1975
- constructor(message, code, origin, statusCode, statusText) {
1976
- super(message, code, origin);
1977
- this.statusCode = statusCode;
1978
- this.statusText = statusText;
1979
- Object.defineProperty(this, "name", {
1980
- value: "AsgardeoAPIError",
1981
- configurable: true,
1982
- writable: true
1983
- });
2588
+ // src/utils/isEmpty.ts
2589
+ var isEmpty = (value) => {
2590
+ if (value === null || value === void 0) {
2591
+ return true;
1984
2592
  }
1985
- /**
1986
- * Returns a string representation of the API error
1987
- * @returns Formatted error string with name, code, status, and message
1988
- */
1989
- toString() {
1990
- const status = this.statusCode ? ` (HTTP ${this.statusCode} - ${this.statusText})` : "";
1991
- return `[${this.name}] (code="${this.code}")${status}
1992
- Message: ${this.message}`;
2593
+ if (typeof value === "string") {
2594
+ return value.trim() === "";
2595
+ }
2596
+ if (Array.isArray(value)) {
2597
+ return value.length === 0;
1993
2598
  }
2599
+ if (typeof value === "object" && value.constructor === Object) {
2600
+ return Object.keys(value).length === 0;
2601
+ }
2602
+ return false;
1994
2603
  };
2604
+ var isEmpty_default = isEmpty;
1995
2605
 
1996
- // src/api/oidc/getUserInfo.ts
1997
- var getUserInfo = async ({ url, ...requestConfig }) => {
2606
+ // src/api/updateOrganization.ts
2607
+ var updateOrganization = async ({
2608
+ baseUrl,
2609
+ organizationId,
2610
+ operations,
2611
+ fetcher,
2612
+ ...requestConfig
2613
+ }) => {
1998
2614
  try {
1999
- new URL(url);
2615
+ new URL(baseUrl);
2000
2616
  } catch (error) {
2001
2617
  throw new AsgardeoAPIError(
2002
- "Invalid endpoint URL provided",
2003
- "getUserInfo-ValidationError-001",
2618
+ `Invalid base URL provided. ${error?.toString()}`,
2619
+ "updateOrganization-ValidationError-001",
2620
+ "javascript",
2621
+ 400,
2622
+ "The provided `baseUrl` does not adhere to the URL schema."
2623
+ );
2624
+ }
2625
+ if (!organizationId) {
2626
+ throw new AsgardeoAPIError(
2627
+ "Organization ID is required",
2628
+ "updateOrganization-ValidationError-002",
2004
2629
  "javascript",
2005
2630
  400,
2006
2631
  "Invalid Request"
2007
2632
  );
2008
2633
  }
2009
- const response = await fetch(url, {
2010
- method: "GET",
2634
+ if (!operations || !Array.isArray(operations) || operations.length === 0) {
2635
+ throw new AsgardeoAPIError(
2636
+ "Operations array is required and cannot be empty",
2637
+ "updateOrganization-ValidationError-003",
2638
+ "javascript",
2639
+ 400,
2640
+ "Invalid Request"
2641
+ );
2642
+ }
2643
+ const fetchFn = fetcher || fetch;
2644
+ const resolvedUrl = `${baseUrl}/api/server/v1/organizations/${organizationId}`;
2645
+ const requestInit = {
2646
+ method: "PATCH",
2011
2647
  headers: {
2012
2648
  "Content-Type": "application/json",
2013
- Accept: "application/json"
2649
+ Accept: "application/json",
2650
+ ...requestConfig.headers
2014
2651
  },
2652
+ body: JSON.stringify(operations),
2015
2653
  ...requestConfig
2654
+ };
2655
+ try {
2656
+ const response = await fetchFn(resolvedUrl, requestInit);
2657
+ if (!response?.ok) {
2658
+ const errorText = await response.text();
2659
+ throw new AsgardeoAPIError(
2660
+ `Failed to update organization: ${errorText}`,
2661
+ "updateOrganization-ResponseError-001",
2662
+ "javascript",
2663
+ response.status,
2664
+ response.statusText
2665
+ );
2666
+ }
2667
+ return await response.json();
2668
+ } catch (error) {
2669
+ if (error instanceof AsgardeoAPIError) {
2670
+ throw error;
2671
+ }
2672
+ throw new AsgardeoAPIError(
2673
+ `Network or parsing error: ${error instanceof Error ? error.message : "Unknown error"}`,
2674
+ "updateOrganization-NetworkError-001",
2675
+ "javascript",
2676
+ 0,
2677
+ "Network Error"
2678
+ );
2679
+ }
2680
+ };
2681
+ var createPatchOperations = (payload) => {
2682
+ return Object.entries(payload).map(([key, value]) => {
2683
+ if (isEmpty_default(value)) {
2684
+ return {
2685
+ operation: "REMOVE",
2686
+ path: `/${key}`
2687
+ };
2688
+ }
2689
+ return {
2690
+ operation: "REPLACE",
2691
+ path: `/${key}`,
2692
+ value
2693
+ };
2016
2694
  });
2017
- if (!response.ok) {
2018
- const errorText = await response.text();
2695
+ };
2696
+ var updateOrganization_default = updateOrganization;
2697
+
2698
+ // src/api/updateMeProfile.ts
2699
+ var updateMeProfile = async ({
2700
+ url,
2701
+ baseUrl,
2702
+ payload,
2703
+ fetcher,
2704
+ ...requestConfig
2705
+ }) => {
2706
+ try {
2707
+ new URL(url ?? baseUrl);
2708
+ } catch (error) {
2019
2709
  throw new AsgardeoAPIError(
2020
- `Failed to fetch user info: ${errorText}`,
2021
- "getUserInfo-ResponseError-001",
2710
+ `Invalid URL provided. ${error?.toString()}`,
2711
+ "updateMeProfile-ValidationError-001",
2022
2712
  "javascript",
2023
- response.status,
2024
- response.statusText
2713
+ 400,
2714
+ "The provided `url` or `baseUrl` path does not adhere to the URL schema."
2715
+ );
2716
+ }
2717
+ const data = {
2718
+ Operations: [
2719
+ {
2720
+ op: "replace",
2721
+ value: payload
2722
+ }
2723
+ ],
2724
+ schemas: ["urn:ietf:params:scim:api:messages:2.0:PatchOp"]
2725
+ };
2726
+ const fetchFn = fetcher || fetch;
2727
+ const resolvedUrl = url ?? `${baseUrl}/scim2/Me`;
2728
+ const requestInit = {
2729
+ method: "PATCH",
2730
+ headers: {
2731
+ "Content-Type": "application/scim+json",
2732
+ Accept: "application/json",
2733
+ ...requestConfig.headers
2734
+ },
2735
+ body: JSON.stringify(data),
2736
+ ...requestConfig
2737
+ };
2738
+ try {
2739
+ const response = await fetchFn(resolvedUrl, requestInit);
2740
+ if (!response?.ok) {
2741
+ const errorText = await response.text();
2742
+ throw new AsgardeoAPIError(
2743
+ `Failed to update user profile: ${errorText}`,
2744
+ "updateMeProfile-ResponseError-001",
2745
+ "javascript",
2746
+ response.status,
2747
+ response.statusText
2748
+ );
2749
+ }
2750
+ return await response.json();
2751
+ } catch (error) {
2752
+ if (error instanceof AsgardeoAPIError) {
2753
+ throw error;
2754
+ }
2755
+ throw new AsgardeoAPIError(
2756
+ `Network or parsing error: ${error instanceof Error ? error.message : "Unknown error"}`,
2757
+ "updateMeProfile-NetworkError-001",
2758
+ "javascript",
2759
+ 0,
2760
+ "Network Error"
2025
2761
  );
2026
2762
  }
2027
- return await response.json();
2028
2763
  };
2029
- var getUserInfo_default = getUserInfo;
2764
+ var updateMeProfile_default = updateMeProfile;
2030
2765
 
2031
- // src/errors/AsgardeoRuntimeError.ts
2032
- var AsgardeoRuntimeError = class extends AsgardeoError {
2033
- /**
2034
- * Creates an instance of AsgardeoRuntimeError.
2035
- *
2036
- * @param message - Human-readable description of the error
2037
- * @param code - A unique error code that identifies the error type
2038
- * @param details - Additional details about the error that might be helpful for debugging
2039
- * @param origin - Optional. The SDK origin (e.g. 'react', 'vue'). Defaults to generic 'Asgardeo'
2040
- * @constructor
2041
- */
2042
- constructor(message, code, origin, details) {
2043
- super(message, code, origin);
2044
- this.details = details;
2045
- Object.defineProperty(this, "name", {
2046
- value: "AsgardeoRuntimeError",
2047
- configurable: true,
2048
- writable: true
2049
- });
2766
+ // src/constants/ApplicationNativeAuthenticationConstants.ts
2767
+ var ApplicationNativeAuthenticationConstants = {
2768
+ SupportedAuthenticators: {
2769
+ IdentifierFirst: "SWRlbnRpZmllckV4ZWN1dG9yOkxPQ0FM",
2770
+ EmailOtp: "ZW1haWwtb3RwLWF1dGhlbnRpY2F0b3I6TE9DQUw",
2771
+ Totp: "dG90cDpMT0NBTA",
2772
+ UsernamePassword: "QmFzaWNBdXRoZW50aWNhdG9yOkxPQ0FM",
2773
+ PushNotification: "cHVzaC1ub3RpZmljYXRpb24tYXV0aGVudGljYXRvcjpMT0NBTA",
2774
+ Passkey: "RklET0F1dGhlbnRpY2F0b3I6TE9DQUw",
2775
+ SmsOtp: "c21zLW90cC1hdXRoZW50aWNhdG9yOkxPQ0FM",
2776
+ MagicLink: "TWFnaWNMaW5rQXV0aGVudGljYXRvcjpMT0NBTA",
2777
+ Google: "R29vZ2xlT0lEQ0F1dGhlbnRpY2F0b3I6R29vZ2xl",
2778
+ GitHub: "R2l0aHViQXV0aGVudGljYXRvcjpHaXRIdWI",
2779
+ Microsoft: "T3BlbklEQ29ubmVjdEF1dGhlbnRpY2F0b3I6TWljcm9zb2Z0",
2780
+ Facebook: "RmFjZWJvb2tBdXRoZW50aWNhdG9yOkZhY2Vib29r",
2781
+ LinkedIn: "TGlua2VkSW5PSURDOkxpbmtlZElu",
2782
+ SignInWithEthereum: "T3BlbklEQ29ubmVjdEF1dGhlbnRpY2F0b3I6U2lnbiBJbiBXaXRoIEV0aGVyZXVt"
2050
2783
  }
2784
+ };
2785
+ var ApplicationNativeAuthenticationConstants_default = ApplicationNativeAuthenticationConstants;
2786
+
2787
+ // src/constants/VendorConstants.ts
2788
+ var VendorConstants = {
2051
2789
  /**
2052
- * Returns a string representation of the runtime error
2053
- * @returns Formatted error string with name, code, details, and message
2790
+ * The prefix used for vendor-specific API endpoints, CSS classes, or other identifiers.
2054
2791
  */
2055
- toString() {
2056
- const details = this.details ? `
2057
- Details: ${JSON.stringify(this.details, null, 2)}` : "";
2058
- return `[${this.name}] (code="${this.code}")${details}
2059
- Message: ${this.message}`;
2060
- }
2792
+ VENDOR_PREFIX: "asgardeo"
2061
2793
  };
2794
+ var VendorConstants_default = VendorConstants;
2795
+
2796
+ // src/models/embedded-signin-flow.ts
2797
+ var EmbeddedSignInFlowStatus = /* @__PURE__ */ ((EmbeddedSignInFlowStatus2) => {
2798
+ EmbeddedSignInFlowStatus2["FailCompleted"] = "FAIL_COMPLETED";
2799
+ EmbeddedSignInFlowStatus2["FailIncomplete"] = "FAIL_INCOMPLETE";
2800
+ EmbeddedSignInFlowStatus2["Incomplete"] = "INCOMPLETE";
2801
+ EmbeddedSignInFlowStatus2["SuccessCompleted"] = "SUCCESS_COMPLETED";
2802
+ return EmbeddedSignInFlowStatus2;
2803
+ })(EmbeddedSignInFlowStatus || {});
2804
+ var EmbeddedSignInFlowType = /* @__PURE__ */ ((EmbeddedSignInFlowType2) => {
2805
+ EmbeddedSignInFlowType2["Authentication"] = "AUTHENTICATION";
2806
+ return EmbeddedSignInFlowType2;
2807
+ })(EmbeddedSignInFlowType || {});
2808
+ var EmbeddedSignInFlowStepType = /* @__PURE__ */ ((EmbeddedSignInFlowStepType2) => {
2809
+ EmbeddedSignInFlowStepType2["AuthenticatorPrompt"] = "AUTHENTICATOR_PROMPT";
2810
+ EmbeddedSignInFlowStepType2["MultiOptionsPrompt"] = "MULTI_OPTIONS_PROMPT";
2811
+ return EmbeddedSignInFlowStepType2;
2812
+ })(EmbeddedSignInFlowStepType || {});
2813
+ var EmbeddedSignInFlowAuthenticatorParamType = /* @__PURE__ */ ((EmbeddedSignInFlowAuthenticatorParamType2) => {
2814
+ EmbeddedSignInFlowAuthenticatorParamType2["Integer"] = "INTEGER";
2815
+ EmbeddedSignInFlowAuthenticatorParamType2["MultiValued"] = "MULTI_VALUED";
2816
+ EmbeddedSignInFlowAuthenticatorParamType2["String"] = "STRING";
2817
+ return EmbeddedSignInFlowAuthenticatorParamType2;
2818
+ })(EmbeddedSignInFlowAuthenticatorParamType || {});
2819
+ var EmbeddedSignInFlowAuthenticatorKnownIdPType = /* @__PURE__ */ ((EmbeddedSignInFlowAuthenticatorKnownIdPType2) => {
2820
+ EmbeddedSignInFlowAuthenticatorKnownIdPType2["Local"] = "LOCAL";
2821
+ return EmbeddedSignInFlowAuthenticatorKnownIdPType2;
2822
+ })(EmbeddedSignInFlowAuthenticatorKnownIdPType || {});
2823
+ var EmbeddedSignInFlowAuthenticatorPromptType = /* @__PURE__ */ ((EmbeddedSignInFlowAuthenticatorPromptType2) => {
2824
+ EmbeddedSignInFlowAuthenticatorPromptType2["InternalPrompt"] = "INTERNAL_PROMPT";
2825
+ EmbeddedSignInFlowAuthenticatorPromptType2["RedirectionPrompt"] = "REDIRECTION_PROMPT";
2826
+ EmbeddedSignInFlowAuthenticatorPromptType2["UserPrompt"] = "USER_PROMPT";
2827
+ return EmbeddedSignInFlowAuthenticatorPromptType2;
2828
+ })(EmbeddedSignInFlowAuthenticatorPromptType || {});
2829
+
2830
+ // src/models/flow.ts
2831
+ var FlowMode = /* @__PURE__ */ ((FlowMode2) => {
2832
+ FlowMode2["Embedded"] = "DIRECT";
2833
+ FlowMode2["Redirect"] = "REDIRECTION";
2834
+ return FlowMode2;
2835
+ })(FlowMode || {});
2062
2836
 
2063
2837
  // src/models/scim2-schema.ts
2064
2838
  var WellKnownSchemaIds = /* @__PURE__ */ ((WellKnownSchemaIds2) => {
@@ -2070,6 +2844,22 @@ var WellKnownSchemaIds = /* @__PURE__ */ ((WellKnownSchemaIds2) => {
2070
2844
  return WellKnownSchemaIds2;
2071
2845
  })(WellKnownSchemaIds || {});
2072
2846
 
2847
+ // src/models/field.ts
2848
+ var FieldType = /* @__PURE__ */ ((FieldType2) => {
2849
+ FieldType2["Text"] = "TEXT";
2850
+ FieldType2["Password"] = "PASSWORD";
2851
+ FieldType2["Email"] = "EMAIL";
2852
+ FieldType2["Number"] = "NUMBER";
2853
+ FieldType2["Select"] = "SELECT";
2854
+ FieldType2["Checkbox"] = "CHECKBOX";
2855
+ FieldType2["Radio"] = "RADIO";
2856
+ FieldType2["Otp"] = "OTP";
2857
+ FieldType2["Date"] = "DATE";
2858
+ FieldType2["Time"] = "TIME";
2859
+ FieldType2["Textarea"] = "TEXTAREA";
2860
+ return FieldType2;
2861
+ })(FieldType || {});
2862
+
2073
2863
  // src/AsgardeoJavaScriptClient.ts
2074
2864
  var AsgardeoJavaScriptClient = class {
2075
2865
  };
@@ -2087,7 +2877,7 @@ var lightTheme = {
2087
2877
  contrastText: "#ffffff"
2088
2878
  },
2089
2879
  background: {
2090
- surface: "#f5f5f5",
2880
+ surface: "#ffffff",
2091
2881
  disabled: "#f0f0f0",
2092
2882
  body: {
2093
2883
  main: "#1a1a1a"
@@ -2097,7 +2887,14 @@ var lightTheme = {
2097
2887
  main: "#d32f2f",
2098
2888
  contrastText: "#ffffff"
2099
2889
  },
2100
- surface: "#f5f5f5",
2890
+ success: {
2891
+ main: "#4caf50",
2892
+ contrastText: "#ffffff"
2893
+ },
2894
+ warning: {
2895
+ main: "#ff9800",
2896
+ contrastText: "#ffffff"
2897
+ },
2101
2898
  text: {
2102
2899
  primary: "#1a1a1a",
2103
2900
  secondary: "#666666"
@@ -2111,6 +2908,11 @@ var lightTheme = {
2111
2908
  small: "4px",
2112
2909
  medium: "8px",
2113
2910
  large: "16px"
2911
+ },
2912
+ shadows: {
2913
+ small: "0 2px 8px rgba(0, 0, 0, 0.1)",
2914
+ medium: "0 4px 16px rgba(0, 0, 0, 0.15)",
2915
+ large: "0 8px 32px rgba(0, 0, 0, 0.2)"
2114
2916
  }
2115
2917
  };
2116
2918
  var darkTheme = {
@@ -2134,7 +2936,14 @@ var darkTheme = {
2134
2936
  main: "#d32f2f",
2135
2937
  contrastText: "#ffffff"
2136
2938
  },
2137
- surface: "#2d2d2d",
2939
+ success: {
2940
+ main: "#4caf50",
2941
+ contrastText: "#ffffff"
2942
+ },
2943
+ warning: {
2944
+ main: "#ff9800",
2945
+ contrastText: "#ffffff"
2946
+ },
2138
2947
  text: {
2139
2948
  primary: "#ffffff",
2140
2949
  secondary: "#b3b3b3"
@@ -2148,6 +2957,11 @@ var darkTheme = {
2148
2957
  small: "4px",
2149
2958
  medium: "8px",
2150
2959
  large: "16px"
2960
+ },
2961
+ shadows: {
2962
+ small: "0 2px 8px rgba(0, 0, 0, 0.3)",
2963
+ medium: "0 4px 16px rgba(0, 0, 0, 0.4)",
2964
+ large: "0 8px 32px rgba(0, 0, 0, 0.5)"
2151
2965
  }
2152
2966
  };
2153
2967
  var toCssVariables = (theme) => {
@@ -2161,7 +2975,10 @@ var toCssVariables = (theme) => {
2161
2975
  cssVars["--asgardeo-color-background-body-main"] = theme.colors.background.body.main;
2162
2976
  cssVars["--asgardeo-color-error-main"] = theme.colors.error.main;
2163
2977
  cssVars["--asgardeo-color-error-contrastText"] = theme.colors.error.contrastText;
2164
- cssVars["--asgardeo-color-surface"] = theme.colors.surface;
2978
+ cssVars["--asgardeo-color-success-main"] = theme.colors.success.main;
2979
+ cssVars["--asgardeo-color-success-contrastText"] = theme.colors.success.contrastText;
2980
+ cssVars["--asgardeo-color-warning-main"] = theme.colors.warning.main;
2981
+ cssVars["--asgardeo-color-warning-contrastText"] = theme.colors.warning.contrastText;
2165
2982
  cssVars["--asgardeo-color-text-primary"] = theme.colors.text.primary;
2166
2983
  cssVars["--asgardeo-color-text-secondary"] = theme.colors.text.secondary;
2167
2984
  cssVars["--asgardeo-color-border"] = theme.colors.border;
@@ -2169,6 +2986,9 @@ var toCssVariables = (theme) => {
2169
2986
  cssVars["--asgardeo-border-radius-small"] = theme.borderRadius.small;
2170
2987
  cssVars["--asgardeo-border-radius-medium"] = theme.borderRadius.medium;
2171
2988
  cssVars["--asgardeo-border-radius-large"] = theme.borderRadius.large;
2989
+ cssVars["--asgardeo-shadow-small"] = theme.shadows.small;
2990
+ cssVars["--asgardeo-shadow-medium"] = theme.shadows.medium;
2991
+ cssVars["--asgardeo-shadow-large"] = theme.shadows.large;
2172
2992
  return cssVars;
2173
2993
  };
2174
2994
  var createTheme = (config = {}, isDark = false) => {
@@ -2191,6 +3011,10 @@ var createTheme = (config = {}, isDark = false) => {
2191
3011
  borderRadius: {
2192
3012
  ...baseTheme.borderRadius,
2193
3013
  ...config.borderRadius
3014
+ },
3015
+ shadows: {
3016
+ ...baseTheme.shadows,
3017
+ ...config.shadows
2194
3018
  }
2195
3019
  };
2196
3020
  return {
@@ -2200,28 +3024,417 @@ var createTheme = (config = {}, isDark = false) => {
2200
3024
  };
2201
3025
  var createTheme_default = createTheme;
2202
3026
 
3027
+ // src/utils/deepMerge.ts
3028
+ var isPlainObject = (value) => {
3029
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date) && !(value instanceof RegExp) && Object.prototype.toString.call(value) === "[object Object]";
3030
+ };
3031
+ var deepMerge = (target, ...sources) => {
3032
+ if (!target || typeof target !== "object") {
3033
+ throw new Error("Target must be an object");
3034
+ }
3035
+ const result = { ...target };
3036
+ sources.forEach((source) => {
3037
+ if (!source || typeof source !== "object") {
3038
+ return;
3039
+ }
3040
+ Object.keys(source).forEach((key) => {
3041
+ const sourceValue = source[key];
3042
+ const targetValue = result[key];
3043
+ if (isPlainObject(sourceValue) && isPlainObject(targetValue)) {
3044
+ result[key] = deepMerge(targetValue, sourceValue);
3045
+ } else if (sourceValue !== void 0) {
3046
+ result[key] = sourceValue;
3047
+ }
3048
+ });
3049
+ });
3050
+ return result;
3051
+ };
3052
+ var deepMerge_default = deepMerge;
3053
+
3054
+ // src/utils/flattenUserSchema.ts
3055
+ var flattenUserSchema = (schemas) => {
3056
+ const flattenedAttributes = [];
3057
+ schemas.forEach((schema) => {
3058
+ if (schema.attributes && Array.isArray(schema.attributes)) {
3059
+ schema.attributes.forEach((attribute) => {
3060
+ if (attribute.subAttributes && Array.isArray(attribute.subAttributes)) {
3061
+ attribute.subAttributes.forEach((subAttribute) => {
3062
+ flattenedAttributes.push({
3063
+ ...subAttribute,
3064
+ name: `${attribute.name}.${subAttribute.name}`,
3065
+ schemaId: schema.id
3066
+ });
3067
+ });
3068
+ } else {
3069
+ flattenedAttributes.push({
3070
+ ...attribute,
3071
+ schemaId: schema.id
3072
+ });
3073
+ }
3074
+ });
3075
+ }
3076
+ });
3077
+ return flattenedAttributes;
3078
+ };
3079
+ var flattenUserSchema_default = flattenUserSchema;
3080
+
3081
+ // src/utils/get.ts
3082
+ var get = (object, path, defaultValue) => {
3083
+ if (!object || !path) return defaultValue;
3084
+ const pathArray = Array.isArray(path) ? path : path.split(".");
3085
+ const result = pathArray.reduce((current, key) => {
3086
+ return current?.[key];
3087
+ }, object);
3088
+ return result !== void 0 ? result : defaultValue;
3089
+ };
3090
+ var get_default = get;
3091
+
3092
+ // src/utils/set.ts
3093
+ var set = (object, path, value) => {
3094
+ if (!object || !path) return object;
3095
+ const pathArray = Array.isArray(path) ? path : path.split(".");
3096
+ const lastIndex = pathArray.length - 1;
3097
+ pathArray.reduce((current, key, index) => {
3098
+ if (index === lastIndex) {
3099
+ current[key] = value;
3100
+ } else {
3101
+ if (!(key in current) || typeof current[key] !== "object" || current[key] === null) {
3102
+ const nextKey = pathArray[index + 1];
3103
+ current[key] = /^\d+$/.test(nextKey) ? [] : {};
3104
+ }
3105
+ }
3106
+ return current[key];
3107
+ }, object);
3108
+ return object;
3109
+ };
3110
+ var set_default = set;
3111
+
3112
+ // src/utils/generateUserProfile.ts
3113
+ var generateUserProfile = (meResponse, processedSchemas) => {
3114
+ const profile = {};
3115
+ processedSchemas.forEach((schema) => {
3116
+ const { name, type, multiValued } = schema;
3117
+ if (!name) return;
3118
+ let value = get_default(meResponse, name);
3119
+ if (value !== void 0) {
3120
+ if (multiValued && !Array.isArray(value)) {
3121
+ value = [value];
3122
+ }
3123
+ } else {
3124
+ if (multiValued) {
3125
+ value = void 0;
3126
+ } else if (type === "STRING") {
3127
+ value = "";
3128
+ } else {
3129
+ value = void 0;
3130
+ }
3131
+ }
3132
+ set_default(profile, name, value);
3133
+ });
3134
+ return profile;
3135
+ };
3136
+ var generateUserProfile_default = generateUserProfile;
3137
+
3138
+ // src/utils/getLatestStateParam.ts
3139
+ var getLatestPkceStorageKey = (tempStore) => {
3140
+ const keys = [];
3141
+ Object.keys(tempStore).forEach((key) => {
3142
+ if (key.startsWith(PKCEConstants_default.Storage.StorageKeys.CODE_VERIFIER)) {
3143
+ keys.push(key);
3144
+ }
3145
+ });
3146
+ const lastKey = keys.sort().pop();
3147
+ return lastKey ?? null;
3148
+ };
3149
+ var getLatestStateParam = (tempStore, state) => {
3150
+ const latestPkceKey = getLatestPkceStorageKey(tempStore);
3151
+ if (!latestPkceKey) {
3152
+ return null;
3153
+ }
3154
+ return generateStateParamForRequestCorrelation_default(latestPkceKey, state);
3155
+ };
3156
+ var getLatestStateParam_default = getLatestStateParam;
3157
+
3158
+ // src/utils/generateFlattenedUserProfile.ts
3159
+ var generateFlattenedUserProfile = (meResponse, processedSchemas) => {
3160
+ const profile = {};
3161
+ const allSchemaNames = processedSchemas.map((schema) => schema.name).filter(Boolean);
3162
+ processedSchemas.forEach((schema) => {
3163
+ const { name, type, multiValued } = schema;
3164
+ if (!name) return;
3165
+ const hasChildProperties = allSchemaNames.some(
3166
+ (schemaName) => schemaName !== name && schemaName.startsWith(`${name}.`)
3167
+ );
3168
+ if (hasChildProperties) {
3169
+ return;
3170
+ }
3171
+ let value = get_default(meResponse, name);
3172
+ if (value === void 0) {
3173
+ const schemaNamespaces = [
3174
+ "urn:ietf:params:scim:schemas:core:2.0:User",
3175
+ "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User",
3176
+ "urn:scim:wso2:schema",
3177
+ "urn:scim:schemas:extension:custom:User"
3178
+ ];
3179
+ schemaNamespaces.some((namespace) => {
3180
+ if (meResponse[namespace]) {
3181
+ if (meResponse[namespace][name] !== void 0) {
3182
+ value = meResponse[namespace][name];
3183
+ return true;
3184
+ }
3185
+ const nestedValue = get_default(meResponse[namespace], name);
3186
+ if (nestedValue !== void 0) {
3187
+ value = nestedValue;
3188
+ return true;
3189
+ }
3190
+ }
3191
+ return false;
3192
+ });
3193
+ }
3194
+ if (value !== void 0) {
3195
+ if (multiValued && !Array.isArray(value)) {
3196
+ value = [value];
3197
+ }
3198
+ } else if (multiValued) {
3199
+ value = void 0;
3200
+ } else if (type === "STRING") {
3201
+ value = "";
3202
+ } else {
3203
+ value = void 0;
3204
+ }
3205
+ profile[name] = value;
3206
+ });
3207
+ const flattenObject = (obj, prefix = "") => {
3208
+ if (obj && typeof obj === "object" && !Array.isArray(obj)) {
3209
+ Object.keys(obj).forEach((key) => {
3210
+ const fullKey = prefix ? `${prefix}.${key}` : key;
3211
+ const value = obj[key];
3212
+ if (Object.prototype.hasOwnProperty.call(profile, fullKey)) {
3213
+ return;
3214
+ }
3215
+ const hasSchemaChildProperties = allSchemaNames.some(
3216
+ (schemaName) => schemaName.startsWith(`${fullKey}.`)
3217
+ );
3218
+ if (hasSchemaChildProperties) {
3219
+ flattenObject(value, fullKey);
3220
+ } else {
3221
+ profile[fullKey] = value;
3222
+ }
3223
+ });
3224
+ }
3225
+ };
3226
+ flattenObject(meResponse);
3227
+ return profile;
3228
+ };
3229
+ var generateFlattenedUserProfile_default = generateFlattenedUserProfile;
3230
+
3231
+ // src/i18n/index.ts
3232
+ var i18n_exports = {};
3233
+ __export(i18n_exports, {
3234
+ en_US: () => en_US_default
3235
+ });
3236
+
3237
+ // src/i18n/en-US.ts
3238
+ var translations = {
3239
+ /* |---------------------------------------------------------------| */
3240
+ /* | Elements | */
3241
+ /* |---------------------------------------------------------------| */
3242
+ //* Buttons */
3243
+ "elements.buttons.signIn": "Sign In",
3244
+ "elements.buttons.signOut": "Sign Out",
3245
+ "elements.buttons.signUp": "Sign Up",
3246
+ "elements.buttons.facebook": "Continue with Facebook",
3247
+ "elements.buttons.google": "Continue with Google",
3248
+ "elements.buttons.github": "Continue with GitHub",
3249
+ "elements.buttons.microsoft": "Continue with Microsoft",
3250
+ "elements.buttons.linkedin": "Continue with LinkedIn",
3251
+ "elements.buttons.ethereum": "Continue with Sign In Ethereum",
3252
+ "elements.buttons.multi.option": "Continue with {connection}",
3253
+ "elements.buttons.social": "Continue with {connection}",
3254
+ /* Fields */
3255
+ "elements.fields.placeholder": "Enter your {field}",
3256
+ /* |---------------------------------------------------------------| */
3257
+ /* | Widgets | */
3258
+ /* |---------------------------------------------------------------| */
3259
+ /* Base Sign In */
3260
+ "signin.title": "Sign In",
3261
+ "signin.subtitle": "Enter your credentials to continue.",
3262
+ /* Base Sign Up */
3263
+ "signup.title": "Sign Up",
3264
+ "signup.subtitle": "Create a new account to get started.",
3265
+ /* Email OTP */
3266
+ "email.otp.title": "OTP Verification",
3267
+ "email.otp.subtitle": "Enter the code sent to your email address.",
3268
+ "email.otp.submit.button": "Continue",
3269
+ /* Identifier First */
3270
+ "identifier.first.title": "Sign In",
3271
+ "identifier.first.subtitle": "Enter your username or email address.",
3272
+ "identifier.first.submit.button": "Continue",
3273
+ /* SMS OTP */
3274
+ "sms.otp.title": "OTP Verification",
3275
+ "sms.otp.subtitle": "Enter the code sent to your phone number.",
3276
+ "sms.otp.submit.button": "Continue",
3277
+ /* TOTP */
3278
+ "totp.title": "Verify Your Identity",
3279
+ "totp.subtitle": "Enter the code from your authenticator app.",
3280
+ "totp.submit.button": "Continue",
3281
+ /* Username Password */
3282
+ "username.password.submit.button": "Continue",
3283
+ "username.password.title": "Sign In",
3284
+ "username.password.subtitle": "Enter your username and password to continue.",
3285
+ /* |---------------------------------------------------------------| */
3286
+ /* | Organization Switcher | */
3287
+ /* |---------------------------------------------------------------| */
3288
+ "organization.switcher.select.organization": "Select Organization",
3289
+ "organization.switcher.switch.organization": "Switch Organization",
3290
+ "organization.switcher.loading.organizations": "Loading organizations...",
3291
+ "organization.switcher.members": "members",
3292
+ "organization.switcher.member": "member",
3293
+ "organization.switcher.create.organization": "Create Organization",
3294
+ "organization.switcher.manage.organizations": "Manage Organization",
3295
+ "organization.switcher.manage.button": "Manage",
3296
+ "organization.profile.title": "Organization Profile",
3297
+ "organization.profile.loading": "Loading organization...",
3298
+ "organization.profile.error": "Failed to load organization",
3299
+ "organization.create.title": "Create Organization",
3300
+ "organization.create.name.label": "Organization Name",
3301
+ "organization.create.name.placeholder": "Enter organization name",
3302
+ "organization.create.handle.label": "Organization Handle",
3303
+ "organization.create.handle.placeholder": "my-organization",
3304
+ "organization.create.description.label": "Description",
3305
+ "organization.create.description.placeholder": "Enter organization description",
3306
+ "organization.create.button": "Create Organization",
3307
+ "organization.create.creating": "Creating...",
3308
+ "organization.create.cancel": "Cancel",
3309
+ /* |---------------------------------------------------------------| */
3310
+ /* | Messages | */
3311
+ /* |---------------------------------------------------------------| */
3312
+ "messages.loading": "Loading...",
3313
+ /* |---------------------------------------------------------------| */
3314
+ /* | Errors | */
3315
+ /* |---------------------------------------------------------------| */
3316
+ "errors.title": "Error",
3317
+ "errors.sign.in.initialization": "An error occurred while initializing. Please try again later.",
3318
+ "errors.sign.in.flow.failure": "An error occurred during the sign-in flow. Please try again later.",
3319
+ "errors.sign.in.flow.completion.failure": "An error occurred while completing the sign-in flow. Please try again later.",
3320
+ "errors.sign.in.flow.passkeys.failure": "An error occurred while signing in with passkeys. Please try again later.",
3321
+ "errors.sign.in.flow.passkeys.completion.failure": "An error occurred while completing the passkeys sign-in flow. Please try again later."
3322
+ };
3323
+ var metadata = {
3324
+ localeCode: "en-US",
3325
+ countryCode: "US",
3326
+ languageCode: "en",
3327
+ displayName: "English (United States)",
3328
+ direction: "ltr"
3329
+ };
3330
+ var en_US = {
3331
+ metadata,
3332
+ translations
3333
+ };
3334
+ var en_US_default = en_US;
3335
+
3336
+ // src/utils/getI18nBundles.ts
3337
+ var getI18nBundles = () => {
3338
+ return i18n_exports;
3339
+ };
3340
+ var getI18nBundles_default = getI18nBundles;
3341
+
2203
3342
  // src/utils/removeTrailingSlash.ts
2204
3343
  var removeTrailingSlash = (path) => path.endsWith("/") ? path.slice(0, -1) : path;
2205
3344
  var removeTrailingSlash_default = removeTrailingSlash;
3345
+
3346
+ // src/utils/resolveFieldType.ts
3347
+ var resolveFieldType = (field) => {
3348
+ if (field.type === "STRING" /* String */) {
3349
+ if (field.param === "OTPCode" /* Otp */) {
3350
+ return "OTP" /* Otp */;
3351
+ } else if (field?.confidential) {
3352
+ return "PASSWORD" /* Password */;
3353
+ }
3354
+ return "TEXT" /* Text */;
3355
+ }
3356
+ throw new AsgardeoRuntimeError(
3357
+ "Field type is not supported: " + field.type,
3358
+ "resolveFieldType-Invalid-001",
3359
+ "javascript",
3360
+ "The provided field type is not supported. Please check the field configuration."
3361
+ );
3362
+ };
3363
+ var resolveFieldType_default = resolveFieldType;
3364
+
3365
+ // src/utils/resolveFieldName.ts
3366
+ var resolveFieldName = (field) => {
3367
+ if (field.param) {
3368
+ return field.param;
3369
+ }
3370
+ throw new AsgardeoRuntimeError(
3371
+ "Field name is not supported: ",
3372
+ "resolveFieldName-Invalid-001",
3373
+ "javascript",
3374
+ "The provided field name is not supported. Please check the field configuration."
3375
+ );
3376
+ };
3377
+ var resolveFieldName_default = resolveFieldName;
3378
+
3379
+ // src/utils/withVendorCSSClassPrefix.ts
3380
+ var withVendorCSSClassPrefix = (className) => `${VendorConstants_default.VENDOR_PREFIX}-${className}`;
3381
+ var withVendorCSSClassPrefix_default = withVendorCSSClassPrefix;
2206
3382
  // Annotate the CommonJS export names for ESM import in node:
2207
3383
  0 && (module.exports = {
2208
- ASGARDEO_SESSION_ACTIVE,
3384
+ ApplicationNativeAuthenticationConstants,
2209
3385
  AsgardeoAPIError,
2210
3386
  AsgardeoAuthClient,
2211
3387
  AsgardeoAuthException,
2212
3388
  AsgardeoError,
2213
3389
  AsgardeoJavaScriptClient,
2214
3390
  AsgardeoRuntimeError,
2215
- DataLayer,
3391
+ EmbeddedFlowComponentType,
3392
+ EmbeddedFlowResponseType,
3393
+ EmbeddedFlowStatus,
3394
+ EmbeddedFlowType,
3395
+ EmbeddedSignInFlowAuthenticatorKnownIdPType,
3396
+ EmbeddedSignInFlowAuthenticatorParamType,
3397
+ EmbeddedSignInFlowAuthenticatorPromptType,
3398
+ EmbeddedSignInFlowStatus,
3399
+ EmbeddedSignInFlowStepType,
3400
+ EmbeddedSignInFlowType,
3401
+ FieldType,
3402
+ FlowMode,
2216
3403
  IsomorphicCrypto,
2217
3404
  OIDCRequestConstants,
2218
- ResponseMode,
3405
+ StorageManager,
2219
3406
  TokenConstants,
3407
+ VendorConstants,
2220
3408
  WellKnownSchemaIds,
3409
+ createOrganization,
3410
+ createPatchOperations,
2221
3411
  createTheme,
3412
+ deepMerge,
3413
+ executeEmbeddedSignInFlow,
3414
+ executeEmbeddedSignUpFlow,
2222
3415
  extractPkceStorageKeyFromState,
2223
3416
  extractUserClaimsFromIdToken,
3417
+ flattenUserSchema,
3418
+ generateFlattenedUserProfile,
3419
+ generateUserProfile,
3420
+ get,
3421
+ getAllOrganizations,
3422
+ getI18nBundles,
3423
+ getLatestStateParam,
3424
+ getMeOrganizations,
3425
+ getOrganization,
3426
+ getSchemas,
3427
+ getScim2Me,
2224
3428
  getUserInfo,
2225
- removeTrailingSlash
3429
+ initializeEmbeddedSignInFlow,
3430
+ isEmpty,
3431
+ processOpenIDScopes,
3432
+ removeTrailingSlash,
3433
+ resolveFieldName,
3434
+ resolveFieldType,
3435
+ set,
3436
+ updateMeProfile,
3437
+ updateOrganization,
3438
+ withVendorCSSClassPrefix
2226
3439
  });
2227
3440
  //# sourceMappingURL=index.js.map