@asgardeo/react 0.5.6 → 0.5.8

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.
@@ -17,6 +17,7 @@
17
17
  */
18
18
  import { Context } from 'react';
19
19
  import { Organization } from '@asgardeo/browser';
20
+ import AsgardeoReactClient from '../../AsgardeoReactClient';
20
21
  /**
21
22
  * Props interface of {@link AsgardeoContext}
22
23
  */
@@ -42,6 +43,7 @@ export type AsgardeoContextProps = {
42
43
  * TODO: Fix the types.
43
44
  */
44
45
  signIn: any;
46
+ signInSilently: AsgardeoReactClient['signInSilently'];
45
47
  /**
46
48
  * Sign-out function to terminate the authentication session.
47
49
  * @remark This is the programmatic version of the `SignOutButton` component.
@@ -15,19 +15,23 @@
15
15
  * specific language governing permissions and limitations
16
16
  * under the License.
17
17
  */
18
- import { AllOrganizationsApiResponse, Organization } from '@asgardeo/browser';
18
+ import { AllOrganizationsApiResponse, Organization, CreateOrganizationPayload } from '@asgardeo/browser';
19
19
  import { Context } from 'react';
20
20
  /**
21
21
  * Props interface of {@link OrganizationContext}
22
22
  */
23
23
  export type OrganizationContextProps = {
24
+ /**
25
+ * Function to create a new organization.
26
+ */
27
+ createOrganization?: (payload: CreateOrganizationPayload, sessionId: string) => Promise<Organization>;
24
28
  currentOrganization: Organization | null;
25
29
  error: string | null;
30
+ getAllOrganizations: () => Promise<AllOrganizationsApiResponse>;
26
31
  isLoading: boolean;
27
32
  myOrganizations: Organization[];
28
- switchOrganization: (organization: Organization) => Promise<void>;
29
33
  revalidateMyOrganizations: () => Promise<Organization[]>;
30
- getAllOrganizations: () => Promise<AllOrganizationsApiResponse>;
34
+ switchOrganization: (organization: Organization) => Promise<void>;
31
35
  };
32
36
  /**
33
37
  * Context object for managing organization data and related operations.
@@ -15,7 +15,7 @@
15
15
  * specific language governing permissions and limitations
16
16
  * under the License.
17
17
  */
18
- import { Organization, AllOrganizationsApiResponse } from '@asgardeo/browser';
18
+ import { Organization, AllOrganizationsApiResponse, CreateOrganizationPayload } from '@asgardeo/browser';
19
19
  import { FC, PropsWithChildren } from 'react';
20
20
  /**
21
21
  * Props interface of {@link OrganizationProvider}
@@ -25,10 +25,18 @@ export interface OrganizationProviderProps {
25
25
  * Whether to automatically fetch organizations on mount
26
26
  */
27
27
  autoFetch?: boolean;
28
+ /**
29
+ * Function to create a new organization.
30
+ */
31
+ createOrganization?: (payload: CreateOrganizationPayload, sessionId: string) => Promise<Organization>;
28
32
  /**
29
33
  * Initial current organization
30
34
  */
31
35
  currentOrganization?: Organization | null;
36
+ /**
37
+ * Initial list of organizations
38
+ */
39
+ getAllOrganizations?: () => Promise<AllOrganizationsApiResponse>;
32
40
  /**
33
41
  * List of organizations the signed-in user belongs to.
34
42
  */
@@ -41,10 +49,6 @@ export interface OrganizationProviderProps {
41
49
  * Callback function called when switching organizations
42
50
  */
43
51
  onOrganizationSwitch?: (organization: Organization) => Promise<void>;
44
- /**
45
- * Initial list of organizations
46
- */
47
- getAllOrganizations?: () => Promise<AllOrganizationsApiResponse>;
48
52
  /**
49
53
  * Refetch the my organizations list.
50
54
  * @returns
package/dist/index.d.ts CHANGED
@@ -193,3 +193,4 @@ export { default as getSchemas, GetSchemasConfig } from './api/getSchemas';
193
193
  export { default as updateMeProfile, UpdateMeProfileConfig } from './api/updateMeProfile';
194
194
  export { default as getMeProfile } from './api/getScim2Me';
195
195
  export * from './api/getScim2Me';
196
+ export { AsgardeoRuntimeError } from '@asgardeo/browser';
package/dist/index.js CHANGED
@@ -24,6 +24,7 @@ var AsgardeoContext = createContext({
24
24
  isSignedIn: false,
25
25
  organization: null,
26
26
  signIn: null,
27
+ signInSilently: null,
27
28
  signOut: null,
28
29
  signUp: null,
29
30
  user: null
@@ -356,29 +357,14 @@ var _AuthAPI = class _AuthAPI {
356
357
  *
357
358
  * @example
358
359
  *```
359
- * client.trySignInSilently()
360
+ * client.signInSilently()
360
361
  *```
361
362
  */
362
- async trySignInSilently(state, dispatch, additionalParams, tokenRequestConfig) {
363
- return this._client.trySignInSilently(additionalParams, tokenRequestConfig).then(async (response) => {
363
+ async signInSilently(additionalParams, tokenRequestConfig) {
364
+ return this._client.signInSilently(additionalParams, tokenRequestConfig).then(async (response) => {
364
365
  if (!response) {
365
- this.updateState({ ...this.getState(), isLoading: false });
366
- dispatch({ ...state, isLoading: false });
367
366
  return false;
368
367
  }
369
- if (await this._client.isSignedIn()) {
370
- const basicUserInfo = response;
371
- const stateToUpdate = {
372
- displayName: basicUserInfo.displayName,
373
- email: basicUserInfo.email,
374
- isSignedIn: true,
375
- isLoading: false,
376
- isSigningOut: false,
377
- username: basicUserInfo.username
378
- };
379
- this.updateState(stateToUpdate);
380
- dispatch({ ...state, ...stateToUpdate });
381
- }
382
368
  return response;
383
369
  }).catch((error) => Promise.reject(error));
384
370
  }
@@ -514,14 +500,38 @@ var AsgardeoReactClient = class extends AsgardeoBrowserClient {
514
500
  constructor() {
515
501
  super();
516
502
  __publicField(this, "asgardeo");
503
+ __publicField(this, "_isLoading", false);
517
504
  this.asgardeo = new api_default();
518
505
  }
506
+ /**
507
+ * Set the loading state of the client
508
+ * @param loading - Boolean indicating if the client is in a loading state
509
+ */
510
+ setLoading(loading) {
511
+ this._isLoading = loading;
512
+ }
513
+ /**
514
+ * Wrap async operations with loading state management
515
+ * @param operation - The async operation to execute
516
+ * @returns Promise with the result of the operation
517
+ */
518
+ async withLoading(operation) {
519
+ this.setLoading(true);
520
+ try {
521
+ const result = await operation();
522
+ return result;
523
+ } finally {
524
+ this.setLoading(false);
525
+ }
526
+ }
519
527
  initialize(config) {
520
528
  let resolvedOrganizationHandle = config?.organizationHandle;
521
529
  if (!resolvedOrganizationHandle) {
522
530
  resolvedOrganizationHandle = deriveOrganizationHandleFromBaseUrl(config?.baseUrl);
523
531
  }
524
- return this.asgardeo.init({ ...config, organizationHandle: resolvedOrganizationHandle });
532
+ return this.withLoading(async () => {
533
+ return this.asgardeo.init({ ...config, organizationHandle: resolvedOrganizationHandle });
534
+ });
525
535
  }
526
536
  async updateUserProfile(payload, userId) {
527
537
  throw new Error("Not implemented");
@@ -610,47 +620,49 @@ var AsgardeoReactClient = class extends AsgardeoBrowserClient {
610
620
  };
611
621
  }
612
622
  async switchOrganization(organization, sessionId) {
613
- try {
614
- const configData = await this.asgardeo.getConfigData();
615
- const scopes = configData?.scopes;
616
- if (!organization.id) {
623
+ return this.withLoading(async () => {
624
+ try {
625
+ const configData = await this.asgardeo.getConfigData();
626
+ const scopes = configData?.scopes;
627
+ if (!organization.id) {
628
+ throw new AsgardeoRuntimeError(
629
+ "Organization ID is required for switching organizations",
630
+ "react-AsgardeoReactClient-SwitchOrganizationError-001",
631
+ "react",
632
+ "The organization object must contain a valid ID to perform the organization switch."
633
+ );
634
+ }
635
+ const exchangeConfig = {
636
+ attachToken: false,
637
+ data: {
638
+ client_id: "{{clientId}}",
639
+ grant_type: "organization_switch",
640
+ scope: "{{scopes}}",
641
+ switching_organization: organization.id,
642
+ token: "{{accessToken}}"
643
+ },
644
+ id: "organization-switch",
645
+ returnsSession: true,
646
+ signInRequired: true
647
+ };
648
+ return await this.asgardeo.exchangeToken(
649
+ exchangeConfig,
650
+ (user) => {
651
+ },
652
+ () => null
653
+ );
654
+ } catch (error) {
617
655
  throw new AsgardeoRuntimeError(
618
- "Organization ID is required for switching organizations",
619
- "react-AsgardeoReactClient-SwitchOrganizationError-001",
656
+ `Failed to switch organization: ${error.message || error}`,
657
+ "react-AsgardeoReactClient-SwitchOrganizationError-003",
620
658
  "react",
621
- "The organization object must contain a valid ID to perform the organization switch."
659
+ "An error occurred while switching to the specified organization. Please try again."
622
660
  );
623
661
  }
624
- const exchangeConfig = {
625
- attachToken: false,
626
- data: {
627
- client_id: "{{clientId}}",
628
- grant_type: "organization_switch",
629
- scope: "{{scopes}}",
630
- switching_organization: organization.id,
631
- token: "{{accessToken}}"
632
- },
633
- id: "organization-switch",
634
- returnsSession: true,
635
- signInRequired: true
636
- };
637
- return await this.asgardeo.exchangeToken(
638
- exchangeConfig,
639
- (user) => {
640
- },
641
- () => null
642
- );
643
- } catch (error) {
644
- throw new AsgardeoRuntimeError(
645
- `Failed to switch organization: ${error.message || error}`,
646
- "react-AsgardeoReactClient-SwitchOrganizationError-003",
647
- "react",
648
- "An error occurred while switching to the specified organization. Please try again."
649
- );
650
- }
662
+ });
651
663
  }
652
664
  isLoading() {
653
- return this.asgardeo.isLoading();
665
+ return this._isLoading || this.asgardeo.isLoading();
654
666
  }
655
667
  async isInitialized() {
656
668
  return this.asgardeo.isInitialized();
@@ -662,15 +674,22 @@ var AsgardeoReactClient = class extends AsgardeoBrowserClient {
662
674
  return this.asgardeo.getConfigData();
663
675
  }
664
676
  async signIn(...args) {
665
- const arg1 = args[0];
666
- const arg2 = args[1];
667
- if (typeof arg1 === "object" && "flowId" in arg1 && typeof arg2 === "object" && "url" in arg2) {
668
- return executeEmbeddedSignInFlow({
669
- payload: arg1,
670
- url: arg2.url
671
- });
672
- }
673
- return await this.asgardeo.signIn(arg1);
677
+ return this.withLoading(async () => {
678
+ const arg1 = args[0];
679
+ const arg2 = args[1];
680
+ if (typeof arg1 === "object" && "flowId" in arg1 && typeof arg2 === "object" && "url" in arg2) {
681
+ return executeEmbeddedSignInFlow({
682
+ payload: arg1,
683
+ url: arg2.url
684
+ });
685
+ }
686
+ return await this.asgardeo.signIn(arg1);
687
+ });
688
+ }
689
+ async signInSilently(options) {
690
+ return this.withLoading(async () => {
691
+ return this.asgardeo.signInSilently(options);
692
+ });
674
693
  }
675
694
  async signOut(...args) {
676
695
  if (args[1] && typeof args[1] !== "function") {
@@ -968,22 +987,25 @@ var I18nProvider = ({
968
987
  var I18nProvider_default = I18nProvider;
969
988
 
970
989
  // src/contexts/Organization/OrganizationProvider.tsx
971
- import { AsgardeoRuntimeError as AsgardeoRuntimeError2 } from "@asgardeo/browser";
990
+ import {
991
+ AsgardeoRuntimeError as AsgardeoRuntimeError2
992
+ } from "@asgardeo/browser";
972
993
  import { useCallback as useCallback3, useMemo as useMemo3, useState as useState3 } from "react";
973
994
 
974
995
  // src/contexts/Organization/OrganizationContext.ts
975
996
  import { createContext as createContext4 } from "react";
976
997
  var OrganizationContext = createContext4({
998
+ createOrganization: () => null,
977
999
  currentOrganization: null,
978
1000
  error: null,
979
- isLoading: false,
980
- myOrganizations: null,
981
- switchOrganization: () => Promise.resolve(),
982
- revalidateMyOrganizations: () => Promise.resolve([]),
983
1001
  getAllOrganizations: () => Promise.resolve({
984
1002
  count: 0,
985
1003
  organizations: []
986
- })
1004
+ }),
1005
+ isLoading: false,
1006
+ myOrganizations: null,
1007
+ revalidateMyOrganizations: () => Promise.resolve([]),
1008
+ switchOrganization: () => Promise.resolve()
987
1009
  });
988
1010
  OrganizationContext.displayName = "OrganizationContext";
989
1011
  var OrganizationContext_default = OrganizationContext;
@@ -997,7 +1019,8 @@ var OrganizationProvider = ({
997
1019
  myOrganizations,
998
1020
  onOrganizationSwitch,
999
1021
  revalidateMyOrganizations,
1000
- getAllOrganizations: getAllOrganizations2
1022
+ getAllOrganizations: getAllOrganizations2,
1023
+ createOrganization: createOrganization2
1001
1024
  }) => {
1002
1025
  const [isLoading, setIsLoading] = useState3(false);
1003
1026
  const [error, setError] = useState3(null);
@@ -1030,13 +1053,14 @@ var OrganizationProvider = ({
1030
1053
  );
1031
1054
  const contextValue = useMemo3(
1032
1055
  () => ({
1056
+ createOrganization: createOrganization2,
1033
1057
  currentOrganization,
1034
1058
  error,
1059
+ getAllOrganizations: getAllOrganizations2,
1035
1060
  isLoading,
1036
1061
  myOrganizations,
1037
- switchOrganization,
1038
1062
  revalidateMyOrganizations,
1039
- getAllOrganizations: getAllOrganizations2
1063
+ switchOrganization
1040
1064
  }),
1041
1065
  [
1042
1066
  currentOrganization,
@@ -1045,7 +1069,8 @@ var OrganizationProvider = ({
1045
1069
  myOrganizations,
1046
1070
  switchOrganization,
1047
1071
  revalidateMyOrganizations,
1048
- getAllOrganizations2
1072
+ getAllOrganizations2,
1073
+ createOrganization2
1049
1074
  ]
1050
1075
  );
1051
1076
  return /* @__PURE__ */ jsx3(OrganizationContext_default.Provider, { value: contextValue, children });
@@ -1342,6 +1367,7 @@ var AsgardeoProvider = ({
1342
1367
  const [currentOrganization, setCurrentOrganization] = useState7(null);
1343
1368
  const [isSignedInSync, setIsSignedInSync] = useState7(false);
1344
1369
  const [isInitializedSync, setIsInitializedSync] = useState7(false);
1370
+ const [isLoadingSync, setIsLoadingSync] = useState7(true);
1345
1371
  const [myOrganizations, setMyOrganizations] = useState7([]);
1346
1372
  const [userProfile, setUserProfile] = useState7(null);
1347
1373
  const [baseUrl, setBaseUrl] = useState7(_baseUrl);
@@ -1435,16 +1461,32 @@ var AsgardeoProvider = ({
1435
1461
  }
1436
1462
  })();
1437
1463
  }, [asgardeo]);
1464
+ useEffect5(() => {
1465
+ const checkLoadingState = () => {
1466
+ const loadingState = asgardeo.isLoading();
1467
+ setIsLoadingSync(loadingState);
1468
+ };
1469
+ checkLoadingState();
1470
+ const interval = setInterval(checkLoadingState, 100);
1471
+ return () => {
1472
+ clearInterval(interval);
1473
+ };
1474
+ }, [asgardeo]);
1438
1475
  const updateSession = async () => {
1439
- let _baseUrl2 = baseUrl;
1440
- if ((await asgardeo.getDecodedIdToken())?.["user_org"]) {
1441
- _baseUrl2 = `${(await asgardeo.getConfiguration()).baseUrl}/o`;
1442
- setBaseUrl(_baseUrl2);
1443
- }
1444
- setUser(await asgardeo.getUser({ baseUrl: _baseUrl2 }));
1445
- setUserProfile(await asgardeo.getUserProfile({ baseUrl: _baseUrl2 }));
1446
- setCurrentOrganization(await asgardeo.getCurrentOrganization());
1447
- setMyOrganizations(await asgardeo.getMyOrganizations());
1476
+ try {
1477
+ setIsLoadingSync(true);
1478
+ let _baseUrl2 = baseUrl;
1479
+ if ((await asgardeo.getDecodedIdToken())?.["user_org"]) {
1480
+ _baseUrl2 = `${(await asgardeo.getConfiguration()).baseUrl}/o`;
1481
+ setBaseUrl(_baseUrl2);
1482
+ }
1483
+ setUser(await asgardeo.getUser({ baseUrl: _baseUrl2 }));
1484
+ setUserProfile(await asgardeo.getUserProfile({ baseUrl: _baseUrl2 }));
1485
+ setCurrentOrganization(await asgardeo.getCurrentOrganization());
1486
+ setMyOrganizations(await asgardeo.getMyOrganizations());
1487
+ } finally {
1488
+ setIsLoadingSync(asgardeo.isLoading());
1489
+ }
1448
1490
  };
1449
1491
  const fetchBranding = useCallback7(async () => {
1450
1492
  if (!baseUrl) {
@@ -1492,6 +1534,7 @@ var AsgardeoProvider = ({
1492
1534
  ]);
1493
1535
  const signIn = async (...args) => {
1494
1536
  try {
1537
+ setIsLoadingSync(true);
1495
1538
  const response = await asgardeo.signIn(...args);
1496
1539
  if (await asgardeo.isSignedIn()) {
1497
1540
  await updateSession();
@@ -1499,6 +1542,27 @@ var AsgardeoProvider = ({
1499
1542
  return response;
1500
1543
  } catch (error) {
1501
1544
  throw new Error(`Error while signing in: ${error}`);
1545
+ } finally {
1546
+ setIsLoadingSync(asgardeo.isLoading());
1547
+ }
1548
+ };
1549
+ const signInSilently = async (options) => {
1550
+ try {
1551
+ setIsLoadingSync(true);
1552
+ const response = await asgardeo.signInSilently(options);
1553
+ if (await asgardeo.isSignedIn()) {
1554
+ await updateSession();
1555
+ }
1556
+ return response;
1557
+ } catch (error) {
1558
+ throw new AsgardeoRuntimeError3(
1559
+ `Error while signing in silently: ${error.message || error}`,
1560
+ "asgardeo-signInSilently-Error",
1561
+ "react",
1562
+ "An error occurred while trying to sign in silently."
1563
+ );
1564
+ } finally {
1565
+ setIsLoadingSync(asgardeo.isLoading());
1502
1566
  }
1503
1567
  };
1504
1568
  const signUp = async (payload) => {
@@ -1516,6 +1580,7 @@ var AsgardeoProvider = ({
1516
1580
  const signOut = async (options, afterSignOut) => asgardeo.signOut(options, afterSignOut);
1517
1581
  const switchOrganization = async (organization) => {
1518
1582
  try {
1583
+ setIsLoadingSync(true);
1519
1584
  await asgardeo.switchOrganization(organization);
1520
1585
  if (await asgardeo.isSignedIn()) {
1521
1586
  await updateSession();
@@ -1527,6 +1592,8 @@ var AsgardeoProvider = ({
1527
1592
  "react",
1528
1593
  "An error occurred while switching to the specified organization."
1529
1594
  );
1595
+ } finally {
1596
+ setIsLoadingSync(asgardeo.isLoading());
1530
1597
  }
1531
1598
  };
1532
1599
  const isDarkMode = useMemo6(() => {
@@ -1554,10 +1621,11 @@ var AsgardeoProvider = ({
1554
1621
  afterSignInUrl,
1555
1622
  baseUrl,
1556
1623
  isInitialized: isInitializedSync,
1557
- isLoading: asgardeo.isLoading(),
1624
+ isLoading: isLoadingSync,
1558
1625
  isSignedIn: isSignedInSync,
1559
1626
  organization: currentOrganization,
1560
1627
  signIn,
1628
+ signInSilently,
1561
1629
  signOut,
1562
1630
  signUp,
1563
1631
  user
@@ -11009,6 +11077,9 @@ var OrganizationSwitcher = ({
11009
11077
  ] });
11010
11078
  };
11011
11079
  var OrganizationSwitcher_default = OrganizationSwitcher;
11080
+
11081
+ // src/index.ts
11082
+ import { AsgardeoRuntimeError as AsgardeoRuntimeError7 } from "@asgardeo/browser";
11012
11083
  export {
11013
11084
  Alert_default as Alert,
11014
11085
  AlertDescription,
@@ -11016,6 +11087,7 @@ export {
11016
11087
  AsgardeoContext_default as AsgardeoContext,
11017
11088
  AsgardeoLoading_default as AsgardeoLoading,
11018
11089
  AsgardeoProvider_default as AsgardeoProvider,
11090
+ AsgardeoRuntimeError7 as AsgardeoRuntimeError,
11019
11091
  BaseCreateOrganization,
11020
11092
  BaseOrganization_default as BaseOrganization,
11021
11093
  BaseOrganizationList_default as BaseOrganizationList,