UNPKG

@asgardeo/react

Version:
1,427 lines (1,400 loc) 471 kB
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); // src/index.ts var index_exports = {}; __export(index_exports, { Alert: () => Alert_default, AlertDescription: () => AlertDescription, AlertTitle: () => AlertTitle, AsgardeoContext: () => AsgardeoContext_default, AsgardeoProvider: () => AsgardeoProvider_default, AsgardeoRuntimeError: () => import_browser68.AsgardeoRuntimeError, BaseCreateOrganization: () => BaseCreateOrganization, BaseOrganization: () => BaseOrganization_default, BaseOrganizationList: () => BaseOrganizationList_default, BaseOrganizationProfile: () => BaseOrganizationProfile_default, BaseOrganizationSwitcher: () => BaseOrganizationSwitcher_default, BaseSignIn: () => BaseSignIn_default, BaseSignInButton: () => BaseSignInButton_default, BaseSignOutButton: () => BaseSignOutButton_default, BaseSignUp: () => BaseSignUp_default, BaseSignUpButton: () => BaseSignUpButton_default, BaseUser: () => BaseUser_default, BaseUserDropdown: () => BaseUserDropdown_default, BaseUserProfile: () => BaseUserProfile_default, BrandingContext: () => BrandingContext_default, BrandingProvider: () => BrandingProvider_default, BuildingAlt: () => BuildingAlt_default, Button: () => Button_default, Card: () => Card_default, CardAction: () => CardAction, CardContent: () => CardContent, CardDescription: () => CardDescription, CardFooter: () => CardFooter, CardHeader: () => CardHeader, CardTitle: () => CardTitle, Checkbox: () => Checkbox_default, CircleAlert: () => CircleAlert_default, CircleCheck: () => CircleCheck_default, CreateOrganization: () => CreateOrganization, DatePicker: () => DatePicker_default, Divider: () => Divider_default, EmailOtp: () => EmailOtp_default, Eye: () => Eye_default, EyeOff: () => EyeOff_default, FacebookButton: () => FacebookButton_default, FieldFactory: () => FieldFactory, FlowContext: () => FlowContext_default, FlowProvider: () => FlowProvider_default, FormControl: () => FormControl_default, GitHubButton: () => GitHubButton_default, GoogleButton: () => GoogleButton_default, I18nContext: () => I18nContext_default, I18nProvider: () => I18nProvider_default, IdentifierFirst: () => IdentifierFirst_default, Info: () => Info_default, InputLabel: () => InputLabel_default, KeyValueInput: () => KeyValueInput_default, LinkedInButton: () => LinkedInButton_default, Loading: () => Loading_default, LogOut: () => LogOut_default, Logo: () => Logo_default, MicrosoftButton: () => MicrosoftButton_default, MultiInput: () => MultiInput_default, MultiOptionButton: () => MultiOptionButton_default, Organization: () => Organization_default, OrganizationContext: () => OrganizationContext_default, OrganizationList: () => OrganizationList_default, OrganizationProfile: () => OrganizationProfile_default, OrganizationProvider: () => OrganizationProvider_default, OrganizationSwitcher: () => OrganizationSwitcher_default, OtpField: () => OtpField_default, PasswordField: () => PasswordField_default, Select: () => Select_default, SignIn: () => SignIn_default, SignInButton: () => SignInButton_default, SignInWithEthereumButton: () => SignInWithEthereumButton_default, SignOutButton: () => SignOutButton_default, SignUp: () => SignUp_default, SignUpButton: () => SignUpButton_default, SignedIn: () => SignedIn_default, SignedOut: () => SignedOut_default, SmsOtp: () => SmsOtp_default, SocialButton: () => SocialButton_default, Spinner: () => Spinner_default, TextField: () => TextField_default, ThemeContext: () => ThemeContext_default, ThemeProvider: () => ThemeProvider_default, Totp: () => Totp_default, TriangleAlert: () => TriangleAlert_default, Typography: () => Typography_default, User: () => User_default, UserContext: () => UserContext_default, UserDropdown: () => UserDropdown_default, UserIcon: () => User_default2, UserProfile: () => UserProfile_default, UserProvider: () => UserProvider_default, UsernamePassword: () => UsernamePassword_default, createField: () => createField, createOrganization: () => createOrganization_default, createPatchOperations: () => import_browser67.createPatchOperations, createSignInOption: () => createSignInOption, createSignInOptionFromAuthenticator: () => createSignInOptionFromAuthenticator, getAllOrganizations: () => getAllOrganizations_default, getMeOrganizations: () => getMeOrganizations_default, getMeProfile: () => getScim2Me_default, getOrganization: () => getOrganization_default, getSchemas: () => getSchemas_default, updateMeProfile: () => updateMeProfile_default, updateOrganization: () => updateOrganization_default, useAlertVariant: () => useAlertVariant, useAsgardeo: () => useAsgardeo_default, useBranding: () => useBranding_default, useBrandingContext: () => useBrandingContext_default, useBrowserUrl: () => useBrowserUrl_default, useFlow: () => useFlow_default, useForm: () => useForm_default, useI18n: () => useI18n_default, useOrganization: () => useOrganization_default, useTheme: () => useTheme_default, useTranslation: () => useTranslation_default, useUser: () => useUser_default, validateFieldValue: () => validateFieldValue }); module.exports = __toCommonJS(index_exports); // src/contexts/Asgardeo/AsgardeoProvider.tsx var import_browser13 = require("@asgardeo/browser"); var import_react15 = require("react"); // src/contexts/Asgardeo/AsgardeoContext.ts var import_react = require("react"); var AsgardeoContext = (0, import_react.createContext)({ organizationHandle: void 0, applicationId: void 0, signInUrl: void 0, signUpUrl: void 0, afterSignInUrl: void 0, baseUrl: void 0, isInitialized: false, isLoading: true, isSignedIn: false, organization: null, signIn: null, signInSilently: null, signOut: null, signUp: null, user: null, http: { request: () => null, requestAll: () => null }, signInOptions: {}, getDecodedIdToken: null }); AsgardeoContext.displayName = "AsgardeoContext"; var AsgardeoContext_default = AsgardeoContext; // src/AsgardeoReactClient.ts var import_browser6 = require("@asgardeo/browser"); // src/__temp__/api.ts var import_browser = require("@asgardeo/browser"); var _AuthAPI = class _AuthAPI { constructor(spaClient) { __publicField(this, "_authState", _AuthAPI.DEFAULT_STATE); __publicField(this, "_client"); __publicField(this, "_isLoading"); this._client = spaClient ?? import_browser.AsgardeoSPAClient.getInstance(); this.getState = this.getState.bind(this); this.init = this.init.bind(this); this.signIn = this.signIn.bind(this); this.signOut = this.signOut.bind(this); this.updateState = this.updateState.bind(this); } _setIsLoading(isLoading) { this._isLoading = isLoading; } _getIsLoading() { return this._isLoading; } isLoading() { return this._getIsLoading(); } /** * Method to return Auth Client instance authentication state. * * @return {AuthStateInterface} Authentication State. */ getState() { return this._authState; } /** * Method to initialize the AuthClient instance. * * @param {Config} config - `dispatch` function from React Auth Context. */ async init(config) { return this._client.initialize(config); } /** * Method to get the configuration data. * * @returns {Promise<AuthClientConfig<Config>>} - A promise that resolves with the configuration data. */ async getConfigData() { return this._client.getConfigData(); } /** * Method to get the configuration data. * * @returns {Promise<AuthClientConfig<Config>>} - A promise that resolves with the configuration data. */ async isInitialized() { return this._client.isInitialized(); } /** * Method to handle user Sign In requests. * * @param {any} dispatch - `dispatch` function from React Auth Context. * @param {AuthStateInterface} state - Current authentication state in React Auth Context. * @param {any} callback - Action to trigger on successful sign in. */ async signIn(config, authorizationCode, sessionState, authState, callback, tokenRequestConfig) { return this._client.signIn(config, authorizationCode, sessionState, authState, tokenRequestConfig).then(async (response) => { if (!response) { return null; } if (await this._client.isSignedIn()) { const stateToUpdate = { displayName: response.displayName, email: response.email, isSignedIn: true, isLoading: false, isSigningOut: false, username: response.username }; this.updateState(stateToUpdate); this._setIsLoading(false); if (callback) { callback(response); } } return response; }).catch((error) => Promise.reject(error)); } /** * Method to handle user Sign Out requests. * * @param {any} dispatch - `dispatch` function from React Auth Context. * @param {AuthStateInterface} state - Current authentication state in React Auth Context. * @param {any} callback - Action to trigger on successful sign out. */ signOut(callback) { return this._client.signOut().then((response) => { if (callback) { callback(response); } return response; }).catch((error) => Promise.reject(error)); } /** * Method to update Auth Client instance authentication state. * * @param {AuthStateInterface} state - State values to update in authentication state. */ updateState(state) { this._authState = { ...this._authState, ...state }; } /** * This method returns a Promise that resolves with the basic user information obtained from the ID token. * * @return {Promise<User>} - A promise that resolves with the user information. */ async getUser() { return this._client.getUser(); } /** * This method sends an API request to a protected endpoint. * The access token is automatically attached to the header of the request. * This is the only way by which protected endpoints can be accessed * when the web worker is used to store session information. * * @param {HttpRequestConfig} config - The config object containing attributes necessary to send a request. * * @return {Promise<Response>} - Returns a Promise that resolves with the response to the request. */ async httpRequest(config) { return this._client.httpRequest(config); } /** * This method sends multiple API requests to a protected endpoint. * The access token is automatically attached to the header of the request. * This is the only way by which multiple requests can be sent to protected endpoints * when the web worker is used to store session information. * * @param {HttpRequestConfig[]} config - The config object containing attributes necessary to send a request. * * @return {Promise<Response>} - Returns a Promise that resolves with the responses to the requests. */ async httpRequestAll(configs) { return this._client.httpRequestAll(configs); } /** * This method allows you to send a request with a custom grant. * * @param {CustomGrantRequestParams} config - The request parameters. * * @return {Promise<Response | SignInResponse>} - A Promise that resolves with * the value returned by the custom grant request. */ exchangeToken(config, callback) { return this._client.exchangeToken(config).then((response) => { if (!response) { return null; } if (config.returnsSession) { this.updateState({ ...this.getState(), ...response, isSignedIn: true, isLoading: false }); } callback && callback(response); return response; }).catch((error) => Promise.reject(error)); } /** * This method ends a user session. The access token is revoked and the session information is destroyed. * * @return {Promise<boolean>} - A promise that resolves with `true` if the process is successful. */ async revokeAccessToken(dispatch) { return this._client.revokeAccessToken().then(() => { this.updateState({ ..._AuthAPI.DEFAULT_STATE, isLoading: false }); dispatch(_AuthAPI.DEFAULT_STATE); return true; }).catch((error) => Promise.reject(error)); } /** * This method returns a Promise that resolves with an object containing the service endpoints. * * @return {Promise<ServiceResourcesType} - A Promise that resolves with an object containing the service endpoints. */ async getOpenIDProviderEndpoints() { return this._client.getOpenIDProviderEndpoints(); } /** * This methods returns the Axios http client. * * @return {HttpClientInstance} - The Axios HTTP client. */ async getHttpClient() { return this._client.getHttpClient(); } /** * This method decodes the payload of the id token and returns it. * * @return {Promise<DecodedIDTokenPayloadInterface>} - A Promise that resolves with * the decoded payload of the id token. */ async getDecodedIdToken(sessionId) { return this._client.getDecodedIdToken(sessionId); } /** * This method decodes the payload of the idp id token and returns it. * * @return {Promise<DecodedIDTokenPayloadInterface>} - A Promise that resolves with * the decoded payload of the idp id token. */ async getDecodedIDPIDToken() { return this._client.getDecodedIdToken(); } /** * This method returns the ID token. * * @return {Promise<string>} - A Promise that resolves with the id token. */ async getIdToken() { return this._client.getIdToken(); } /** * This method return a Promise that resolves with the access token. * * **This method will not return the access token if the storage type is set to `webWorker`.** * * @return {Promise<string>} - A Promise that resolves with the access token. */ async getAccessToken(sessionId) { return this._client.getAccessToken(sessionId); } /** * This method return a Promise that resolves with the idp access token. * * **This method will not return the idp access token if the storage type is set to `webWorker`.** * **This can be used to access the IDP access token when custom auth grant functionalities are used** * * @return {Promise<string>} - A Promise that resolves with the idp access token. */ async getIDPAccessToken() { return this._client.getIDPAccessToken(); } /** * This method refreshes the access token. * * @return {TokenResponseInterface} - A Promise that resolves with an object containing * information about the refreshed access token. */ async refreshAccessToken() { return this._client.refreshAccessToken(); } /** * This method specifies if the user is authenticated or not. * * @return {Promise<boolean>} - A Promise that resolves with `true` if teh user is authenticated. */ async isSignedIn() { return this._client.isSignedIn(); } /** * This method specifies if the session is active or not. * * @return {Promise<boolean>} - A Promise that resolves with `true` if there is an active session. */ async isSessionActive() { return this._client.isSessionActive(); } /** * This method enables callback functions attached to the http client. * * @return {Promise<boolean>} - A promise that resolves with True. * */ async enableHttpHandler() { return this._client.enableHttpHandler(); } /** * This method disables callback functions attached to the http client. * * @return {Promise<boolean>} - A promise that resolves with True. */ async disableHttpHandler() { return this._client.disableHttpHandler(); } /** * This method updates the configuration that was passed into the constructor when instantiating this class. * * @param {Partial<AuthClientConfig<T>>} config - A config object to update the SDK configurations with. */ async reInitialize(config) { return this._client.reInitialize(config); } on(hook, callback, id) { if (hook === import_browser.Hooks.CustomGrant) { return this._client.on(hook, callback, id); } return this._client.on(hook, callback); } /** * This method allows you to sign in silently. * First, this method sends a prompt none request to see if there is an active user session in the identity server. * If there is one, then it requests the access token and stores it. Else, it returns false. * * @return {Promise<User | boolean>} - A Promise that resolves with the user information after signing in * or with `false` if the user is not signed in. * * @example *``` * client.signInSilently() *``` */ async signInSilently(additionalParams, tokenRequestConfig) { return this._client.signInSilently(additionalParams, tokenRequestConfig).then(async (response) => { if (!response) { return false; } return response; }).catch((error) => Promise.reject(error)); } }; __publicField(_AuthAPI, "DEFAULT_STATE"); var AuthAPI = _AuthAPI; AuthAPI.DEFAULT_STATE = { displayName: "", email: "", isSignedIn: false, isLoading: true, username: "" }; var api_default = AuthAPI; // src/api/getMeOrganizations.ts var import_browser2 = require("@asgardeo/browser"); var httpClient = import_browser2.AsgardeoSPAClient.getInstance().httpRequest.bind(import_browser2.AsgardeoSPAClient.getInstance()); var getMeOrganizations = async ({ fetcher, ...requestConfig }) => { const defaultFetcher = async (url, config) => { const response = await httpClient({ url, method: config.method || "GET", headers: config.headers }); return { ok: response.status >= 200 && response.status < 300, status: response.status, statusText: response.statusText || "", json: () => Promise.resolve(response.data), text: () => Promise.resolve(typeof response.data === "string" ? response.data : JSON.stringify(response.data)) }; }; return (0, import_browser2.getMeOrganizations)({ ...requestConfig, fetcher: fetcher || defaultFetcher }); }; var getMeOrganizations_default = getMeOrganizations; // src/api/getScim2Me.ts var import_browser3 = require("@asgardeo/browser"); var httpClient2 = import_browser3.AsgardeoSPAClient.getInstance().httpRequest.bind(import_browser3.AsgardeoSPAClient.getInstance()); var getScim2Me = async ({ fetcher, ...requestConfig }) => { const defaultFetcher = async (url, config) => { const response = await httpClient2({ url, method: config.method || "GET", headers: config.headers }); return { ok: response.status >= 200 && response.status < 300, status: response.status, statusText: response.statusText || "", json: () => Promise.resolve(response.data), text: () => Promise.resolve(typeof response.data === "string" ? response.data : JSON.stringify(response.data)) }; }; return (0, import_browser3.getScim2Me)({ ...requestConfig, fetcher: fetcher || defaultFetcher }); }; var getScim2Me_default = getScim2Me; // src/api/getSchemas.ts var import_browser4 = require("@asgardeo/browser"); var httpClient3 = import_browser4.AsgardeoSPAClient.getInstance().httpRequest.bind(import_browser4.AsgardeoSPAClient.getInstance()); var getSchemas = async ({ fetcher, ...requestConfig }) => { const defaultFetcher = async (url, config) => { const response = await httpClient3({ url, method: config.method || "GET", headers: config.headers }); return { ok: response.status >= 200 && response.status < 300, status: response.status, statusText: response.statusText || "", json: () => Promise.resolve(response.data), text: () => Promise.resolve(typeof response.data === "string" ? response.data : JSON.stringify(response.data)) }; }; return (0, import_browser4.getSchemas)({ ...requestConfig, fetcher: fetcher || defaultFetcher }); }; var getSchemas_default = getSchemas; // src/api/getAllOrganizations.ts var import_browser5 = require("@asgardeo/browser"); var httpClient4 = import_browser5.AsgardeoSPAClient.getInstance().httpRequest.bind(import_browser5.AsgardeoSPAClient.getInstance()); var getAllOrganizations = async ({ fetcher, ...requestConfig }) => { const defaultFetcher = async (url, config) => { const response = await httpClient4({ url, method: config.method || "GET", headers: config.headers }); return { ok: response.status >= 200 && response.status < 300, status: response.status, statusText: response.statusText || "", json: () => Promise.resolve(response.data), text: () => Promise.resolve(typeof response.data === "string" ? response.data : JSON.stringify(response.data)) }; }; return (0, import_browser5.getAllOrganizations)({ ...requestConfig, fetcher: fetcher || defaultFetcher }); }; var getAllOrganizations_default = getAllOrganizations; // src/AsgardeoReactClient.ts var AsgardeoReactClient = class extends import_browser6.AsgardeoBrowserClient { constructor() { super(); __publicField(this, "asgardeo"); __publicField(this, "_isLoading", false); this.asgardeo = new api_default(); } /** * Set the loading state of the client * @param loading - Boolean indicating if the client is in a loading state */ setLoading(loading) { this._isLoading = loading; } /** * Wrap async operations with loading state management * @param operation - The async operation to execute * @returns Promise with the result of the operation */ async withLoading(operation) { this.setLoading(true); try { const result = await operation(); return result; } finally { this.setLoading(false); } } initialize(config, storage) { let resolvedOrganizationHandle = config?.organizationHandle; if (!resolvedOrganizationHandle) { resolvedOrganizationHandle = (0, import_browser6.deriveOrganizationHandleFromBaseUrl)(config?.baseUrl); } return this.withLoading(async () => { return this.asgardeo.init({ ...config, organizationHandle: resolvedOrganizationHandle }); }); } async updateUserProfile(payload, userId) { throw new Error("Not implemented"); } async getUser(options) { try { let baseUrl = options?.baseUrl; if (!baseUrl) { const configData = await this.asgardeo.getConfigData(); baseUrl = configData?.baseUrl; } const profile = await getScim2Me_default({ baseUrl }); const schemas = await getSchemas_default({ baseUrl }); return (0, import_browser6.generateUserProfile)(profile, (0, import_browser6.flattenUserSchema)(schemas)); } catch (error) { return (0, import_browser6.extractUserClaimsFromIdToken)(await this.getDecodedIdToken()); } } async getDecodedIdToken(sessionId) { return this.asgardeo.getDecodedIdToken(sessionId); } async getUserProfile(options) { try { let baseUrl = options?.baseUrl; if (!baseUrl) { const configData = await this.asgardeo.getConfigData(); baseUrl = configData?.baseUrl; } const profile = await getScim2Me_default({ baseUrl }); const schemas = await getSchemas_default({ baseUrl }); const processedSchemas = (0, import_browser6.flattenUserSchema)(schemas); const output = { schemas: processedSchemas, flattenedProfile: (0, import_browser6.generateFlattenedUserProfile)(profile, processedSchemas), profile }; return output; } catch (error) { return { schemas: [], flattenedProfile: (0, import_browser6.extractUserClaimsFromIdToken)(await this.getDecodedIdToken()), profile: (0, import_browser6.extractUserClaimsFromIdToken)(await this.getDecodedIdToken()) }; } } async getMyOrganizations(options, sessionId) { try { let baseUrl = options?.baseUrl; if (!baseUrl) { const configData = await this.asgardeo.getConfigData(); baseUrl = configData?.baseUrl; } return getMeOrganizations_default({ baseUrl }); } catch (error) { throw new import_browser6.AsgardeoRuntimeError( `Failed to fetch the user's associated organizations: ${error instanceof Error ? error.message : String(error)}`, "AsgardeoReactClient-getMyOrganizations-RuntimeError-001", "react", "An error occurred while fetching associated organizations of the signed-in user." ); } } async getAllOrganizations(options, sessionId) { try { let baseUrl = options?.baseUrl; if (!baseUrl) { const configData = await this.asgardeo.getConfigData(); baseUrl = configData?.baseUrl; } return getAllOrganizations_default({ baseUrl }); } catch (error) { throw new import_browser6.AsgardeoRuntimeError( `Failed to fetch all organizations: ${error instanceof Error ? error.message : String(error)}`, "AsgardeoReactClient-getAllOrganizations-RuntimeError-001", "react", "An error occurred while fetching all the organizations associated with the user." ); } } async getCurrentOrganization() { const idToken = await this.getDecodedIdToken(); return { orgHandle: idToken?.org_handle, name: idToken?.org_name, id: idToken?.org_id }; } async switchOrganization(organization, sessionId) { return this.withLoading(async () => { try { const configData = await this.asgardeo.getConfigData(); if (!organization.id) { throw new import_browser6.AsgardeoRuntimeError( "Organization ID is required for switching organizations", "react-AsgardeoReactClient-SwitchOrganizationError-001", "react", "The organization object must contain a valid ID to perform the organization switch." ); } const exchangeConfig = { attachToken: false, data: { client_id: "{{clientId}}", grant_type: "organization_switch", scope: "{{scopes}}", switching_organization: organization.id, token: "{{accessToken}}" }, id: "organization-switch", returnsSession: true, signInRequired: true }; return await this.asgardeo.exchangeToken(exchangeConfig, (user) => { }); } catch (error) { throw new import_browser6.AsgardeoRuntimeError( `Failed to switch organization: ${error.message || error}`, "react-AsgardeoReactClient-SwitchOrganizationError-003", "react", "An error occurred while switching to the specified organization. Please try again." ); } }); } isLoading() { return this._isLoading || this.asgardeo.isLoading(); } async isInitialized() { return this.asgardeo.isInitialized(); } isSignedIn() { return this.asgardeo.isSignedIn(); } getConfiguration() { return this.asgardeo.getConfigData(); } async signIn(...args) { return this.withLoading(async () => { const arg1 = args[0]; const arg2 = args[1]; if (typeof arg1 === "object" && "flowId" in arg1 && typeof arg2 === "object" && "url" in arg2) { return (0, import_browser6.executeEmbeddedSignInFlow)({ payload: arg1, url: arg2.url }); } return await this.asgardeo.signIn(arg1); }); } async signInSilently(options) { return this.withLoading(async () => { return this.asgardeo.signInSilently(options); }); } async signOut(...args) { if (args[1] && typeof args[1] !== "function") { throw new Error("The second argument must be a function."); } const response = await this.asgardeo.signOut(args[1]); return Promise.resolve(String(response)); } async signUp(...args) { if (args.length === 0) { throw new import_browser6.AsgardeoRuntimeError( "No arguments provided for signUp method.", "react-AsgardeoReactClient-ValidationError-001", "react", "The signUp method requires at least one argument, either a SignUpOptions object or an EmbeddedFlowExecuteRequestPayload." ); } const firstArg = args[0]; if (typeof firstArg === "object" && "flowType" in firstArg) { const configData = await this.asgardeo.getConfigData(); const baseUrl = configData?.baseUrl; return (0, import_browser6.executeEmbeddedSignUpFlow)({ baseUrl, payload: firstArg }); } throw new import_browser6.AsgardeoRuntimeError( "Not implemented", "react-AsgardeoReactClient-ValidationError-002", "react", "The signUp method with SignUpOptions is not implemented in the React client." ); } async request(requestConfig) { return this.asgardeo.httpRequest(requestConfig); } async requestAll(requestConfigs) { return this.asgardeo.httpRequestAll(requestConfigs); } async getAccessToken(sessionId) { return this.asgardeo.getAccessToken(sessionId); } }; var AsgardeoReactClient_default = AsgardeoReactClient; // src/hooks/useBrowserUrl.ts var import_browser7 = require("@asgardeo/browser"); var useBrowserUrl = () => { const hasAuthParams = (url, afterSignInUrl) => (0, import_browser7.hasAuthParamsInUrl)() && new URL(url.origin + url.pathname).toString() === new URL(afterSignInUrl).toString() || // authParams?.authorizationCode || // FIXME: These are sent externally. Need to see what we can do about this. url.searchParams.get("error") !== null; return { hasAuthParams }; }; var useBrowserUrl_default = useBrowserUrl; // src/contexts/Flow/FlowProvider.tsx var import_react3 = require("react"); // src/contexts/Flow/FlowContext.ts var import_react2 = require("react"); var FlowContext = (0, import_react2.createContext)(void 0); FlowContext.displayName = "FlowContext"; var FlowContext_default = FlowContext; // src/contexts/Flow/FlowProvider.tsx var import_jsx_runtime = require("react/jsx-runtime"); var FlowProvider = ({ children, initialStep = null, initialTitle = "", initialSubtitle, onFlowChange }) => { const [currentStep, setCurrentStepState] = (0, import_react3.useState)(initialStep); const [title, setTitle] = (0, import_react3.useState)(initialTitle); const [subtitle, setSubtitle] = (0, import_react3.useState)(initialSubtitle); const [messages, setMessages] = (0, import_react3.useState)([]); const [error, setError] = (0, import_react3.useState)(null); const [isLoading, setIsLoading] = (0, import_react3.useState)(false); const [showBackButton, setShowBackButton] = (0, import_react3.useState)(false); const [onGoBack, setOnGoBack] = (0, import_react3.useState)(void 0); const setCurrentStep = (0, import_react3.useCallback)( (step) => { setCurrentStepState(step); if (step) { setTitle(step.title); setSubtitle(step.subtitle); setShowBackButton(step.canGoBack ?? false); } onFlowChange?.(step); }, [onFlowChange] ); const addMessage = (0, import_react3.useCallback)((message) => { const messageWithId = { ...message, id: message.id ?? `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}` }; setMessages((prev) => [...prev, messageWithId]); }, []); const removeMessage = (0, import_react3.useCallback)((messageId) => { setMessages((prev) => prev.filter((msg) => msg.id !== messageId)); }, []); const clearMessages = (0, import_react3.useCallback)(() => { setMessages([]); }, []); const reset = (0, import_react3.useCallback)(() => { setCurrentStepState(initialStep); setTitle(initialTitle); setSubtitle(initialSubtitle); setMessages([]); setError(null); setIsLoading(false); setShowBackButton(false); setOnGoBack(void 0); }, [initialStep, initialTitle, initialSubtitle]); const navigateToFlow = (0, import_react3.useCallback)( (flowType, options) => { const stepId = `${flowType}-${Date.now()}`; const step = { id: stepId, type: flowType, title: options?.title, subtitle: options?.subtitle, canGoBack: flowType !== "signin", // Usually allow going back except for main signin metadata: options?.metadata }; setCurrentStep(step); clearMessages(); setError(null); }, [setCurrentStep, clearMessages] ); const contextValue = (0, import_react3.useMemo)( () => ({ currentStep, setCurrentStep, title, setTitle, subtitle, setSubtitle, messages, addMessage, removeMessage, clearMessages, error, setError, isLoading, setIsLoading, showBackButton, setShowBackButton, onGoBack, setOnGoBack, reset, navigateToFlow }), [ currentStep, setCurrentStep, title, subtitle, messages, addMessage, removeMessage, clearMessages, error, isLoading, showBackButton, onGoBack, reset, navigateToFlow ] ); return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FlowContext_default.Provider, { value: contextValue, children }); }; var FlowProvider_default = FlowProvider; // src/contexts/I18n/I18nProvider.tsx var import_react5 = require("react"); var import_browser8 = require("@asgardeo/browser"); var import_browser9 = require("@asgardeo/browser"); // src/contexts/I18n/I18nContext.ts var import_react4 = require("react"); var I18nContext = (0, import_react4.createContext)(null); I18nContext.displayName = "I18nContext"; var I18nContext_default = I18nContext; // src/contexts/I18n/I18nProvider.tsx var import_jsx_runtime2 = require("react/jsx-runtime"); var I18N_LANGUAGE_STORAGE_KEY = "asgardeo-i18n-language"; var detectBrowserLanguage = () => { if (typeof window !== "undefined" && window.navigator) { return window.navigator.language || "en-US"; } return "en-US"; }; var getStoredLanguage = () => { if (typeof window !== "undefined" && window.localStorage) { try { return window.localStorage.getItem(I18N_LANGUAGE_STORAGE_KEY); } catch (error) { return null; } } return null; }; var storeLanguage = (language) => { if (typeof window !== "undefined" && window.localStorage) { try { window.localStorage.setItem(I18N_LANGUAGE_STORAGE_KEY, language); } catch (error) { console.warn("Failed to store language preference:", error); } } }; var I18nProvider = ({ children, preferences }) => { const defaultBundles = (0, import_browser9.getI18nBundles)(); const determineInitialLanguage = () => { const configLanguage = preferences?.language; const storedLanguage = getStoredLanguage(); const browserLanguage = detectBrowserLanguage(); const fallbackLanguage2 = preferences?.fallbackLanguage || "en-US"; return configLanguage || storedLanguage || browserLanguage || fallbackLanguage2; }; const [currentLanguage, setCurrentLanguage] = (0, import_react5.useState)(determineInitialLanguage); const mergedBundles = (0, import_react5.useMemo)(() => { const merged = {}; Object.entries(defaultBundles).forEach(([key, bundle]) => { const languageKey = key.replace("_", "-"); merged[languageKey] = bundle; }); if (preferences?.bundles) { Object.entries(preferences.bundles).forEach(([key, userBundle]) => { if (merged[key]) { merged[key] = { ...merged[key], translations: (0, import_browser8.deepMerge)(merged[key].translations, userBundle.translations), metadata: userBundle.metadata ? { ...merged[key].metadata, ...userBundle.metadata } : merged[key].metadata }; } else { merged[key] = userBundle; } }); } return merged; }, [defaultBundles, preferences?.bundles]); const fallbackLanguage = preferences?.fallbackLanguage || "en-US"; (0, import_react5.useEffect)(() => { storeLanguage(currentLanguage); }, [currentLanguage]); const t = (0, import_react5.useCallback)( (key, params) => { let translation; const currentBundle = mergedBundles[currentLanguage]; if (currentBundle?.translations[key]) { translation = currentBundle.translations[key]; } if (!translation && currentLanguage !== fallbackLanguage) { const fallbackBundle = mergedBundles[fallbackLanguage]; if (fallbackBundle?.translations[key]) { translation = fallbackBundle.translations[key]; } } if (!translation) { translation = key; } if (params && Object.keys(params).length > 0) { return Object.entries(params).reduce((acc, [paramKey, paramValue]) => { return acc.replace(new RegExp(`\\{${paramKey}\\}`, "g"), String(paramValue)); }, translation); } return translation; }, [mergedBundles, currentLanguage, fallbackLanguage] ); const setLanguage = (0, import_react5.useCallback)( (language) => { if (mergedBundles[language]) { setCurrentLanguage(language); } else { console.warn( `Language '${language}' is not available. Available languages: ${Object.keys(mergedBundles).join(", ")}` ); } }, [mergedBundles] ); const contextValue = (0, import_react5.useMemo)( () => ({ currentLanguage, fallbackLanguage, bundles: mergedBundles, setLanguage, t }), [currentLanguage, fallbackLanguage, mergedBundles, setLanguage, t] ); return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(I18nContext_default.Provider, { value: contextValue, children }); }; var I18nProvider_default = I18nProvider; // src/contexts/Organization/OrganizationProvider.tsx var import_browser10 = require("@asgardeo/browser"); var import_react7 = require("react"); // src/contexts/Organization/OrganizationContext.ts var import_react6 = require("react"); var OrganizationContext = (0, import_react6.createContext)({ createOrganization: () => null, currentOrganization: null, error: null, getAllOrganizations: () => Promise.resolve({ count: 0, organizations: [] }), isLoading: false, myOrganizations: null, revalidateMyOrganizations: () => Promise.resolve([]), switchOrganization: () => Promise.resolve() }); OrganizationContext.displayName = "OrganizationContext"; var OrganizationContext_default = OrganizationContext; // src/contexts/Organization/OrganizationProvider.tsx var import_jsx_runtime3 = require("react/jsx-runtime"); var OrganizationProvider = ({ children, currentOrganization, onError, myOrganizations, onOrganizationSwitch, revalidateMyOrganizations, getAllOrganizations: getAllOrganizations2, createOrganization: createOrganization2 }) => { const [isLoading, setIsLoading] = (0, import_react7.useState)(false); const [error, setError] = (0, import_react7.useState)(null); const switchOrganization = (0, import_react7.useCallback)( async (organization) => { if (!onOrganizationSwitch) { throw new import_browser10.AsgardeoRuntimeError( "onOrganizationSwitch callback is required", "OrganizationProvider-SwitchError-001", "react", "The onOrganizationSwitch callback must be provided to handle organization switching." ); } setIsLoading(true); setError(null); try { await onOrganizationSwitch(organization); } catch (switchError) { const errorMessage = switchError instanceof Error ? switchError.message : "Failed to switch organization"; setError(errorMessage); if (onError) { onError(errorMessage); } throw switchError; } finally { setIsLoading(false); } }, [onOrganizationSwitch, onError] ); const contextValue = (0, import_react7.useMemo)( () => ({ createOrganization: createOrganization2, currentOrganization, error, getAllOrganizations: getAllOrganizations2, isLoading, myOrganizations, revalidateMyOrganizations, switchOrganization }), [ currentOrganization, error, isLoading, myOrganizations, switchOrganization, revalidateMyOrganizations, getAllOrganizations2, createOrganization2 ] ); return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(OrganizationContext_default.Provider, { value: contextValue, children }); }; var OrganizationProvider_default = OrganizationProvider; // src/contexts/Theme/ThemeProvider.tsx var import_react11 = require("react"); var import_browser11 = require("@asgardeo/browser"); // src/contexts/Theme/ThemeContext.ts var import_react8 = require("react"); var ThemeContext = (0, import_react8.createContext)(null); ThemeContext.displayName = "ThemeContext"; var ThemeContext_default = ThemeContext; // src/contexts/Branding/useBrandingContext.ts var import_react10 = require("react"); // src/contexts/Branding/BrandingContext.ts var import_react9 = require("react"); var BrandingContext = (0, import_react9.createContext)(null); BrandingContext.displayName = "BrandingContext"; var BrandingContext_default = BrandingContext; // src/contexts/Branding/useBrandingContext.ts var useBrandingContext = () => { const context = (0, import_react10.useContext)(BrandingContext_default); if (!context) { throw new Error("useBrandingContext must be used within a BrandingProvider"); } return context; }; var useBrandingContext_default = useBrandingContext; // src/contexts/Theme/ThemeProvider.tsx var import_jsx_runtime4 = require("react/jsx-runtime"); var applyThemeToDOM = (theme) => { Object.entries(theme.cssVariables).forEach(([key, value]) => { document.documentElement.style.setProperty(key, value); }); }; var ThemeProvider = ({ children, theme: themeConfig, mode = "system", detection = {}, inheritFromBranding = true }) => { const [colorScheme, setColorScheme] = (0, import_react11.useState)(() => { if (mode === "light" || mode === "dark") { return mode; } if (mode === "branding") { return (0, import_browser11.detectThemeMode)("system", detection); } return (0, import_browser11.detectThemeMode)(mode, detection); }); let brandingTheme = null; let brandingActiveTheme = null; let isBrandingLoading = false; let brandingError = null; try { const brandingContext = useBrandingContext_default(); brandingTheme = brandingContext.theme; brandingActiveTheme = brandingContext.activeTheme; isBrandingLoading = brandingContext.isLoading; brandingError = brandingContext.error; } catch (error) { if (inheritFromBranding) { console.warn( "ThemeProvider: inheritFromBranding is enabled but BrandingProvider is not available. Make sure to wrap your app with BrandingProvider or AsgardeoProvider with branding preferences." ); } } (0, import_react11.useEffect)(() => { if (inheritFromBranding && brandingActiveTheme) { if (mode === "branding") { setColorScheme(brandingActiveTheme); } else if (mode === "system" && !isBrandingLoading) { setColorScheme(brandingActiveTheme); } } }, [inheritFromBranding, brandingActiveTheme, mode, isBrandingLoading]); const finalThemeConfig = (0, import_react11.useMemo)(() => { if (!inheritFromBranding || !brandingTheme) { return themeConfig; } const brandingThemeConfig = { colors: brandingTheme.colors, borderRadius: brandingTheme.borderRadius, shadows: brandingTheme.shadows, spacing: brandingTheme.spacing, images: brandingTheme.images, components: brandingTheme.components }; return { ...brandingThemeConfig, ...themeConfig, colors: { ...brandingThemeConfig.colors, ...themeConfig?.colors }, borderRadius: { ...brandingThemeConfig.borderRadius, ...themeConfig?.borderRadius }, shadows: { ...brandingThemeConfig.shadows, ...themeConfig?.shadows }, spacing: { ...brandingThemeConfig.spacing, ...themeConfig?.spacing }, images: { ...brandingThemeConfig.images, ...themeConfig?.images }, components: { ...brandingThemeConfig.components, ...themeConfig?.components } }; }, [inheritFromBranding, brandingTheme, themeConfig]); const theme = (0, import_react11.useMemo)(() => (0, import_browser11.createTheme)(finalThemeConfig, colorScheme === "dark"), [finalThemeConfig, colorScheme]); const handleThemeChange = (0, import_react11.useCallback)((isDark) => { setColorScheme(isDark ? "dark" : "light"); }, []); const toggleTheme = (0, import_react11.useCallback)(() => { setColorScheme((prev) => prev === "light" ? "dark" : "light"); }, []); (0, import_react11.useEffect)(() => { let observer = null; let mediaQuery = null; if (mode === "branding") { return null; } if (mode === "class") { const targetElement = detection.targetElement || document.documentElement; if (targetElement) { observer = (0, import_browser11.createClassObserver)(targetElement, handleThemeChange, detection); } } else if (mode === "system") { if (!inheritFromBranding || !brandingActiveTheme) { mediaQuery = (0, import_browser11.createMediaQueryListener)(handleThemeChange); } } return () => { if (observer) { observer.disconnect(); } if (mediaQuery) { if (mediaQuery.removeEventListener) { mediaQuery.removeEventListener("change", handleThemeChange); } else { mediaQuery.removeListener(handleThemeChange); } } }; }, [mode, detection, handleThemeChange, inheritFromBranding, brandingActiveTheme]); (0, import_react11.useEffect)(() => { applyThemeToDOM(theme); }, [theme]); const value = { theme, colorScheme, toggleTheme, isBrandingLoading, brandingError, inheritFromBranding }; return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ThemeContext_default.Provider, { value, children }); }; var ThemeProvider_default = ThemeProvider; // src/contexts/Branding/BrandingProvider.tsx var import_react12 = require("react"); var import_browser12 = require("@asgardeo/browser"); var import_jsx_runtime5 = require("react/jsx-runtime"); var BrandingProvider = ({ children, brandingPreference: externalBrandingPreference, forceTheme, enabled = true, isLoading: externalIsLoading = false, error: externalError = null, refetch: externalRefetch }) => { const [theme, setTheme] = (0, import_react12.useState)(null); const [activeTheme, setActiveTheme] = (0, import_react12.useState)(null); (0, import_react12.useEffect)(() => { if (!enabled || !externalBrandingPreference) { setTheme(null); setActiveTheme(null); return; } const activeThemeFromBranding = externalBrandingPreference?.preference?.theme?.activeTheme; let extractedActiveTheme = null; if (activeThemeFromBranding) { const themeMode = activeThemeFromBranding.toLowerCase(); if (themeMode === "light" || themeMode === "dark") { extractedActiveTheme = themeMode; } } setActiveTheme(extractedActiveTheme); const transformedTheme = (0, import_browser12.transformBrandingPreferenceToTheme)(externalBrandingPreference, forceTheme); setTheme(transformedTheme); }, [externalBrandingPreference, forceTheme, enabled]); (0, import_react12.useEffect)(() => { if (!enabled) { setTheme(null); setActiveTheme(null); } }, [enabled]); const fetchBranding = (0, import_react12.useCallback)(async () => { if (externalRefetch) { await externalRefetch(); } }, [externalRefetch]); const value = { brandingPreference: externalBrandingPreference || null, theme, activeTheme, isLoading: externalIsLoading, error: externalError, fetchBrandi