@thunderid/react 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/components/presentation/auth/SignUp/BaseSignUp.cjs +3 -1
- package/dist/cjs/components/presentation/auth/SignUp/BaseSignUp.cjs.map +1 -1
- package/dist/cjs/components/presentation/auth/SignUp/SignUp.cjs +1 -1
- package/dist/cjs/components/presentation/auth/SignUp/SignUp.cjs.map +1 -1
- package/dist/cjs/contexts/I18n/I18nProvider.cjs +1 -2
- package/dist/cjs/contexts/I18n/I18nProvider.cjs.map +1 -1
- package/dist/cjs/hooks/useTranslation.cjs +1 -2
- package/dist/cjs/hooks/useTranslation.cjs.map +1 -1
- package/dist/cjs/utils/flowTransformer.cjs +12 -6
- package/dist/cjs/utils/flowTransformer.cjs.map +1 -1
- package/dist/components/presentation/auth/SignUp/BaseSignUp.d.ts.map +1 -1
- package/dist/components/presentation/auth/SignUp/BaseSignUp.js +3 -1
- package/dist/components/presentation/auth/SignUp/BaseSignUp.js.map +1 -1
- package/dist/components/presentation/auth/SignUp/SignUp.d.ts.map +1 -1
- package/dist/components/presentation/auth/SignUp/SignUp.js +1 -1
- package/dist/components/presentation/auth/SignUp/SignUp.js.map +1 -1
- package/dist/contexts/I18n/I18nProvider.d.ts.map +1 -1
- package/dist/contexts/I18n/I18nProvider.js +2 -3
- package/dist/contexts/I18n/I18nProvider.js.map +1 -1
- package/dist/hooks/useTranslation.d.ts.map +1 -1
- package/dist/hooks/useTranslation.js +2 -3
- package/dist/hooks/useTranslation.js.map +1 -1
- package/dist/utils/flowTransformer.d.ts +7 -11
- package/dist/utils/flowTransformer.d.ts.map +1 -1
- package/dist/utils/flowTransformer.js +10 -6
- package/dist/utils/flowTransformer.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useTranslation.js","names":["context: any","I18nContext","contextPreferences: I18nPreferences | undefined","ComponentPreferencesContext","effectivePreferences: I18nPreferences | undefined","mergedBundles: Record<string, I18nBundle>","merged: Record<string, I18nBundle>","normalizedTranslations: I18nTranslations","enhancedT: (key: string, params?: Record<string, string | number>) => string","translation: string | undefined","currentBundle: I18nBundle | undefined","fallbackBundle: I18nBundle | undefined"],"sources":["../../src/hooks/useTranslation.ts"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n deepMerge,\n I18nPreferences,\n Preferences,\n I18nBundle,\n I18nTranslations,\n normalizeTranslations,\n} from '@thunderid/browser';\nimport {useContext, useMemo} from 'react';\nimport ComponentPreferencesContext from '../contexts/I18n/ComponentPreferencesContext';\nimport I18nContext from '../contexts/I18n/I18nContext';\n\nexport interface UseTranslation {\n /**\n * All available language codes\n */\n availableLanguages: string[];\n\n /**\n * The current language code\n */\n currentLanguage: string;\n\n /**\n * Function to change the current language\n */\n setLanguage: (language: string) => void;\n\n /**\n * Translation function that returns a translated string for the given key\n */\n t: (key: string, params?: Record<string, string | number>) => string;\n}\n\nexport interface UseTranslationWithPreferences extends UseTranslation {\n /**\n * Enhanced translation function that merges component-level preferences\n */\n t: (key: string, params?: Record<string, string | number>) => string;\n}\n\n/**\n * Hook for accessing translation functions and language management.\n * Must be used within an I18nProvider context.\n *\n * @param componentPreferences - Optional component-level i18n preferences to merge with global ones\n * @returns An object containing translation function and language management utilities\n * @throws Error if used outside of I18nProvider context\n */\nconst useTranslation = (componentPreferences?: I18nPreferences): UseTranslationWithPreferences => {\n const context: any = useContext(I18nContext);\n const componentPrefs: Preferences | undefined = useContext(ComponentPreferencesContext);\n const contextPreferences: I18nPreferences | undefined = componentPrefs?.i18n;\n\n if (!context) {\n throw new Error(\n 'useTranslation must be used within an I18nProvider. Make sure your component is wrapped with ThunderIDProvider which includes I18nProvider.',\n );\n }\n\n // Direct parameter takes precedence over context-provided preferences\n const effectivePreferences: I18nPreferences | undefined = componentPreferences ?? contextPreferences;\n\n const {t: globalT, currentLanguage, setLanguage, bundles: globalBundles, fallbackLanguage} = context;\n\n // Merge global bundles with component-level bundles if provided\n const mergedBundles: Record<string, I18nBundle> = useMemo(() => {\n if (!effectivePreferences?.bundles) {\n return globalBundles;\n }\n\n const merged: Record<string, I18nBundle> = {};\n\n // Start with global bundles\n Object.entries(globalBundles).forEach(([key, bundle]: [string, I18nBundle]) => {\n merged[key] = bundle;\n });\n\n // Merge component-level bundles using deepMerge for better merging\n Object.entries(effectivePreferences.bundles).forEach(([key, componentBundle]: [string, I18nBundle]) => {\n const normalizedTranslations: I18nTranslations = normalizeTranslations(\n componentBundle.translations as unknown as Record<string, string | Record<string, string>>,\n );\n if (merged[key]) {\n // Deep merge component bundle with existing global bundle\n merged[key] = {\n ...merged[key],\n metadata: componentBundle.metadata\n ? {...merged[key].metadata, ...componentBundle.metadata}\n : merged[key].metadata,\n translations: deepMerge(merged[key].translations, normalizedTranslations),\n };\n } else {\n // No global bundle for this language, use component bundle as-is\n merged[key] = {...componentBundle, translations: normalizedTranslations};\n }\n });\n\n return merged;\n }, [globalBundles, effectivePreferences?.bundles]);\n\n // Create enhanced translation function that uses merged bundles\n const enhancedT: (key: string, params?: Record<string, string | number>) => string = useMemo(() => {\n if (!effectivePreferences?.bundles) {\n // No component preferences, use global translation function\n return globalT;\n }\n\n return (key: string, params?: Record<string, string | number>): string => {\n let translation: string | undefined;\n\n // Try to get translation from current language bundle\n const currentBundle: I18nBundle | undefined = mergedBundles[currentLanguage];\n if (currentBundle?.translations?.[key]) {\n translation = currentBundle.translations[key];\n }\n\n // Fallback to fallback language if translation not found\n if (!translation && currentLanguage !== fallbackLanguage) {\n const fallbackBundle: I18nBundle | undefined = mergedBundles[fallbackLanguage];\n if (fallbackBundle?.translations?.[key]) {\n translation = fallbackBundle.translations[key];\n }\n }\n\n // If still no translation found, return the key itself\n if (!translation) {\n translation = key;\n }\n\n // Replace parameters if provided\n
|
|
1
|
+
{"version":3,"file":"useTranslation.js","names":["context: any","I18nContext","contextPreferences: I18nPreferences | undefined","ComponentPreferencesContext","effectivePreferences: I18nPreferences | undefined","mergedBundles: Record<string, I18nBundle>","merged: Record<string, I18nBundle>","normalizedTranslations: I18nTranslations","enhancedT: (key: string, params?: Record<string, string | number>) => string","translation: string | undefined","currentBundle: I18nBundle | undefined","fallbackBundle: I18nBundle | undefined"],"sources":["../../src/hooks/useTranslation.ts"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n deepMerge,\n I18nPreferences,\n Preferences,\n I18nBundle,\n I18nTranslations,\n normalizeTranslations,\n substituteTranslationParams,\n} from '@thunderid/browser';\nimport {useContext, useMemo} from 'react';\nimport ComponentPreferencesContext from '../contexts/I18n/ComponentPreferencesContext';\nimport I18nContext from '../contexts/I18n/I18nContext';\n\nexport interface UseTranslation {\n /**\n * All available language codes\n */\n availableLanguages: string[];\n\n /**\n * The current language code\n */\n currentLanguage: string;\n\n /**\n * Function to change the current language\n */\n setLanguage: (language: string) => void;\n\n /**\n * Translation function that returns a translated string for the given key\n */\n t: (key: string, params?: Record<string, string | number>) => string;\n}\n\nexport interface UseTranslationWithPreferences extends UseTranslation {\n /**\n * Enhanced translation function that merges component-level preferences\n */\n t: (key: string, params?: Record<string, string | number>) => string;\n}\n\n/**\n * Hook for accessing translation functions and language management.\n * Must be used within an I18nProvider context.\n *\n * @param componentPreferences - Optional component-level i18n preferences to merge with global ones\n * @returns An object containing translation function and language management utilities\n * @throws Error if used outside of I18nProvider context\n */\nconst useTranslation = (componentPreferences?: I18nPreferences): UseTranslationWithPreferences => {\n const context: any = useContext(I18nContext);\n const componentPrefs: Preferences | undefined = useContext(ComponentPreferencesContext);\n const contextPreferences: I18nPreferences | undefined = componentPrefs?.i18n;\n\n if (!context) {\n throw new Error(\n 'useTranslation must be used within an I18nProvider. Make sure your component is wrapped with ThunderIDProvider which includes I18nProvider.',\n );\n }\n\n // Direct parameter takes precedence over context-provided preferences\n const effectivePreferences: I18nPreferences | undefined = componentPreferences ?? contextPreferences;\n\n const {t: globalT, currentLanguage, setLanguage, bundles: globalBundles, fallbackLanguage} = context;\n\n // Merge global bundles with component-level bundles if provided\n const mergedBundles: Record<string, I18nBundle> = useMemo(() => {\n if (!effectivePreferences?.bundles) {\n return globalBundles;\n }\n\n const merged: Record<string, I18nBundle> = {};\n\n // Start with global bundles\n Object.entries(globalBundles).forEach(([key, bundle]: [string, I18nBundle]) => {\n merged[key] = bundle;\n });\n\n // Merge component-level bundles using deepMerge for better merging\n Object.entries(effectivePreferences.bundles).forEach(([key, componentBundle]: [string, I18nBundle]) => {\n const normalizedTranslations: I18nTranslations = normalizeTranslations(\n componentBundle.translations as unknown as Record<string, string | Record<string, string>>,\n );\n if (merged[key]) {\n // Deep merge component bundle with existing global bundle\n merged[key] = {\n ...merged[key],\n metadata: componentBundle.metadata\n ? {...merged[key].metadata, ...componentBundle.metadata}\n : merged[key].metadata,\n translations: deepMerge(merged[key].translations, normalizedTranslations),\n };\n } else {\n // No global bundle for this language, use component bundle as-is\n merged[key] = {...componentBundle, translations: normalizedTranslations};\n }\n });\n\n return merged;\n }, [globalBundles, effectivePreferences?.bundles]);\n\n // Create enhanced translation function that uses merged bundles\n const enhancedT: (key: string, params?: Record<string, string | number>) => string = useMemo(() => {\n if (!effectivePreferences?.bundles) {\n // No component preferences, use global translation function\n return globalT;\n }\n\n return (key: string, params?: Record<string, string | number>): string => {\n let translation: string | undefined;\n\n // Try to get translation from current language bundle\n const currentBundle: I18nBundle | undefined = mergedBundles[currentLanguage];\n if (currentBundle?.translations?.[key]) {\n translation = currentBundle.translations[key];\n }\n\n // Fallback to fallback language if translation not found\n if (!translation && currentLanguage !== fallbackLanguage) {\n const fallbackBundle: I18nBundle | undefined = mergedBundles[fallbackLanguage];\n if (fallbackBundle?.translations?.[key]) {\n translation = fallbackBundle.translations[key];\n }\n }\n\n // If still no translation found, return the key itself\n if (!translation) {\n translation = key;\n }\n\n // Replace parameters if provided\n return substituteTranslationParams(translation, params);\n };\n }, [mergedBundles, currentLanguage, fallbackLanguage, globalT, effectivePreferences?.bundles]);\n\n return {\n availableLanguages: Object.keys(mergedBundles),\n currentLanguage,\n setLanguage,\n t: enhancedT,\n };\n};\n\nexport default useTranslation;\n"],"mappings":";;;;;;;;;;;;;;AAqDA,MAAM,kBAAkB,yBAA0E;CAChG,MAAMA,UAAe,WAAWC,oBAAY;CAE5C,MAAMC,qBAD0C,WAAWC,oCAA4B,EACf;AAExE,KAAI,CAAC,QACH,OAAM,IAAI,MACR,8IACD;CAIH,MAAMC,uBAAoD,wBAAwB;CAElF,MAAM,EAAC,GAAG,SAAS,iBAAiB,aAAa,SAAS,eAAe,qBAAoB;CAG7F,MAAMC,gBAA4C,cAAc;AAC9D,MAAI,CAAC,sBAAsB,QACzB,QAAO;EAGT,MAAMC,SAAqC,EAAE;AAG7C,SAAO,QAAQ,cAAc,CAAC,SAAS,CAAC,KAAK,YAAkC;AAC7E,UAAO,OAAO;IACd;AAGF,SAAO,QAAQ,qBAAqB,QAAQ,CAAC,SAAS,CAAC,KAAK,qBAA2C;GACrG,MAAMC,yBAA2C,sBAC/C,gBAAgB,aACjB;AACD,OAAI,OAAO,KAET,QAAO,OAAO;IACZ,GAAG,OAAO;IACV,UAAU,gBAAgB,WACtB;KAAC,GAAG,OAAO,KAAK;KAAU,GAAG,gBAAgB;KAAS,GACtD,OAAO,KAAK;IAChB,cAAc,UAAU,OAAO,KAAK,cAAc,uBAAuB;IAC1E;OAGD,QAAO,OAAO;IAAC,GAAG;IAAiB,cAAc;IAAuB;IAE1E;AAEF,SAAO;IACN,CAAC,eAAe,sBAAsB,QAAQ,CAAC;CAGlD,MAAMC,YAA+E,cAAc;AACjG,MAAI,CAAC,sBAAsB,QAEzB,QAAO;AAGT,UAAQ,KAAa,WAAqD;GACxE,IAAIC;GAGJ,MAAMC,gBAAwC,cAAc;AAC5D,OAAI,eAAe,eAAe,KAChC,eAAc,cAAc,aAAa;AAI3C,OAAI,CAAC,eAAe,oBAAoB,kBAAkB;IACxD,MAAMC,iBAAyC,cAAc;AAC7D,QAAI,gBAAgB,eAAe,KACjC,eAAc,eAAe,aAAa;;AAK9C,OAAI,CAAC,YACH,eAAc;AAIhB,UAAO,4BAA4B,aAAa,OAAO;;IAExD;EAAC;EAAe;EAAiB;EAAkB;EAAS,sBAAsB;EAAQ,CAAC;AAE9F,QAAO;EACL,oBAAoB,OAAO,KAAK,cAAc;EAC9C;EACA;EACA,GAAG;EACJ;;AAGH,6BAAe"}
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
* This transformer is used by both SignIn and SignUp v2 components to ensure
|
|
24
24
|
* consistent response handling across all embedded flows.
|
|
25
25
|
*/
|
|
26
|
-
import { EmbeddedFlowComponent, FlowMetadataResponse } from '@thunderid/browser';
|
|
26
|
+
import { EmbeddedFlowComponent, FlowMetadataResponse, I18nMessage } from '@thunderid/browser';
|
|
27
27
|
import { UseTranslation } from '../hooks/useTranslation';
|
|
28
28
|
/**
|
|
29
29
|
* Generic flow error response interface that covers common error structure
|
|
@@ -31,14 +31,8 @@ import { UseTranslation } from '../hooks/useTranslation';
|
|
|
31
31
|
export interface FlowErrorResponse {
|
|
32
32
|
error?: {
|
|
33
33
|
code: string;
|
|
34
|
-
description:
|
|
35
|
-
|
|
36
|
-
defaultValue?: string;
|
|
37
|
-
};
|
|
38
|
-
message: {
|
|
39
|
-
key: string;
|
|
40
|
-
defaultValue?: string;
|
|
41
|
-
};
|
|
34
|
+
description: I18nMessage;
|
|
35
|
+
message: I18nMessage;
|
|
42
36
|
};
|
|
43
37
|
executionId: string;
|
|
44
38
|
flowStatus: 'ERROR';
|
|
@@ -79,8 +73,10 @@ export declare const transformComponents: (response: any, t: UseTranslation["t"]
|
|
|
79
73
|
* Extract error message from flow error response.
|
|
80
74
|
*
|
|
81
75
|
* Resolution order:
|
|
82
|
-
* 1. Structured `error` object: try i18n lookup via `t(error.message.key)`.
|
|
83
|
-
*
|
|
76
|
+
* 1. Structured `error` object: try i18n lookup via `t(error.message.key, error.message.params)`.
|
|
77
|
+
* Bundle entries keep the backend's `{{param(name)}}` placeholders, so `params` must be passed
|
|
78
|
+
* through; a resolved value that still holds an unsubstituted placeholder is treated as a miss.
|
|
79
|
+
* 2. Fallback to `defaultValue` from `message`, then `description` (the backend pre-substitutes it).
|
|
84
80
|
* 3. Standard `Error.message`.
|
|
85
81
|
* 4. Generic translated fallback via `defaultErrorKey`.
|
|
86
82
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flowTransformer.d.ts","sourceRoot":"","sources":["../../src/utils/flowTransformer.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,
|
|
1
|
+
{"version":3,"file":"flowTransformer.d.ts","sourceRoot":"","sources":["../../src/utils/flowTransformer.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,WAAW,EAEZ,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAC,cAAc,EAAC,MAAM,yBAAyB,CAAC;AAEvD;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,KAAK,CAAC,EAAE;QACN,IAAI,EAAE,MAAM,CAAC;QACb,WAAW,EAAE,WAAW,CAAC;QACzB,OAAO,EAAE,WAAW,CAAC;KACtB,CAAC;IACF,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,OAAO,CAAC;CACrB;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;;OAGG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AAmHD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,mBAAmB,GAC9B,UAAU,GAAG,EACb,GAAG,cAAc,CAAC,GAAG,CAAC,EACtB,6BAA0B,EAC1B,OAAO,oBAAoB,GAAG,IAAI,KACjC,qBAAqB,EAsBvB,CAAC;AAEF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,mBAAmB,GAC9B,OAAO,iBAAiB,GAAG,GAAG,EAC9B,GAAG,cAAc,CAAC,GAAG,CAAC,EACtB,wBAAuC,KACtC,MAsCF,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,qBAAqB,GAChC,UAAU,GAAG,EACb,GAAG,cAAc,CAAC,GAAG,CAAC,EACtB,wBAAuC,KACtC,MAAM,GAAG,IAMX,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,GAChC,UAAU,GAAG,EACb,GAAG,cAAc,CAAC,GAAG,CAAC,EACtB,UAAS,oBAAyB,EAClC,OAAO,oBAAoB,GAAG,IAAI,KACjC;IACD,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACpC,UAAU,EAAE,qBAAqB,EAAE,CAAC;IACpC,WAAW,EAAE,MAAM,CAAC;CA8BrB,CAAC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import resolveTranslationsInArray_default from "./resolveTranslationsInArray.js";
|
|
2
|
+
import { hasUnresolvedTranslationParams } from "@thunderid/browser";
|
|
2
3
|
|
|
3
4
|
//#region src/utils/flowTransformer.ts
|
|
4
5
|
/**
|
|
@@ -87,8 +88,10 @@ const transformComponents = (response, t, resolveTranslations = true, meta) => {
|
|
|
87
88
|
* Extract error message from flow error response.
|
|
88
89
|
*
|
|
89
90
|
* Resolution order:
|
|
90
|
-
* 1. Structured `error` object: try i18n lookup via `t(error.message.key)`.
|
|
91
|
-
*
|
|
91
|
+
* 1. Structured `error` object: try i18n lookup via `t(error.message.key, error.message.params)`.
|
|
92
|
+
* Bundle entries keep the backend's `{{param(name)}}` placeholders, so `params` must be passed
|
|
93
|
+
* through; a resolved value that still holds an unsubstituted placeholder is treated as a miss.
|
|
94
|
+
* 2. Fallback to `defaultValue` from `message`, then `description` (the backend pre-substitutes it).
|
|
92
95
|
* 3. Standard `Error.message`.
|
|
93
96
|
* 4. Generic translated fallback via `defaultErrorKey`.
|
|
94
97
|
*/
|
|
@@ -96,11 +99,12 @@ const extractErrorMessage = (error, t, defaultErrorKey = "errors.flow.generic")
|
|
|
96
99
|
if (error && typeof error === "object" && error.error) {
|
|
97
100
|
const flowError = error.error;
|
|
98
101
|
if (flowError?.message?.key) {
|
|
99
|
-
const
|
|
100
|
-
|
|
102
|
+
const params = flowError.message.params;
|
|
103
|
+
const translated = t(flowError.message.key, params);
|
|
104
|
+
if (translated && translated !== flowError.message.key && !hasUnresolvedTranslationParams(translated)) return translated;
|
|
101
105
|
const systemKey = `system.${flowError.message.key}`;
|
|
102
|
-
const systemTranslated = t(systemKey);
|
|
103
|
-
if (systemTranslated && systemTranslated !== systemKey) return systemTranslated;
|
|
106
|
+
const systemTranslated = t(systemKey, params);
|
|
107
|
+
if (systemTranslated && systemTranslated !== systemKey && !hasUnresolvedTranslationParams(systemTranslated)) return systemTranslated;
|
|
104
108
|
}
|
|
105
109
|
const fallback = flowError?.message?.defaultValue ?? flowError?.description?.defaultValue;
|
|
106
110
|
if (fallback) return fallback;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flowTransformer.js","names":["mapping: Map<string, string>","transformedComponent: any","inputData: any","value: string","refMapping: Map<string, string>","actionMapping: Map<string, string>","inputsData: any[]","resolveTranslationsInArray","flowError: FlowErrorResponse['error']","translated: string","systemTranslated: string","fallback: string | undefined","additionalData: Record<string, any>","parsed: any"],"sources":["../../src/utils/flowTransformer.ts"],"sourcesContent":["// Copyright 2025-2026 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * @fileoverview Shared flow response transformer utilities for v2 embedded flows.\n *\n * This module provides reusable transformation functions for normalizing embedded flow\n * responses from ThunderID APIs. It handles both successful responses with component\n * extraction and error responses with proper error message extraction.\n *\n * Key features:\n * - Component extraction from flow meta structure\n * - Translation string resolution in components\n * - Error response detection and message extraction\n * - Configurable error handling (throw vs return errors)\n *\n * Usage:\n * ```typescript\n * import { normalizeFlowResponse } from '../../../utils/flowTransformer';\n *\n * const { executionId, components } = normalizeFlowResponse(apiResponse, t, {\n * defaultErrorKey: 'components.signIn.errors.generic'\n * });\n * ```\n *\n * This transformer is used by both SignIn and SignUp v2 components to ensure\n * consistent response handling across all embedded flows.\n */\n\nimport {EmbeddedFlowComponent, FlowMetadataResponse} from '@thunderid/browser';\nimport resolveTranslationsInArray from './resolveTranslationsInArray';\nimport {UseTranslation} from '../hooks/useTranslation';\n\n/**\n * Generic flow error response interface that covers common error structure\n */\nexport interface FlowErrorResponse {\n error?: {\n code: string;\n description: {key: string; defaultValue?: string};\n message: {key: string; defaultValue?: string};\n };\n executionId: string;\n flowStatus: 'ERROR';\n}\n\n/**\n * Configuration options for flow transformation\n */\nexport interface FlowTransformOptions {\n /**\n * Default error message key for translation fallback\n * @default 'errors.flow.generic'\n */\n defaultErrorKey?: string;\n /**\n * Whether to resolve translation strings or keep them as i18n keys\n * @default true\n */\n resolveTranslations?: boolean;\n /**\n * Whether to throw errors or return them as normalized response\n * @default true\n */\n throwOnError?: boolean;\n}\n\n/**\n * Create a mapping from ref to identifier based on data.inputs array.\n * This handles cases where meta.components use 'ref' to reference inputs,\n * and data.inputs contain the actual 'identifier' field.\n *\n * @param response - The flow response object\n * @returns Map of ref to identifier\n */\nconst createInputRefMapping = (response: any): Map<string, string> => {\n const mapping: Map<string, string> = new Map<string, string>();\n\n if (response?.data?.inputs && Array.isArray(response.data.inputs)) {\n response.data.inputs.forEach((input: any) => {\n if (input.ref && input.identifier) {\n mapping.set(input.ref, input.identifier);\n }\n });\n }\n\n return mapping;\n};\n\n/**\n * Create a mapping from action ref to nextNode based on data.actions array.\n * This handles cases where meta.components reference actions by ref,\n * and data.actions contain the actual nextNode field for routing.\n *\n * @param response - The flow response object\n * @returns Map of action ref to nextNode\n */\nconst createActionRefMapping = (response: any): Map<string, string> => {\n const mapping: Map<string, string> = new Map<string, string>();\n\n if (response?.data?.actions && Array.isArray(response.data.actions)) {\n response.data.actions.forEach((action: any) => {\n if (action.ref && action.nextNode) {\n mapping.set(action.ref, action.nextNode);\n }\n });\n }\n\n return mapping;\n};\n\n/**\n * Apply input ref mapping to components recursively.\n * This ensures that component.ref values are mapped to the correct identifier\n * from data.inputs, enabling proper form submission.\n *\n * @param components - Array of components to transform\n * @param refMapping - Map of ref to identifier\n * @param actionMapping - Map of action ref to nextNode\n * @param inputsData - Array of input data for resolving SELECT options\n * @returns Transformed components with correct identifiers and action references\n */\nconst applyInputRefMapping = (\n components: EmbeddedFlowComponent[],\n refMapping: Map<string, string>,\n actionMapping: Map<string, string>,\n inputsData: any[] = [],\n): EmbeddedFlowComponent[] =>\n components.map((component: EmbeddedFlowComponent) => {\n const transformedComponent: any = {...component} as EmbeddedFlowComponent & {\n actionRef?: string;\n options?: {label: string; value: string}[];\n };\n\n // If this component has a ref that maps to an identifier, update it\n if (transformedComponent.ref && refMapping.has(transformedComponent.ref)) {\n transformedComponent.ref = refMapping.get(transformedComponent.ref);\n }\n\n // For SELECT components, copy options from data.inputs\n // The component.id matches the input.ref in the data structure\n if (transformedComponent.type === 'SELECT' && component.id) {\n const inputData: any = inputsData.find((input: any) => input.ref === component.id);\n if (inputData?.options) {\n transformedComponent.options = inputData.options.map((opt: any) => {\n if (typeof opt === 'string') {\n return {label: opt, value: opt};\n }\n // Safely handle non-string values to prevent React key crashes\n const value: string = typeof opt.value === 'object' ? JSON.stringify(opt.value) : String(opt.value || '');\n const label: string = typeof opt.label === 'object' ? JSON.stringify(opt.label) : String(opt.label || value);\n\n return {label, value};\n });\n }\n }\n\n // If this is an action component, map its id to the nextNode\n // Store the nextNode reference as actionRef property for later use\n if (\n transformedComponent.type === 'ACTION' &&\n transformedComponent.id &&\n actionMapping.has(transformedComponent.id)\n ) {\n transformedComponent.actionRef = actionMapping.get(transformedComponent.id);\n }\n\n // Recursively apply to nested components\n if (transformedComponent.components && Array.isArray(transformedComponent.components)) {\n transformedComponent.components = applyInputRefMapping(\n transformedComponent.components,\n refMapping,\n actionMapping,\n inputsData,\n );\n }\n\n return transformedComponent;\n });\n\n/**\n * Transform and resolve translations in components from flow response.\n * This function extracts components from the response meta structure and optionally resolves\n * any translation strings within them. It also handles mapping of input refs to identifiers\n * and action refs to nextNode values.\n *\n * @param response - The flow response object containing components in meta structure\n * @param t - Translation function from useTranslation hook\n * @param resolveTranslations - Whether to resolve translation strings or keep them as i18n keys (default: true)\n * @returns Array of flow components with resolved or unresolved translations\n */\nexport const transformComponents = (\n response: any,\n t: UseTranslation['t'],\n resolveTranslations = true,\n meta?: FlowMetadataResponse | null,\n): EmbeddedFlowComponent[] => {\n if (!response?.data?.meta?.components) {\n return [];\n }\n\n let {components} = response.data.meta;\n\n // Create mapping from ref to identifier based on data.inputs\n const refMapping: Map<string, string> = createInputRefMapping(response);\n\n // Create mapping from action ref to nextNode based on data.actions\n const actionMapping: Map<string, string> = createActionRefMapping(response);\n\n // Get inputs data for SELECT option resolution\n const inputsData: any[] = response?.data?.inputs || [];\n\n // Apply ref and action mapping if there are any mappings\n if (refMapping.size > 0 || actionMapping.size > 0 || inputsData.length > 0) {\n components = applyInputRefMapping(components, refMapping, actionMapping, inputsData);\n }\n\n return resolveTranslations ? resolveTranslationsInArray(components, t, undefined, meta) : components;\n};\n\n/**\n * Extract error message from flow error response.\n *\n * Resolution order:\n * 1. Structured `error` object: try i18n lookup via `t(error.message.key)`.\n * 2. Fallback to `defaultValue` from `message`, then `description`.\n * 3. Standard `Error.message`.\n * 4. Generic translated fallback via `defaultErrorKey`.\n */\nexport const extractErrorMessage = (\n error: FlowErrorResponse | any,\n t: UseTranslation['t'],\n defaultErrorKey = 'errors.flow.generic',\n): string => {\n if (error && typeof error === 'object' && error.error) {\n const flowError: FlowErrorResponse['error'] = error.error;\n\n // 1. Try i18n lookup on message.key first (preferred for user-facing errors)\n if (flowError?.message?.key) {\n const translated: string = t(flowError.message.key);\n if (translated && translated !== flowError.message.key) {\n return translated;\n }\n\n // If the key resolved to itself, retry under the 'system:' namespace\n const systemKey = `system.${flowError.message.key}`;\n const systemTranslated: string = t(systemKey);\n if (systemTranslated && systemTranslated !== systemKey) {\n return systemTranslated;\n }\n }\n\n // 2. Fall back to defaultValue from message, then description\n const fallback: string | undefined = flowError?.message?.defaultValue ?? flowError?.description?.defaultValue;\n if (fallback) {\n return fallback;\n }\n }\n\n // Legacy backward compatibility\n if (error && typeof error === 'object' && error.failureReason) {\n return error.failureReason;\n }\n\n if (error instanceof Error && error.message) {\n return error.message;\n }\n\n return t(defaultErrorKey);\n};\n\n/**\n * Check if a response is an error response and extract the error message.\n * This function identifies error responses by checking for ERROR status and failure reasons.\n *\n * @param response - The flow response to check\n * @param t - Translation function for error messages\n * @param defaultErrorKey - Default translation key for generic errors\n * @returns Error message string if response is an error, null otherwise\n */\nexport const checkForErrorResponse = (\n response: any,\n t: UseTranslation['t'],\n defaultErrorKey = 'errors.flow.generic',\n): string | null => {\n if (response?.flowStatus === 'ERROR') {\n return extractErrorMessage(response, t, defaultErrorKey);\n }\n\n return null;\n};\n\n/**\n * Generic flow response normalizer that handles both success and error responses.\n * This is the main transformer function that should be used by all flow components.\n *\n * @param response - The raw flow response from the API\n * @param t - Translation function from useTranslation hook\n * @param options - Configuration options for transformation behavior\n * @returns Normalized flow response with executionId and transformed components\n * @throws {any} The original response if it's an error and throwOnError is true\n */\nexport const normalizeFlowResponse = (\n response: any,\n t: UseTranslation['t'],\n options: FlowTransformOptions = {},\n meta?: FlowMetadataResponse | null,\n): {\n additionalData: Record<string, any>;\n components: EmbeddedFlowComponent[];\n executionId: string;\n} => {\n const {throwOnError = true, defaultErrorKey = 'errors.flow.generic', resolveTranslations = true} = options;\n\n // Check if this is an error response\n const errorMessage: string | null = checkForErrorResponse(response, t, defaultErrorKey);\n\n if (errorMessage && throwOnError) {\n // Throw the original response so it can be caught by error handling\n throw response;\n }\n\n const additionalData: Record<string, any> = (response?.data?.additionalData as Record<string, any>) ?? {};\n\n // The consent prompt is serialized as a JSON string (array) by the backend.\n // Parse it and wrap in the expected {purposes: [...]} structure.\n if (typeof additionalData['consentPrompt'] === 'string') {\n try {\n const parsed: any = JSON.parse(additionalData['consentPrompt']);\n additionalData['consentPrompt'] = {purposes: Array.isArray(parsed) ? parsed : []};\n } catch {\n // Leave unparseable value as-is\n }\n }\n\n return {\n additionalData,\n components: transformComponents(response, t, resolveTranslations, meta),\n executionId: response.executionId,\n };\n};\n"],"mappings":";;;;;;;;;;;AA2EA,MAAM,yBAAyB,aAAuC;CACpE,MAAMA,0BAA+B,IAAI,KAAqB;AAE9D,KAAI,UAAU,MAAM,UAAU,MAAM,QAAQ,SAAS,KAAK,OAAO,CAC/D,UAAS,KAAK,OAAO,SAAS,UAAe;AAC3C,MAAI,MAAM,OAAO,MAAM,WACrB,SAAQ,IAAI,MAAM,KAAK,MAAM,WAAW;GAE1C;AAGJ,QAAO;;;;;;;;;;AAWT,MAAM,0BAA0B,aAAuC;CACrE,MAAMA,0BAA+B,IAAI,KAAqB;AAE9D,KAAI,UAAU,MAAM,WAAW,MAAM,QAAQ,SAAS,KAAK,QAAQ,CACjE,UAAS,KAAK,QAAQ,SAAS,WAAgB;AAC7C,MAAI,OAAO,OAAO,OAAO,SACvB,SAAQ,IAAI,OAAO,KAAK,OAAO,SAAS;GAE1C;AAGJ,QAAO;;;;;;;;;;;;;AAcT,MAAM,wBACJ,YACA,YACA,eACA,aAAoB,EAAE,KAEtB,WAAW,KAAK,cAAqC;CACnD,MAAMC,uBAA4B,EAAC,GAAG,WAAU;AAMhD,KAAI,qBAAqB,OAAO,WAAW,IAAI,qBAAqB,IAAI,CACtE,sBAAqB,MAAM,WAAW,IAAI,qBAAqB,IAAI;AAKrE,KAAI,qBAAqB,SAAS,YAAY,UAAU,IAAI;EAC1D,MAAMC,YAAiB,WAAW,MAAM,UAAe,MAAM,QAAQ,UAAU,GAAG;AAClF,M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QAAQ,IAAI;AACnD,OAAI,cAAc,eAAe,UAAU,QAAQ,IACjD,QAAO;GAIT,MAAM,YAAY,UAAU,UAAU,QAAQ;GAC9C,MAAMC,mBAA2B,EAAE,UAAU;AAC7C,OAAI,oBAAoB,qBAAqB,UAC3C,QAAO;;EAKX,MAAMC,WAA+B,WAAW,SAAS,gBAAgB,WAAW,aAAa;AACjG,MAAI,SACF,QAAO;;AAKX,KAAI,SAAS,OAAO,UAAU,YAAY,MAAM,cAC9C,QAAO,MAAM;AAGf,KAAI,iBAAiB,SAAS,MAAM,QAClC,QAAO,MAAM;AAGf,QAAO,EAAE,gBAAgB;;;;;;;;;;;AAY3B,MAAa,yBACX,UACA,GACA,kBAAkB,0BACA;AAClB,KAAI,UAAU,eAAe,QAC3B,QAAO,oBAAoB,UAAU,GAAG,gBAAgB;AAG1D,QAAO;;;;;;;;;;;;AAaT,MAAa,yBACX,UACA,GACA,UAAgC,EAAE,EAClC,SAKG;CACH,MAAM,EAAC,eAAe,MAAM,kBAAkB,uBAAuB,sBAAsB,SAAQ;AAKnG,KAFoC,sBAAsB,UAAU,GAAG,gBAAgB,IAEnE,aAElB,OAAM;CAGR,MAAMC,iBAAuC,UAAU,MAAM,kBAA0C,EAAE;AAIzG,KAAI,OAAO,eAAe,qBAAqB,SAC7C,KAAI;EACF,MAAMC,SAAc,KAAK,MAAM,eAAe,iBAAiB;AAC/D,iBAAe,mBAAmB,EAAC,UAAU,MAAM,QAAQ,OAAO,GAAG,SAAS,EAAE,EAAC;SAC3E;AAKV,QAAO;EACL;EACA,YAAY,oBAAoB,UAAU,GAAG,qBAAqB,KAAK;EACvE,aAAa,SAAS;EACvB"}
|
|
1
|
+
{"version":3,"file":"flowTransformer.js","names":["mapping: Map<string, string>","transformedComponent: any","inputData: any","value: string","refMapping: Map<string, string>","actionMapping: Map<string, string>","inputsData: any[]","resolveTranslationsInArray","flowError: FlowErrorResponse['error']","params: Record<string, string> | undefined","translated: string","systemTranslated: string","fallback: string | undefined","additionalData: Record<string, any>","parsed: any"],"sources":["../../src/utils/flowTransformer.ts"],"sourcesContent":["// Copyright 2025-2026 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * @fileoverview Shared flow response transformer utilities for v2 embedded flows.\n *\n * This module provides reusable transformation functions for normalizing embedded flow\n * responses from ThunderID APIs. It handles both successful responses with component\n * extraction and error responses with proper error message extraction.\n *\n * Key features:\n * - Component extraction from flow meta structure\n * - Translation string resolution in components\n * - Error response detection and message extraction\n * - Configurable error handling (throw vs return errors)\n *\n * Usage:\n * ```typescript\n * import { normalizeFlowResponse } from '../../../utils/flowTransformer';\n *\n * const { executionId, components } = normalizeFlowResponse(apiResponse, t, {\n * defaultErrorKey: 'components.signIn.errors.generic'\n * });\n * ```\n *\n * This transformer is used by both SignIn and SignUp v2 components to ensure\n * consistent response handling across all embedded flows.\n */\n\nimport {\n EmbeddedFlowComponent,\n FlowMetadataResponse,\n I18nMessage,\n hasUnresolvedTranslationParams,\n} from '@thunderid/browser';\nimport resolveTranslationsInArray from './resolveTranslationsInArray';\nimport {UseTranslation} from '../hooks/useTranslation';\n\n/**\n * Generic flow error response interface that covers common error structure\n */\nexport interface FlowErrorResponse {\n error?: {\n code: string;\n description: I18nMessage;\n message: I18nMessage;\n };\n executionId: string;\n flowStatus: 'ERROR';\n}\n\n/**\n * Configuration options for flow transformation\n */\nexport interface FlowTransformOptions {\n /**\n * Default error message key for translation fallback\n * @default 'errors.flow.generic'\n */\n defaultErrorKey?: string;\n /**\n * Whether to resolve translation strings or keep them as i18n keys\n * @default true\n */\n resolveTranslations?: boolean;\n /**\n * Whether to throw errors or return them as normalized response\n * @default true\n */\n throwOnError?: boolean;\n}\n\n/**\n * Create a mapping from ref to identifier based on data.inputs array.\n * This handles cases where meta.components use 'ref' to reference inputs,\n * and data.inputs contain the actual 'identifier' field.\n *\n * @param response - The flow response object\n * @returns Map of ref to identifier\n */\nconst createInputRefMapping = (response: any): Map<string, string> => {\n const mapping: Map<string, string> = new Map<string, string>();\n\n if (response?.data?.inputs && Array.isArray(response.data.inputs)) {\n response.data.inputs.forEach((input: any) => {\n if (input.ref && input.identifier) {\n mapping.set(input.ref, input.identifier);\n }\n });\n }\n\n return mapping;\n};\n\n/**\n * Create a mapping from action ref to nextNode based on data.actions array.\n * This handles cases where meta.components reference actions by ref,\n * and data.actions contain the actual nextNode field for routing.\n *\n * @param response - The flow response object\n * @returns Map of action ref to nextNode\n */\nconst createActionRefMapping = (response: any): Map<string, string> => {\n const mapping: Map<string, string> = new Map<string, string>();\n\n if (response?.data?.actions && Array.isArray(response.data.actions)) {\n response.data.actions.forEach((action: any) => {\n if (action.ref && action.nextNode) {\n mapping.set(action.ref, action.nextNode);\n }\n });\n }\n\n return mapping;\n};\n\n/**\n * Apply input ref mapping to components recursively.\n * This ensures that component.ref values are mapped to the correct identifier\n * from data.inputs, enabling proper form submission.\n *\n * @param components - Array of components to transform\n * @param refMapping - Map of ref to identifier\n * @param actionMapping - Map of action ref to nextNode\n * @param inputsData - Array of input data for resolving SELECT options\n * @returns Transformed components with correct identifiers and action references\n */\nconst applyInputRefMapping = (\n components: EmbeddedFlowComponent[],\n refMapping: Map<string, string>,\n actionMapping: Map<string, string>,\n inputsData: any[] = [],\n): EmbeddedFlowComponent[] =>\n components.map((component: EmbeddedFlowComponent) => {\n const transformedComponent: any = {...component} as EmbeddedFlowComponent & {\n actionRef?: string;\n options?: {label: string; value: string}[];\n };\n\n // If this component has a ref that maps to an identifier, update it\n if (transformedComponent.ref && refMapping.has(transformedComponent.ref)) {\n transformedComponent.ref = refMapping.get(transformedComponent.ref);\n }\n\n // For SELECT components, copy options from data.inputs\n // The component.id matches the input.ref in the data structure\n if (transformedComponent.type === 'SELECT' && component.id) {\n const inputData: any = inputsData.find((input: any) => input.ref === component.id);\n if (inputData?.options) {\n transformedComponent.options = inputData.options.map((opt: any) => {\n if (typeof opt === 'string') {\n return {label: opt, value: opt};\n }\n // Safely handle non-string values to prevent React key crashes\n const value: string = typeof opt.value === 'object' ? JSON.stringify(opt.value) : String(opt.value || '');\n const label: string = typeof opt.label === 'object' ? JSON.stringify(opt.label) : String(opt.label || value);\n\n return {label, value};\n });\n }\n }\n\n // If this is an action component, map its id to the nextNode\n // Store the nextNode reference as actionRef property for later use\n if (\n transformedComponent.type === 'ACTION' &&\n transformedComponent.id &&\n actionMapping.has(transformedComponent.id)\n ) {\n transformedComponent.actionRef = actionMapping.get(transformedComponent.id);\n }\n\n // Recursively apply to nested components\n if (transformedComponent.components && Array.isArray(transformedComponent.components)) {\n transformedComponent.components = applyInputRefMapping(\n transformedComponent.components,\n refMapping,\n actionMapping,\n inputsData,\n );\n }\n\n return transformedComponent;\n });\n\n/**\n * Transform and resolve translations in components from flow response.\n * This function extracts components from the response meta structure and optionally resolves\n * any translation strings within them. It also handles mapping of input refs to identifiers\n * and action refs to nextNode values.\n *\n * @param response - The flow response object containing components in meta structure\n * @param t - Translation function from useTranslation hook\n * @param resolveTranslations - Whether to resolve translation strings or keep them as i18n keys (default: true)\n * @returns Array of flow components with resolved or unresolved translations\n */\nexport const transformComponents = (\n response: any,\n t: UseTranslation['t'],\n resolveTranslations = true,\n meta?: FlowMetadataResponse | null,\n): EmbeddedFlowComponent[] => {\n if (!response?.data?.meta?.components) {\n return [];\n }\n\n let {components} = response.data.meta;\n\n // Create mapping from ref to identifier based on data.inputs\n const refMapping: Map<string, string> = createInputRefMapping(response);\n\n // Create mapping from action ref to nextNode based on data.actions\n const actionMapping: Map<string, string> = createActionRefMapping(response);\n\n // Get inputs data for SELECT option resolution\n const inputsData: any[] = response?.data?.inputs || [];\n\n // Apply ref and action mapping if there are any mappings\n if (refMapping.size > 0 || actionMapping.size > 0 || inputsData.length > 0) {\n components = applyInputRefMapping(components, refMapping, actionMapping, inputsData);\n }\n\n return resolveTranslations ? resolveTranslationsInArray(components, t, undefined, meta) : components;\n};\n\n/**\n * Extract error message from flow error response.\n *\n * Resolution order:\n * 1. Structured `error` object: try i18n lookup via `t(error.message.key, error.message.params)`.\n * Bundle entries keep the backend's `{{param(name)}}` placeholders, so `params` must be passed\n * through; a resolved value that still holds an unsubstituted placeholder is treated as a miss.\n * 2. Fallback to `defaultValue` from `message`, then `description` (the backend pre-substitutes it).\n * 3. Standard `Error.message`.\n * 4. Generic translated fallback via `defaultErrorKey`.\n */\nexport const extractErrorMessage = (\n error: FlowErrorResponse | any,\n t: UseTranslation['t'],\n defaultErrorKey = 'errors.flow.generic',\n): string => {\n if (error && typeof error === 'object' && error.error) {\n const flowError: FlowErrorResponse['error'] = error.error;\n\n // 1. Try i18n lookup on message.key first (preferred for user-facing errors)\n if (flowError?.message?.key) {\n const params: Record<string, string> | undefined = flowError.message.params;\n\n const translated: string = t(flowError.message.key, params);\n if (translated && translated !== flowError.message.key && !hasUnresolvedTranslationParams(translated)) {\n return translated;\n }\n\n // If the key resolved to itself, retry under the 'system:' namespace\n const systemKey = `system.${flowError.message.key}`;\n const systemTranslated: string = t(systemKey, params);\n if (systemTranslated && systemTranslated !== systemKey && !hasUnresolvedTranslationParams(systemTranslated)) {\n return systemTranslated;\n }\n }\n\n // 2. Fall back to defaultValue from message, then description\n const fallback: string | undefined = flowError?.message?.defaultValue ?? flowError?.description?.defaultValue;\n if (fallback) {\n return fallback;\n }\n }\n\n // Legacy backward compatibility\n if (error && typeof error === 'object' && error.failureReason) {\n return error.failureReason;\n }\n\n if (error instanceof Error && error.message) {\n return error.message;\n }\n\n return t(defaultErrorKey);\n};\n\n/**\n * Check if a response is an error response and extract the error message.\n * This function identifies error responses by checking for ERROR status and failure reasons.\n *\n * @param response - The flow response to check\n * @param t - Translation function for error messages\n * @param defaultErrorKey - Default translation key for generic errors\n * @returns Error message string if response is an error, null otherwise\n */\nexport const checkForErrorResponse = (\n response: any,\n t: UseTranslation['t'],\n defaultErrorKey = 'errors.flow.generic',\n): string | null => {\n if (response?.flowStatus === 'ERROR') {\n return extractErrorMessage(response, t, defaultErrorKey);\n }\n\n return null;\n};\n\n/**\n * Generic flow response normalizer that handles both success and error responses.\n * This is the main transformer function that should be used by all flow components.\n *\n * @param response - The raw flow response from the API\n * @param t - Translation function from useTranslation hook\n * @param options - Configuration options for transformation behavior\n * @returns Normalized flow response with executionId and transformed components\n * @throws {any} The original response if it's an error and throwOnError is true\n */\nexport const normalizeFlowResponse = (\n response: any,\n t: UseTranslation['t'],\n options: FlowTransformOptions = {},\n meta?: FlowMetadataResponse | null,\n): {\n additionalData: Record<string, any>;\n components: EmbeddedFlowComponent[];\n executionId: string;\n} => {\n const {throwOnError = true, defaultErrorKey = 'errors.flow.generic', resolveTranslations = true} = options;\n\n // Check if this is an error response\n const errorMessage: string | null = checkForErrorResponse(response, t, defaultErrorKey);\n\n if (errorMessage && throwOnError) {\n // Throw the original response so it can be caught by error handling\n throw response;\n }\n\n const additionalData: Record<string, any> = (response?.data?.additionalData as Record<string, any>) ?? {};\n\n // The consent prompt is serialized as a JSON string (array) by the backend.\n // Parse it and wrap in the expected {purposes: [...]} structure.\n if (typeof additionalData['consentPrompt'] === 'string') {\n try {\n const parsed: any = JSON.parse(additionalData['consentPrompt']);\n additionalData['consentPrompt'] = {purposes: Array.isArray(parsed) ? parsed : []};\n } catch {\n // Leave unparseable value as-is\n }\n }\n\n return {\n additionalData,\n components: transformComponents(response, t, resolveTranslations, meta),\n executionId: response.executionId,\n };\n};\n"],"mappings":";;;;;;;;;;;;AAgFA,MAAM,yBAAyB,aAAuC;CACpE,MAAMA,0BAA+B,IAAI,KAAqB;AAE9D,KAAI,UAAU,MAAM,UAAU,MAAM,QAAQ,SAAS,KAAK,OAAO,CAC/D,UAAS,KAAK,OAAO,SAAS,UAAe;AAC3C,MAAI,MAAM,OAAO,MAAM,WACrB,SAAQ,IAAI,MAAM,KAAK,MAAM,WAAW;GAE1C;AAGJ,QAAO;;;;;;;;;;AAWT,MAAM,0BAA0B,aAAuC;CACrE,MAAMA,0BAA+B,IAAI,KAAqB;AAE9D,KAAI,UAAU,MAAM,WAAW,MAAM,QAAQ,SAAS,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AuB,sBAAsB,SAAQ;AAKnG,KAFoC,sBAAsB,UAAU,GAAG,gBAAgB,IAEnE,aAElB,OAAM;CAGR,MAAMC,iBAAuC,UAAU,MAAM,kBAA0C,EAAE;AAIzG,KAAI,OAAO,eAAe,qBAAqB,SAC7C,KAAI;EACF,MAAMC,SAAc,KAAK,MAAM,eAAe,iBAAiB;AAC/D,iBAAe,mBAAmB,EAAC,UAAU,MAAM,QAAQ,OAAO,GAAG,SAAS,EAAE,EAAC;SAC3E;AAKV,QAAO;EACL;EACA,YAAY,oBAAoB,UAAU,GAAG,qBAAqB,KAAK;EACvE,aAAa,SAAS;EACvB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@thunderid/react",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.1",
|
|
4
4
|
"description": "React SDK for ThunderID",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"thunderid",
|
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
"@floating-ui/react": "0.27.12",
|
|
63
63
|
"dompurify": "3.4.11",
|
|
64
64
|
"tslib": "2.8.1",
|
|
65
|
-
"@thunderid/browser": "^1.0.
|
|
65
|
+
"@thunderid/browser": "^1.0.1"
|
|
66
66
|
},
|
|
67
67
|
"publishConfig": {
|
|
68
68
|
"access": "public"
|