@asgardeo/react 0.5.7 → 0.5.9

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.
@@ -15,7 +15,7 @@
15
15
  * specific language governing permissions and limitations
16
16
  * under the License.
17
17
  */
18
- import { AsgardeoBrowserClient, UserProfile, SignInOptions, SignOutOptions, User, EmbeddedFlowExecuteResponse, SignUpOptions, EmbeddedFlowExecuteRequestPayload, EmbeddedSignInFlowHandleRequestPayload, Organization, IdToken, EmbeddedFlowExecuteRequestConfig, AllOrganizationsApiResponse, TokenResponse } from '@asgardeo/browser';
18
+ import { AsgardeoBrowserClient, UserProfile, SignInOptions, SignOutOptions, User, EmbeddedFlowExecuteResponse, SignUpOptions, EmbeddedFlowExecuteRequestPayload, EmbeddedSignInFlowHandleRequestPayload, Organization, IdToken, EmbeddedFlowExecuteRequestConfig, AllOrganizationsApiResponse, TokenResponse, HttpRequestConfig, HttpResponse } from '@asgardeo/browser';
19
19
  import { AsgardeoReactConfig } from './models/config';
20
20
  /**
21
21
  * Client for mplementing Asgardeo in React applications.
@@ -25,7 +25,19 @@ import { AsgardeoReactConfig } from './models/config';
25
25
  */
26
26
  declare class AsgardeoReactClient<T extends AsgardeoReactConfig = AsgardeoReactConfig> extends AsgardeoBrowserClient<T> {
27
27
  private asgardeo;
28
+ private _isLoading;
28
29
  constructor();
30
+ /**
31
+ * Set the loading state of the client
32
+ * @param loading - Boolean indicating if the client is in a loading state
33
+ */
34
+ private setLoading;
35
+ /**
36
+ * Wrap async operations with loading state management
37
+ * @param operation - The async operation to execute
38
+ * @returns Promise with the result of the operation
39
+ */
40
+ private withLoading;
29
41
  initialize(config: AsgardeoReactConfig): Promise<boolean>;
30
42
  updateUserProfile(payload: any, userId?: string): Promise<User>;
31
43
  getUser(options?: any): Promise<User>;
@@ -41,9 +53,11 @@ declare class AsgardeoReactClient<T extends AsgardeoReactConfig = AsgardeoReactC
41
53
  getConfiguration(): T;
42
54
  signIn(options?: SignInOptions, sessionId?: string, onSignInSuccess?: (afterSignInUrl: string) => void): Promise<User>;
43
55
  signIn(payload: EmbeddedSignInFlowHandleRequestPayload, request: EmbeddedFlowExecuteRequestConfig, sessionId?: string, onSignInSuccess?: (afterSignInUrl: string) => void): Promise<User>;
56
+ signInSilently(options?: SignInOptions): Promise<User | boolean>;
44
57
  signOut(options?: SignOutOptions, afterSignOut?: (afterSignOutUrl: string) => void): Promise<string>;
45
58
  signOut(options?: SignOutOptions, sessionId?: string, afterSignOut?: (afterSignOutUrl: string) => void): Promise<string>;
46
59
  signUp(options?: SignUpOptions): Promise<void>;
47
60
  signUp(payload: EmbeddedFlowExecuteRequestPayload): Promise<EmbeddedFlowExecuteResponse>;
61
+ fetch(url: string, options?: HttpRequestConfig): Promise<HttpResponse<any>>;
48
62
  }
49
63
  export default AsgardeoReactClient;
@@ -224,10 +224,10 @@ declare class AuthAPI {
224
224
  *
225
225
  * @example
226
226
  *```
227
- * client.trySignInSilently()
227
+ * client.signInSilently()
228
228
  *```
229
229
  */
230
- trySignInSilently(state: AuthStateInterface, dispatch: (state: AuthStateInterface) => void, additionalParams?: Record<string, string | boolean>, tokenRequestConfig?: {
230
+ signInSilently(additionalParams?: Record<string, string | boolean>, tokenRequestConfig?: {
231
231
  params: Record<string, unknown>;
232
232
  }): Promise<User | boolean | undefined>;
233
233
  }
@@ -78,7 +78,7 @@ export interface AuthContextInterface {
78
78
  enableHttpHandler(): Promise<boolean>;
79
79
  disableHttpHandler(): Promise<boolean>;
80
80
  reInitialize(config: Partial<AuthClientConfig<Config>>): Promise<void>;
81
- trySignInSilently: (additionalParams?: Record<string, string | boolean>, tokenRequestConfig?: {
81
+ signInSilently: (additionalParams?: Record<string, string | boolean>, tokenRequestConfig?: {
82
82
  params: Record<string, unknown>;
83
83
  }) => Promise<boolean | User>;
84
84
  on(hook: Hooks.CustomGrant, callback: (response?: any) => void, id: string): void;
package/dist/cjs/index.js CHANGED
@@ -37,6 +37,7 @@ __export(index_exports, {
37
37
  AsgardeoContext: () => AsgardeoContext_default,
38
38
  AsgardeoLoading: () => AsgardeoLoading_default,
39
39
  AsgardeoProvider: () => AsgardeoProvider_default,
40
+ AsgardeoRuntimeError: () => import_browser66.AsgardeoRuntimeError,
40
41
  BaseCreateOrganization: () => BaseCreateOrganization,
41
42
  BaseOrganization: () => BaseOrganization_default,
42
43
  BaseOrganizationList: () => BaseOrganizationList_default,
@@ -167,9 +168,11 @@ var AsgardeoContext = (0, import_react.createContext)({
167
168
  isSignedIn: false,
168
169
  organization: null,
169
170
  signIn: null,
171
+ signInSilently: null,
170
172
  signOut: null,
171
173
  signUp: null,
172
- user: null
174
+ user: null,
175
+ fetch: () => null
173
176
  });
174
177
  AsgardeoContext.displayName = "AsgardeoContext";
175
178
  var AsgardeoContext_default = AsgardeoContext;
@@ -486,29 +489,14 @@ var _AuthAPI = class _AuthAPI {
486
489
  *
487
490
  * @example
488
491
  *```
489
- * client.trySignInSilently()
492
+ * client.signInSilently()
490
493
  *```
491
494
  */
492
- async trySignInSilently(state, dispatch, additionalParams, tokenRequestConfig) {
493
- return this._client.trySignInSilently(additionalParams, tokenRequestConfig).then(async (response) => {
495
+ async signInSilently(additionalParams, tokenRequestConfig) {
496
+ return this._client.signInSilently(additionalParams, tokenRequestConfig).then(async (response) => {
494
497
  if (!response) {
495
- this.updateState({ ...this.getState(), isLoading: false });
496
- dispatch({ ...state, isLoading: false });
497
498
  return false;
498
499
  }
499
- if (await this._client.isSignedIn()) {
500
- const basicUserInfo = response;
501
- const stateToUpdate = {
502
- displayName: basicUserInfo.displayName,
503
- email: basicUserInfo.email,
504
- isSignedIn: true,
505
- isLoading: false,
506
- isSigningOut: false,
507
- username: basicUserInfo.username
508
- };
509
- this.updateState(stateToUpdate);
510
- dispatch({ ...state, ...stateToUpdate });
511
- }
512
500
  return response;
513
501
  }).catch((error) => Promise.reject(error));
514
502
  }
@@ -632,14 +620,38 @@ var AsgardeoReactClient = class extends import_browser6.AsgardeoBrowserClient {
632
620
  constructor() {
633
621
  super();
634
622
  __publicField(this, "asgardeo");
623
+ __publicField(this, "_isLoading", false);
635
624
  this.asgardeo = new api_default();
636
625
  }
626
+ /**
627
+ * Set the loading state of the client
628
+ * @param loading - Boolean indicating if the client is in a loading state
629
+ */
630
+ setLoading(loading) {
631
+ this._isLoading = loading;
632
+ }
633
+ /**
634
+ * Wrap async operations with loading state management
635
+ * @param operation - The async operation to execute
636
+ * @returns Promise with the result of the operation
637
+ */
638
+ async withLoading(operation) {
639
+ this.setLoading(true);
640
+ try {
641
+ const result = await operation();
642
+ return result;
643
+ } finally {
644
+ this.setLoading(false);
645
+ }
646
+ }
637
647
  initialize(config) {
638
648
  let resolvedOrganizationHandle = config?.organizationHandle;
639
649
  if (!resolvedOrganizationHandle) {
640
650
  resolvedOrganizationHandle = (0, import_browser6.deriveOrganizationHandleFromBaseUrl)(config?.baseUrl);
641
651
  }
642
- return this.asgardeo.init({ ...config, organizationHandle: resolvedOrganizationHandle });
652
+ return this.withLoading(async () => {
653
+ return this.asgardeo.init({ ...config, organizationHandle: resolvedOrganizationHandle });
654
+ });
643
655
  }
644
656
  async updateUserProfile(payload, userId) {
645
657
  throw new Error("Not implemented");
@@ -728,47 +740,49 @@ var AsgardeoReactClient = class extends import_browser6.AsgardeoBrowserClient {
728
740
  };
729
741
  }
730
742
  async switchOrganization(organization, sessionId) {
731
- try {
732
- const configData = await this.asgardeo.getConfigData();
733
- const scopes = configData?.scopes;
734
- if (!organization.id) {
743
+ return this.withLoading(async () => {
744
+ try {
745
+ const configData = await this.asgardeo.getConfigData();
746
+ const scopes = configData?.scopes;
747
+ if (!organization.id) {
748
+ throw new import_browser6.AsgardeoRuntimeError(
749
+ "Organization ID is required for switching organizations",
750
+ "react-AsgardeoReactClient-SwitchOrganizationError-001",
751
+ "react",
752
+ "The organization object must contain a valid ID to perform the organization switch."
753
+ );
754
+ }
755
+ const exchangeConfig = {
756
+ attachToken: false,
757
+ data: {
758
+ client_id: "{{clientId}}",
759
+ grant_type: "organization_switch",
760
+ scope: "{{scopes}}",
761
+ switching_organization: organization.id,
762
+ token: "{{accessToken}}"
763
+ },
764
+ id: "organization-switch",
765
+ returnsSession: true,
766
+ signInRequired: true
767
+ };
768
+ return await this.asgardeo.exchangeToken(
769
+ exchangeConfig,
770
+ (user) => {
771
+ },
772
+ () => null
773
+ );
774
+ } catch (error) {
735
775
  throw new import_browser6.AsgardeoRuntimeError(
736
- "Organization ID is required for switching organizations",
737
- "react-AsgardeoReactClient-SwitchOrganizationError-001",
776
+ `Failed to switch organization: ${error.message || error}`,
777
+ "react-AsgardeoReactClient-SwitchOrganizationError-003",
738
778
  "react",
739
- "The organization object must contain a valid ID to perform the organization switch."
779
+ "An error occurred while switching to the specified organization. Please try again."
740
780
  );
741
781
  }
742
- const exchangeConfig = {
743
- attachToken: false,
744
- data: {
745
- client_id: "{{clientId}}",
746
- grant_type: "organization_switch",
747
- scope: "{{scopes}}",
748
- switching_organization: organization.id,
749
- token: "{{accessToken}}"
750
- },
751
- id: "organization-switch",
752
- returnsSession: true,
753
- signInRequired: true
754
- };
755
- return await this.asgardeo.exchangeToken(
756
- exchangeConfig,
757
- (user) => {
758
- },
759
- () => null
760
- );
761
- } catch (error) {
762
- throw new import_browser6.AsgardeoRuntimeError(
763
- `Failed to switch organization: ${error.message || error}`,
764
- "react-AsgardeoReactClient-SwitchOrganizationError-003",
765
- "react",
766
- "An error occurred while switching to the specified organization. Please try again."
767
- );
768
- }
782
+ });
769
783
  }
770
784
  isLoading() {
771
- return this.asgardeo.isLoading();
785
+ return this._isLoading || this.asgardeo.isLoading();
772
786
  }
773
787
  async isInitialized() {
774
788
  return this.asgardeo.isInitialized();
@@ -780,15 +794,22 @@ var AsgardeoReactClient = class extends import_browser6.AsgardeoBrowserClient {
780
794
  return this.asgardeo.getConfigData();
781
795
  }
782
796
  async signIn(...args) {
783
- const arg1 = args[0];
784
- const arg2 = args[1];
785
- if (typeof arg1 === "object" && "flowId" in arg1 && typeof arg2 === "object" && "url" in arg2) {
786
- return (0, import_browser6.executeEmbeddedSignInFlow)({
787
- payload: arg1,
788
- url: arg2.url
789
- });
790
- }
791
- return await this.asgardeo.signIn(arg1);
797
+ return this.withLoading(async () => {
798
+ const arg1 = args[0];
799
+ const arg2 = args[1];
800
+ if (typeof arg1 === "object" && "flowId" in arg1 && typeof arg2 === "object" && "url" in arg2) {
801
+ return (0, import_browser6.executeEmbeddedSignInFlow)({
802
+ payload: arg1,
803
+ url: arg2.url
804
+ });
805
+ }
806
+ return await this.asgardeo.signIn(arg1);
807
+ });
808
+ }
809
+ async signInSilently(options) {
810
+ return this.withLoading(async () => {
811
+ return this.asgardeo.signInSilently(options);
812
+ });
792
813
  }
793
814
  async signOut(...args) {
794
815
  if (args[1] && typeof args[1] !== "function") {
@@ -822,6 +843,12 @@ var AsgardeoReactClient = class extends import_browser6.AsgardeoBrowserClient {
822
843
  "The signUp method with SignUpOptions is not implemented in the React client."
823
844
  );
824
845
  }
846
+ async fetch(url, options) {
847
+ return this.asgardeo.httpRequest({
848
+ url,
849
+ ...options
850
+ });
851
+ }
825
852
  };
826
853
  var AsgardeoReactClient_default = AsgardeoReactClient;
827
854
 
@@ -1459,6 +1486,7 @@ var AsgardeoProvider = ({
1459
1486
  const [currentOrganization, setCurrentOrganization] = (0, import_react15.useState)(null);
1460
1487
  const [isSignedInSync, setIsSignedInSync] = (0, import_react15.useState)(false);
1461
1488
  const [isInitializedSync, setIsInitializedSync] = (0, import_react15.useState)(false);
1489
+ const [isLoadingSync, setIsLoadingSync] = (0, import_react15.useState)(true);
1462
1490
  const [myOrganizations, setMyOrganizations] = (0, import_react15.useState)([]);
1463
1491
  const [userProfile, setUserProfile] = (0, import_react15.useState)(null);
1464
1492
  const [baseUrl, setBaseUrl] = (0, import_react15.useState)(_baseUrl);
@@ -1552,16 +1580,32 @@ var AsgardeoProvider = ({
1552
1580
  }
1553
1581
  })();
1554
1582
  }, [asgardeo]);
1583
+ (0, import_react15.useEffect)(() => {
1584
+ const checkLoadingState = () => {
1585
+ const loadingState = asgardeo.isLoading();
1586
+ setIsLoadingSync(loadingState);
1587
+ };
1588
+ checkLoadingState();
1589
+ const interval = setInterval(checkLoadingState, 100);
1590
+ return () => {
1591
+ clearInterval(interval);
1592
+ };
1593
+ }, [asgardeo]);
1555
1594
  const updateSession = async () => {
1556
- let _baseUrl2 = baseUrl;
1557
- if ((await asgardeo.getDecodedIdToken())?.["user_org"]) {
1558
- _baseUrl2 = `${(await asgardeo.getConfiguration()).baseUrl}/o`;
1559
- setBaseUrl(_baseUrl2);
1560
- }
1561
- setUser(await asgardeo.getUser({ baseUrl: _baseUrl2 }));
1562
- setUserProfile(await asgardeo.getUserProfile({ baseUrl: _baseUrl2 }));
1563
- setCurrentOrganization(await asgardeo.getCurrentOrganization());
1564
- setMyOrganizations(await asgardeo.getMyOrganizations());
1595
+ try {
1596
+ setIsLoadingSync(true);
1597
+ let _baseUrl2 = baseUrl;
1598
+ if ((await asgardeo.getDecodedIdToken())?.["user_org"]) {
1599
+ _baseUrl2 = `${(await asgardeo.getConfiguration()).baseUrl}/o`;
1600
+ setBaseUrl(_baseUrl2);
1601
+ }
1602
+ setUser(await asgardeo.getUser({ baseUrl: _baseUrl2 }));
1603
+ setUserProfile(await asgardeo.getUserProfile({ baseUrl: _baseUrl2 }));
1604
+ setCurrentOrganization(await asgardeo.getCurrentOrganization());
1605
+ setMyOrganizations(await asgardeo.getMyOrganizations());
1606
+ } finally {
1607
+ setIsLoadingSync(asgardeo.isLoading());
1608
+ }
1565
1609
  };
1566
1610
  const fetchBranding = (0, import_react15.useCallback)(async () => {
1567
1611
  if (!baseUrl) {
@@ -1609,6 +1653,7 @@ var AsgardeoProvider = ({
1609
1653
  ]);
1610
1654
  const signIn = async (...args) => {
1611
1655
  try {
1656
+ setIsLoadingSync(true);
1612
1657
  const response = await asgardeo.signIn(...args);
1613
1658
  if (await asgardeo.isSignedIn()) {
1614
1659
  await updateSession();
@@ -1616,6 +1661,27 @@ var AsgardeoProvider = ({
1616
1661
  return response;
1617
1662
  } catch (error) {
1618
1663
  throw new Error(`Error while signing in: ${error}`);
1664
+ } finally {
1665
+ setIsLoadingSync(asgardeo.isLoading());
1666
+ }
1667
+ };
1668
+ const signInSilently = async (options) => {
1669
+ try {
1670
+ setIsLoadingSync(true);
1671
+ const response = await asgardeo.signInSilently(options);
1672
+ if (await asgardeo.isSignedIn()) {
1673
+ await updateSession();
1674
+ }
1675
+ return response;
1676
+ } catch (error) {
1677
+ throw new import_browser13.AsgardeoRuntimeError(
1678
+ `Error while signing in silently: ${error.message || error}`,
1679
+ "asgardeo-signInSilently-Error",
1680
+ "react",
1681
+ "An error occurred while trying to sign in silently."
1682
+ );
1683
+ } finally {
1684
+ setIsLoadingSync(asgardeo.isLoading());
1619
1685
  }
1620
1686
  };
1621
1687
  const signUp = async (payload) => {
@@ -1633,6 +1699,7 @@ var AsgardeoProvider = ({
1633
1699
  const signOut = async (options, afterSignOut) => asgardeo.signOut(options, afterSignOut);
1634
1700
  const switchOrganization = async (organization) => {
1635
1701
  try {
1702
+ setIsLoadingSync(true);
1636
1703
  await asgardeo.switchOrganization(organization);
1637
1704
  if (await asgardeo.isSignedIn()) {
1638
1705
  await updateSession();
@@ -1644,6 +1711,8 @@ var AsgardeoProvider = ({
1644
1711
  "react",
1645
1712
  "An error occurred while switching to the specified organization."
1646
1713
  );
1714
+ } finally {
1715
+ setIsLoadingSync(asgardeo.isLoading());
1647
1716
  }
1648
1717
  };
1649
1718
  const isDarkMode = (0, import_react15.useMemo)(() => {
@@ -1660,6 +1729,9 @@ var AsgardeoProvider = ({
1660
1729
  flattenedProfile: (0, import_browser13.generateFlattenedUserProfile)(payload, prev?.schemas)
1661
1730
  }));
1662
1731
  };
1732
+ const fetch = async (url, options) => {
1733
+ return asgardeo.fetch(url, options);
1734
+ };
1663
1735
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
1664
1736
  AsgardeoContext_default.Provider,
1665
1737
  {
@@ -1671,13 +1743,15 @@ var AsgardeoProvider = ({
1671
1743
  afterSignInUrl,
1672
1744
  baseUrl,
1673
1745
  isInitialized: isInitializedSync,
1674
- isLoading: asgardeo.isLoading(),
1746
+ isLoading: isLoadingSync,
1675
1747
  isSignedIn: isSignedInSync,
1676
1748
  organization: currentOrganization,
1677
1749
  signIn,
1750
+ signInSilently,
1678
1751
  signOut,
1679
1752
  signUp,
1680
- user
1753
+ user,
1754
+ fetch
1681
1755
  },
1682
1756
  children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(I18nProvider_default, { preferences: preferences?.i18n, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
1683
1757
  BrandingProvider_default,
@@ -11043,4 +11117,7 @@ var OrganizationSwitcher = ({
11043
11117
  ] });
11044
11118
  };
11045
11119
  var OrganizationSwitcher_default = OrganizationSwitcher;
11120
+
11121
+ // src/index.ts
11122
+ var import_browser66 = require("@asgardeo/browser");
11046
11123
  //# sourceMappingURL=index.js.map