@thunderid/react 0.11.1 → 0.11.3

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 (29) hide show
  1. package/dist/ThunderIDReactClient.d.ts.map +1 -1
  2. package/dist/ThunderIDReactClient.js +13 -7
  3. package/dist/ThunderIDReactClient.js.map +1 -1
  4. package/dist/cjs/ThunderIDReactClient.cjs +12 -6
  5. package/dist/cjs/ThunderIDReactClient.cjs.map +1 -1
  6. package/dist/cjs/components/presentation/auth/InviteUser/InviteUser.cjs +4 -3
  7. package/dist/cjs/components/presentation/auth/InviteUser/InviteUser.cjs.map +1 -1
  8. package/dist/cjs/components/presentation/auth/SignIn/SignIn.cjs +1 -1
  9. package/dist/cjs/components/presentation/auth/SignIn/SignIn.cjs.map +1 -1
  10. package/dist/cjs/contexts/FlowMeta/FlowMetaProvider.cjs +5 -1
  11. package/dist/cjs/contexts/FlowMeta/FlowMetaProvider.cjs.map +1 -1
  12. package/dist/cjs/contexts/ThunderID/ThunderIDContext.cjs.map +1 -1
  13. package/dist/cjs/contexts/ThunderID/ThunderIDProvider.cjs +33 -17
  14. package/dist/cjs/contexts/ThunderID/ThunderIDProvider.cjs.map +1 -1
  15. package/dist/components/presentation/auth/InviteUser/InviteUser.d.ts.map +1 -1
  16. package/dist/components/presentation/auth/InviteUser/InviteUser.js +5 -4
  17. package/dist/components/presentation/auth/InviteUser/InviteUser.js.map +1 -1
  18. package/dist/components/presentation/auth/SignIn/SignIn.js +1 -1
  19. package/dist/components/presentation/auth/SignIn/SignIn.js.map +1 -1
  20. package/dist/contexts/FlowMeta/FlowMetaProvider.d.ts.map +1 -1
  21. package/dist/contexts/FlowMeta/FlowMetaProvider.js +6 -2
  22. package/dist/contexts/FlowMeta/FlowMetaProvider.js.map +1 -1
  23. package/dist/contexts/ThunderID/ThunderIDContext.d.ts +5 -0
  24. package/dist/contexts/ThunderID/ThunderIDContext.d.ts.map +1 -1
  25. package/dist/contexts/ThunderID/ThunderIDContext.js.map +1 -1
  26. package/dist/contexts/ThunderID/ThunderIDProvider.d.ts.map +1 -1
  27. package/dist/contexts/ThunderID/ThunderIDProvider.js +34 -18
  28. package/dist/contexts/ThunderID/ThunderIDProvider.js.map +1 -1
  29. package/package.json +2 -2
@@ -34,7 +34,7 @@ react_jsx_runtime = require_rolldown_runtime.__toESM(react_jsx_runtime);
34
34
  * ```
35
35
  */
36
36
  const FlowMetaProvider = ({ children, enabled = true, initialMeta = null }) => {
37
- const { baseUrl, applicationId, isInitialized } = require_useThunderID.default();
37
+ const { baseUrl, endpoints, applicationId, isInitialized } = require_useThunderID.default();
38
38
  const i18nContext = require_useI18n.default();
39
39
  const [meta, setMeta] = (0, react.useState)(initialMeta);
40
40
  const [isLoading, setIsLoading] = (0, react.useState)(!initialMeta);
@@ -54,6 +54,7 @@ const FlowMetaProvider = ({ children, enabled = true, initialMeta = null }) => {
54
54
  try {
55
55
  setMeta(await (0, __thunderid_browser.getFlowMeta)({
56
56
  baseUrl,
57
+ url: (0, __thunderid_browser.resolveResourceEndpoint)("flowMeta", { endpoints }),
57
58
  ...applicationId ? {
58
59
  id: applicationId,
59
60
  type: __thunderid_browser.FlowMetaType.App
@@ -68,6 +69,7 @@ const FlowMetaProvider = ({ children, enabled = true, initialMeta = null }) => {
68
69
  }, [
69
70
  enabled,
70
71
  baseUrl,
72
+ endpoints,
71
73
  applicationId,
72
74
  isInitialized,
73
75
  i18nContext?.currentLanguage
@@ -79,6 +81,7 @@ const FlowMetaProvider = ({ children, enabled = true, initialMeta = null }) => {
79
81
  try {
80
82
  const result = await (0, __thunderid_browser.getFlowMeta)({
81
83
  baseUrl,
84
+ url: (0, __thunderid_browser.resolveResourceEndpoint)("flowMeta", { endpoints }),
82
85
  ...applicationId ? {
83
86
  id: applicationId,
84
87
  type: __thunderid_browser.FlowMetaType.App
@@ -105,6 +108,7 @@ const FlowMetaProvider = ({ children, enabled = true, initialMeta = null }) => {
105
108
  }, [
106
109
  enabled,
107
110
  baseUrl,
111
+ endpoints,
108
112
  applicationId,
109
113
  i18nContext
110
114
  ]);
@@ -1 +1 @@
1
- {"version":3,"file":"FlowMetaProvider.cjs","names":["FlowMetaProvider: FC<PropsWithChildren<FlowMetaProviderProps>>","useThunderID","i18nContext: I18nContextValue","useI18n","lastFetchedRef: RefObject<(() => Promise<void>) | null>","initialMetaConsumedRef: RefObject<boolean>","fetchFlowMeta: () => Promise<void>","FlowMetaType","err: unknown","switchLanguage: (language: string) => Promise<void>","result: FlowMetadataResponse","flatTranslations: Record<string, string>","value","bundle: I18nBundle","metaLanguage: string","TranslationBundleConstants","bundlesToInject: Record<string, I18nBundle>","value: any","FlowMetaContext"],"sources":["../../../../src/contexts/FlowMeta/FlowMetaProvider.tsx"],"sourcesContent":["/**\n * Copyright (c) 2026, WSO2 LLC. (https://www.wso2.com).\n *\n * WSO2 LLC. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport {\n FlowMetadataResponse,\n FlowMetaType,\n getFlowMeta,\n I18nBundle,\n TranslationBundleConstants,\n} from '@thunderid/browser';\nimport {FC, PropsWithChildren, ReactElement, RefObject, useCallback, useEffect, useRef, useState} from 'react';\nimport FlowMetaContext from './FlowMetaContext';\nimport {I18nContextValue} from '../I18n/I18nContext';\nimport useI18n from '../I18n/useI18n';\nimport useThunderID from '../ThunderID/useThunderID';\n\nexport interface FlowMetaProviderProps {\n /**\n * When false the provider skips fetching and provides null meta.\n * @default true\n */\n enabled?: boolean;\n\n /**\n * Flow metadata resolved ahead of time (e.g. fetched server-side during SSR) and used to seed\n * the provider's state. When present, the provider skips its own initial client-side fetch —\n * avoiding a redundant request and the flash of untranslated i18n keys while that fetch is in\n * flight — but still fetches normally on subsequent changes (e.g. an explicit language switch).\n */\n initialMeta?: FlowMetadataResponse | null;\n}\n\n/**\n * FlowMetaProvider fetches flow metadata from the `GET /flow/meta` endpoint\n * (v2 API) and makes it available to child components through `FlowMetaContext`.\n *\n * It is designed to be used in v2 embedded-flow scenarios and integrates with\n * `ThemeProvider` so that theme settings (colors, direction, typography, …)\n * from the server-side design configuration are applied automatically.\n *\n * @example\n * ```tsx\n * <FlowMetaProvider\n * config={{\n * baseUrl: 'https://localhost:8090',\n * type: FlowMetaType.App,\n * id: 'your-app-id',\n * }}\n * >\n * <ThemeProvider>\n * <App />\n * </ThemeProvider>\n * </FlowMetaProvider>\n * ```\n */\nconst FlowMetaProvider: FC<PropsWithChildren<FlowMetaProviderProps>> = ({\n children,\n enabled = true,\n initialMeta = null,\n}: PropsWithChildren<FlowMetaProviderProps>): ReactElement => {\n const {baseUrl, applicationId, isInitialized} = useThunderID();\n const i18nContext: I18nContextValue = useI18n();\n\n const [meta, setMeta] = useState<FlowMetadataResponse | null>(initialMeta);\n const [isLoading, setIsLoading] = useState<boolean>(!initialMeta);\n const [error, setError] = useState<Error | null>(null);\n const [pendingLanguage, setPendingLanguage] = useState<string | null>(null);\n\n // Track the last fetchFlowMeta reference that was actually dispatched.\n // This prevents two classes of double-fetch:\n // 1. React StrictMode simulates unmount+remount — the re-mount fires the\n // effect again with the same fetchFlowMeta reference; without this guard\n // the else-branch would issue a redundant second network request.\n // 2. Rapid dependency changes (e.g. baseUrl stabilising) that produce two\n // effect firings before the first fetch completes.\n const lastFetchedRef: RefObject<(() => Promise<void>) | null> = useRef<(() => Promise<void>) | null>(null);\n const initialMetaConsumedRef: RefObject<boolean> = useRef(false);\n const fetchFlowMeta: () => Promise<void> = useCallback(async (): Promise<void> => {\n if (!enabled) {\n setMeta(null);\n setIsLoading(false);\n return;\n }\n\n // Defer until ThunderID finishes initializing (e.g. loading applicationId\n // from storage on refresh). Once initialized, proceed even if applicationId\n // is absent — some flows (e.g. AcceptInvite) have no applicationId by design.\n if (!isInitialized && !applicationId) {\n return;\n }\n\n setIsLoading(true);\n setError(null);\n\n try {\n const result: FlowMetadataResponse = await getFlowMeta({\n baseUrl,\n ...(applicationId ? {id: applicationId, type: FlowMetaType.App} : {}),\n language: i18nContext?.currentLanguage,\n });\n setMeta(result);\n } catch (err: unknown) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setIsLoading(false);\n }\n }, [enabled, baseUrl, applicationId, isInitialized, i18nContext?.currentLanguage]);\n\n const switchLanguage: (language: string) => Promise<void> = useCallback(\n async (language: string): Promise<void> => {\n if (!enabled) return;\n\n setIsLoading(true);\n setError(null);\n\n try {\n const result: FlowMetadataResponse = await getFlowMeta({\n baseUrl,\n ...(applicationId ? {id: applicationId, type: FlowMetaType.App} : {}),\n language,\n });\n\n // Inject translations for the new language before switching\n if (result.i18n?.translations && i18nContext?.injectBundles) {\n const flatTranslations: Record<string, string> = {};\n Object.entries(result.i18n.translations).forEach(([namespace, keys]: [string, Record<string, string>]) => {\n Object.entries(keys).forEach(([key, value]: [string, string]) => {\n flatTranslations[`${namespace}.${key}`] = value;\n });\n });\n const bundle: I18nBundle = {translations: flatTranslations} as unknown as I18nBundle;\n i18nContext.injectBundles({[language]: bundle});\n }\n\n // Defer setLanguage to the next effect cycle so injectBundles state\n // is committed before I18nProvider's setLanguage checks mergedBundles.\n setPendingLanguage(language);\n setMeta(result);\n } catch (err: unknown) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setIsLoading(false);\n }\n },\n [enabled, baseUrl, applicationId, i18nContext],\n );\n\n // After injectBundles + setPendingLanguage are batched and committed, this\n // effect fires with the updated i18nContext (mergedBundles now includes the\n // new language), so setLanguage succeeds on the first switch.\n useEffect(() => {\n if (pendingLanguage && i18nContext?.setLanguage) {\n i18nContext.setLanguage(pendingLanguage);\n setPendingLanguage(null);\n }\n }, [pendingLanguage, i18nContext?.setLanguage]);\n\n useEffect(() => {\n if (!initialMetaConsumedRef.current) {\n initialMetaConsumedRef.current = true;\n\n if (initialMeta) {\n // Seeded from SSR (or another caller) — skip the redundant first client-side fetch.\n // Later dependency changes (e.g. an explicit language switch) still fetch normally.\n lastFetchedRef.current = fetchFlowMeta;\n return;\n }\n }\n\n if (lastFetchedRef.current === fetchFlowMeta) {\n // Same reference as the last dispatch — this is a StrictMode re-mount\n // or an effect re-fire with unchanged deps. Skip to avoid a duplicate fetch.\n return;\n }\n\n lastFetchedRef.current = fetchFlowMeta;\n fetchFlowMeta();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [fetchFlowMeta]);\n\n // When meta loads with i18n translations, inject them into the i18n system.\n // Meta translations act as the base layer — prop-provided bundles still take precedence.\n useEffect(() => {\n if (!meta?.i18n?.translations || !i18nContext?.injectBundles) {\n return;\n }\n\n const metaLanguage: string = meta.i18n.language || TranslationBundleConstants.FALLBACK_LOCALE;\n\n // Flatten namespace-keyed translations to dot-path keys:\n // { \"signin\": { \"heading\": \"Sign In\" } } → { \"signin.heading\": \"Sign In\" }\n const flatTranslations: Record<string, string> = {};\n Object.entries(meta.i18n.translations).forEach(([namespace, keys]: [string, Record<string, string>]) => {\n Object.entries(keys).forEach(([key, value]: [string, string]) => {\n flatTranslations[`${namespace}.${key}`] = value;\n });\n });\n\n const bundle: I18nBundle = {translations: flatTranslations} as unknown as I18nBundle;\n\n // Inject under the meta language code and the i18n current language so\n // lookups succeed regardless of whether the system uses \"en\" or \"en-US\".\n const bundlesToInject: Record<string, I18nBundle> = {[metaLanguage]: bundle};\n if (i18nContext.currentLanguage && i18nContext.currentLanguage !== metaLanguage) {\n bundlesToInject[i18nContext.currentLanguage] = bundle;\n }\n if (i18nContext.fallbackLanguage && i18nContext.fallbackLanguage !== metaLanguage) {\n bundlesToInject[i18nContext.fallbackLanguage] = bundle;\n }\n\n i18nContext.injectBundles(bundlesToInject);\n }, [meta?.i18n?.translations, i18nContext?.injectBundles]);\n\n const value: any = {\n error,\n fetchFlowMeta,\n isLoading,\n meta,\n switchLanguage,\n };\n\n return <FlowMetaContext.Provider value={value}>{children}</FlowMetaContext.Provider>;\n};\n\nexport default FlowMetaProvider;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,MAAMA,oBAAkE,EACtE,UACA,UAAU,MACV,cAAc,WAC8C;CAC5D,MAAM,EAAC,SAAS,eAAe,kBAAiBC,8BAAc;CAC9D,MAAMC,cAAgCC,yBAAS;CAE/C,MAAM,CAAC,MAAM,+BAAiD,YAAY;CAC1E,MAAM,CAAC,WAAW,oCAAkC,CAAC,YAAY;CACjE,MAAM,CAAC,OAAO,gCAAmC,KAAK;CACtD,MAAM,CAAC,iBAAiB,0CAA8C,KAAK;CAS3E,MAAMC,mCAA+F,KAAK;CAC1G,MAAMC,2CAAoD,MAAM;CAChE,MAAMC,uCAAiD,YAA2B;AAChF,MAAI,CAAC,SAAS;AACZ,WAAQ,KAAK;AACb,gBAAa,MAAM;AACnB;;AAMF,MAAI,CAAC,iBAAiB,CAAC,cACrB;AAGF,eAAa,KAAK;AAClB,WAAS,KAAK;AAEd,MAAI;AAMF,WALqC,2CAAkB;IACrD;IACA,GAAI,gBAAgB;KAAC,IAAI;KAAe,MAAMC,iCAAa;KAAI,GAAG,EAAE;IACpE,UAAU,aAAa;IACxB,CAAC,CACa;WACRC,KAAc;AACrB,YAAS,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,IAAI,CAAC,CAAC;YACrD;AACR,gBAAa,MAAM;;IAEpB;EAAC;EAAS;EAAS;EAAe;EAAe,aAAa;EAAgB,CAAC;CAElF,MAAMC,wCACJ,OAAO,aAAoC;AACzC,MAAI,CAAC,QAAS;AAEd,eAAa,KAAK;AAClB,WAAS,KAAK;AAEd,MAAI;GACF,MAAMC,SAA+B,2CAAkB;IACrD;IACA,GAAI,gBAAgB;KAAC,IAAI;KAAe,MAAMH,iCAAa;KAAI,GAAG,EAAE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EAAC,cAAc,kBAAiB;EAI3D,MAAMG,kBAA8C,GAAE,eAAe,QAAO;AAC5E,MAAI,YAAY,mBAAmB,YAAY,oBAAoB,aACjE,iBAAgB,YAAY,mBAAmB;AAEjD,MAAI,YAAY,oBAAoB,YAAY,qBAAqB,aACnE,iBAAgB,YAAY,oBAAoB;AAGlD,cAAY,cAAc,gBAAgB;IACzC,CAAC,MAAM,MAAM,cAAc,aAAa,cAAc,CAAC;CAE1D,MAAMC,QAAa;EACjB;EACA;EACA;EACA;EACA;EACD;AAED,QAAO,2CAACC,gCAAgB;EAAgB;EAAQ;GAAoC;;AAGtF,+BAAe"}
1
+ {"version":3,"file":"FlowMetaProvider.cjs","names":["FlowMetaProvider: FC<PropsWithChildren<FlowMetaProviderProps>>","useThunderID","i18nContext: I18nContextValue","useI18n","lastFetchedRef: RefObject<(() => Promise<void>) | null>","initialMetaConsumedRef: RefObject<boolean>","fetchFlowMeta: () => Promise<void>","FlowMetaType","err: unknown","switchLanguage: (language: string) => Promise<void>","result: FlowMetadataResponse","flatTranslations: Record<string, string>","value","bundle: I18nBundle","metaLanguage: string","TranslationBundleConstants","bundlesToInject: Record<string, I18nBundle>","value: any","FlowMetaContext"],"sources":["../../../../src/contexts/FlowMeta/FlowMetaProvider.tsx"],"sourcesContent":["/**\n * Copyright (c) 2026, WSO2 LLC. (https://www.wso2.com).\n *\n * WSO2 LLC. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport {\n FlowMetadataResponse,\n FlowMetaType,\n getFlowMeta,\n I18nBundle,\n resolveResourceEndpoint,\n TranslationBundleConstants,\n} from '@thunderid/browser';\nimport {FC, PropsWithChildren, ReactElement, RefObject, useCallback, useEffect, useRef, useState} from 'react';\nimport FlowMetaContext from './FlowMetaContext';\nimport {I18nContextValue} from '../I18n/I18nContext';\nimport useI18n from '../I18n/useI18n';\nimport useThunderID from '../ThunderID/useThunderID';\n\nexport interface FlowMetaProviderProps {\n /**\n * When false the provider skips fetching and provides null meta.\n * @default true\n */\n enabled?: boolean;\n\n /**\n * Flow metadata resolved ahead of time (e.g. fetched server-side during SSR) and used to seed\n * the provider's state. When present, the provider skips its own initial client-side fetch —\n * avoiding a redundant request and the flash of untranslated i18n keys while that fetch is in\n * flight — but still fetches normally on subsequent changes (e.g. an explicit language switch).\n */\n initialMeta?: FlowMetadataResponse | null;\n}\n\n/**\n * FlowMetaProvider fetches flow metadata from the `GET /flow/meta` endpoint\n * (v2 API) and makes it available to child components through `FlowMetaContext`.\n *\n * It is designed to be used in v2 embedded-flow scenarios and integrates with\n * `ThemeProvider` so that theme settings (colors, direction, typography, …)\n * from the server-side design configuration are applied automatically.\n *\n * @example\n * ```tsx\n * <FlowMetaProvider\n * config={{\n * baseUrl: 'https://localhost:8090',\n * type: FlowMetaType.App,\n * id: 'your-app-id',\n * }}\n * >\n * <ThemeProvider>\n * <App />\n * </ThemeProvider>\n * </FlowMetaProvider>\n * ```\n */\nconst FlowMetaProvider: FC<PropsWithChildren<FlowMetaProviderProps>> = ({\n children,\n enabled = true,\n initialMeta = null,\n}: PropsWithChildren<FlowMetaProviderProps>): ReactElement => {\n const {baseUrl, endpoints, applicationId, isInitialized} = useThunderID();\n const i18nContext: I18nContextValue = useI18n();\n\n const [meta, setMeta] = useState<FlowMetadataResponse | null>(initialMeta);\n const [isLoading, setIsLoading] = useState<boolean>(!initialMeta);\n const [error, setError] = useState<Error | null>(null);\n const [pendingLanguage, setPendingLanguage] = useState<string | null>(null);\n\n // Track the last fetchFlowMeta reference that was actually dispatched.\n // This prevents two classes of double-fetch:\n // 1. React StrictMode simulates unmount+remount — the re-mount fires the\n // effect again with the same fetchFlowMeta reference; without this guard\n // the else-branch would issue a redundant second network request.\n // 2. Rapid dependency changes (e.g. baseUrl stabilising) that produce two\n // effect firings before the first fetch completes.\n const lastFetchedRef: RefObject<(() => Promise<void>) | null> = useRef<(() => Promise<void>) | null>(null);\n const initialMetaConsumedRef: RefObject<boolean> = useRef(false);\n const fetchFlowMeta: () => Promise<void> = useCallback(async (): Promise<void> => {\n if (!enabled) {\n setMeta(null);\n setIsLoading(false);\n return;\n }\n\n // Defer until ThunderID finishes initializing (e.g. loading applicationId\n // from storage on refresh). Once initialized, proceed even if applicationId\n // is absent — some flows (e.g. AcceptInvite) have no applicationId by design.\n if (!isInitialized && !applicationId) {\n return;\n }\n\n setIsLoading(true);\n setError(null);\n\n try {\n const result: FlowMetadataResponse = await getFlowMeta({\n baseUrl,\n url: resolveResourceEndpoint('flowMeta', {endpoints}),\n ...(applicationId ? {id: applicationId, type: FlowMetaType.App} : {}),\n language: i18nContext?.currentLanguage,\n });\n setMeta(result);\n } catch (err: unknown) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setIsLoading(false);\n }\n }, [enabled, baseUrl, endpoints, applicationId, isInitialized, i18nContext?.currentLanguage]);\n\n const switchLanguage: (language: string) => Promise<void> = useCallback(\n async (language: string): Promise<void> => {\n if (!enabled) return;\n\n setIsLoading(true);\n setError(null);\n\n try {\n const result: FlowMetadataResponse = await getFlowMeta({\n baseUrl,\n url: resolveResourceEndpoint('flowMeta', {endpoints}),\n ...(applicationId ? {id: applicationId, type: FlowMetaType.App} : {}),\n language,\n });\n\n // Inject translations for the new language before switching\n if (result.i18n?.translations && i18nContext?.injectBundles) {\n const flatTranslations: Record<string, string> = {};\n Object.entries(result.i18n.translations).forEach(([namespace, keys]: [string, Record<string, string>]) => {\n Object.entries(keys).forEach(([key, value]: [string, string]) => {\n flatTranslations[`${namespace}.${key}`] = value;\n });\n });\n const bundle: I18nBundle = {translations: flatTranslations} as unknown as I18nBundle;\n i18nContext.injectBundles({[language]: bundle});\n }\n\n // Defer setLanguage to the next effect cycle so injectBundles state\n // is committed before I18nProvider's setLanguage checks mergedBundles.\n setPendingLanguage(language);\n setMeta(result);\n } catch (err: unknown) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setIsLoading(false);\n }\n },\n [enabled, baseUrl, endpoints, applicationId, i18nContext],\n );\n\n // After injectBundles + setPendingLanguage are batched and committed, this\n // effect fires with the updated i18nContext (mergedBundles now includes the\n // new language), so setLanguage succeeds on the first switch.\n useEffect(() => {\n if (pendingLanguage && i18nContext?.setLanguage) {\n i18nContext.setLanguage(pendingLanguage);\n setPendingLanguage(null);\n }\n }, [pendingLanguage, i18nContext?.setLanguage]);\n\n useEffect(() => {\n if (!initialMetaConsumedRef.current) {\n initialMetaConsumedRef.current = true;\n\n if (initialMeta) {\n // Seeded from SSR (or another caller) — skip the redundant first client-side fetch.\n // Later dependency changes (e.g. an explicit language switch) still fetch normally.\n lastFetchedRef.current = fetchFlowMeta;\n return;\n }\n }\n\n if (lastFetchedRef.current === fetchFlowMeta) {\n // Same reference as the last dispatch — this is a StrictMode re-mount\n // or an effect re-fire with unchanged deps. Skip to avoid a duplicate fetch.\n return;\n }\n\n lastFetchedRef.current = fetchFlowMeta;\n fetchFlowMeta();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [fetchFlowMeta]);\n\n // When meta loads with i18n translations, inject them into the i18n system.\n // Meta translations act as the base layer — prop-provided bundles still take precedence.\n useEffect(() => {\n if (!meta?.i18n?.translations || !i18nContext?.injectBundles) {\n return;\n }\n\n const metaLanguage: string = meta.i18n.language || TranslationBundleConstants.FALLBACK_LOCALE;\n\n // Flatten namespace-keyed translations to dot-path keys:\n // { \"signin\": { \"heading\": \"Sign In\" } } → { \"signin.heading\": \"Sign In\" }\n const flatTranslations: Record<string, string> = {};\n Object.entries(meta.i18n.translations).forEach(([namespace, keys]: [string, Record<string, string>]) => {\n Object.entries(keys).forEach(([key, value]: [string, string]) => {\n flatTranslations[`${namespace}.${key}`] = value;\n });\n });\n\n const bundle: I18nBundle = {translations: flatTranslations} as unknown as I18nBundle;\n\n // Inject under the meta language code and the i18n current language so\n // lookups succeed regardless of whether the system uses \"en\" or \"en-US\".\n const bundlesToInject: Record<string, I18nBundle> = {[metaLanguage]: bundle};\n if (i18nContext.currentLanguage && i18nContext.currentLanguage !== metaLanguage) {\n bundlesToInject[i18nContext.currentLanguage] = bundle;\n }\n if (i18nContext.fallbackLanguage && i18nContext.fallbackLanguage !== metaLanguage) {\n bundlesToInject[i18nContext.fallbackLanguage] = bundle;\n }\n\n i18nContext.injectBundles(bundlesToInject);\n }, [meta?.i18n?.translations, i18nContext?.injectBundles]);\n\n const value: any = {\n error,\n fetchFlowMeta,\n isLoading,\n meta,\n switchLanguage,\n };\n\n return <FlowMetaContext.Provider value={value}>{children}</FlowMetaContext.Provider>;\n};\n\nexport default FlowMetaProvider;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,MAAMA,oBAAkE,EACtE,UACA,UAAU,MACV,cAAc,WAC8C;CAC5D,MAAM,EAAC,SAAS,WAAW,eAAe,kBAAiBC,8BAAc;CACzE,MAAMC,cAAgCC,yBAAS;CAE/C,MAAM,CAAC,MAAM,+BAAiD,YAAY;CAC1E,MAAM,CAAC,WAAW,oCAAkC,CAAC,YAAY;CACjE,MAAM,CAAC,OAAO,gCAAmC,KAAK;CACtD,MAAM,CAAC,iBAAiB,0CAA8C,KAAK;CAS3E,MAAMC,mCAA+F,KAAK;CAC1G,MAAMC,2CAAoD,MAAM;CAChE,MAAMC,uCAAiD,YAA2B;AAChF,MAAI,CAAC,SAAS;AACZ,WAAQ,KAAK;AACb,gBAAa,MAAM;AACnB;;AAMF,MAAI,CAAC,iBAAiB,CAAC,cACrB;AAGF,eAAa,KAAK;AAClB,WAAS,KAAK;AAEd,MAAI;AAOF,WANqC,2CAAkB;IACrD;IACA,sDAA6B,YAAY,EAAC,WAAU,CAAC;IACrD,GA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uBAAuB,SAAS;AACnC,0BAAuB,UAAU;AAEjC,OAAI,aAAa;AAGf,mBAAe,UAAU;AACzB;;;AAIJ,MAAI,eAAe,YAAY,cAG7B;AAGF,iBAAe,UAAU;AACzB,iBAAe;IAEd,CAAC,cAAc,CAAC;AAInB,4BAAgB;AACd,MAAI,CAAC,MAAM,MAAM,gBAAgB,CAAC,aAAa,cAC7C;EAGF,MAAMM,eAAuB,KAAK,KAAK,YAAYC,+CAA2B;EAI9E,MAAMJ,mBAA2C,EAAE;AACnD,SAAO,QAAQ,KAAK,KAAK,aAAa,CAAC,SAAS,CAAC,WAAW,UAA4C;AACtG,UAAO,QAAQ,KAAK,CAAC,SAAS,CAAC,KAAKC,aAA6B;AAC/D,qBAAiB,GAAG,UAAU,GAAG,SAASA;KAC1C;IACF;EAEF,MAAMC,SAAqB,EAAC,cAAc,kBAAiB;EAI3D,MAAMG,kBAA8C,GAAE,eAAe,QAAO;AAC5E,MAAI,YAAY,mBAAmB,YAAY,oBAAoB,aACjE,iBAAgB,YAAY,mBAAmB;AAEjD,MAAI,YAAY,oBAAoB,YAAY,qBAAqB,aACnE,iBAAgB,YAAY,oBAAoB;AAGlD,cAAY,cAAc,gBAAgB;IACzC,CAAC,MAAM,MAAM,cAAc,aAAa,cAAc,CAAC;CAE1D,MAAMC,QAAa;EACjB;EACA;EACA;EACA;EACA;EACD;AAED,QAAO,2CAACC,gCAAgB;EAAgB;EAAQ;GAAoC;;AAGtF,+BAAe"}
@@ -1 +1 @@
1
- {"version":3,"file":"ThunderIDContext.cjs","names":["ThunderIDContext: Context<ThunderIDContextProps | null>","VendorConstants"],"sources":["../../../../src/contexts/ThunderID/ThunderIDContext.ts"],"sourcesContent":["/**\n * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).\n *\n * WSO2 LLC. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport {\n FlowMetadataResponse,\n HttpRequestConfig,\n HttpResponse,\n IdToken,\n OIDCDiscoveryApiResponse,\n SignInOptions,\n TokenExchangeRequestConfig,\n TokenResponse,\n VendorConstants,\n} from '@thunderid/browser';\nimport {Context, createContext} from 'react';\nimport {ThunderIDReactConfig} from '../../models/config';\nimport ThunderIDReactClient from '../../ThunderIDReactClient';\n\n/**\n * Props interface of {@link ThunderIDContext}\n */\nexport type ThunderIDContextProps = {\n afterSignInUrl: string | undefined;\n applicationId: string | undefined;\n baseUrl: string | undefined;\n clientId: string | undefined;\n preferences?: ThunderIDReactConfig['preferences'];\n scopes: string | string[] | undefined;\n /**\n * OIDC discovery data.\n */\n discovery: {\n /**\n * The response from the `.well-known/openid-configuration` endpoint.\n * Contains server capabilities, supported endpoints, and metadata.\n * `null` while loading or when discovery has not been fetched.\n */\n wellKnown: OIDCDiscoveryApiResponse | null;\n };\n /**\n * Swaps the current access token with a new one based on the provided configuration (with a grant type).\n * @param config - Configuration for the token exchange request.\n * @returns A promise that resolves to the token response or the raw response.\n */\n exchangeToken: (config: TokenExchangeRequestConfig) => Promise<TokenResponse | Response>;\n /**\n * Retrieves the access token stored in the storage.\n * This function retrieves the access token and returns it.\n * @remarks This does not work in the `webWorker` or any other worker environment.\n * @returns A promise that resolves to the access token.\n */\n getAccessToken: () => Promise<string>;\n /**\n * Function to retrieve the decoded ID token.\n * This function decodes the ID token and returns its payload.\n * It can be used to access user claims and other information contained in the ID token.\n *\n * @returns A promise that resolves to the decoded ID token payload.\n */\n getDecodedIdToken: () => Promise<IdToken>;\n /**\n * Function to retrieve the ID token.\n * This function retrieves the ID token and returns it.\n *\n * @returns A promise that resolves to the ID token.\n */\n getIdToken: () => Promise<string>;\n /**\n * Returns the underlying StorageManager instance for reading and writing SDK-managed storage.\n */\n getStorageManager: () => Promise<any>;\n /**\n * HTTP request function to make API calls.\n * @param requestConfig - Configuration for the HTTP request.\n * @returns A promise that resolves to the HTTP response.\n */\n http: {\n /**\n * Makes an HTTP request using the provided configuration.\n * @param requestConfig - Configuration for the HTTP request.\n * @returns A promise that resolves to the HTTP response.\n */\n request: (requestConfig?: HttpRequestConfig) => Promise<HttpResponse<any>>;\n /**\n * Makes multiple HTTP requests based on the provided configuration.\n * @param requestConfigs - Set of configurations for the HTTP requests.\n * @returns A promise that resolves to an array of HTTP responses.\n */\n requestAll: (requestConfigs?: HttpRequestConfig[]) => Promise<HttpResponse<any>[]>;\n };\n /**\n * Instance ID for multi-instance support.\n */\n instanceId: number;\n isInitialized: boolean;\n /**\n * Flag indicating whether the SDK is working in the background.\n */\n isLoading: boolean;\n /**\n * Flag indicating whether flow metadata is currently being fetched.\n */\n isMetaLoading: boolean;\n /**\n * Flag indicating whether the user is signed in or not.\n */\n isSignedIn: boolean;\n\n /**\n * Flow metadata returned by `GET /flow/meta` (v2 platform only).\n * `null` while loading or when `resolveFromMeta` is disabled.\n */\n meta: FlowMetadataResponse | null;\n\n organizationHandle: string | undefined;\n\n /**\n * Re-initializes the client with a new configuration.\n *\n * @remarks\n * This can be partial configuration to update only specific fields.\n *\n * @param config - New configuration to re-initialize the client with.\n * @returns Promise resolving to boolean indicating success.\n */\n reInitialize: (config: Partial<ThunderIDReactConfig>) => Promise<boolean>;\n\n /**\n * Recovery function to initiate the account/password recovery flow.\n */\n recover: (...args: any[]) => Promise<any>;\n\n /**\n * Resolves `{{ t(key) }}` and `{{ meta(path) }}` template expressions in a string,\n * using the current i18n translation function and flow metadata from context.\n *\n * Useful in render-props patterns where consumers need to expand template strings\n * that come from the server (e.g. component labels, placeholders, headings).\n *\n * @example\n * const {resolveFlowTemplateLiterals} = useThunderID();\n * resolveFlowTemplateLiterals('{{ t(signin.heading.label) }}') // → 'Sign In'\n * resolveFlowTemplateLiterals('Login to {{ meta(application.name) }}') // → 'Login to My App'\n */\n resolveFlowTemplateLiterals: (text: string | undefined) => string;\n\n /**\n * Sign-in function to initiate the authentication process.\n * @remark This is the programmatic version of the `SignInButton` component.\n * TODO: Fix the types.\n */\n signIn: (...args: any) => Promise<any>;\n\n /**\n * Optional additional parameters to be sent in the sign-in request.\n * This can include custom parameters that your authorization server supports.\n * These parameters will be included in the authorization request sent to the server.\n * If not provided, no additional parameters will be sent.\n *\n * @example\n * signInOptions: { prompt: \"login\", fidp: \"OrganizationSSO\" }\n */\n signInOptions?: SignInOptions;\n\n /**\n * Optional token request configuration. params are appended to the token endpoint POST body.\n *\n * @example\n * tokenRequest: { params: { resource: \"https://api.example.com\" } }\n */\n tokenRequest?: {\n params?: Record<string, unknown>;\n };\n\n /**\n * Silent sign-in function to re-authenticate the user without user interaction.\n * @remark This is the programmatic version of the `SilentSignIn` component.\n */\n signInSilently: ThunderIDReactClient['signInSilently'];\n\n signInUrl: string | undefined;\n /**\n * Sign-out function to terminate the authentication session.\n * @remark This is the programmatic version of the `SignOutButton` component.\n * FIXME: Fix the types.\n */\n signOut: any;\n\n /**\n * Sign-up function to initiate the registration process.\n * @remark This is the programmatic version of the `SignUpButton` component.\n */\n signUp: (...args: any[]) => Promise<any>;\n\n signUpUrl: string | undefined;\n\n user: any;\n\n /**\n * Vendor/brand namespace used to prefix storage keys, cookie names, and CSS class names.\n * Resolved from the `vendor` config option, defaulting to `'thunderid'`.\n */\n vendor: string;\n} & Pick<ThunderIDReactClient, 'clearSession'>;\n\n/**\n * Context object for managing the Authentication flow builder core context.\n */\nconst ThunderIDContext: Context<ThunderIDContextProps | null> = createContext<null | ThunderIDContextProps>({\n afterSignInUrl: undefined,\n applicationId: undefined,\n baseUrl: undefined,\n clearSession: () => {},\n clientId: undefined,\n preferences: undefined,\n scopes: undefined,\n discovery: {\n wellKnown: null,\n },\n exchangeToken: null as unknown as ThunderIDContextProps['exchangeToken'],\n getAccessToken: null as unknown as ThunderIDContextProps['getAccessToken'],\n getDecodedIdToken: null as unknown as ThunderIDContextProps['getDecodedIdToken'],\n getIdToken: null as unknown as ThunderIDContextProps['getIdToken'],\n getStorageManager: () => Promise.resolve(null),\n http: {\n request: () => null as unknown as Promise<HttpResponse<any>>,\n requestAll: () => null as unknown as Promise<HttpResponse<any>[]>,\n },\n instanceId: 0,\n isInitialized: false,\n isLoading: true,\n isMetaLoading: false,\n isSignedIn: false,\n meta: null,\n organizationHandle: undefined,\n reInitialize: null as unknown as ThunderIDContextProps['reInitialize'],\n recover: () => Promise.resolve({} as any),\n resolveFlowTemplateLiterals: (text: string | undefined) => text ?? '',\n signIn: () => Promise.resolve({} as any),\n signInSilently: () => Promise.resolve({} as any),\n signInUrl: undefined,\n signOut: () => Promise.resolve({} as any),\n signUp: () => Promise.resolve({} as any),\n signUpUrl: undefined,\n user: null,\n vendor: VendorConstants.VENDOR_PREFIX,\n});\n\nThunderIDContext.displayName = 'ThunderIDContext';\n\nexport default ThunderIDContext;\n"],"mappings":";;;;;;;;;;AA+NA,MAAMA,4CAAsG;CAC1G,gBAAgB;CAChB,eAAe;CACf,SAAS;CACT,oBAAoB;CACpB,UAAU;CACV,aAAa;CACb,QAAQ;CACR,WAAW,EACT,WAAW,MACZ;CACD,eAAe;CACf,gBAAgB;CAChB,mBAAmB;CACnB,YAAY;CACZ,yBAAyB,QAAQ,QAAQ,KAAK;CAC9C,MAAM;EACJ,eAAe;EACf,kBAAkB;EACnB;CACD,YAAY;CACZ,eAAe;CACf,WAAW;CACX,eAAe;CACf,YAAY;CACZ,MAAM;CACN,oBAAoB;CACpB,cAAc;CACd,eAAe,QAAQ,QAAQ,EAAE,CAAQ;CACzC,8BAA8B,SAA6B,QAAQ;CACnE,cAAc,QAAQ,QAAQ,EAAE,CAAQ;CACxC,sBAAsB,QAAQ,QAAQ,EAAE,CAAQ;CAChD,WAAW;CACX,eAAe,QAAQ,QAAQ,EAAE,CAAQ;CACzC,cAAc,QAAQ,QAAQ,EAAE,CAAQ;CACxC,WAAW;CACX,MAAM;CACN,QAAQC,oCAAgB;CACzB,CAAC;AAEF,iBAAiB,cAAc;AAE/B,+BAAe"}
1
+ {"version":3,"file":"ThunderIDContext.cjs","names":["ThunderIDContext: Context<ThunderIDContextProps | null>","VendorConstants"],"sources":["../../../../src/contexts/ThunderID/ThunderIDContext.ts"],"sourcesContent":["/**\n * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).\n *\n * WSO2 LLC. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport {\n FlowMetadataResponse,\n HttpRequestConfig,\n HttpResponse,\n IdToken,\n OIDCDiscoveryApiResponse,\n SignInOptions,\n TokenExchangeRequestConfig,\n TokenResponse,\n VendorConstants,\n} from '@thunderid/browser';\nimport {Context, createContext} from 'react';\nimport {ThunderIDReactConfig} from '../../models/config';\nimport ThunderIDReactClient from '../../ThunderIDReactClient';\n\n/**\n * Props interface of {@link ThunderIDContext}\n */\nexport type ThunderIDContextProps = {\n afterSignInUrl: string | undefined;\n applicationId: string | undefined;\n baseUrl: string | undefined;\n clientId: string | undefined;\n /**\n * Optional endpoint URL overrides from the client config. Used to resolve resource-server\n * endpoints (e.g. flow/user-management) independently of `baseUrl` — see `resolveResourceEndpoint`.\n */\n endpoints?: ThunderIDReactConfig['endpoints'];\n preferences?: ThunderIDReactConfig['preferences'];\n scopes: string | string[] | undefined;\n /**\n * OIDC discovery data.\n */\n discovery: {\n /**\n * The response from the `.well-known/openid-configuration` endpoint.\n * Contains server capabilities, supported endpoints, and metadata.\n * `null` while loading or when discovery has not been fetched.\n */\n wellKnown: OIDCDiscoveryApiResponse | null;\n };\n /**\n * Swaps the current access token with a new one based on the provided configuration (with a grant type).\n * @param config - Configuration for the token exchange request.\n * @returns A promise that resolves to the token response or the raw response.\n */\n exchangeToken: (config: TokenExchangeRequestConfig) => Promise<TokenResponse | Response>;\n /**\n * Retrieves the access token stored in the storage.\n * This function retrieves the access token and returns it.\n * @remarks This does not work in the `webWorker` or any other worker environment.\n * @returns A promise that resolves to the access token.\n */\n getAccessToken: () => Promise<string>;\n /**\n * Function to retrieve the decoded ID token.\n * This function decodes the ID token and returns its payload.\n * It can be used to access user claims and other information contained in the ID token.\n *\n * @returns A promise that resolves to the decoded ID token payload.\n */\n getDecodedIdToken: () => Promise<IdToken>;\n /**\n * Function to retrieve the ID token.\n * This function retrieves the ID token and returns it.\n *\n * @returns A promise that resolves to the ID token.\n */\n getIdToken: () => Promise<string>;\n /**\n * Returns the underlying StorageManager instance for reading and writing SDK-managed storage.\n */\n getStorageManager: () => Promise<any>;\n /**\n * HTTP request function to make API calls.\n * @param requestConfig - Configuration for the HTTP request.\n * @returns A promise that resolves to the HTTP response.\n */\n http: {\n /**\n * Makes an HTTP request using the provided configuration.\n * @param requestConfig - Configuration for the HTTP request.\n * @returns A promise that resolves to the HTTP response.\n */\n request: (requestConfig?: HttpRequestConfig) => Promise<HttpResponse<any>>;\n /**\n * Makes multiple HTTP requests based on the provided configuration.\n * @param requestConfigs - Set of configurations for the HTTP requests.\n * @returns A promise that resolves to an array of HTTP responses.\n */\n requestAll: (requestConfigs?: HttpRequestConfig[]) => Promise<HttpResponse<any>[]>;\n };\n /**\n * Instance ID for multi-instance support.\n */\n instanceId: number;\n isInitialized: boolean;\n /**\n * Flag indicating whether the SDK is working in the background.\n */\n isLoading: boolean;\n /**\n * Flag indicating whether flow metadata is currently being fetched.\n */\n isMetaLoading: boolean;\n /**\n * Flag indicating whether the user is signed in or not.\n */\n isSignedIn: boolean;\n\n /**\n * Flow metadata returned by `GET /flow/meta` (v2 platform only).\n * `null` while loading or when `resolveFromMeta` is disabled.\n */\n meta: FlowMetadataResponse | null;\n\n organizationHandle: string | undefined;\n\n /**\n * Re-initializes the client with a new configuration.\n *\n * @remarks\n * This can be partial configuration to update only specific fields.\n *\n * @param config - New configuration to re-initialize the client with.\n * @returns Promise resolving to boolean indicating success.\n */\n reInitialize: (config: Partial<ThunderIDReactConfig>) => Promise<boolean>;\n\n /**\n * Recovery function to initiate the account/password recovery flow.\n */\n recover: (...args: any[]) => Promise<any>;\n\n /**\n * Resolves `{{ t(key) }}` and `{{ meta(path) }}` template expressions in a string,\n * using the current i18n translation function and flow metadata from context.\n *\n * Useful in render-props patterns where consumers need to expand template strings\n * that come from the server (e.g. component labels, placeholders, headings).\n *\n * @example\n * const {resolveFlowTemplateLiterals} = useThunderID();\n * resolveFlowTemplateLiterals('{{ t(signin.heading.label) }}') // → 'Sign In'\n * resolveFlowTemplateLiterals('Login to {{ meta(application.name) }}') // → 'Login to My App'\n */\n resolveFlowTemplateLiterals: (text: string | undefined) => string;\n\n /**\n * Sign-in function to initiate the authentication process.\n * @remark This is the programmatic version of the `SignInButton` component.\n * TODO: Fix the types.\n */\n signIn: (...args: any) => Promise<any>;\n\n /**\n * Optional additional parameters to be sent in the sign-in request.\n * This can include custom parameters that your authorization server supports.\n * These parameters will be included in the authorization request sent to the server.\n * If not provided, no additional parameters will be sent.\n *\n * @example\n * signInOptions: { prompt: \"login\", fidp: \"OrganizationSSO\" }\n */\n signInOptions?: SignInOptions;\n\n /**\n * Optional token request configuration. params are appended to the token endpoint POST body.\n *\n * @example\n * tokenRequest: { params: { resource: \"https://api.example.com\" } }\n */\n tokenRequest?: {\n params?: Record<string, unknown>;\n };\n\n /**\n * Silent sign-in function to re-authenticate the user without user interaction.\n * @remark This is the programmatic version of the `SilentSignIn` component.\n */\n signInSilently: ThunderIDReactClient['signInSilently'];\n\n signInUrl: string | undefined;\n /**\n * Sign-out function to terminate the authentication session.\n * @remark This is the programmatic version of the `SignOutButton` component.\n * FIXME: Fix the types.\n */\n signOut: any;\n\n /**\n * Sign-up function to initiate the registration process.\n * @remark This is the programmatic version of the `SignUpButton` component.\n */\n signUp: (...args: any[]) => Promise<any>;\n\n signUpUrl: string | undefined;\n\n user: any;\n\n /**\n * Vendor/brand namespace used to prefix storage keys, cookie names, and CSS class names.\n * Resolved from the `vendor` config option, defaulting to `'thunderid'`.\n */\n vendor: string;\n} & Pick<ThunderIDReactClient, 'clearSession'>;\n\n/**\n * Context object for managing the Authentication flow builder core context.\n */\nconst ThunderIDContext: Context<ThunderIDContextProps | null> = createContext<null | ThunderIDContextProps>({\n afterSignInUrl: undefined,\n applicationId: undefined,\n baseUrl: undefined,\n clearSession: () => {},\n clientId: undefined,\n preferences: undefined,\n scopes: undefined,\n discovery: {\n wellKnown: null,\n },\n exchangeToken: null as unknown as ThunderIDContextProps['exchangeToken'],\n getAccessToken: null as unknown as ThunderIDContextProps['getAccessToken'],\n getDecodedIdToken: null as unknown as ThunderIDContextProps['getDecodedIdToken'],\n getIdToken: null as unknown as ThunderIDContextProps['getIdToken'],\n getStorageManager: () => Promise.resolve(null),\n http: {\n request: () => null as unknown as Promise<HttpResponse<any>>,\n requestAll: () => null as unknown as Promise<HttpResponse<any>[]>,\n },\n instanceId: 0,\n isInitialized: false,\n isLoading: true,\n isMetaLoading: false,\n isSignedIn: false,\n meta: null,\n organizationHandle: undefined,\n reInitialize: null as unknown as ThunderIDContextProps['reInitialize'],\n recover: () => Promise.resolve({} as any),\n resolveFlowTemplateLiterals: (text: string | undefined) => text ?? '',\n signIn: () => Promise.resolve({} as any),\n signInSilently: () => Promise.resolve({} as any),\n signInUrl: undefined,\n signOut: () => Promise.resolve({} as any),\n signUp: () => Promise.resolve({} as any),\n signUpUrl: undefined,\n user: null,\n vendor: VendorConstants.VENDOR_PREFIX,\n});\n\nThunderIDContext.displayName = 'ThunderIDContext';\n\nexport default ThunderIDContext;\n"],"mappings":";;;;;;;;;;AAoOA,MAAMA,4CAAsG;CAC1G,gBAAgB;CAChB,eAAe;CACf,SAAS;CACT,oBAAoB;CACpB,UAAU;CACV,aAAa;CACb,QAAQ;CACR,WAAW,EACT,WAAW,MACZ;CACD,eAAe;CACf,gBAAgB;CAChB,mBAAmB;CACnB,YAAY;CACZ,yBAAyB,QAAQ,QAAQ,KAAK;CAC9C,MAAM;EACJ,eAAe;EACf,kBAAkB;EACnB;CACD,YAAY;CACZ,eAAe;CACf,WAAW;CACX,eAAe;CACf,YAAY;CACZ,MAAM;CACN,oBAAoB;CACpB,cAAc;CACd,eAAe,QAAQ,QAAQ,EAAE,CAAQ;CACzC,8BAA8B,SAA6B,QAAQ;CACnE,cAAc,QAAQ,QAAQ,EAAE,CAAQ;CACxC,sBAAsB,QAAQ,QAAQ,EAAE,CAAQ;CAChD,WAAW;CACX,eAAe,QAAQ,QAAQ,EAAE,CAAQ;CACzC,cAAc,QAAQ,QAAQ,EAAE,CAAQ;CACxC,WAAW;CACX,MAAM;CACN,QAAQC,oCAAgB;CACzB,CAAC;AAEF,iBAAiB,cAAc;AAE/B,+BAAe"}
@@ -47,6 +47,7 @@ const ThunderIDProvider = ({ afterSignInUrl, afterSignOutUrl, baseUrl: initialBa
47
47
  });
48
48
  const [isUpdatingSession, setIsUpdatingSession] = (0, react.useState)(false);
49
49
  const [wellKnown, setWellKnown] = (0, react.useState)(null);
50
+ const pendingSessionUpdateRef = (0, react.useRef)(null);
50
51
  (0, react.useEffect)(() => {
51
52
  setBaseUrl(initialBaseUrl ?? "");
52
53
  }, [initialBaseUrl]);
@@ -57,7 +58,7 @@ const ThunderIDProvider = ({ afterSignInUrl, afterSignOutUrl, baseUrl: initialBa
57
58
  setWellKnown(await client.getDiscoveryResponse());
58
59
  })();
59
60
  }, []);
60
- async function updateSession() {
61
+ async function performSessionUpdate() {
61
62
  try {
62
63
  setIsUpdatingSession(true);
63
64
  setIsLoadingSync(true);
@@ -74,6 +75,7 @@ const ThunderIDProvider = ({ afterSignInUrl, afterSignOutUrl, baseUrl: initialBa
74
75
  if (currentSignInStatus && shouldFetchProfile) try {
75
76
  const fetchedProfile = await require_getUsersMe.default({
76
77
  baseUrl: resolvedBaseUrl,
78
+ url: (0, __thunderid_browser.resolveResourceEndpoint)("usersMe", config),
77
79
  instanceId
78
80
  });
79
81
  profileData = {
@@ -94,6 +96,20 @@ const ThunderIDProvider = ({ afterSignInUrl, afterSignOutUrl, baseUrl: initialBa
94
96
  setIsLoadingSync(client.isLoading());
95
97
  }
96
98
  }
99
+ /**
100
+ * Single-flight wrapper around {@link performSessionUpdate}.
101
+ *
102
+ * Concurrent callers share the in-flight request instead of each issuing their own `/users/me`.
103
+ * This is not a cache: once the request settles the ref is cleared, so a later caller (e.g.
104
+ * revalidation after a profile update) fetches again.
105
+ */
106
+ async function updateSession() {
107
+ if (pendingSessionUpdateRef.current) return pendingSessionUpdateRef.current;
108
+ pendingSessionUpdateRef.current = performSessionUpdate().finally(() => {
109
+ pendingSessionUpdateRef.current = null;
110
+ });
111
+ return pendingSessionUpdateRef.current;
112
+ }
97
113
  async function signIn(...args) {
98
114
  const arg1 = args[0];
99
115
  const isV2FlowRequest = typeof arg1 === "object" && arg1 !== null && ("executionId" in arg1 || "applicationId" in arg1);
@@ -122,22 +138,13 @@ const ThunderIDProvider = ({ afterSignInUrl, afterSignOutUrl, baseUrl: initialBa
122
138
  await client.on("sign-in", async () => {
123
139
  await updateSession();
124
140
  });
125
- const isAlreadySignedIn = await client.isSignedIn();
126
- const scheduleAutoRefresh = async () => {
127
- try {
128
- await client.startAutoRefreshToken();
129
- } catch (error) {
130
- logger.warn("Failed to schedule automatic token refresh.", error);
131
- }
132
- };
133
- const resumeSession = async () => {
134
- await updateSession();
135
- await scheduleAutoRefresh();
136
- };
137
- if (isAlreadySignedIn) await resumeSession();
138
- await scheduleAutoRefresh();
141
+ try {
142
+ await client.startAutoRefreshToken();
143
+ } catch (error) {
144
+ logger.warn("Failed to schedule automatic token refresh.", error);
145
+ }
139
146
  if (await client.isSignedIn()) {
140
- await resumeSession();
147
+ await updateSession();
141
148
  return;
142
149
  }
143
150
  const currentUrl = new URL(window.location.href);
@@ -241,11 +248,19 @@ const ThunderIDProvider = ({ afterSignInUrl, afterSignOutUrl, baseUrl: initialBa
241
248
  const recover = (0, react.useCallback)(async (payload) => client.recover(payload), [client]);
242
249
  const signUp = (0, react.useCallback)(async (...args) => client.signUp(...args), [client]);
243
250
  const clearSession = (0, react.useCallback)(async (...args) => client.clearSession(...args), [client]);
244
- const reInitialize = (0, react.useCallback)(async (reInitConfig) => client.reInitialize(reInitConfig), [client]);
251
+ const reInitialize = (0, react.useCallback)(async (reInitConfig) => {
252
+ const result = await client.reInitialize(reInitConfig);
253
+ const reinitializedConfig = await client.getConfiguration();
254
+ setConfig(reinitializedConfig);
255
+ setBaseUrl(reinitializedConfig.baseUrl ?? "");
256
+ setWellKnown(await client.getDiscoveryResponse());
257
+ return result;
258
+ }, [client]);
245
259
  const value = (0, react.useMemo)(() => ({
246
260
  afterSignInUrl: config.afterSignInUrl,
247
261
  applicationId: config.applicationId,
248
262
  baseUrl,
263
+ endpoints: config.endpoints,
249
264
  scopes: config.scopes,
250
265
  clearSession,
251
266
  clientId,
@@ -284,6 +299,7 @@ const ThunderIDProvider = ({ afterSignInUrl, afterSignOutUrl, baseUrl: initialBa
284
299
  config?.organizationHandle,
285
300
  config.vendor,
286
301
  config.afterSignInUrl,
302
+ config.endpoints,
287
303
  config.scopes,
288
304
  signInUrl,
289
305
  signUpUrl,
@@ -1 +1 @@
1
- {"version":3,"file":"ThunderIDProvider.cjs","names":["logger: ReturnType<typeof createPackageComponentLogger>","ThunderIDProvider: FC<PropsWithChildren<ThunderIDProviderProps>>","reRenderCheckRef: RefObject<boolean>","client: ThunderIDReactClient","ThunderIDReactClient","storageManagerRef: any","useBrowserUrl","resolvedBaseUrl: string","decodedToken: IdToken","shouldFetchProfile: boolean","claims: User","currentSignInStatus: boolean","getUsersMe","arg1: any","isV2FlowRequest: boolean","ThunderIDRuntimeError","isAlreadySignedIn: boolean","currentUrl: URL","urlParams: URLSearchParams","code: string | null","executionIdFromUrl: string | null","storedExecutionId: string | null","interval: NodeJS.Timeout","status: boolean","getDecodedIdToken: () => Promise<IdToken>","getIdToken: () => Promise<string>","getAccessToken: () => Promise<string>","getStorageManager: () => Promise<any>","storageManager: any","request: (...args: any[]) => Promise<any>","requestAll: (...args: any[]) => Promise<any>","exchangeToken: (exchangeConfig: any) => Promise<any>","signOut: (...args: any[]) => Promise<any>","recover: (payload: any) => Promise<any>","signUp: (...args: any[]) => Promise<any>","clearSession: (...args: any[]) => Promise<any>","reInitialize: (reInitConfig: any) => Promise<any>","value: any","ThunderIDContext","I18nProvider","FlowMetaProvider","ThemeProvider","FlowProvider","UserProvider","ComponentRendererProvider"],"sources":["../../../../src/contexts/ThunderID/ThunderIDProvider.tsx"],"sourcesContent":["/**\n * Copyright (c) 2025-2026, WSO2 LLC. (https://www.wso2.com).\n *\n * WSO2 LLC. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport {\n ThunderIDRuntimeError,\n generateFlattenedUserProfile,\n OIDCDiscoveryApiResponse,\n SignInOptions,\n User,\n UserProfile,\n IdToken,\n extractUserClaimsFromIdToken,\n EmbeddedSignInFlowResponse,\n createPackageComponentLogger,\n getVendorPrefix,\n} from '@thunderid/browser';\nimport {FC, RefObject, PropsWithChildren, ReactElement, useEffect, useMemo, useRef, useState, useCallback} from 'react';\nimport ThunderIDContext from './ThunderIDContext';\nimport useBrowserUrl from '../../hooks/useBrowserUrl';\nimport {ThunderIDReactConfig} from '../../models/config';\nimport ThunderIDReactClient from '../../ThunderIDReactClient';\nimport ComponentRendererProvider from '../ComponentRenderer/ComponentRendererProvider';\nimport FlowProvider from '../Flow/FlowProvider';\nimport FlowMetaProvider from '../FlowMeta/FlowMetaProvider';\nimport I18nProvider from '../I18n/I18nProvider';\nimport ThemeProvider from '../Theme/ThemeProvider';\nimport UserProvider from '../User/UserProvider';\nimport getUsersMe from '../../api/getUsersMe';\n\nconst logger: ReturnType<typeof createPackageComponentLogger> = createPackageComponentLogger(\n '@thunderid/react',\n 'ThunderIDProvider',\n);\n\n/**\n * Props interface of {@link ThunderIDProvider}\n */\nexport type ThunderIDProviderProps = ThunderIDReactConfig;\n\nconst ThunderIDProvider: FC<PropsWithChildren<ThunderIDProviderProps>> = ({\n afterSignInUrl,\n afterSignOutUrl,\n baseUrl: initialBaseUrl,\n clientId,\n children,\n extensions,\n scopes,\n preferences,\n signInUrl,\n signUpUrl,\n organizationHandle,\n applicationId,\n signInOptions,\n tokenRequest,\n syncSession,\n instanceId = 0,\n organizationChain,\n ...rest\n}: PropsWithChildren<ThunderIDProviderProps>): ReactElement => {\n const reRenderCheckRef: RefObject<boolean> = useRef(false);\n const client: ThunderIDReactClient = useMemo(() => new ThunderIDReactClient(instanceId), [instanceId]);\n const storageManagerRef: any = useRef<any>(null);\n const {hasAuthParams, hasCalledForThisInstance} = useBrowserUrl();\n const [user, setUser] = useState<any | null>(null);\n const [isSignedInSync, setIsSignedInSync] = useState<boolean>(false);\n const [isInitializedSync, setIsInitializedSync] = useState<boolean>(false);\n const [isLoadingSync, setIsLoadingSync] = useState<boolean>(true);\n\n const [userProfile, setUserProfile] = useState<UserProfile | null>(null);\n const [baseUrl, setBaseUrl] = useState<string>(initialBaseUrl ?? '');\n const [config, setConfig] = useState<ThunderIDReactConfig>({\n afterSignInUrl: afterSignInUrl ?? window.location.origin,\n afterSignOutUrl: afterSignOutUrl ?? window.location.origin,\n applicationId,\n baseUrl,\n clientId,\n organizationChain,\n organizationHandle,\n scopes,\n signInOptions,\n tokenRequest,\n signInUrl,\n signUpUrl,\n syncSession,\n ...rest,\n });\n\n const [isUpdatingSession, setIsUpdatingSession] = useState<boolean>(false);\n const [wellKnown, setWellKnown] = useState<OIDCDiscoveryApiResponse | null>(null);\n\n useEffect(() => {\n setBaseUrl(initialBaseUrl ?? '');\n }, [initialBaseUrl]);\n\n useEffect(() => {\n (async (): Promise<void> => {\n await client.initialize(config);\n const initializedConfig: ThunderIDReactConfig = await client.getConfiguration();\n setConfig(initializedConfig);\n setWellKnown(await client.getDiscoveryResponse());\n })();\n }, []);\n\n async function updateSession(): Promise<void> {\n try {\n // Set flag to prevent loading state tracking from interfering\n setIsUpdatingSession(true);\n setIsLoadingSync(true);\n let resolvedBaseUrl: string = baseUrl;\n\n const decodedToken: IdToken = await client.getDecodedIdToken();\n\n // If there's a `user_org` claim in the ID token,\n // Treat this login as a organization login.\n if (decodedToken?.['user_org']) {\n resolvedBaseUrl = `${(await client.getConfiguration()).baseUrl}/o`;\n setBaseUrl(resolvedBaseUrl);\n }\n\n const shouldFetchProfile: boolean = preferences?.user?.fetchUserProfile !== false;\n const claims: User = extractUserClaimsFromIdToken(decodedToken) as User;\n let profileData = claims;\n const currentSignInStatus: boolean = await client.isSignedIn();\n\n if (currentSignInStatus && shouldFetchProfile) {\n try {\n const fetchedProfile = await getUsersMe({baseUrl: resolvedBaseUrl, instanceId});\n profileData = {...claims, ...fetchedProfile};\n } catch (err) {\n logger.warn('Failed to fetch user profile from /users/me:', err);\n }\n }\n\n setUser(profileData);\n setUserProfile({\n flattenedProfile: generateFlattenedUserProfile(profileData, []),\n profile: profileData,\n });\n\n // CRITICAL: Update sign-in status BEFORE setting loading to false\n // This prevents the race condition where ProtectedRoute sees isLoading=false but isSignedIn=false\n setIsSignedInSync(currentSignInStatus);\n } catch (error) {\n // TODO: Add an error log.\n } finally {\n // Clear the flag and set final loading state\n setIsUpdatingSession(false);\n setIsLoadingSync(client.isLoading());\n }\n }\n\n async function signIn(...args: any): Promise<User | EmbeddedSignInFlowResponse> {\n // Check if this is a V2 embedded flow request BEFORE calling signIn\n // This allows us to skip session checks entirely for V2 flows\n const arg1: any = args[0];\n const isV2FlowRequest: boolean =\n typeof arg1 === 'object' && arg1 !== null && ('executionId' in arg1 || 'applicationId' in arg1);\n\n try {\n if (!isV2FlowRequest) {\n setIsUpdatingSession(true);\n setIsLoadingSync(true);\n }\n\n return await client.signIn(...args);\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Sign in failed: ${error instanceof Error ? error.message : String(JSON.stringify(error))}`,\n 'thunderid-signIn-Error',\n 'react',\n 'An error occurred while trying to sign in.',\n );\n } finally {\n if (!isV2FlowRequest) {\n setIsUpdatingSession(false);\n setIsLoadingSync(client.isLoading());\n }\n }\n }\n\n /**\n * Try signing in when the component is mounted.\n */\n useEffect(() => {\n // React 18.x Strict.Mode has a new check for `Ensuring reusable state` to facilitate an upcoming react feature.\n // https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state\n // This will remount all the useEffects to ensure that there are no unexpected side effects.\n // When react remounts the signIn hook of the AuthProvider, it will cause a race condition. Hence, we have to\n // prevent the re-render of this hook as suggested in the following discussion.\n // https://github.com/reactwg/react-18/discussions/18#discussioncomment-795623\n if (reRenderCheckRef.current) {\n return;\n }\n\n reRenderCheckRef.current = true;\n\n (async (): Promise<void> => {\n // Sync session state whenever sign-in completes (both redirect and embedded V2 flows).\n // Pass the user returned by the SDK's sign-in flow so users/me result is not discarded.\n await client.on('sign-in', async () => {\n await updateSession();\n });\n\n // User is already authenticated. Skip...\n const isAlreadySignedIn: boolean = await client.isSignedIn();\n\n // Start auto-refresh with a soft failure.\n const scheduleAutoRefresh = async (): Promise<void> => {\n try {\n await client.startAutoRefreshToken();\n } catch (error) {\n logger.warn('Failed to schedule automatic token refresh.', error);\n }\n };\n\n // Restore session state and kick off the refresh timer.\n const resumeSession = async (): Promise<void> => {\n await updateSession();\n await scheduleAutoRefresh();\n };\n\n if (isAlreadySignedIn) {\n await resumeSession();\n }\n\n // The access token may have expired while the refresh token is still valid.\n // Attempt a silent refresh — startAutoRefreshToken() calls refreshAccessToken()\n // immediately when timeUntilRefresh <= 0, then re-check sign-in status.\n await scheduleAutoRefresh();\n\n if (await client.isSignedIn()) {\n await resumeSession();\n return;\n }\n\n const currentUrl: URL = new URL(window.location.href);\n const hasAuthParamsResult: boolean =\n hasAuthParams(currentUrl, config.afterSignInUrl!) && hasCalledForThisInstance(currentUrl, instanceId ?? 0);\n\n if (hasAuthParamsResult) {\n try {\n const urlParams: URLSearchParams = currentUrl.searchParams;\n const code: string | null = urlParams.get('code');\n const executionIdFromUrl: string | null = urlParams.get('executionId');\n const storedExecutionId: string | null = sessionStorage.getItem(\n `${getVendorPrefix(config.vendor)}_execution_id`,\n );\n\n if (code && !executionIdFromUrl && !storedExecutionId) {\n await signIn();\n }\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Sign in failed: ${error instanceof Error ? error.message : String(JSON.stringify(error))}`,\n 'thunderid-signIn-Error',\n 'react',\n 'An error occurred while trying to sign in.',\n );\n }\n }\n })();\n }, []);\n\n /**\n * Check if the user is signed in and update the state accordingly.\n * This will also set an interval to check for the sign-in status every second\n * until the user is signed in.\n */\n useEffect(() => {\n let interval: NodeJS.Timeout;\n\n (async (): Promise<void> => {\n try {\n const status: boolean = await client.isSignedIn();\n\n setIsSignedInSync(status);\n\n if (!status) {\n interval = setInterval(async () => {\n const newStatus: boolean = await client.isSignedIn();\n\n if (newStatus) {\n setIsSignedInSync(true);\n clearInterval(interval);\n }\n }, 1000);\n } else {\n // TODO: Add a debug log to indicate that the user is already signed in.\n }\n } catch (error) {\n setIsSignedInSync(false);\n }\n })();\n\n return (): void => {\n if (interval) {\n clearInterval(interval);\n }\n };\n }, [client]);\n\n useEffect(() => {\n (async (): Promise<void> => {\n try {\n const status: boolean = await client.isInitialized();\n\n setIsInitializedSync(status);\n } catch (error) {\n setIsInitializedSync(false);\n }\n })();\n }, [client]);\n\n /**\n * Track loading state changes from the ThunderID client\n */\n useEffect(() => {\n const checkLoadingState = (): void => {\n // Don't override loading state during critical session updates\n if (isUpdatingSession) {\n return;\n }\n\n // Don't set loading=false while auth params are in the URL and user isn't signed in yet.\n // This prevents ProtectedRoute from redirecting before the sign-in effect processes the auth code.\n const currentUrl: URL = new URL(window.location.href);\n if (!isSignedInSync && hasAuthParams(currentUrl, config.afterSignInUrl!)) {\n return;\n }\n\n setIsLoadingSync(client.isLoading());\n };\n\n // Initial check\n checkLoadingState();\n\n // Set up an interval to check for loading state changes\n const interval: NodeJS.Timeout = setInterval(checkLoadingState, 100);\n\n return (): void => {\n clearInterval(interval);\n };\n }, [client, isLoadingSync, isSignedInSync, isUpdatingSession]);\n\n const signInSilently = async (options?: SignInOptions): Promise<User | boolean> => {\n try {\n setIsUpdatingSession(true);\n setIsLoadingSync(true);\n return await client.signInSilently(options);\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Error while signing in silently: ${error instanceof Error ? error.message : String(JSON.stringify(error))}`,\n 'thunderid-signInSilently-Error',\n 'react',\n 'An error occurred while trying to sign in silently.',\n );\n } finally {\n setIsUpdatingSession(false);\n setIsLoadingSync(client.isLoading());\n }\n };\n\n const handleProfileUpdate = (payload: User): void => {\n setUser(payload);\n setUserProfile((prev: UserProfile | null) => ({\n flattenedProfile: generateFlattenedUserProfile(payload),\n profile: payload,\n }));\n };\n\n const getDecodedIdToken: () => Promise<IdToken> = useCallback(\n async (): Promise<IdToken> => client.getDecodedIdToken(),\n [client],\n );\n\n const getIdToken: () => Promise<string> = useCallback(async (): Promise<string> => client.getIdToken(), [client]);\n\n const getAccessToken: () => Promise<string> = useCallback(\n async (): Promise<string> => client.getAccessToken(),\n [client],\n );\n\n const getStorageManager: () => Promise<any> = useCallback(async (): Promise<any> => {\n const storageManager: any = storageManagerRef.current ?? (await client.getStorageManager());\n if (storageManager) {\n storageManagerRef.current = storageManager;\n }\n return storageManager;\n }, [client]);\n\n const request: (...args: any[]) => Promise<any> = useCallback(\n async (...args: any[]): Promise<any> => client.request(...args),\n [client],\n );\n\n const requestAll: (...args: any[]) => Promise<any> = useCallback(\n async (...args: any[]): Promise<any> => client.requestAll(...args),\n [client],\n );\n\n const exchangeToken: (exchangeConfig: any) => Promise<any> = useCallback(\n async (exchangeConfig: any): Promise<any> => client.exchangeToken(exchangeConfig),\n [client],\n );\n\n const signOut: (...args: any[]) => Promise<any> = useCallback(\n async (...args: any[]): Promise<any> => client.signOut(...args),\n [client],\n );\n\n const recover: (payload: any) => Promise<any> = useCallback(\n async (payload: any): Promise<any> => client.recover(payload),\n [client],\n );\n\n const signUp: (...args: any[]) => Promise<any> = useCallback(\n async (...args: any[]): Promise<any> => client.signUp(...args),\n [client],\n );\n\n const clearSession: (...args: any[]) => Promise<any> = useCallback(\n async (...args: any[]): Promise<any> => client.clearSession(...args),\n [client],\n );\n\n const reInitialize: (reInitConfig: any) => Promise<any> = useCallback(\n async (reInitConfig: any): Promise<any> => client.reInitialize(reInitConfig),\n [client],\n );\n\n const value: any = useMemo(\n () => ({\n afterSignInUrl: config.afterSignInUrl,\n applicationId: config.applicationId,\n baseUrl,\n scopes: config.scopes,\n clearSession,\n clientId,\n discovery: {\n wellKnown,\n },\n exchangeToken,\n getAccessToken,\n getDecodedIdToken,\n getIdToken,\n getStorageManager,\n http: {\n request,\n requestAll,\n },\n instanceId,\n isInitialized: isInitializedSync,\n isLoading: isLoadingSync,\n isSignedIn: isSignedInSync,\n organizationChain,\n organizationHandle: config?.organizationHandle,\n preferences,\n reInitialize,\n recover,\n signIn,\n signInOptions,\n tokenRequest,\n signInSilently,\n signInUrl,\n signOut,\n signUp,\n signUpUrl,\n syncSession,\n user,\n vendor: getVendorPrefix(config.vendor),\n }),\n [\n applicationId,\n config?.organizationHandle,\n config.vendor,\n config.afterSignInUrl,\n config.scopes,\n signInUrl,\n signUpUrl,\n baseUrl,\n clientId,\n wellKnown,\n isInitializedSync,\n isLoadingSync,\n isSignedInSync,\n signIn,\n signInSilently,\n user,\n client,\n signInOptions,\n tokenRequest,\n syncSession,\n getDecodedIdToken,\n clearSession,\n exchangeToken,\n getAccessToken,\n getStorageManager,\n instanceId,\n organizationChain,\n preferences,\n recover,\n reInitialize,\n request,\n requestAll,\n signOut,\n signUp,\n ],\n );\n\n return (\n <ThunderIDContext.Provider value={value}>\n <I18nProvider preferences={preferences?.i18n} vendor={getVendorPrefix(config.vendor)}>\n <FlowMetaProvider enabled={preferences?.resolveFromMeta !== false}>\n <ThemeProvider\n theme={{\n ...preferences?.theme?.overrides,\n direction: preferences?.theme?.direction,\n }}\n >\n <FlowProvider>\n <UserProvider profile={userProfile!} onUpdateProfile={handleProfileUpdate}>\n <ComponentRendererProvider renderers={(extensions?.components?.renderers ?? {}) as any}>\n {children}\n </ComponentRendererProvider>\n </UserProvider>\n </FlowProvider>\n </ThemeProvider>\n </FlowMetaProvider>\n </I18nProvider>\n </ThunderIDContext.Provider>\n );\n};\n\nexport default ThunderIDProvider;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4CA,MAAMA,+DACJ,oBACA,oBACD;AAOD,MAAMC,qBAAoE,EACxE,gBACA,iBACA,SAAS,gBACT,UACA,UACA,YACA,QACA,aACA,WACA,WACA,oBACA,eACA,eACA,cACA,aACA,aAAa,GACb,kBACA,GAAG,WAC0D;CAC7D,MAAMC,qCAA8C,MAAM;CAC1D,MAAMC,kCAA6C,IAAIC,qCAAqB,WAAW,EAAE,CAAC,WAAW,CAAC;CACtG,MAAMC,sCAAqC,KAAK;CAChD,MAAM,EAAC,eAAe,6BAA4BC,+BAAe;CACjE,MAAM,CAAC,MAAM,+BAAgC,KAAK;CAClD,MAAM,CAAC,gBAAgB,yCAAuC,MAAM;CACpE,MAAM,CAAC,mBAAmB,4CAA0C,MAAM;CAC1E,MAAM,CAAC,eAAe,wCAAsC,KAAK;CAEjE,MAAM,CAAC,aAAa,sCAA+C,KAAK;CACxE,MAAM,CAAC,SAAS,kCAA+B,kBAAkB,GAAG;CACpE,MAAM,CAAC,QAAQ,iCAA4C;EACzD,gBAAgB,kBAAkB,OAAO,SAAS;E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AC,OAAO,CACT;CAED,MAAMC,kCACG;EACL,gBAAgB,OAAO;EACvB,eAAe,OAAO;EACtB;EACA,QAAQ,OAAO;EACf;EACA;EACA,WAAW,EACT,WACD;EACD;EACA;EACA;EACA;EACA;EACA,MAAM;GACJ;GACA;GACD;EACD;EACA,eAAe;EACf,WAAW;EACX,YAAY;EACZ;EACA,oBAAoB,QAAQ;EAC5B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,iDAAwB,OAAO,OAAO;EACvC,GACD;EACE;EACA,QAAQ;EACR,OAAO;EACP,OAAO;EACP,OAAO;EACP;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CACF;AAED,QACE,2CAACC,iCAAiB;EAAgB;YAChC,2CAACC;GAAa,aAAa,aAAa;GAAM,iDAAwB,OAAO,OAAO;aAClF,2CAACC;IAAiB,SAAS,aAAa,oBAAoB;cAC1D,2CAACC;KACC,OAAO;MACL,GAAG,aAAa,OAAO;MACvB,WAAW,aAAa,OAAO;MAChC;eAED,2CAACC,0CACC,2CAACC;MAAa,SAAS;MAAc,iBAAiB;gBACpD,2CAACC;OAA0B,WAAY,YAAY,YAAY,aAAa,EAAE;OAC3E;QACyB;OACf,GACF;MACD;KACC;IACN;GACW;;AAIhC,gCAAe"}
1
+ {"version":3,"file":"ThunderIDProvider.cjs","names":["logger: ReturnType<typeof createPackageComponentLogger>","ThunderIDProvider: FC<PropsWithChildren<ThunderIDProviderProps>>","reRenderCheckRef: RefObject<boolean>","client: ThunderIDReactClient","ThunderIDReactClient","storageManagerRef: any","useBrowserUrl","pendingSessionUpdateRef: RefObject<Promise<void> | null>","resolvedBaseUrl: string","decodedToken: IdToken","shouldFetchProfile: boolean","claims: User","currentSignInStatus: boolean","getUsersMe","arg1: any","isV2FlowRequest: boolean","ThunderIDRuntimeError","currentUrl: URL","urlParams: URLSearchParams","code: string | null","executionIdFromUrl: string | null","storedExecutionId: string | null","interval: NodeJS.Timeout","status: boolean","getDecodedIdToken: () => Promise<IdToken>","getIdToken: () => Promise<string>","getAccessToken: () => Promise<string>","getStorageManager: () => Promise<any>","storageManager: any","request: (...args: any[]) => Promise<any>","requestAll: (...args: any[]) => Promise<any>","exchangeToken: (exchangeConfig: any) => Promise<any>","signOut: (...args: any[]) => Promise<any>","recover: (payload: any) => Promise<any>","signUp: (...args: any[]) => Promise<any>","clearSession: (...args: any[]) => Promise<any>","reInitialize: (reInitConfig: any) => Promise<any>","result: any","reinitializedConfig: ThunderIDReactConfig","value: any","ThunderIDContext","I18nProvider","FlowMetaProvider","ThemeProvider","FlowProvider","UserProvider","ComponentRendererProvider"],"sources":["../../../../src/contexts/ThunderID/ThunderIDProvider.tsx"],"sourcesContent":["/**\n * Copyright (c) 2025-2026, WSO2 LLC. (https://www.wso2.com).\n *\n * WSO2 LLC. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport {\n ThunderIDRuntimeError,\n generateFlattenedUserProfile,\n OIDCDiscoveryApiResponse,\n SignInOptions,\n User,\n UserProfile,\n IdToken,\n extractUserClaimsFromIdToken,\n EmbeddedSignInFlowResponse,\n createPackageComponentLogger,\n getVendorPrefix,\n resolveResourceEndpoint,\n} from '@thunderid/browser';\nimport {FC, RefObject, PropsWithChildren, ReactElement, useEffect, useMemo, useRef, useState, useCallback} from 'react';\nimport ThunderIDContext from './ThunderIDContext';\nimport useBrowserUrl from '../../hooks/useBrowserUrl';\nimport {ThunderIDReactConfig} from '../../models/config';\nimport ThunderIDReactClient from '../../ThunderIDReactClient';\nimport ComponentRendererProvider from '../ComponentRenderer/ComponentRendererProvider';\nimport FlowProvider from '../Flow/FlowProvider';\nimport FlowMetaProvider from '../FlowMeta/FlowMetaProvider';\nimport I18nProvider from '../I18n/I18nProvider';\nimport ThemeProvider from '../Theme/ThemeProvider';\nimport UserProvider from '../User/UserProvider';\nimport getUsersMe from '../../api/getUsersMe';\n\nconst logger: ReturnType<typeof createPackageComponentLogger> = createPackageComponentLogger(\n '@thunderid/react',\n 'ThunderIDProvider',\n);\n\n/**\n * Props interface of {@link ThunderIDProvider}\n */\nexport type ThunderIDProviderProps = ThunderIDReactConfig;\n\nconst ThunderIDProvider: FC<PropsWithChildren<ThunderIDProviderProps>> = ({\n afterSignInUrl,\n afterSignOutUrl,\n baseUrl: initialBaseUrl,\n clientId,\n children,\n extensions,\n scopes,\n preferences,\n signInUrl,\n signUpUrl,\n organizationHandle,\n applicationId,\n signInOptions,\n tokenRequest,\n syncSession,\n instanceId = 0,\n organizationChain,\n ...rest\n}: PropsWithChildren<ThunderIDProviderProps>): ReactElement => {\n const reRenderCheckRef: RefObject<boolean> = useRef(false);\n const client: ThunderIDReactClient = useMemo(() => new ThunderIDReactClient(instanceId), [instanceId]);\n const storageManagerRef: any = useRef<any>(null);\n const {hasAuthParams, hasCalledForThisInstance} = useBrowserUrl();\n const [user, setUser] = useState<any | null>(null);\n const [isSignedInSync, setIsSignedInSync] = useState<boolean>(false);\n const [isInitializedSync, setIsInitializedSync] = useState<boolean>(false);\n const [isLoadingSync, setIsLoadingSync] = useState<boolean>(true);\n\n const [userProfile, setUserProfile] = useState<UserProfile | null>(null);\n const [baseUrl, setBaseUrl] = useState<string>(initialBaseUrl ?? '');\n const [config, setConfig] = useState<ThunderIDReactConfig>({\n afterSignInUrl: afterSignInUrl ?? window.location.origin,\n afterSignOutUrl: afterSignOutUrl ?? window.location.origin,\n applicationId,\n baseUrl,\n clientId,\n organizationChain,\n organizationHandle,\n scopes,\n signInOptions,\n tokenRequest,\n signInUrl,\n signUpUrl,\n syncSession,\n ...rest,\n });\n\n const [isUpdatingSession, setIsUpdatingSession] = useState<boolean>(false);\n const [wellKnown, setWellKnown] = useState<OIDCDiscoveryApiResponse | null>(null);\n\n // Holds the in-flight `updateSession()` promise so concurrent callers coalesce onto a single\n // `/users/me` request instead of issuing one each.\n const pendingSessionUpdateRef: RefObject<Promise<void> | null> = useRef<Promise<void> | null>(null);\n\n useEffect(() => {\n setBaseUrl(initialBaseUrl ?? '');\n }, [initialBaseUrl]);\n\n useEffect(() => {\n (async (): Promise<void> => {\n await client.initialize(config);\n const initializedConfig: ThunderIDReactConfig = await client.getConfiguration();\n setConfig(initializedConfig);\n setWellKnown(await client.getDiscoveryResponse());\n })();\n }, []);\n\n async function performSessionUpdate(): Promise<void> {\n try {\n // Set flag to prevent loading state tracking from interfering\n setIsUpdatingSession(true);\n setIsLoadingSync(true);\n let resolvedBaseUrl: string = baseUrl;\n\n const decodedToken: IdToken = await client.getDecodedIdToken();\n\n // If there's a `user_org` claim in the ID token,\n // Treat this login as a organization login.\n if (decodedToken?.['user_org']) {\n resolvedBaseUrl = `${(await client.getConfiguration()).baseUrl}/o`;\n setBaseUrl(resolvedBaseUrl);\n }\n\n const shouldFetchProfile: boolean = preferences?.user?.fetchUserProfile !== false;\n const claims: User = extractUserClaimsFromIdToken(decodedToken) as User;\n let profileData = claims;\n const currentSignInStatus: boolean = await client.isSignedIn();\n\n if (currentSignInStatus && shouldFetchProfile) {\n try {\n const fetchedProfile = await getUsersMe({\n baseUrl: resolvedBaseUrl,\n url: resolveResourceEndpoint('usersMe', config),\n instanceId,\n });\n profileData = {...claims, ...fetchedProfile};\n } catch (err) {\n logger.warn('Failed to fetch user profile from /users/me:', err);\n }\n }\n\n setUser(profileData);\n setUserProfile({\n flattenedProfile: generateFlattenedUserProfile(profileData, []),\n profile: profileData,\n });\n\n // CRITICAL: Update sign-in status BEFORE setting loading to false\n // This prevents the race condition where ProtectedRoute sees isLoading=false but isSignedIn=false\n setIsSignedInSync(currentSignInStatus);\n } catch (error) {\n // TODO: Add an error log.\n } finally {\n // Clear the flag and set final loading state\n setIsUpdatingSession(false);\n setIsLoadingSync(client.isLoading());\n }\n }\n\n /**\n * Single-flight wrapper around {@link performSessionUpdate}.\n *\n * Concurrent callers share the in-flight request instead of each issuing their own `/users/me`.\n * This is not a cache: once the request settles the ref is cleared, so a later caller (e.g.\n * revalidation after a profile update) fetches again.\n */\n async function updateSession(): Promise<void> {\n if (pendingSessionUpdateRef.current) {\n return pendingSessionUpdateRef.current;\n }\n\n pendingSessionUpdateRef.current = performSessionUpdate().finally(() => {\n pendingSessionUpdateRef.current = null;\n });\n\n return pendingSessionUpdateRef.current;\n }\n\n async function signIn(...args: any): Promise<User | EmbeddedSignInFlowResponse> {\n // Check if this is a V2 embedded flow request BEFORE calling signIn\n // This allows us to skip session checks entirely for V2 flows\n const arg1: any = args[0];\n const isV2FlowRequest: boolean =\n typeof arg1 === 'object' && arg1 !== null && ('executionId' in arg1 || 'applicationId' in arg1);\n\n try {\n if (!isV2FlowRequest) {\n setIsUpdatingSession(true);\n setIsLoadingSync(true);\n }\n\n return await client.signIn(...args);\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Sign in failed: ${error instanceof Error ? error.message : String(JSON.stringify(error))}`,\n 'thunderid-signIn-Error',\n 'react',\n 'An error occurred while trying to sign in.',\n );\n } finally {\n if (!isV2FlowRequest) {\n setIsUpdatingSession(false);\n setIsLoadingSync(client.isLoading());\n }\n }\n }\n\n /**\n * Try signing in when the component is mounted.\n */\n useEffect(() => {\n // React 18.x Strict.Mode has a new check for `Ensuring reusable state` to facilitate an upcoming react feature.\n // https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state\n // This will remount all the useEffects to ensure that there are no unexpected side effects.\n // When react remounts the signIn hook of the AuthProvider, it will cause a race condition. Hence, we have to\n // prevent the re-render of this hook as suggested in the following discussion.\n // https://github.com/reactwg/react-18/discussions/18#discussioncomment-795623\n if (reRenderCheckRef.current) {\n return;\n }\n\n reRenderCheckRef.current = true;\n\n (async (): Promise<void> => {\n // Sync session state whenever sign-in completes (both redirect and embedded V2 flows).\n // Pass the user returned by the SDK's sign-in flow so users/me result is not discarded.\n await client.on('sign-in', async () => {\n await updateSession();\n });\n\n // Start auto-refresh with a soft failure. This also covers the case where the access token\n // expired while the refresh token is still valid — startAutoRefreshToken() calls\n // refreshAccessToken() immediately when timeUntilRefresh <= 0 — so the sign-in check below\n // sees the refreshed state.\n try {\n await client.startAutoRefreshToken();\n } catch (error) {\n logger.warn('Failed to schedule automatic token refresh.', error);\n }\n\n // User is already authenticated. Restore the session and skip the sign-in path.\n if (await client.isSignedIn()) {\n await updateSession();\n\n return;\n }\n\n const currentUrl: URL = new URL(window.location.href);\n const hasAuthParamsResult: boolean =\n hasAuthParams(currentUrl, config.afterSignInUrl!) && hasCalledForThisInstance(currentUrl, instanceId ?? 0);\n\n if (hasAuthParamsResult) {\n try {\n const urlParams: URLSearchParams = currentUrl.searchParams;\n const code: string | null = urlParams.get('code');\n const executionIdFromUrl: string | null = urlParams.get('executionId');\n const storedExecutionId: string | null = sessionStorage.getItem(\n `${getVendorPrefix(config.vendor)}_execution_id`,\n );\n\n if (code && !executionIdFromUrl && !storedExecutionId) {\n await signIn();\n }\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Sign in failed: ${error instanceof Error ? error.message : String(JSON.stringify(error))}`,\n 'thunderid-signIn-Error',\n 'react',\n 'An error occurred while trying to sign in.',\n );\n }\n }\n })();\n }, []);\n\n /**\n * Check if the user is signed in and update the state accordingly.\n * This will also set an interval to check for the sign-in status every second\n * until the user is signed in.\n */\n useEffect(() => {\n let interval: NodeJS.Timeout;\n\n (async (): Promise<void> => {\n try {\n const status: boolean = await client.isSignedIn();\n\n setIsSignedInSync(status);\n\n if (!status) {\n interval = setInterval(async () => {\n const newStatus: boolean = await client.isSignedIn();\n\n if (newStatus) {\n setIsSignedInSync(true);\n clearInterval(interval);\n }\n }, 1000);\n } else {\n // TODO: Add a debug log to indicate that the user is already signed in.\n }\n } catch (error) {\n setIsSignedInSync(false);\n }\n })();\n\n return (): void => {\n if (interval) {\n clearInterval(interval);\n }\n };\n }, [client]);\n\n useEffect(() => {\n (async (): Promise<void> => {\n try {\n const status: boolean = await client.isInitialized();\n\n setIsInitializedSync(status);\n } catch (error) {\n setIsInitializedSync(false);\n }\n })();\n }, [client]);\n\n /**\n * Track loading state changes from the ThunderID client\n */\n useEffect(() => {\n const checkLoadingState = (): void => {\n // Don't override loading state during critical session updates\n if (isUpdatingSession) {\n return;\n }\n\n // Don't set loading=false while auth params are in the URL and user isn't signed in yet.\n // This prevents ProtectedRoute from redirecting before the sign-in effect processes the auth code.\n const currentUrl: URL = new URL(window.location.href);\n if (!isSignedInSync && hasAuthParams(currentUrl, config.afterSignInUrl!)) {\n return;\n }\n\n setIsLoadingSync(client.isLoading());\n };\n\n // Initial check\n checkLoadingState();\n\n // Set up an interval to check for loading state changes\n const interval: NodeJS.Timeout = setInterval(checkLoadingState, 100);\n\n return (): void => {\n clearInterval(interval);\n };\n }, [client, isLoadingSync, isSignedInSync, isUpdatingSession]);\n\n const signInSilently = async (options?: SignInOptions): Promise<User | boolean> => {\n try {\n setIsUpdatingSession(true);\n setIsLoadingSync(true);\n return await client.signInSilently(options);\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Error while signing in silently: ${error instanceof Error ? error.message : String(JSON.stringify(error))}`,\n 'thunderid-signInSilently-Error',\n 'react',\n 'An error occurred while trying to sign in silently.',\n );\n } finally {\n setIsUpdatingSession(false);\n setIsLoadingSync(client.isLoading());\n }\n };\n\n const handleProfileUpdate = (payload: User): void => {\n setUser(payload);\n setUserProfile((prev: UserProfile | null) => ({\n flattenedProfile: generateFlattenedUserProfile(payload),\n profile: payload,\n }));\n };\n\n const getDecodedIdToken: () => Promise<IdToken> = useCallback(\n async (): Promise<IdToken> => client.getDecodedIdToken(),\n [client],\n );\n\n const getIdToken: () => Promise<string> = useCallback(async (): Promise<string> => client.getIdToken(), [client]);\n\n const getAccessToken: () => Promise<string> = useCallback(\n async (): Promise<string> => client.getAccessToken(),\n [client],\n );\n\n const getStorageManager: () => Promise<any> = useCallback(async (): Promise<any> => {\n const storageManager: any = storageManagerRef.current ?? (await client.getStorageManager());\n if (storageManager) {\n storageManagerRef.current = storageManager;\n }\n return storageManager;\n }, [client]);\n\n const request: (...args: any[]) => Promise<any> = useCallback(\n async (...args: any[]): Promise<any> => client.request(...args),\n [client],\n );\n\n const requestAll: (...args: any[]) => Promise<any> = useCallback(\n async (...args: any[]): Promise<any> => client.requestAll(...args),\n [client],\n );\n\n const exchangeToken: (exchangeConfig: any) => Promise<any> = useCallback(\n async (exchangeConfig: any): Promise<any> => client.exchangeToken(exchangeConfig),\n [client],\n );\n\n const signOut: (...args: any[]) => Promise<any> = useCallback(\n async (...args: any[]): Promise<any> => client.signOut(...args),\n [client],\n );\n\n const recover: (payload: any) => Promise<any> = useCallback(\n async (payload: any): Promise<any> => client.recover(payload),\n [client],\n );\n\n const signUp: (...args: any[]) => Promise<any> = useCallback(\n async (...args: any[]): Promise<any> => client.signUp(...args),\n [client],\n );\n\n const clearSession: (...args: any[]) => Promise<any> = useCallback(\n async (...args: any[]): Promise<any> => client.clearSession(...args),\n [client],\n );\n\n const reInitialize: (reInitConfig: any) => Promise<any> = useCallback(\n async (reInitConfig: any): Promise<any> => {\n const result: any = await client.reInitialize(reInitConfig);\n\n // Refresh React state from the reinitialized client so the context (config.endpoints,\n // baseUrl, discovery) reflects the new configuration instead of the pre-reinitialization state.\n const reinitializedConfig: ThunderIDReactConfig = await client.getConfiguration();\n setConfig(reinitializedConfig);\n setBaseUrl(reinitializedConfig.baseUrl ?? '');\n setWellKnown(await client.getDiscoveryResponse());\n\n return result;\n },\n [client],\n );\n\n const value: any = useMemo(\n () => ({\n afterSignInUrl: config.afterSignInUrl,\n applicationId: config.applicationId,\n baseUrl,\n endpoints: config.endpoints,\n scopes: config.scopes,\n clearSession,\n clientId,\n discovery: {\n wellKnown,\n },\n exchangeToken,\n getAccessToken,\n getDecodedIdToken,\n getIdToken,\n getStorageManager,\n http: {\n request,\n requestAll,\n },\n instanceId,\n isInitialized: isInitializedSync,\n isLoading: isLoadingSync,\n isSignedIn: isSignedInSync,\n organizationChain,\n organizationHandle: config?.organizationHandle,\n preferences,\n reInitialize,\n recover,\n signIn,\n signInOptions,\n tokenRequest,\n signInSilently,\n signInUrl,\n signOut,\n signUp,\n signUpUrl,\n syncSession,\n user,\n vendor: getVendorPrefix(config.vendor),\n }),\n [\n applicationId,\n config?.organizationHandle,\n config.vendor,\n config.afterSignInUrl,\n config.endpoints,\n config.scopes,\n signInUrl,\n signUpUrl,\n baseUrl,\n clientId,\n wellKnown,\n isInitializedSync,\n isLoadingSync,\n isSignedInSync,\n signIn,\n signInSilently,\n user,\n client,\n signInOptions,\n tokenRequest,\n syncSession,\n getDecodedIdToken,\n clearSession,\n exchangeToken,\n getAccessToken,\n getStorageManager,\n instanceId,\n organizationChain,\n preferences,\n recover,\n reInitialize,\n request,\n requestAll,\n signOut,\n signUp,\n ],\n );\n\n return (\n <ThunderIDContext.Provider value={value}>\n <I18nProvider preferences={preferences?.i18n} vendor={getVendorPrefix(config.vendor)}>\n <FlowMetaProvider enabled={preferences?.resolveFromMeta !== false}>\n <ThemeProvider\n theme={{\n ...preferences?.theme?.overrides,\n direction: preferences?.theme?.direction,\n }}\n >\n <FlowProvider>\n <UserProvider profile={userProfile!} onUpdateProfile={handleProfileUpdate}>\n <ComponentRendererProvider renderers={(extensions?.components?.renderers ?? {}) as any}>\n {children}\n </ComponentRendererProvider>\n </UserProvider>\n </FlowProvider>\n </ThemeProvider>\n </FlowMetaProvider>\n </I18nProvider>\n </ThunderIDContext.Provider>\n );\n};\n\nexport default ThunderIDProvider;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6CA,MAAMA,+DACJ,oBACA,oBACD;AAOD,MAAMC,qBAAoE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;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CACF;AAED,QACE,2CAACC,iCAAiB;EAAgB;YAChC,2CAACC;GAAa,aAAa,aAAa;GAAM,iDAAwB,OAAO,OAAO;aAClF,2CAACC;IAAiB,SAAS,aAAa,oBAAoB;cAC1D,2CAACC;KACC,OAAO;MACL,GAAG,aAAa,OAAO;MACvB,WAAW,aAAa,OAAO;MAChC;eAED,2CAACC,0CACC,2CAACC;MAAa,SAAS;MAAc,iBAAiB;gBACpD,2CAACC;OAA0B,WAAY,YAAY,YAAY,aAAa,EAAE;OAC3E;QACyB;OACf,GACF;MACD;KACC;IACN;GACW;;AAIhC,gCAAe"}
@@ -1 +1 @@
1
- {"version":3,"file":"InviteUser.d.ts","sourceRoot":"","sources":["../../../../../src/components/presentation/auth/InviteUser/InviteUser.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAGH,OAAO,EAAC,EAAE,EAAgB,SAAS,EAAc,MAAM,OAAO,CAAC;AAE/D,OAAuB,EAAC,yBAAyB,EAAE,sBAAsB,EAAC,MAAM,kBAAkB,CAAC;AAGnG;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG,yBAAyB,CAAC;AAE9D;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;;OAGG;IACH,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,qBAAqB,KAAK,SAAS,CAAC;IAEvD;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAEjC;;OAEG;IACH,YAAY,CAAC,EAAE,CAAC,QAAQ,EAAE,sBAAsB,KAAK,IAAI,CAAC;IAE1D;;OAEG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IAEvB;;OA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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,QAAA,MAAM,UAAU,EAAE,EAAE,CAAC,eAAe,CA+FnC,CAAC;AAEF,eAAe,UAAU,CAAC"}
@@ -1,6 +1,6 @@
1
1
  import useThunderID_default from "../../../../contexts/ThunderID/useThunderID.js";
2
2
  import BaseInviteUser_default from "./BaseInviteUser.js";
3
- import { EmbeddedFlowType, getOrganizationUnitChildren } from "@thunderid/browser";
3
+ import { EmbeddedFlowType, getOrganizationUnitChildren, resolveResourceEndpoint } from "@thunderid/browser";
4
4
  import { useCallback } from "react";
5
5
  import { jsx } from "react/jsx-runtime";
6
6
 
@@ -46,7 +46,8 @@ import { jsx } from "react/jsx-runtime";
46
46
  * ```
47
47
  */
48
48
  const InviteUser = ({ onError, onFlowChange, className, children, size = "medium", variant = "outlined", showTitle = true, showSubtitle = true }) => {
49
- const { http, baseUrl, getAccessToken, isInitialized } = useThunderID_default();
49
+ const { http, baseUrl, endpoints, getAccessToken, isInitialized } = useThunderID_default();
50
+ const flowExecuteUrl = resolveResourceEndpoint("flowExecute", { endpoints }) ?? `${baseUrl}/flow/execute`;
50
51
  /**
51
52
  * Initialize the invite user flow.
52
53
  * Makes an authenticated request to /flow/execute with flowType: USER_ONBOARDING.
@@ -63,7 +64,7 @@ const InviteUser = ({ onError, onFlowChange, className, children, size = "medium
63
64
  "Content-Type": "application/json"
64
65
  },
65
66
  method: "POST",
66
- url: `${baseUrl}/flow/execute`
67
+ url: flowExecuteUrl
67
68
  })).data;
68
69
  };
69
70
  /**
@@ -81,7 +82,7 @@ const InviteUser = ({ onError, onFlowChange, className, children, size = "medium
81
82
  "Content-Type": "application/json"
82
83
  },
83
84
  method: "POST",
84
- url: `${baseUrl}/flow/execute`
85
+ url: flowExecuteUrl
85
86
  })).data;
86
87
  };
87
88
  return /* @__PURE__ */ jsx(BaseInviteUser_default, {
@@ -1 +1 @@
1
- {"version":3,"file":"InviteUser.js","names":["InviteUser: FC<InviteUserProps>","useThunderID","BaseInviteUser"],"sources":["../../../../../src/components/presentation/auth/InviteUser/InviteUser.tsx"],"sourcesContent":["/**\n * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).\n *\n * WSO2 LLC. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport {EmbeddedFlowType, getOrganizationUnitChildren, OrganizationUnitListResponse} from '@thunderid/browser';\nimport {FC, ReactElement, ReactNode, useCallback} from 'react';\n// eslint-disable-next-line import/no-named-as-default\nimport BaseInviteUser, {BaseInviteUserRenderProps, InviteUserFlowResponse} from './BaseInviteUser';\nimport useThunderID from '../../../../contexts/ThunderID/useThunderID';\n\n/**\n * Render props for InviteUser (re-exported for convenience).\n */\nexport type InviteUserRenderProps = BaseInviteUserRenderProps;\n\n/**\n * Props for the InviteUser component.\n */\nexport interface InviteUserProps {\n /**\n * Render props function for custom UI.\n * If not provided, default UI will be rendered by the SDK.\n */\n children?: (props: InviteUserRenderProps) => ReactNode;\n\n /**\n * Custom CSS class name.\n */\n className?: string;\n\n /**\n * Callback when an error occurs.\n */\n onError?: (error: Error) => void;\n\n /**\n * Callback when the flow state changes.\n */\n onFlowChange?: (response: InviteUserFlowResponse) => void;\n\n /**\n * Whether to show the subtitle.\n */\n showSubtitle?: boolean;\n\n /**\n * Whether to show the title.\n */\n showTitle?: boolean;\n\n /**\n * Size variant for the component.\n */\n size?: 'small' | 'medium' | 'large';\n\n /**\n * Theme variant for the component card.\n */\n variant?: 'outlined' | 'elevated';\n}\n\n/**\n * InviteUser component for initiating invite user flow.\n *\n * This component is designed for admin users in the thunder-develop app to:\n * 1. Select a user type (if multiple available)\n * 2. Enter user details (username, email)\n * 3. Generate an invite link for the end user\n *\n * The component uses the authenticated ThunderID SDK context to make API calls\n * with the admin's access token (requires 'system' scope).\n *\n * @example\n * ```tsx\n * import { InviteUser } from '@thunderid/react';\n *\n * const InviteUserPage = () => {\n * const [inviteLink, setInviteLink] = useState<string>();\n *\n * return (\n * <InviteUser\n * onInviteLinkGenerated={(link, executionId) => setInviteLink(link)}\n * onError={(error) => console.error(error)}\n * >\n * {({ values, components, isLoading, handleInputChange, handleSubmit, inviteLink, isInviteGenerated }) => (\n * <div>\n * {isInviteGenerated ? (\n * <div>\n * <h2>Invite Link Generated!</h2>\n * <p>{inviteLink}</p>\n * </div>\n * ) : (\n * // Render form based on components\n * )}\n * </div>\n * )}\n * </InviteUser>\n * );\n * };\n * ```\n */\nconst InviteUser: FC<InviteUserProps> = ({\n onError,\n onFlowChange,\n className,\n children,\n size = 'medium',\n variant = 'outlined',\n showTitle = true,\n showSubtitle = true,\n}: InviteUserProps): ReactElement => {\n const {http, baseUrl, getAccessToken, isInitialized} = useThunderID();\n\n /**\n * Initialize the invite user flow.\n * Makes an authenticated request to /flow/execute with flowType: USER_ONBOARDING.\n */\n const handleInitialize = async (payload: Record<string, any>): Promise<InviteUserFlowResponse> => {\n const response: any = await http.request({\n data: {\n ...payload,\n flowType: EmbeddedFlowType.UserOnboarding,\n verbose: true,\n },\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n url: `${baseUrl}/flow/execute`,\n } as any);\n\n return response.data as InviteUserFlowResponse;\n };\n\n /**\n * Submit flow step data.\n * Makes an authenticated request to /flow/execute with the step data.\n */\n const handleSubmit = async (payload: Record<string, any>): Promise<InviteUserFlowResponse> => {\n const response: any = await http.request({\n data: {\n ...payload,\n verbose: true,\n },\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n url: `${baseUrl}/flow/execute`,\n } as any);\n\n return response.data as InviteUserFlowResponse;\n };\n\n const fetchOrganizationUnitChildren: (\n parentId: string,\n limit: number,\n offset: number,\n ) => Promise<OrganizationUnitListResponse> = useCallback(\n async (parentId: string, limit: number, offset: number): Promise<OrganizationUnitListResponse> => {\n const accessToken: string = await getAccessToken();\n\n return getOrganizationUnitChildren({\n baseUrl,\n headers: {Authorization: `Bearer ${accessToken}`},\n limit,\n offset,\n organizationUnitId: parentId,\n });\n },\n [baseUrl, getAccessToken],\n );\n\n return (\n <BaseInviteUser\n onInitialize={handleInitialize}\n onSubmit={handleSubmit}\n onError={onError}\n onFlowChange={onFlowChange}\n className={className}\n fetchOrganizationUnitChildren={fetchOrganizationUnitChildren}\n isInitialized={isInitialized}\n size={size}\n variant={variant}\n showTitle={showTitle}\n showSubtitle={showSubtitle}\n >\n {children}\n </BaseInviteUser>\n );\n};\n\nexport default InviteUser;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmHA,MAAMA,cAAmC,EACvC,SACA,cACA,WACA,UACA,OAAO,UACP,UAAU,YACV,YAAY,MACZ,eAAe,WACoB;CACnC,MAAM,EAAC,MAAM,SAAS,gBAAgB,kBAAiBC,sBAAc;;;;;CAMrE,MAAM,mBAAmB,OAAO,YAAkE;AAehG,UAdsB,MAAM,KAAK,QAAQ;GACvC,MAAM;IACJ,GAAG;IACH,UAAU,iBAAiB;IAC3B,SAAS;IACV;GACD,SAAS;IACP,QAAQ;IACR,gBAAgB;IACjB;GACD,QAAQ;GACR,KAAK,GAAG,QAAQ;GACjB,CAAQ,EAEO;;;;;;CAOlB,MAAM,eAAe,OAAO,YAAkE;AAc5F,UAbsB,MAAM,KAAK,QAAQ;GACvC,MAAM;IACJ,GAAG;IACH,SAAS;IACV;GACD,SAAS;IACP,QAAQ;IACR,gBAAgB;IACjB;GACD,QAAQ;GACR,KAAK,GAAG,QAAQ;GACjB,CAAQ,EAEO;;AAsBlB,QACE,oBAACC;EACC,cAAc;EACd,UAAU;EACD;EACK;EACH;EACX,+BAtByC,YAC3C,OAAO,UAAkB,OAAe,WAA0D;AAGhG,UAAO,4BAA4B;IACjC;IACA,SAAS,EAAC,eAAe,UAJC,MAAM,gBAAgB,IAIC;IACjD;IACA;IACA,oBAAoB;IACrB,CAAC;KAEJ,CAAC,SAAS,eAAe,CAC1B;EAUkB;EACT;EACG;EACE;EACG;EAEb;GACc;;AAIrB,yBAAe"}
1
+ {"version":3,"file":"InviteUser.js","names":["InviteUser: FC<InviteUserProps>","useThunderID","flowExecuteUrl: string","BaseInviteUser"],"sources":["../../../../../src/components/presentation/auth/InviteUser/InviteUser.tsx"],"sourcesContent":["/**\n * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).\n *\n * WSO2 LLC. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport {\n EmbeddedFlowType,\n getOrganizationUnitChildren,\n OrganizationUnitListResponse,\n resolveResourceEndpoint,\n} from '@thunderid/browser';\nimport {FC, ReactElement, ReactNode, useCallback} from 'react';\n// eslint-disable-next-line import/no-named-as-default\nimport BaseInviteUser, {BaseInviteUserRenderProps, InviteUserFlowResponse} from './BaseInviteUser';\nimport useThunderID from '../../../../contexts/ThunderID/useThunderID';\n\n/**\n * Render props for InviteUser (re-exported for convenience).\n */\nexport type InviteUserRenderProps = BaseInviteUserRenderProps;\n\n/**\n * Props for the InviteUser component.\n */\nexport interface InviteUserProps {\n /**\n * Render props function for custom UI.\n * If not provided, default UI will be rendered by the SDK.\n */\n children?: (props: InviteUserRenderProps) => ReactNode;\n\n /**\n * Custom CSS class name.\n */\n className?: string;\n\n /**\n * Callback when an error occurs.\n */\n onError?: (error: Error) => void;\n\n /**\n * Callback when the flow state changes.\n */\n onFlowChange?: (response: InviteUserFlowResponse) => void;\n\n /**\n * Whether to show the subtitle.\n */\n showSubtitle?: boolean;\n\n /**\n * Whether to show the title.\n */\n showTitle?: boolean;\n\n /**\n * Size variant for the component.\n */\n size?: 'small' | 'medium' | 'large';\n\n /**\n * Theme variant for the component card.\n */\n variant?: 'outlined' | 'elevated';\n}\n\n/**\n * InviteUser component for initiating invite user flow.\n *\n * This component is designed for admin users in the thunder-develop app to:\n * 1. Select a user type (if multiple available)\n * 2. Enter user details (username, email)\n * 3. Generate an invite link for the end user\n *\n * The component uses the authenticated ThunderID SDK context to make API calls\n * with the admin's access token (requires 'system' scope).\n *\n * @example\n * ```tsx\n * import { InviteUser } from '@thunderid/react';\n *\n * const InviteUserPage = () => {\n * const [inviteLink, setInviteLink] = useState<string>();\n *\n * return (\n * <InviteUser\n * onInviteLinkGenerated={(link, executionId) => setInviteLink(link)}\n * onError={(error) => console.error(error)}\n * >\n * {({ values, components, isLoading, handleInputChange, handleSubmit, inviteLink, isInviteGenerated }) => (\n * <div>\n * {isInviteGenerated ? (\n * <div>\n * <h2>Invite Link Generated!</h2>\n * <p>{inviteLink}</p>\n * </div>\n * ) : (\n * // Render form based on components\n * )}\n * </div>\n * )}\n * </InviteUser>\n * );\n * };\n * ```\n */\nconst InviteUser: FC<InviteUserProps> = ({\n onError,\n onFlowChange,\n className,\n children,\n size = 'medium',\n variant = 'outlined',\n showTitle = true,\n showSubtitle = true,\n}: InviteUserProps): ReactElement => {\n const {http, baseUrl, endpoints, getAccessToken, isInitialized} = useThunderID();\n\n // The user-onboarding flow runs on the resource server, which may differ from `baseUrl` (the\n // authorization server) in a trusted-issuer setup. Honor the `flowExecute` endpoint override.\n const flowExecuteUrl: string = resolveResourceEndpoint('flowExecute', {endpoints}) ?? `${baseUrl}/flow/execute`;\n\n /**\n * Initialize the invite user flow.\n * Makes an authenticated request to /flow/execute with flowType: USER_ONBOARDING.\n */\n const handleInitialize = async (payload: Record<string, any>): Promise<InviteUserFlowResponse> => {\n const response: any = await http.request({\n data: {\n ...payload,\n flowType: EmbeddedFlowType.UserOnboarding,\n verbose: true,\n },\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n url: flowExecuteUrl,\n } as any);\n\n return response.data as InviteUserFlowResponse;\n };\n\n /**\n * Submit flow step data.\n * Makes an authenticated request to /flow/execute with the step data.\n */\n const handleSubmit = async (payload: Record<string, any>): Promise<InviteUserFlowResponse> => {\n const response: any = await http.request({\n data: {\n ...payload,\n verbose: true,\n },\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n url: flowExecuteUrl,\n } as any);\n\n return response.data as InviteUserFlowResponse;\n };\n\n const fetchOrganizationUnitChildren: (\n parentId: string,\n limit: number,\n offset: number,\n ) => Promise<OrganizationUnitListResponse> = useCallback(\n async (parentId: string, limit: number, offset: number): Promise<OrganizationUnitListResponse> => {\n const accessToken: string = await getAccessToken();\n\n return getOrganizationUnitChildren({\n baseUrl,\n headers: {Authorization: `Bearer ${accessToken}`},\n limit,\n offset,\n organizationUnitId: parentId,\n });\n },\n [baseUrl, getAccessToken],\n );\n\n return (\n <BaseInviteUser\n onInitialize={handleInitialize}\n onSubmit={handleSubmit}\n onError={onError}\n onFlowChange={onFlowChange}\n className={className}\n fetchOrganizationUnitChildren={fetchOrganizationUnitChildren}\n isInitialized={isInitialized}\n size={size}\n variant={variant}\n showTitle={showTitle}\n showSubtitle={showSubtitle}\n >\n {children}\n </BaseInviteUser>\n );\n};\n\nexport default InviteUser;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwHA,MAAMA,cAAmC,EACvC,SACA,cACA,WACA,UACA,OAAO,UACP,UAAU,YACV,YAAY,MACZ,eAAe,WACoB;CACnC,MAAM,EAAC,MAAM,SAAS,WAAW,gBAAgB,kBAAiBC,sBAAc;CAIhF,MAAMC,iBAAyB,wBAAwB,eAAe,EAAC,WAAU,CAAC,IAAI,GAAG,QAAQ;;;;;CAMjG,MAAM,mBAAmB,OAAO,YAAkE;AAehG,UAdsB,MAAM,KAAK,QAAQ;GACvC,MAAM;IACJ,GAAG;IACH,UAAU,iBAAiB;IAC3B,SAAS;IACV;GACD,SAAS;IACP,QAAQ;IACR,gBAAgB;IACjB;GACD,QAAQ;GACR,KAAK;GACN,CAAQ,EAEO;;;;;;CAOlB,MAAM,eAAe,OAAO,YAAkE;AAc5F,UAbsB,MAAM,KAAK,QAAQ;GACvC,MAAM;IACJ,GAAG;IACH,SAAS;IACV;GACD,SAAS;IACP,QAAQ;IACR,gBAAgB;IACjB;GACD,QAAQ;GACR,KAAK;GACN,CAAQ,EAEO;;AAsBlB,QACE,oBAACC;EACC,cAAc;EACd,UAAU;EACD;EACK;EACH;EACX,+BAtByC,YAC3C,OAAO,UAAkB,OAAe,WAA0D;AAGhG,UAAO,4BAA4B;IACjC;IACA,SAAS,EAAC,eAAe,UAJC,MAAM,gBAAgB,IAIC;IACjD;IACA;IACA,oBAAoB;IACrB,CAAC;KAEJ,CAAC,SAAS,eAAe,CAC1B;EAUkB;EACT;EACG;EACE;EACG;EAEb;GACc;;AAIrB,yBAAe"}
@@ -432,7 +432,7 @@ const SignIn = ({ className, preferences, size = "medium", onSuccess, onError, v
432
432
  })), ...(p.optional || []).map((e) => {
433
433
  const key = `__consent_opt__${p.purposeId}__${e.name}`;
434
434
  return {
435
- approved: isDeny ? false : processedInputs[key] !== "false",
435
+ approved: !isDeny && processedInputs[key] === "true",
436
436
  name: e.name
437
437
  };
438
438
  })],