import { a as createI18n, i as setI18nInstance, n as useTranslation, r as hasI18nInstance } from "./i18n-DoP1NB7u.js";
import { _ as y, l as A, p as d, v as u } from "./vendor-preact-DThS2ZQ_.js";
import { t as setUiConfig } from "./uiConfig-D2_wawvr.js";
import { t as Page } from "./page-DidH_RkX.js";
import { t as Button } from "./button-BMYTQ8fc.js";
import { t as ErrorIcon } from "./errorIcon-BA4T6iy-.js";
import { initializeWasmUtil, resolveWasmConfig, setWasmConfig, upgradeToWasmHttpClient, warmupWasm } from "@incodetech/core/wasm";
import { getDeviceClass } from "@incodetech/core/device";
import { createOrchestratedFlowManager, getFlow, getRequiredWasmPipelines } from "@incodetech/core/flow";
import { getFinishStatus, initializeSession } from "@incodetech/core/session";
import { api } from "@incodetech/core/http";
//#region src/shared/terminalErrorPage/terminalErrorPage.tsx
/**
* Terminal error screen shown by `<incode-flow>` / `<incode-workflow>` when
* the SDK reaches an unrecoverable error state — both during initialization
* (e.g. `/omni/start` or `/omni/workflow/info` returns `4028` "not activated")
* and during the flow/workflow lifecycle (e.g. `/omni/workflow/process/node`,
* `/omni/finish-status`, or a child module's terminal error).
*
* When the error carries a backend-provided `error`/`message` (surfaced via
* `IncodeApiError.message` from core's service wrappers), it's rendered
* verbatim as the subtitle. Generic transport failures fall back to a
* translated default.
*
* Layout: `Page` is used for the Incode logo + optional "Verified by Incode"
* footer only — the title/subtitle/titleTopSlot slots are deliberately *not*
* used so we can vertically center the status block (icon + title + message)
* within the available height at every viewport size. The Try again button
* is anchored to the bottom of the content area. The screen intentionally
* has no close button — the only exit is "Try again", which delegates to
* `onRetry`.
*/
var TerminalErrorPage = ({ message, onRetry }) => {
	const { t } = useTranslation();
	const titleRef = A(null);
	y(() => {
		titleRef.current?.focus();
	}, []);
	const handleRetry = () => {
		if (onRetry) {
			onRetry();
			return;
		}
		if (typeof window !== "undefined") window.location.reload();
	};
	return /* @__PURE__ */ u(Page, {
		className: "IncodeTerminalErrorPage",
		"data-testid": "terminal-error-page",
		children: /* @__PURE__ */ u("div", {
			class: "IncodeTerminalErrorPageBody",
			children: [/* @__PURE__ */ u("div", {
				class: "IncodeTerminalErrorPageStatus",
				children: [
					/* @__PURE__ */ u(ErrorIcon, { size: 64 }),
					/* @__PURE__ */ u("h2", {
						ref: titleRef,
						class: "IncodeTerminalErrorPageTitle",
						tabIndex: -1,
						children: t("common.somethingWentWrong")
					}),
					/* @__PURE__ */ u("p", {
						class: "IncodeTerminalErrorPageMessage",
						children: message ?? t("common.unexpectedError")
					})
				]
			}), /* @__PURE__ */ u("div", {
				class: "IncodeTerminalErrorPageFooter",
				children: /* @__PURE__ */ u(Button, {
					onClick: handleRetry,
					children: t("common.tryAgain")
				})
			})]
		})
	});
};
//#endregion
//#region src/styles/generatePalette.ts
function hexToHsl(hex) {
	let normalizedHex = hex.replace("#", "");
	if (normalizedHex.length === 3) normalizedHex = normalizedHex.split("").map((char) => char + char).join("");
	const result = /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(normalizedHex);
	if (!result) return null;
	const r = Number.parseInt(result[1], 16) / 255;
	const g = Number.parseInt(result[2], 16) / 255;
	const b = Number.parseInt(result[3], 16) / 255;
	const max = Math.max(r, g, b);
	const min = Math.min(r, g, b);
	let h = 0;
	let s = 0;
	const l = (max + min) / 2;
	if (max !== min) {
		const d = max - min;
		s = l > .5 ? d / (2 - max - min) : d / (max + min);
		switch (max) {
			case r:
				h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
				break;
			case g:
				h = ((b - r) / d + 2) / 6;
				break;
			case b:
				h = ((r - g) / d + 4) / 6;
				break;
		}
	}
	return {
		h: h * 360,
		s: s * 100,
		l: l * 100
	};
}
function hslToHex(h, s, l) {
	const hNorm = h / 360;
	const sNorm = s / 100;
	const lNorm = l / 100;
	let r;
	let g;
	let b;
	if (sNorm === 0) r = g = b = lNorm;
	else {
		const hue2rgb = (p, q, t) => {
			if (t < 0) t += 1;
			if (t > 1) t -= 1;
			if (t < 1 / 6) return p + (q - p) * 6 * t;
			if (t < 1 / 2) return q;
			if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
			return p;
		};
		const q = lNorm < .5 ? lNorm * (1 + sNorm) : lNorm + sNorm - lNorm * sNorm;
		const p = 2 * lNorm - q;
		r = hue2rgb(p, q, hNorm + 1 / 3);
		g = hue2rgb(p, q, hNorm);
		b = hue2rgb(p, q, hNorm - 1 / 3);
	}
	const toHex = (n) => {
		const hex = Math.round(n * 255).toString(16);
		return hex.length === 1 ? `0${hex}` : hex;
	};
	return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
function generateBrandPalette(mainColor) {
	const hsl = hexToHsl(mainColor);
	if (!hsl) throw new Error(`Invalid color format: ${mainColor}`);
	return {
		"50": hslToHex(hsl.h, hsl.s, 95),
		"200": hslToHex(hsl.h, hsl.s, 80),
		"300": hslToHex(hsl.h, hsl.s, 65),
		"400": hslToHex(hsl.h, hsl.s, Math.min(100, hsl.l + 10)),
		"500": mainColor,
		"600": hslToHex(hsl.h, hsl.s, Math.max(0, hsl.l - 10)),
		"900": hslToHex(hsl.h, hsl.s, 20)
	};
}
//#endregion
//#region src/styles/applyTheme.ts
function applyTheme(mainColor, buttonColor) {
	if (typeof document === "undefined") return;
	const palette = generateBrandPalette(mainColor);
	let styleElement = document.getElementById("incode-theme");
	if (!styleElement) {
		styleElement = document.createElement("style");
		styleElement.id = "incode-theme";
		document.head.appendChild(styleElement);
	}
	const buttonTextColor = buttonColor || "#ffffff";
	const css = `
    :root,
    :host {
      --primitive-color-brand-50: ${palette["50"]};
      --primitive-color-brand-200: ${palette["200"]};
      --primitive-color-brand-300: ${palette["300"]};
      --primitive-color-brand-400: ${palette["400"]};
      --primitive-color-brand-500: ${palette["500"]};
      --primitive-color-brand-600: ${palette["600"]};
      --primitive-color-brand-900: ${palette["900"]};
      --button-primary-text-default: ${buttonTextColor};
    }
  `;
	styleElement.textContent = css;
}
//#endregion
//#region src/styles/fetchTheme.ts
async function fetchAssets() {
	return (await api.get("/omni/asset/fetch-all")).data;
}
var dataUrlCache = /* @__PURE__ */ new Map();
async function urlToDataUrl(url) {
	if (url.startsWith("data:")) return url;
	const cached = dataUrlCache.get(url);
	if (cached) return cached;
	const blob = await (await fetch(url)).blob();
	const dataUrl = await new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.onloadend = () => resolve(reader.result);
		reader.onerror = reject;
		reader.readAsDataURL(blob);
	});
	dataUrlCache.set(url, dataUrl);
	return dataUrl;
}
async function fetchTheme$1() {
	const assets = await fetchAssets();
	if (!assets.theme) throw new Error("Theme URL not found in assets response");
	const themeUrl = assets.theme;
	const isAbsoluteUrl = themeUrl.startsWith("http://") || themeUrl.startsWith("https://");
	let theme;
	if (isAbsoluteUrl) {
		const themeResponse = await fetch(themeUrl);
		if (!themeResponse.ok) throw new Error(`Failed to fetch theme: ${themeResponse.statusText}`);
		theme = await themeResponse.json();
	} else theme = (await api.get(themeUrl)).data;
	const logoUrl = assets["logo.png"] || assets["logo.svg"] || assets["logo.jpg"] || assets["logo.jpeg"] || assets["logo.webp"] || theme.logo;
	let cachedLogoUrl = logoUrl;
	if (logoUrl) cachedLogoUrl = await urlToDataUrl(logoUrl);
	return {
		...theme,
		logo: cachedLogoUrl
	};
}
async function fetchAndApplyTheme() {
	const theme = await fetchTheme$1();
	if (theme.main) applyTheme(theme.main, theme.buttonColor);
	return theme;
}
//#endregion
//#region src/modules/flow/flowInit.ts
var lazyIdModule = () => import("./id/id.es.js").then((m) => m.Id);
var loadLazyHomeScreen = () => import("./homeScreen-W6-PF75j.js").then((m) => m.HomeScreen);
var homeScreenPreloadPromise;
/**
* Headless flow keys: backend-only steps with no UI. `<incode-flow>` renders
* an empty shell while the core machine for the step runs and resolves —
* see `flow.tsx`. Each key still resolves to its own core machine inside
* `getLazyCoreMachineLoader` (e.g. `IP_ADDRESS` → `noOpFlowModuleMachine`,
* `TRUST_GRAPH` → `trustGraphMachine`).
*/
var HEADLESS_FLOW_MODULE_KEYS = new Set(["IP_ADDRESS", "TRUST_GRAPH"]);
function getLazyCoreMachineLoader(moduleKey) {
	if (moduleKey === "IP_ADDRESS") return () => import("@incodetech/core/flow").then((m) => m.noOpFlowModuleMachine);
	if (moduleKey === "TRUST_GRAPH") return () => import("@incodetech/core/trust-graph").then((m) => m.trustGraphMachine);
	if (moduleKey === "REDIRECT_TO_MOBILE") return () => import("@incodetech/core/redirect-to-mobile").then((m) => m.redirectToMobileMachine);
	if (moduleKey === "PHONE") return () => import("@incodetech/core/phone").then((m) => m.phoneMachine);
	if (moduleKey === "EMAIL") return () => import("@incodetech/core/email").then((m) => m.emailMachine);
	if (moduleKey === "SELFIE") return () => import("@incodetech/core/selfie").then((m) => m.selfieMachine);
	if (moduleKey === "AUTHENTICATION") return () => import("@incodetech/core/authentication").then((m) => m.authenticationMachine);
	if (moduleKey === "ID" || moduleKey === "TUTORIAL_ID" || moduleKey === "SECOND_ID") return () => import("@incodetech/core/id").then((m) => m.idCaptureMachine);
	if (moduleKey === "ID_OCR") return () => import("@incodetech/core/id-ocr").then((m) => m.idOcrStateMachine);
	if (moduleKey === "CPF_OCR") return () => import("@incodetech/core/cpf-ocr").then((m) => m.cpfOcrMachine);
	if (moduleKey === "FACE_MATCH") return () => import("@incodetech/core/face-match").then((m) => m.faceMatchMachine);
	if (moduleKey === "CURP_VALIDATION") return () => import("@incodetech/core/curp-validation").then((m) => m.curpValidationMachine);
	if (moduleKey === "GOVT_VALIDATION_PROVISIONING" || moduleKey === "INE_VALIDATION") return () => import("@incodetech/core/government-validation").then((m) => m.governmentValidationMachine);
	if (moduleKey === "GEOLOCATION") return () => import("@incodetech/core/geolocation").then((m) => m.geolocationMachine);
	if (moduleKey === "EXTERNAL_VERIFICATION") return () => import("@incodetech/core/ekyc").then((m) => m.ekycMachine);
	if (moduleKey === "EKYB") return () => import("@incodetech/core/ekyb").then((m) => m.ekybMachine);
	if (moduleKey === "DOCUMENT_CAPTURE" || moduleKey === "ADDRESS") return () => import("@incodetech/core/document-capture").then((m) => m.documentCaptureMachine);
	if (moduleKey === "COMBINED_CONSENT") return () => import("@incodetech/core/consent").then((m) => m.consentMachine);
	if (moduleKey === "MANDATORY_CONSENT" || moduleKey === "ML_CONSENT") return () => import("@incodetech/core/mandatory-consent").then((m) => m.mandatoryConsentMachine);
	if (moduleKey === "SIGNATURE") return () => import("@incodetech/core/signature").then((m) => m.signatureMachine);
	if (moduleKey === "ANTIFRAUD") return () => import("@incodetech/core/antifraud").then((m) => m.antifraudMachine);
	if (moduleKey === "CUSTOM_FIELDS") return () => import("@incodetech/core/custom-fields").then((m) => m.customFieldsMachine);
	if (moduleKey === "WATCHLIST") return () => import("@incodetech/core/watchlist").then((m) => m.watchlistMachine);
	if (moduleKey === "WATCHLIST_BUSINESS") return () => import("@incodetech/core/watchlist-for-business").then((m) => m.watchlistForBusinessMachine);
	if (moduleKey === "INCODE_WATCHLIST") return () => import("@incodetech/core/custom-watchlist").then((m) => m.customWatchlistMachine);
	if (moduleKey === "AE_SIGNATURE") return () => import("@incodetech/core/ae-signature").then((m) => m.aeSignatureMachine);
	if (moduleKey === "QE_SIGNATURE") return () => import("@incodetech/core/qe-signature").then((m) => m.qeSignatureMachine);
	if (moduleKey === "CROSS_DOCUMENT_DATA_MATCH") return () => import("@incodetech/core/cross-document-data-match").then((m) => m.crossDocumentDataMatchMachine);
	if (moduleKey === "DYNAMIC_FORMS") return () => import("@incodetech/core/dynamic-forms").then((m) => m.dynamicFormsMachine);
	if (moduleKey === "CERTIFICATE_ISSUANCE") return () => import("@incodetech/core/certificate-issuance").then((m) => m.certificateIssuanceMachine);
	if (moduleKey === "FIELD_COMPARISON") return () => import("@incodetech/core/field-comparison").then((m) => m.fieldComparisonMachine);
	if (moduleKey === "FISCAL_QR") return () => import("@incodetech/core/fiscal-qr").then((m) => m.fiscalQrMachine);
}
function buildLazyCoreRegistryForFlow(flowModules) {
	const registry = {};
	for (const flowModule of flowModules) {
		const moduleKey = flowModule.key;
		if (registry[moduleKey]) continue;
		const loader = getLazyCoreMachineLoader(moduleKey);
		if (loader) registry[moduleKey] = loader;
	}
	return registry;
}
var LAZY_UI_MODULES = {
	REDIRECT_TO_MOBILE: () => import("./redirect-to-mobile/redirect-to-mobile.es.js").then((m) => m.RedirectToMobile),
	PHONE: () => import("./phone/phone.es.js").then((m) => m.Phone),
	EMAIL: () => import("./email/email.es.js").then((m) => m.Email),
	SELFIE: () => import("./selfie/selfie.es.js").then((m) => m.Selfie),
	AUTHENTICATION: () => import("./authentication/authentication.es.js").then((m) => m.Authentication),
	ID: lazyIdModule,
	ID_CAPTURE: lazyIdModule,
	TUTORIAL_ID: lazyIdModule,
	SECOND_ID: lazyIdModule,
	FACE_MATCH: () => import("./faceMatch-DiL0VrHf.js").then((m) => m.FaceMatch),
	CURP_VALIDATION: () => import("./curp-validation/curp-validation.es.js").then((m) => m.CurpValidation),
	GOVT_VALIDATION_PROVISIONING: () => import("./governmentValidation/governmentValidation.es.js").then((m) => m.GovernmentValidation),
	INE_VALIDATION: () => import("./governmentValidation/governmentValidation.es.js").then((m) => m.GovernmentValidation),
	GEOLOCATION: () => import("./geolocation/geolocation.es.js").then((m) => m.Geolocation),
	EXTERNAL_VERIFICATION: () => import("./ekycModule-BoE8h4bJ.js").then((m) => m.EkycModule),
	EKYB: () => import("./ekybModule-DZ9pDtci.js").then((m) => m.EkybModule),
	DOCUMENT_CAPTURE: () => import("./documentCapture-fTvBfHQV.js").then((m) => m.DocumentCapture),
	ADDRESS: () => import("./documentCapture-fTvBfHQV.js").then((m) => m.DocumentCapture),
	COMBINED_CONSENT: () => import("./consent/consent.es.js").then((m) => m.Consent),
	MANDATORY_CONSENT: () => import("./mandatoryConsent-CLGvxsw5.js").then((m) => m.MandatoryConsent),
	ML_CONSENT: () => import("./mandatoryConsent-CLGvxsw5.js").then((m) => m.MandatoryConsent),
	SIGNATURE: () => import("./signature/signature.es.js").then((m) => m.Signature),
	ID_OCR: () => import("./idOcr-DceREbB3.js").then((m) => m.IdOcr),
	CPF_OCR: () => import("./cpfOcr-CosgY9tM.js").then((m) => m.CpfOcr),
	ANTIFRAUD: () => import("./antifraud/antifraud.es.js").then((m) => m.Antifraud),
	CUSTOM_FIELDS: () => import("./customFields-ni4vyNOO.js").then((m) => m.CustomFields),
	WATCHLIST: () => import("./watchlist/watchlist.es.js").then((m) => m.Watchlist),
	WATCHLIST_BUSINESS: () => import("./watchlistForBusiness-D5U_gDhd.js").then((m) => m.WatchlistForBusiness),
	INCODE_WATCHLIST: () => import("./customWatchlist-B78DSWtc.js").then((m) => m.CustomWatchlist),
	AE_SIGNATURE: () => import("./ae-signature/ae-signature.es.js").then((m) => m.AeSignature),
	QE_SIGNATURE: () => import("./qe-signature/qe-signature.es.js").then((m) => m.QeSignature),
	CROSS_DOCUMENT_DATA_MATCH: () => import("./cross-document-data-match/cross-document-data-match.es.js").then((m) => m.CrossDocumentDataMatch),
	DYNAMIC_FORMS: () => import("./dynamicForms-Cq0F0XHQ.js").then((m) => m.DynamicForms),
	CERTIFICATE_ISSUANCE: () => import("./certificate-issuance/certificate-issuance.es.js").then((m) => m.CertificateIssuance),
	FIELD_COMPARISON: () => import("./fieldComparison-DcCU02Yj.js").then((m) => m.FieldComparison),
	FISCAL_QR: () => import("./fiscal-qr/fiscal-qr.es.js").then((m) => m.FiscalQr)
};
function loadHomeScreen() {
	return loadLazyHomeScreen();
}
function preloadHomeScreen() {
	if (homeScreenPreloadPromise) return;
	homeScreenPreloadPromise = loadHomeScreen();
	homeScreenPreloadPromise.catch(() => {
		homeScreenPreloadPromise = void 0;
	});
}
var redirectToMobilePreloadPromise;
/**
* Eagerly prefetches the REDIRECT_TO_MOBILE UI + core chunks.
* Call on desktop during flow init so the QR paints instantly when the
* orchestrator injects REDIRECT_TO_MOBILE as the first step.
*/
function preloadRedirectToMobile() {
	if (redirectToMobilePreloadPromise) return;
	const uiLoader = LAZY_UI_MODULES.REDIRECT_TO_MOBILE;
	const coreLoader = getLazyCoreMachineLoader("REDIRECT_TO_MOBILE");
	const promises = [];
	if (uiLoader) promises.push(uiLoader());
	if (coreLoader) promises.push(coreLoader());
	redirectToMobilePreloadPromise = Promise.all(promises);
	redirectToMobilePreloadPromise.catch(() => {
		redirectToMobilePreloadPromise = void 0;
	});
}
function createFlowManager(options = {}) {
	const scopedLazyModules = {};
	const isDesktop = options.isDesktop ?? getDeviceClass() === "desktop";
	const { enableHome, ...flowFetchOptions } = options;
	let endScreen = {
		endScreenTitle: null,
		endScreenText: null
	};
	const manager = createOrchestratedFlowManager({
		enableHome,
		getFlow: async (signal) => {
			const flow = await getFlow(signal, {
				...flowFetchOptions,
				isDesktop
			});
			const scopedRegistry = buildLazyCoreRegistryForFlow(flow.flowModules ?? []);
			for (const key of Object.keys(scopedLazyModules)) delete scopedLazyModules[key];
			Object.assign(scopedLazyModules, scopedRegistry);
			return flow;
		},
		getFinishStatus: async (flowId, signal) => {
			return {
				...await getFinishStatus(flowId, signal),
				...endScreen
			};
		},
		lazyModules: scopedLazyModules
	});
	return Object.assign(manager, { setEndScreenTexts(endScreenTitle, endScreenText) {
		endScreen = {
			endScreenTitle,
			endScreenText
		};
	} });
}
async function setupSDK(options) {
	await initializeSession({ token: options.token });
	if (hasI18nInstance()) return;
	setI18nInstance(createI18n(options.lang ? { lang: options.lang } : void 0));
}
async function initializeFlowManager(options) {
	const { token, lang, flowManager } = options;
	await setupSDK({
		token,
		lang
	});
	flowManager.load();
}
async function fetchTheme() {
	try {
		const theme = await fetchAndApplyTheme();
		const uiConfig = {
			logoSrc: theme.logo,
			subtitle: theme.subtitle,
			hideFooterBranding: theme.hideFooterBranding
		};
		setUiConfig(uiConfig);
		return {
			theme,
			uiConfig
		};
	} catch {
		return {};
	}
}
function warmupWasmIfNeeded(managerState, wasmConfig) {
	if (managerState.currentStep === "REDIRECT_TO_MOBILE") return;
	const requiredPipelines = getRequiredWasmPipelines(managerState.flow);
	if (requiredPipelines.length > 0) {
		const resolved = resolveWasmConfig({
			...wasmConfig ?? {},
			pipelines: requiredPipelines
		});
		const configToStore = {
			...resolved,
			pipelines: resolved.pipelines ? [...resolved.pipelines] : void 0
		};
		setWasmConfig(configToStore);
		warmupWasm(resolved).then(() => initializeWasmUtil(configToStore)).then(() => upgradeToWasmHttpClient(configToStore)).catch((error) => {
			console.error("WASM warmup failed:", error);
		});
	}
}
function preloadFirstModule(managerState) {
	const firstStep = managerState.currentStep;
	if (firstStep) {
		const loader = LAZY_UI_MODULES[firstStep];
		if (loader) loader().catch(() => {});
	}
}
//#endregion
//#region src/modules/flow/unsupportedModule.tsx
var UnsupportedModule = ({ moduleKey, onNext }) => {
	return /* @__PURE__ */ u("section", {
		class: "IncodeUnsupportedModule",
		"aria-live": "polite",
		children: /* @__PURE__ */ u("div", {
			class: "IncodeUnsupportedModuleContent",
			children: [
				/* @__PURE__ */ u("h2", {
					class: "IncodeUnsupportedModuleTitle",
					children: "Module not available"
				}),
				/* @__PURE__ */ u("p", {
					class: "IncodeUnsupportedModuleMessage",
					children: [
						"The \"",
						moduleKey,
						"\" module is not yet supported in this version."
					]
				}),
				/* @__PURE__ */ u(Button, {
					onClick: onNext,
					class: "IncodeUnsupportedModuleButton",
					"data-testid": "unsupported-module-next-button",
					children: "Next"
				})
			]
		})
	});
};
//#endregion
//#region src/modules/flow/extractIncodeStatus.ts
/**
* Extract the Incode-specific status code (e.g. `4028` for "Flow is not
* activated", `4081`/`4083` for QR failures) from an error caught during SDK
* init.
*
* Both `QrValidationError` and `IncodeApiError` (thrown from core's
* `validateQrUuid`/`createSession`/`getWorkflowConfig`) expose a numeric
* `status` field, so a duck-typed check is enough — no class-level coupling
* to core, which keeps this safe under stale `dist/*.d.ts` during local dev.
*/
function extractIncodeStatus(err) {
	if (typeof err === "object" && err !== null && "status" in err && typeof err.status === "number") return err.status;
}
//#endregion
//#region src/shared/selfLoading/resolveApiKey.ts
function toHex(buffer) {
	return Array.from(new Uint8Array(buffer), (value) => value.toString(16).padStart(2, "0")).join("");
}
async function sha1(value) {
	const subtle = globalThis.crypto?.subtle;
	if (!subtle) throw new Error("SHA-1 is not available in this environment");
	return toHex(await subtle.digest("SHA-1", new TextEncoder().encode(value)));
}
async function resolveApiKey(config) {
	if (typeof config.apiKey === "string") return config.apiKey;
	if (typeof config.clientId === "string") return sha1(config.clientId);
	throw new Error("Self-loading mode requires apiKey or clientId");
}
//#endregion
//#region src/modules/flow/headlessModule.ts
var HeadlessWorkflowModule = () => null;
var lazyHeadlessWorkflowModule = () => Promise.resolve(HeadlessWorkflowModule);
var HEADLESS_WORKFLOW_MODULE_KEYS = new Set(["IDENTITY_SEARCH"]);
//#endregion
//#region src/modules/flow/useModuleLoader.ts
function getLoadErrorMessage(error, fallbackMessage) {
	return error instanceof Error ? error.message : fallbackMessage;
}
var loadedComponents = /* @__PURE__ */ new WeakMap();
var inflightLoaders = /* @__PURE__ */ new WeakMap();
function getLoaderKey(loader) {
	return loader;
}
function getCachedComponent(loader) {
	if (!loader) return void 0;
	return loadedComponents.get(getLoaderKey(loader));
}
function loadComponent(loader) {
	const key = getLoaderKey(loader);
	const cached = loadedComponents.get(key);
	if (cached) return Promise.resolve(cached);
	const inflight = inflightLoaders.get(key);
	if (inflight) return inflight;
	const promise = loader().then((Component) => {
		loadedComponents.set(key, Component);
		inflightLoaders.delete(key);
		return Component;
	}).catch((error) => {
		inflightLoaders.delete(key);
		throw error;
	});
	inflightLoaders.set(key, promise);
	return promise;
}
function computeInitialState(loader) {
	if (!loader) return { status: "idle" };
	const cached = getCachedComponent(loader);
	if (cached) return {
		status: "loaded",
		Component: cached
	};
	return { status: "loading" };
}
function resolveModuleLoader(moduleKey, modules, headlessModuleKeys) {
	if (!moduleKey) return void 0;
	return modules[moduleKey] ?? (headlessModuleKeys?.has(moduleKey) ? lazyHeadlessWorkflowModule : void 0);
}
function useLazyComponentLoader(options) {
	const { loader, onLoading, onLoaded, onError } = options;
	const [state, setState] = d(() => computeInitialState(loader));
	const prevLoaderRef = A(loader);
	const onLoadingRef = A(onLoading);
	const onLoadedRef = A(onLoaded);
	const onErrorRef = A(onError);
	y(() => {
		onLoadingRef.current = onLoading;
		onLoadedRef.current = onLoaded;
		onErrorRef.current = onError;
	}, [
		onLoading,
		onLoaded,
		onError
	]);
	if (prevLoaderRef.current !== loader) {
		prevLoaderRef.current = loader;
		setState(computeInitialState(loader));
	}
	y(() => {
		if (!loader) return;
		if (getCachedComponent(loader)) {
			onLoadedRef.current?.();
			return;
		}
		onLoadingRef.current?.();
		let cancelled = false;
		loadComponent(loader).then((Component) => {
			if (!cancelled) {
				setState({
					status: "loaded",
					Component
				});
				onLoadedRef.current?.();
			}
		}).catch((error) => {
			if (!cancelled) {
				const errorMessage = getLoadErrorMessage(error, "Failed to load component");
				setState({
					status: "error",
					error: errorMessage
				});
				onErrorRef.current?.(errorMessage);
			}
		});
		return () => {
			cancelled = true;
		};
	}, [loader]);
	return state;
}
function useModuleLoader(options) {
	const { moduleKey, modules, headlessModuleKeys, onModuleLoading, onModuleLoaded, onError } = options;
	const [unsupportedModuleKey, setUnsupportedModuleKey] = d(void 0);
	const loader = resolveModuleLoader(moduleKey, modules, headlessModuleKeys);
	const state = useLazyComponentLoader({
		loader,
		onLoading: moduleKey ? () => onModuleLoading?.(moduleKey) : void 0,
		onLoaded: moduleKey ? () => onModuleLoaded?.(moduleKey) : void 0,
		onError: moduleKey ? (errorMessage) => onError?.(`Failed to load ${moduleKey}: ${errorMessage}`) : void 0
	});
	y(() => {
		if (!moduleKey) {
			setUnsupportedModuleKey(void 0);
			return;
		}
		if (!loader) setUnsupportedModuleKey(moduleKey);
		else setUnsupportedModuleKey(void 0);
	}, [loader, moduleKey]);
	if (!moduleKey) return { status: "idle" };
	if (unsupportedModuleKey) return {
		status: "unsupported",
		moduleKey: unsupportedModuleKey
	};
	if (state.status === "idle" || state.status === "loading") return {
		status: "loading",
		moduleKey
	};
	if (state.status === "error") return {
		status: "error",
		moduleKey,
		error: state.error
	};
	return {
		status: "loaded",
		moduleKey,
		Component: state.Component
	};
}
function useModulePreloader(options) {
	const { moduleKey, modules } = options;
	const loader = moduleKey ? modules[moduleKey] : void 0;
	const state = useLazyComponentLoader({ loader });
	return loader != null && state.status === "loaded";
}
function schedulePrefetch(run) {
	if (typeof requestIdleCallback !== "undefined") requestIdleCallback(() => {
		run();
	});
	else setTimeout(run, 0);
}
function usePrefetchNextModule(steps, currentStepIndex, modules, currentModuleLoaded) {
	const prefetchedRef = A(/* @__PURE__ */ new Set());
	y(() => {
		if (!currentModuleLoaded) return;
		if (currentStepIndex < steps.length - 1) {
			const nextStep = steps[currentStepIndex + 1];
			if (nextStep && !prefetchedRef.current.has(nextStep)) {
				prefetchedRef.current.add(nextStep);
				const loader = modules[nextStep];
				if (loader) schedulePrefetch(() => {
					loader().catch(() => {
						prefetchedRef.current.delete(nextStep);
					});
				});
			}
		}
	}, [
		steps,
		currentStepIndex,
		modules,
		currentModuleLoaded
	]);
}
//#endregion
export { warmupWasmIfNeeded as _, resolveApiKey as a, HEADLESS_FLOW_MODULE_KEYS as c, fetchTheme as d, initializeFlowManager as f, setupSDK as g, preloadRedirectToMobile as h, HEADLESS_WORKFLOW_MODULE_KEYS as i, LAZY_UI_MODULES as l, preloadHomeScreen as m, useModulePreloader as n, extractIncodeStatus as o, preloadFirstModule as p, usePrefetchNextModule as r, UnsupportedModule as s, useModuleLoader as t, createFlowManager as u, fetchAndApplyTheme as v, TerminalErrorPage as y };
