import type { PlatformContext } from '../types' export type ExperimentAwarePlatformContext = PlatformContext & { currentExperiment?: unknown currentExperimentId?: unknown experiment?: unknown experimentId?: unknown } export function getInjectedPlatformContext(): PlatformContext | undefined { if (typeof window === 'undefined') return undefined return (window as unknown as { __MINT_PLATFORM__?: PlatformContext }).__MINT_PLATFORM__ } /** Return the platform's canonical plugin identity for the mounted frontend. */ export function resolveCurrentPluginId(): string | undefined { const pluginId = getInjectedPlatformContext()?.plugin?.id return typeof pluginId === 'string' && pluginId ? pluginId : undefined } export function getInjectedExperimentContext(): ExperimentAwarePlatformContext | undefined { return getInjectedPlatformContext() as ExperimentAwarePlatformContext | undefined } export function currentExperimentFromContext( context: ExperimentAwarePlatformContext | undefined = getInjectedExperimentContext(), ): TExperiment | undefined { const candidate = context?.currentExperiment ?? context?.experiment return candidate && typeof candidate === 'object' ? candidate as TExperiment : undefined } export function currentExperimentIdFromContext( context: ExperimentAwarePlatformContext | undefined = getInjectedExperimentContext(), ): number | undefined { return parseExperimentId( context?.currentExperimentId ?? context?.experimentId ?? context?.currentExperiment ?? context?.experiment, ) } export function currentExperimentIdFromUrl(): number | undefined { if (typeof window === 'undefined') return undefined const location = window.location const params = new URLSearchParams(location?.search ?? '') return parseExperimentId(params.get('experimentId') ?? params.get('experiment_id')) ?? experimentIdFromPath(location?.pathname ?? '') ?? experimentIdFromPath((location?.hash ?? '').replace(/^#\/?/, '/')) } export function resolveCurrentExperimentId( context: ExperimentAwarePlatformContext | undefined = getInjectedExperimentContext(), ): number | undefined { return currentExperimentIdFromContext(context) ?? currentExperimentIdFromUrl() } export function parseExperimentId(value: unknown): number | undefined { if (typeof value === 'number' && Number.isFinite(value)) return value if (typeof value === 'string' && value.trim()) { const parsed = Number(value) return Number.isFinite(parsed) ? parsed : undefined } if (value && typeof value === 'object' && 'id' in value) { return parseExperimentId((value as { id?: unknown }).id) } return undefined } function experimentIdFromPath(path: string): number | undefined { const segments = path.split('/').filter(Boolean) for (let index = 0; index < segments.length - 1; index += 1) { const segment = segments[index]?.toLowerCase() if (segment === 'experiment' || segment === 'experiments') { return parseExperimentId(decodeURIComponent(segments[index + 1] ?? '')) } } return undefined }