@appfunnel-dev/sdk 2.0.0-canary.2 → 2.0.0-canary.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.
- package/dist/{checkout-DiQvRT5q.d.ts → checkout-7Dy6IedP.d.ts} +3 -0
- package/dist/{checkout-CZmEvWfC.d.cts → checkout-Dz8cGkB_.d.cts} +3 -0
- package/dist/{chunk-7UC5VXOR.js → chunk-AKO6XKXP.js} +28 -8
- package/dist/chunk-AKO6XKXP.js.map +1 -0
- package/dist/{chunk-VQOD2Z6Q.cjs → chunk-CY4VBSMX.cjs} +5 -3
- package/dist/chunk-CY4VBSMX.cjs.map +1 -0
- package/dist/{chunk-Z3TWO2PW.cjs → chunk-JSRKA375.cjs} +29 -7
- package/dist/chunk-JSRKA375.cjs.map +1 -0
- package/dist/{chunk-UIR6TGEW.js → chunk-M6U3FNRW.js} +5 -3
- package/dist/chunk-M6U3FNRW.js.map +1 -0
- package/dist/driver-paddle.cjs +14 -14
- package/dist/driver-paddle.d.cts +1 -1
- package/dist/driver-paddle.d.ts +1 -1
- package/dist/driver-paddle.js +1 -1
- package/dist/driver-stripe.cjs +13 -13
- package/dist/driver-stripe.d.cts +1 -1
- package/dist/driver-stripe.d.ts +1 -1
- package/dist/driver-stripe.js +1 -1
- package/dist/index.cjs +56 -43
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -5
- package/dist/index.d.ts +13 -5
- package/dist/index.js +18 -5
- package/dist/index.js.map +1 -1
- package/dist/{manifest-DQThneiG.d.cts → manifest-Cr2y1op6.d.cts} +40 -3
- package/dist/{manifest-DQThneiG.d.ts → manifest-Cr2y1op6.d.ts} +40 -3
- package/dist/manifest-entry.cjs +129 -20
- package/dist/manifest-entry.cjs.map +1 -1
- package/dist/manifest-entry.d.cts +28 -3
- package/dist/manifest-entry.d.ts +28 -3
- package/dist/manifest-entry.js +105 -5
- package/dist/manifest-entry.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-7UC5VXOR.js.map +0 -1
- package/dist/chunk-UIR6TGEW.js.map +0 -1
- package/dist/chunk-VQOD2Z6Q.cjs.map +0 -1
- package/dist/chunk-Z3TWO2PW.cjs.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/state/variableStore.ts","../src/state/store.ts","../src/state/context.ts","../src/tracking/tracking.ts","../src/tracking/bus.ts","../src/i18n/translation.ts","../src/commerce/catalog.ts","../src/flow/flow.tsx","../src/modals/registry.tsx","../src/modals/sheet.tsx","../src/commerce/checkout.tsx","../../../node_modules/sonner/dist/index.mjs","../src/toast/toast.tsx","../src/state/namespaces.ts","../src/tracking/platformTracker.ts","../src/flow/mount.tsx","../src/flow/components.tsx","../src/tracking/catalog.ts","../src/embed/script.tsx"],"names":["now","createContext","createElement","useContext","useMemo","useCallback","useEffect","useState","page","useRef","toast","jsx","height","heights","_toast_classNames","_toast_classNames1","offset","Toaster","toasts","id","position","index","value","Fragment"],"mappings":";;;;;;;;;AAgBO,IAAM,gBAAN,MAAoB;AAAA,EAMzB,YAAY,OAAA,EAAwC;AAJpD,IAAA,IAAA,CAAQ,SAAA,uBAAgB,GAAA,EAAoB;AAE5C;AAAA,IAAA,IAAA,CAAQ,cAAwB,EAAC;AAG/B,IAAA,IAAA,CAAK,KAAA,GAAQ,EAAE,GAAG,OAAA,EAAQ;AAAA,EAC5B;AAAA,EAEA,QAAA,GAA0C;AACxC,IAAA,OAAO,IAAA,CAAK,KAAA;AAAA,EACd;AAAA,EAEA,IAAI,GAAA,EAA4B;AAC9B,IAAA,OAAO,IAAA,CAAK,MAAM,GAAG,CAAA;AAAA,EACvB;AAAA,EAEA,GAAA,CAAI,KAAa,KAAA,EAA4B;AAC3C,IAAA,IAAI,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA,KAAM,KAAA,EAAO;AAC/B,IAAA,IAAA,CAAK,KAAA,GAAQ,EAAE,GAAG,IAAA,CAAK,OAA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AG,CAAC,CAAA;AACrF,MAAA,EAAA,CAAG,gBAAA,CAAiB,MAAA,EAAQ,MAAM,MAAA,IAAU,CAAA;AAC5C,MAAA,EAAA,CAAG,gBAAA,CAAiB,SAAS,MAAM;AACjC,QAAA,QAAA,CAAS,OAAO,GAAG,CAAA;AACnB,QAAA,OAAA,IAAU;AAAA,MACZ,CAAC,CAAA;AACD,MAAA,QAAA,CAAS,IAAA,CAAK,YAAY,EAAE,CAAA;AAAA,IAC9B,CAAA;AAEA,IAAA,IAAI,aAAa,YAAA,EAAc;AAC7B,MAAA,MAAM,MAAO,MAAA,CACV,mBAAA;AACH,MAAA,IAAI,GAAA,EAAK;AACP,QAAA,GAAA,CAAI,MAAM,CAAA;AAAA,MACZ,CAAA,MAAO;AACL,QAAA,MAAM,CAAA,GAAI,UAAA,CAAW,MAAA,EAAQ,CAAC,CAAA;AAC9B,QAAA,OAAO,MAAM,aAAa,CAAC,CAAA;AAAA,MAC7B;AACA,MAAA;AAAA,IACF;AACA,IAAA,MAAA,EAAO;AAAA,EAGT,CAAA,EAAG,CAAC,GAAA,EAAK,EAAE,CAAC,CAAA;AAEZ,EAAA,OAAO,IAAA;AACT","file":"index.js","sourcesContent":["import type { VariableValue } from '../types'\n\n/**\n * External variable store for funnel variables — the flat, reactive key/value\n * store under the v2 namespaces. Components subscribe selectively via\n * `useSyncExternalStore`, so only components depending on changed keys re-render.\n * (Seeding lives in {@link ./store}.`createFunnelStore`.)\n */\ninterface ScopedListener {\n listener: () => void\n /** Exact keys to watch, or null for all changes */\n keys: string[] | null\n /** Prefix to watch (e.g. 'answers.'), or null for all */\n prefix: string | null\n}\n\nexport class VariableStore {\n private state: Record<string, VariableValue>\n private listeners = new Set<ScopedListener>()\n /** Tracks which keys changed in the last mutation — used by scoped notify */\n private changedKeys: string[] = []\n\n constructor(initial: Record<string, VariableValue>) {\n this.state = { ...initial }\n }\n\n getState(): Record<string, VariableValue> {\n return this.state\n }\n\n get(key: string): VariableValue {\n return this.state[key]\n }\n\n set(key: string, value: VariableValue): void {\n if (this.state[key] === value) return\n this.state = { ...this.state, [key]: value }\n this.changedKeys = [key]\n this.notify()\n }\n\n setState(updater: (prev: Record<string, VariableValue>) => Record<string, VariableValue>): void {\n const prev = this.state\n const next = updater(prev)\n if (next === prev) return\n this.state = next\n // Compute changed keys\n this.changedKeys = []\n for (const key of Object.keys(next)) {\n if (next[key] !== prev[key]) this.changedKeys.push(key)\n }\n for (const key of Object.keys(prev)) {\n if (!(key in next) && prev[key] !== undefined) this.changedKeys.push(key)\n }\n this.notify()\n }\n\n /** Batch set multiple variables at once */\n setMany(updates: Record<string, VariableValue>): void {\n const changed: string[] = []\n const next = { ...this.state }\n for (const [key, value] of Object.entries(updates)) {\n if (next[key] !== value) {\n next[key] = value\n changed.push(key)\n }\n }\n if (changed.length === 0) return\n this.state = next\n this.changedKeys = changed\n this.notify()\n }\n\n /**\n * Subscribe to store changes.\n *\n * @param listener - callback fired when relevant keys change\n * @param scope - optional scope to limit notifications:\n * - `{ keys: ['data.x', 'user.email'] }` — only fire when these exact keys change\n * - `{ prefix: 'answers.' }` — only fire when any key starting with this prefix changes\n * - omit or `{}` — fire on every change (global listener)\n */\n subscribe(\n listener: () => void,\n scope?: { keys?: string[]; prefix?: string },\n ): () => void {\n const entry: ScopedListener = {\n listener,\n keys: scope?.keys || null,\n prefix: scope?.prefix || null,\n }\n this.listeners.add(entry)\n return () => this.listeners.delete(entry)\n }\n\n private notify(): void {\n const changed = this.changedKeys\n for (const entry of this.listeners) {\n // Global listener — no scope\n if (!entry.keys && !entry.prefix) {\n entry.listener()\n continue\n }\n // Key-scoped listener\n if (entry.keys) {\n if (changed.some((k) => entry.keys!.includes(k))) {\n entry.listener()\n }\n continue\n }\n // Prefix-scoped listener\n if (entry.prefix) {\n if (changed.some((k) => k.startsWith(entry.prefix!))) {\n entry.listener()\n }\n }\n }\n }\n}\n","/**\n * v2 store seeding — builds a {@link VariableStore} holding only the **writable**\n * namespaces (`user` / `responses` / `data`), each persisted to the backend.\n *\n * Seeds the {@link VariableStore} with v2 prefixes (no legacy `answers.`/`query.`\n * aliasing). Read-only computed values do NOT live\n * here — see {@link ./context}. Three deliberate namespaces:\n *\n * - `user.*` persistent identity attributes (cross-session)\n * - `responses.*` the clean, aggregated funnel answers\n * - `data.*` working/scratch state — persisted (so reload + return survive)\n * but kept separate from responses so analytics aggregates only\n * real answers and `data` can hold intermediate garbage\n */\n\nimport type { VariableValue, VariableConfig } from '../types'\nimport { VariableStore } from './variableStore'\n\n/** v2 namespace → store-key prefix (sans trailing dot). 1:1, no legacy aliasing. */\nexport const NAMESPACE_PREFIX = {\n user: 'user',\n responses: 'responses',\n data: 'data',\n} as const\n\nexport type WritableNamespace = keyof typeof NAMESPACE_PREFIX\n\n/** Built-in user attributes — always present so reads never `undefined`. */\nconst BUILTIN_USER: Record<string, VariableValue> = {\n 'user.email': '',\n 'user.name': '',\n}\n\nexport interface FunnelStoreConfig {\n responses?: Record<string, VariableConfig>\n data?: Record<string, VariableConfig>\n}\n\nfunction defaultFor(type: string): VariableValue {\n switch (type) {\n case 'string': return ''\n case 'number': return 0\n case 'boolean': return false\n case 'stringArray': return []\n default: return ''\n }\n}\n\n/**\n * Seed a store from a funnel's declared `responses`/`data` defaults, then layer\n * server / session-restored values on top (highest priority).\n */\nexport function createFunnelStore(\n config: FunnelStoreConfig = {},\n sessionValues?: Record<string, VariableValue>,\n): VariableStore {\n const initial: Record<string, VariableValue> = { ...BUILTIN_USER }\n\n for (const [key, cfg] of Object.entries(config.responses ?? {})) {\n initial[`responses.${key}`] = cfg.default ?? defaultFor(cfg.type)\n }\n for (const [key, cfg] of Object.entries(config.data ?? {})) {\n initial[`data.${key}`] = cfg.default ?? defaultFor(cfg.type)\n }\n\n if (sessionValues) {\n for (const [key, value] of Object.entries(sessionValues)) {\n if (value !== undefined) initial[key] = value\n }\n }\n\n return new VariableStore(initial)\n}\n","/**\n * v2 `context` — the **read-only, computed** namespace.\n *\n * Everything the funnel can *read* but never *write*: the device, the visitor's\n * locale, the current page, acquisition params (UTM), the session, and system\n * facts (funnel id, test/live mode, clock). It supersedes the v0 flat\n * `page.*`/`device.*`/`browser.*`/`os.*`/`query.*`/`metadata.*` system variables\n * (see {@link ./systemVariables}) by folding them into one nested object.\n *\n * Why it's *not* in the {@link ./variableStore}: the store holds **writable**\n * state (`user`/`responses`/`data`) that persists + re-renders per key. Context\n * is derived and read-only, so it lives as a plain object on a React context —\n * no subscriptions, no churn. The one moving part (`page`) is merged into the\n * snapshot from navigation state at read time.\n *\n * Authors read it through hooks (`useDevice()`, `useLocale()`, `usePage()`,\n * `useUtm()`) or inside routing/condition predicates as `s.context.*`.\n */\n\n// ── Shape ────────────────────────────────────────────────\n\nexport interface DeviceContext {\n type: 'mobile' | 'tablet' | 'desktop'\n isMobile: boolean\n isTablet: boolean\n screenWidth: number\n screenHeight: number\n viewportWidth: number\n viewportHeight: number\n colorDepth: number\n pixelRatio: number\n}\n\nexport interface BrowserContext {\n name: string\n version: string\n userAgent: string\n language: string\n cookieEnabled: boolean\n online: boolean\n}\n\nexport interface OsContext {\n name: string\n timezone: string\n}\n\nexport interface LocaleContext {\n /** Full locale, e.g. `en-US`. */\n locale: string\n /** Language subtag, e.g. `en`. */\n language: string\n /** Region subtag, e.g. `US` (may be empty). */\n region: string\n /** IANA timezone, e.g. `America/New_York`. */\n timeZone: string\n}\n\nexport interface PageContext {\n /** Current page key. */\n key: string\n /** Current page URL slug (`meta.slug`, defaults to the key) — what the renderer puts in the path. */\n slug: string\n /** 0-based position in the visited history. */\n index: number\n /** Total pages in the (expected) flow. */\n total: number\n /** 0–100. */\n progressPercentage: number\n /** Epoch ms the current page was entered. */\n startedAt: number\n}\n\n/** Acquisition / ad params captured on entry (the old `query.*` utm slice). */\nexport interface UtmContext {\n source?: string\n medium?: string\n campaign?: string\n content?: string\n term?: string\n [key: string]: string | undefined\n}\n\n/**\n * Per-network ad **click-ids** captured from the entry URL — the matching signals\n * the server CAPI needs. Named per network (not a generic bag) so the platform +\n * each integration map them precisely; `[key]` catches any others.\n */\nexport interface ClickIdContext {\n /** Meta / Facebook */\n fbclid?: string\n /** Google Ads (+ gbraid/wbraid for app↔web) */\n gclid?: string\n gbraid?: string\n wbraid?: string\n /** Microsoft / Bing */\n msclkid?: string\n /** TikTok */\n ttclid?: string\n /** Twitter / X */\n twclid?: string\n /** Snapchat */\n sccid?: string\n /** LinkedIn */\n li_fat_id?: string\n /** Pinterest */\n epik?: string\n /** Reddit */\n rdt_cid?: string\n [key: string]: string | undefined\n}\n\n/**\n * The full acquisition snapshot captured once on entry — the funnel reads `utm` /\n * `clickIds` off {@link FunnelContext}; the SDK forwards this whole thing to the\n * tracker (`setAcquisition`) so the platform persists it **first-class**: per-visit\n * on the session + **first-touch (write-once) on the Customer**, and the click-ids /\n * `_fbp`/`_fbc` cookies feed CAPI. Not stored as a generic attribute/answer.\n */\nexport interface Acquisition {\n utm: UtmContext\n clickIds: ClickIdContext\n /** CAPI cookies (`_fbp`/`_fbc`) read from `document.cookie` (not funnel-readable). */\n cookies: { fbp?: string; fbc?: string }\n /** `document.referrer` at entry. */\n referrer: string\n /** Entry URL path (the landing page). */\n landingPath: string\n}\n\nexport interface SessionContext {\n /** Server session id; null until resolved. */\n id: string | null\n /** Epoch ms the session began. */\n startedAt: number\n /** `document.referrer` at entry. */\n referrer: string\n}\n\n/**\n * Durable identity for **stable experiment bucketing** (phase-4 §4.2). The\n * preferred seed is `customerId` once known; before identification it's the\n * signed anonymous `visitorId` (P1). It is deliberately **not** the session id or\n * fingerprint — a returning visitor (e.g. via winback) must keep their variant\n * across sessions/devices (landmine #4). Both null = unidentifiable traffic, and\n * the experiment layer falls back to control rather than bucket on nothing.\n */\nexport interface IdentityContext {\n /** Known customer id (post-identification). The preferred bucketing seed. */\n customerId: string | null\n /** Signed anonymous visitor id. The fallback bucketing seed. */\n visitorId: string | null\n}\n\nexport interface SystemContext {\n funnelId: string\n campaignId: string\n /** Render mode — `test` for preview/QA, `live` for public traffic. */\n mode: 'test' | 'live'\n /** Epoch ms captured at build time (stable per render, not a live clock). */\n now: number\n}\n\n/** The whole read-only computed namespace, as read in predicates: `s.context.*`. */\nexport interface FunnelContext {\n device: DeviceContext\n browser: BrowserContext\n os: OsContext\n locale: LocaleContext\n page: PageContext\n utm: UtmContext\n /** Per-network ad click-ids captured on entry (funnel-readable; also forwarded for CAPI). */\n clickIds: ClickIdContext\n session: SessionContext\n identity: IdentityContext\n system: SystemContext\n}\n\n// ── Detection ────────────────────────────────────────────\n\ninterface RawBrowser {\n device: DeviceContext\n browser: BrowserContext\n os: OsContext\n locale: LocaleContext\n}\n\nlet cached: RawBrowser | null = null\n\nfunction extractVersion(ua: string, regex: RegExp): string {\n return ua.match(regex)?.[1] ?? '0'\n}\n\n/**\n * Sniff device/browser/os/locale from the environment, once. SSR-safe: returns\n * neutral defaults when `window` is absent. (Self-contained v2 detector — the v0\n * {@link ./systemVariables} equivalent emits flat store keys; this returns the\n * nested shape.)\n */\nfunction detect(): RawBrowser {\n if (cached) return cached\n\n if (typeof window === 'undefined') {\n cached = {\n device: {\n type: 'desktop', isMobile: false, isTablet: false,\n screenWidth: 0, screenHeight: 0, viewportWidth: 0, viewportHeight: 0,\n colorDepth: 24, pixelRatio: 1,\n },\n browser: {\n name: 'Unknown', version: '0', userAgent: 'unknown',\n language: 'en', cookieEnabled: true, online: true,\n },\n os: { name: 'Unknown', timezone: 'UTC' },\n locale: { locale: 'en', language: 'en', region: '', timeZone: 'UTC' },\n }\n return cached\n }\n\n const ua = navigator.userAgent\n const l = ua.toLowerCase()\n\n let name = 'Unknown'\n let version = '0'\n if (l.includes('firefox')) { name = 'Firefox'; version = extractVersion(ua, /Firefox\\/(\\d+[\\d.]*)/) }\n else if (l.includes('edg')) { name = 'Edge'; version = extractVersion(ua, /Edg\\/(\\d+[\\d.]*)/) }\n else if (l.includes('chrome') && !l.includes('edg')) { name = 'Chrome'; version = extractVersion(ua, /Chrome\\/(\\d+[\\d.]*)/) }\n else if (l.includes('safari') && !l.includes('chrome')) { name = 'Safari'; version = extractVersion(ua, /Version\\/(\\d+[\\d.]*)/) }\n\n let osName = 'Unknown'\n if (l.includes('win')) osName = 'Windows'\n else if (l.includes('mac')) osName = 'macOS'\n else if (l.includes('linux') && !l.includes('android')) osName = 'Linux'\n else if (l.includes('android')) osName = 'Android'\n else if (/iphone|ipad|ipod/.test(l)) osName = 'iOS'\n\n let type: DeviceContext['type'] = 'desktop'\n if (/mobile|android(?!.*tablet)|iphone|ipod/.test(l)) type = 'mobile'\n else if (/tablet|ipad/.test(l)) type = 'tablet'\n\n const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'\n const fullLocale = navigator.language || 'en'\n const [language = 'en', region = ''] = fullLocale.split('-')\n\n cached = {\n device: {\n type, isMobile: type === 'mobile', isTablet: type === 'tablet',\n screenWidth: window.screen?.width || 0,\n screenHeight: window.screen?.height || 0,\n viewportWidth: window.innerWidth || 0,\n viewportHeight: window.innerHeight || 0,\n colorDepth: window.screen?.colorDepth || 24,\n pixelRatio: window.devicePixelRatio || 1,\n },\n browser: {\n name, version, userAgent: ua,\n language: fullLocale,\n cookieEnabled: navigator.cookieEnabled ?? true,\n online: navigator.onLine ?? true,\n },\n os: { name: osName, timezone: timeZone },\n locale: { locale: fullLocale, language, region, timeZone },\n }\n return cached\n}\n\n/** Collect `utm_*` params (and any extras) from the URL. SSR-safe. */\nfunction collectUtm(): UtmContext {\n if (typeof window === 'undefined') return {}\n const out: UtmContext = {}\n const params = new URLSearchParams(window.location.search)\n params.forEach((value, key) => {\n if (key.startsWith('utm_')) out[key.slice(4)] = value\n })\n return out\n}\n\n/** Known ad-network click-id params. Any present in the URL is captured. */\nconst CLICK_ID_PARAMS = [\n 'fbclid', 'gclid', 'gbraid', 'wbraid', 'msclkid', 'ttclid',\n 'twclid', 'sccid', 'li_fat_id', 'epik', 'rdt_cid', 'dclid', 'irclickid',\n]\n\n/** Collect ad-network click-ids from the entry URL. SSR-safe. */\nfunction collectClickIds(): ClickIdContext {\n if (typeof window === 'undefined') return {}\n const out: ClickIdContext = {}\n const params = new URLSearchParams(window.location.search)\n for (const key of CLICK_ID_PARAMS) {\n const v = params.get(key)\n if (v) out[key] = v\n }\n return out\n}\n\n/** Read a cookie value by name. SSR-safe AND sandbox-safe: in an opaque-origin sandboxed\n * iframe (e.g. the editor preview, which deliberately has no allow-same-origin) the native\n * `document.cookie` GETTER throws a SecurityError — degrade to \"no cookie\", never crash. */\nfunction readCookie(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined\n try {\n const m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'))\n return m ? decodeURIComponent(m[1]) : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Assemble the full {@link Acquisition} snapshot from the context + `document`\n * (cookies, referrer, path) — captured once on entry, forwarded to the tracker for\n * first-class persistence (session + first-touch Customer) + CAPI.\n */\nexport function buildAcquisition(context: FunnelContext): Acquisition {\n return {\n utm: context.utm,\n clickIds: context.clickIds,\n cookies: { fbp: readCookie('_fbp'), fbc: readCookie('_fbc') },\n referrer: context.session.referrer,\n landingPath: typeof window !== 'undefined' ? window.location.pathname : '',\n }\n}\n\nexport interface BuildContextOptions {\n funnelId?: string\n campaignId?: string\n mode?: 'test' | 'live'\n /** Stable build-time clock (avoids `Date.now()` churn in renders/tests). */\n now?: number\n sessionId?: string | null\n /** Known customer id — the preferred stable bucketing seed (phase-4 §4.2). */\n customerId?: string | null\n /** Signed anonymous visitor id — the fallback bucketing seed. */\n visitorId?: string | null\n /** Overrides for any slice — used by the server to hydrate `utm`/`session`. */\n overrides?: Partial<FunnelContext>\n}\n\n/**\n * Build the read-only {@link FunnelContext} once, at mount. `page` starts at the\n * first page and is replaced per navigation when assembling a snapshot.\n */\nexport function buildContext(opts: BuildContextOptions = {}): FunnelContext {\n const raw = detect()\n const now = opts.now ?? 0\n const referrer = typeof document !== 'undefined' ? document.referrer : ''\n\n const base: FunnelContext = {\n device: raw.device,\n browser: raw.browser,\n os: raw.os,\n locale: raw.locale,\n utm: collectUtm(),\n clickIds: collectClickIds(),\n page: { key: '', slug: '', index: 0, total: 0, progressPercentage: 0, startedAt: now },\n session: { id: opts.sessionId ?? null, startedAt: now, referrer },\n identity: { customerId: opts.customerId ?? null, visitorId: opts.visitorId ?? null },\n system: {\n funnelId: opts.funnelId ?? '',\n campaignId: opts.campaignId ?? '',\n mode: opts.mode ?? 'live',\n now,\n },\n }\n\n if (!opts.overrides) return base\n return {\n ...base,\n ...opts.overrides,\n device: { ...base.device, ...opts.overrides.device },\n browser: { ...base.browser, ...opts.overrides.browser },\n os: { ...base.os, ...opts.overrides.os },\n locale: { ...base.locale, ...opts.overrides.locale },\n utm: { ...base.utm, ...opts.overrides.utm },\n clickIds: { ...base.clickIds, ...opts.overrides.clickIds },\n page: { ...base.page, ...opts.overrides.page },\n session: { ...base.session, ...opts.overrides.session },\n identity: { ...base.identity, ...opts.overrides.identity },\n system: { ...base.system, ...opts.overrides.system },\n }\n}\n\n/** Internal: reset the detection cache (tests only). */\nexport function __resetContextCache(): void {\n cached = null\n}\n","/**\n * v2 tracking seam — the funnel runtime emits a **fixed event taxonomy**, but\n * never talks to the network itself. It calls a {@link Tracker} the platform/CLI\n * injects via {@link FunnelProvider}. The real implementation is the existing\n * {@link ./tracker}.`FunnelTracker` (session id, ad attribution, debounced\n * persistence, CAPI fan-out); tests and local dev use {@link createConsoleTracker}.\n *\n * The taxonomy is preserved verbatim from v0 so analytics keep working:\n * funnel.start · page.view · page.exit · user.registered · experiment.exposure ·\n * checkout.start · checkout.payment_added · checkout.failed · purchase.complete\n *\n * Where each fires (all from the SDK runtime):\n * - `funnel.start` / `page.view` / `page.exit` / `experiment.exposure` — navigation\n * ({@link ../flow/flow}.`FunnelView`); `page.exit` carries duration + active (visible) time.\n * - `user.registered` — `identify()`, the first time `user.email` is written.\n * - `checkout.*` / `purchase.complete` — the commerce primitives ({@link ../commerce/checkout}).\n * `checkout.payment_added` is reported by an inline driver via `onPaymentAdded` (optional).\n *\n * A `responses.set(...)` does **not** emit a discrete event — values are batched into\n * `userData` and persisted (debounced). Only the events above fire.\n */\n\nimport {\n createContext,\n createElement,\n useCallback,\n useContext,\n type ReactNode,\n} from 'react'\nimport type { Acquisition } from '../state/context'\n\n// ── Event taxonomy (typed, preserved from v0) ────────────\n\nexport interface FunnelEventDataMap {\n 'funnel.start': Record<string, never>\n 'page.view': { pageId: string; pageKey?: string; pageName?: string; isInitial?: boolean; eventId?: string }\n 'page.exit': { pageId: string; durationMs: number; activeMs: number }\n 'user.registered': { email: string; eventId?: string }\n 'checkout.start': { productId?: string; priceId?: string; productName?: string; surface?: string }\n 'checkout.payment_added': Record<string, never>\n 'checkout.failed': { category: string; declineCode?: string; productId?: string; intent?: string }\n 'purchase.complete': { amount?: number; currency?: string; email?: string; eventId?: string }\n 'experiment.exposure': { experimentId: string; variant: string; version?: number }\n}\n\n/**\n * Build the `experiment.exposure` payload — ONE constructor for both exposure\n * emitters (the PAGE path in flow.tsx and the FUNNEL path in platformTracker),\n * so the wire shape can't drift between them. `version` is the platform record\n * version results key on; omitted (not `undefined`) when the record has none.\n */\nexport function exposurePayload(\n experimentId: string,\n variant: string,\n version?: number,\n): FunnelEventDataMap['experiment.exposure'] {\n return { experimentId, variant, ...(version !== undefined ? { version } : {}) }\n}\n\n/**\n * A unique id for an analytics event, used as the **dedup key** between the\n * browser pixel (`fbq(..., { eventID })`) and the server CAPI call. Browser-\n * originated events (page.view, registration) mint one with this; **purchase /\n * subscription events carry the id the *server* minted** (the charge is the source\n * of truth) — see `CheckoutResult.eventId`.\n */\nlet _eventIdCounter = 0\nexport function newEventId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID()\n return `af_${Date.now().toString(36)}_${(_eventIdCounter++).toString(36)}`\n}\n\nexport type KnownFunnelEvent = keyof FunnelEventDataMap\n\n/**\n * The surface the runtime needs from a tracker. A subset of `FunnelTracker`, so\n * the real one satisfies it directly; the console tracker is a trivial stub.\n */\nexport interface Tracker {\n /** Emit a known event (typed) or any custom event name. */\n track<E extends KnownFunnelEvent>(event: E, data?: FunnelEventDataMap[E], userData?: Record<string, unknown>): void\n track(event: string, data?: Record<string, unknown>, userData?: Record<string, unknown>): void\n /**\n * Identify by email — fires `user.registered` (idempotent in the impl). The\n * optional `eventId` is the browser↔CAPI dedup key for the registration event.\n */\n identify(email: string, eventId?: string): void\n /** Push the latest variable snapshot for batched/debounced persistence. */\n setVariables?(variables: Record<string, unknown>): void\n /**\n * The acquisition snapshot (utm + click-ids + `_fbp`/`_fbc` + referrer), pushed\n * once on entry. The platform persists it first-class — per-visit on the session +\n * **first-touch (write-once) on the Customer** — and feeds it to CAPI. Optional;\n * the console/test trackers ignore it.\n */\n setAcquisition?(acquisition: Acquisition): void\n}\n\n/** A no-op-ish tracker that logs to the console — for tests, preview, local dev. */\nexport function createConsoleTracker(opts: { silent?: boolean } = {}): Tracker {\n const log = (label: string, ...args: unknown[]) => {\n if (!opts.silent) console.info(`[appfunnel] ${label}`, ...args)\n }\n return {\n track: (event: string, data?: unknown) => log(`track ${event}`, data ?? {}),\n identify: (email: string, eventId?: string) => log('identify', email, eventId),\n setVariables: (vars) => log('vars', vars),\n setAcquisition: (acq) => log('acquisition', acq),\n }\n}\n\n// ── React wiring ─────────────────────────────────────────\n\nconst TrackerContext = createContext<Tracker | null>(null)\n\nexport function TrackerProvider({\n tracker,\n children,\n}: {\n tracker: Tracker\n children: ReactNode\n}): ReactNode {\n return createElement(TrackerContext.Provider, { value: tracker }, children)\n}\n\n/** Internal: the raw tracker, or a silent console fallback if none provided. */\nexport function useTrackerRef(): Tracker {\n return useContext(TrackerContext) ?? FALLBACK\n}\n\nconst FALLBACK = createConsoleTracker({ silent: true })\n\n/**\n * `const { track } = useTracker()` — emit a custom event. Auto events\n * (page.view, identify, purchase, …) fire on their own; this is the escape\n * hatch for funnel-specific events (`track('quiz_skipped', { step: 3 })`).\n */\nexport function useTracker(): { track: Tracker['track'] } {\n const tracker = useTrackerRef()\n const track = useCallback(\n (event: string, data?: Record<string, unknown>, userData?: Record<string, unknown>) =>\n tracker.track(event, data as never, userData),\n [tracker],\n )\n return { track }\n}\n","/**\n * The **`window.appfunnel` event bus** — the client-side integration surface\n * (port of v0 `admin/lib/funnel/utils/appfunnelRuntime.ts`).\n *\n * Every taxonomy event the runtime emits is mirrored here, so on-page pixels and\n * custom scripts integrate by **subscribing** — `window.appfunnel.on('purchase.complete', …)`\n * — instead of the funnel hand-injecting pixel config per page. The pre-built pixel\n * loaders (Meta/TikTok/GTM/Clarity) are just subscribers; CAPI stays the server-side\n * default (this is the *client* sink of the same events). See doc 08 §3.\n *\n * Two deliberate properties vs. v0:\n * - **Replay history** (`events`): async pixels load *after* `funnel.start`/`page.view`\n * fire, so a late subscriber would miss them. The bus keeps a bounded history a\n * subscriber can replay (the GTM `dataLayer` trick) — no lost events.\n * - **Subscribe + read only.** The window surface exposes `on`/`off`/`events` + read\n * getters; it has **no `emit`** (third-party code can't forge events) and **no\n * mutating actions** (`setVariable`/navigation) — the funnel can't be driven through\n * it. (v0's full-control Custom-JS API is deferred pending the bus-control-scope\n * decision; doc 08 §3 + §4.)\n */\n\nimport { newEventId, type Tracker } from './tracking'\n\n/** Read accessors the bus exposes — wired to the funnel's store + context. */\nexport interface BusAccessors {\n getVariable: (key: string) => unknown\n getVariables: () => Record<string, unknown>\n getCurrentPageId: () => string | null\n getCustomerId: () => string | null\n getVisitorId: () => string | null\n}\n\nexport interface BusEvent {\n event: string\n data: unknown\n /** Epoch ms the event was emitted (for ordering / replay). */\n ts: number\n}\n\ntype Listener = (data: unknown) => void\n\n/** The public `window.appfunnel` surface — subscribe + read, never emit or mutate. */\nexport interface AppFunnelBusApi extends BusAccessors {\n /** Subscribe to an event (or `'*'` for all). Returns an unsubscribe fn. */\n on(event: string, cb: Listener): () => void\n off(event: string, cb: Listener): void\n /** Bounded replay history — read past events, then `on()` for future ones. */\n readonly events: BusEvent[]\n}\n\nconst MAX_HISTORY = 250\n\n/**\n * The internal bus: the public {@link AppFunnelBusApi} plus `emit` (SDK-only) and\n * `now` injection. The SDK holds this; only {@link AppFunnelBusApi} reaches `window`.\n */\nexport interface FunnelBus extends AppFunnelBusApi {\n emit(event: string, data?: unknown): void\n}\n\n/** Create a bus over the given read accessors. `now` is injectable for tests. */\nexport function createBus(accessors: BusAccessors, now: () => number = () => Date.now()): FunnelBus {\n const listeners = new Map<string, Set<Listener>>()\n const events: BusEvent[] = []\n\n const on: AppFunnelBusApi['on'] = (event, cb) => {\n let set = listeners.get(event)\n if (!set) listeners.set(event, (set = new Set()))\n set.add(cb)\n return () => off(event, cb)\n }\n const off: AppFunnelBusApi['off'] = (event, cb) => {\n listeners.get(event)?.delete(cb)\n }\n\n const emit = (event: string, data?: unknown) => {\n events.push({ event, data, ts: now() })\n if (events.length > MAX_HISTORY) events.shift()\n // Exact-event listeners, then wildcard. A throwing subscriber never breaks the rest.\n for (const cb of listeners.get(event) ?? []) {\n try { cb(data) } catch { /* a pixel error must not break the funnel */ }\n }\n for (const cb of listeners.get('*') ?? []) {\n try { cb({ event, data }) } catch { /* ignore */ }\n }\n }\n\n return { on, off, events, emit, ...accessors }\n}\n\n/**\n * Wrap a {@link Tracker} so every emitted taxonomy event is mirrored to the bus\n * (the client sink). `identify()` also surfaces a `user.registered` to the bus, so\n * pixels see registration. The server sink (the inner tracker → CAPI) is untouched.\n */\nexport function withBus(tracker: Tracker, bus: FunnelBus): Tracker {\n return {\n // Spread preserves the original call arity (don't append an undefined userData).\n track: ((...args: [string, unknown?, Record<string, unknown>?]) => {\n ;(tracker.track as (...a: unknown[]) => void)(...args)\n bus.emit(args[0], args[1])\n }) as Tracker['track'],\n identify: (email: string, eventId?: string) => {\n // One id shared by the server (inner.identify → CAPI) and the bus (pixel) so\n // CompleteRegistration dedupes across browser + server.\n const id = eventId ?? newEventId()\n tracker.identify(email, id)\n bus.emit('user.registered', { email, eventId: id })\n },\n setVariables: tracker.setVariables ? (v) => tracker.setVariables!(v) : undefined,\n // Acquisition is persistence (session + first-touch Customer), not a bus event.\n setAcquisition: tracker.setAcquisition ? (a) => tracker.setAcquisition!(a) : undefined,\n }\n}\n\ndeclare global {\n interface Window {\n appfunnel?: AppFunnelBusApi\n }\n}\n\n/**\n * Attach the bus's public surface to `window.appfunnel` (client-side only).\n * Returns a detach fn for unmount. No-op under SSR.\n */\nexport function attachBus(bus: FunnelBus): () => void {\n if (typeof window === 'undefined') return () => {}\n const { on, off, getVariable, getVariables, getCurrentPageId, getCustomerId, getVisitorId } = bus\n const api: AppFunnelBusApi = {\n on, off, getVariable, getVariables, getCurrentPageId, getCustomerId, getVisitorId,\n get events() { return bus.events },\n }\n window.appfunnel = api\n return () => {\n if (window.appfunnel === api) delete window.appfunnel\n }\n}\n","/**\n * v2 localization — translated **text** (prices already localize via `Intl` in\n * {@link ./catalog}). Per doc 05: locales live in the funnel source — supported\n * locales + default + fallback are funnel config ({@link FunnelLocales}), and\n * each locale is a flat `key → string` **catalog** (`messages/en.json`, …),\n * versioned + published with the funnel. The dashboard's manual translation\n * table edits exactly these catalogs.\n *\n * Lookup walks a **fallback chain** (active → fallback → default) so a missing\n * string never blanks — it falls through, and only as a last resort returns the\n * key (flagged in dev). Interpolation is simple `{{var}}`; plurals use the\n * built-in `Intl.PluralRules`; numbers/dates/percent use `Intl`. No ICU, no rich\n * markup (markup stays in TSX).\n */\n\nimport {\n createContext,\n createElement,\n useContext,\n useEffect,\n useMemo,\n useState,\n type ReactNode,\n} from 'react'\nimport type { FunnelLocales } from '../flow/spine'\nimport { isRtl, resolveLocale, type Direction } from './locale'\n\n// Pure locale resolution lives in ./locale (React-free, shared with the\n// server/tooling entry); re-exported here so existing imports keep working.\nexport { isRtl, resolveLocale } from './locale'\nexport type { Direction } from './locale'\n\n/** locale → (message key → string). The shape of `messages/<locale>.json`. */\nexport type MessageCatalog = Record<string, Record<string, string>>\n\nexport type PluralCategory = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other'\n\n/** Replace `{{name}}` placeholders; leaves unknown ones intact. */\nfunction interpolate(str: string, params?: Record<string, string | number>): string {\n if (!params) return str\n return str.replace(/\\{\\{(\\w+)\\}\\}/g, (_, k: string) => (k in params ? String(params[k]) : `{{${k}}}`))\n}\n\n/** Walk the fallback chain for a key; undefined if absent everywhere. */\nfunction lookup(catalog: MessageCatalog, chain: string[], key: string): string | undefined {\n for (const loc of chain) {\n const v = catalog[loc]?.[key]\n if (v !== undefined) return v\n }\n return undefined\n}\n\nfunction devWarn(message: string): void {\n const env = (globalThis as { process?: { env?: { NODE_ENV?: string } } }).process?.env?.NODE_ENV\n if (env === 'production') return\n try {\n console.warn(message)\n } catch {\n /* no-op */\n }\n}\n\n// ── Public types ─────────────────────────────────────────\n\nexport interface TFunction {\n /** Translate a key, with optional `{{var}}` params. Missing → fallback → key. */\n (key: string, params?: Record<string, string | number>): string\n /** Locale-correct plural: `t.plural(n, { one: '# day', other: '# days' })` (`#` → n). */\n plural: (\n n: number,\n forms: Partial<Record<PluralCategory, string>>,\n params?: Record<string, string | number>,\n ) => string\n}\n\nexport interface Formatters {\n number: (n: number, opts?: Intl.NumberFormatOptions) => string\n date: (d: Date | number, opts?: Intl.DateTimeFormatOptions) => string\n percent: (n: number, opts?: Intl.NumberFormatOptions) => string\n}\n\nexport interface Translation {\n t: TFunction\n fmt: Formatters\n /** The active (resolved) locale. */\n locale: string\n /** Switch locale at runtime (preview / language picker). */\n setLocale: (locale: string) => void\n /** Text direction for the active locale. */\n dir: Direction\n /** The funnel's supported locales. */\n locales: string[]\n}\n\n// ── React wiring ─────────────────────────────────────────\n\ninterface LocaleContextValue {\n locale: string\n setLocale: (locale: string) => void\n config?: FunnelLocales\n catalog: MessageCatalog\n}\n\nconst LocaleContext = createContext<LocaleContextValue | null>(null)\n\nexport interface LocaleProviderProps {\n config?: FunnelLocales\n catalog?: MessageCatalog\n /** Device/browser locale (from computed context) — the resolution input. */\n detected: string\n /** Explicit override (URL/param/geo), highest priority. */\n override?: string\n children: ReactNode\n}\n\n/** Resolves + holds the active locale and the message catalog. */\nexport function LocaleProvider({\n config,\n catalog = {},\n detected,\n override,\n children,\n}: LocaleProviderProps): ReactNode {\n const [locale, setLocale] = useState(() => resolveLocale(config, detected, override))\n // Re-resolve when the inputs change (SSR-hydrated override arriving late, a\n // preview switching `locale`, config swap). A runtime `setLocale` (language\n // picker) survives re-renders — this only fires when a *prop* changes; React\n // bails out when the re-resolved locale is unchanged.\n useEffect(() => {\n setLocale(resolveLocale(config, detected, override))\n }, [config, detected, override])\n const value = useMemo<LocaleContextValue>(\n () => ({ locale, setLocale, config, catalog }),\n [locale, config, catalog],\n )\n return createElement(LocaleContext.Provider, { value }, children)\n}\n\n/** The active (resolved) funnel locale, or `'en'` if no provider — for display\n * formatting (e.g. {@link ./catalog} prices) without building the full handle. */\nexport function useActiveLocale(): string {\n return useContext(LocaleContext)?.locale ?? 'en'\n}\n\n/**\n * `const { t, fmt, locale, dir } = useTranslation()` — translated text +\n * locale-aware `Intl` formatters for the active funnel locale.\n */\nexport function useTranslation(): Translation {\n const ctx = useContext(LocaleContext)\n if (!ctx) throw new Error('useTranslation must be used inside <FunnelProvider>')\n const { locale, setLocale, config, catalog } = ctx\n\n const chain = useMemo(() => {\n const def = config?.default\n const fb = config?.fallback\n return Array.from(new Set([locale, fb, def].filter(Boolean) as string[]))\n }, [locale, config])\n\n const t = useMemo<TFunction>(() => {\n const fn = ((key: string, params?: Record<string, string | number>) => {\n const raw = lookup(catalog, chain, key)\n if (raw === undefined) {\n devWarn(`[appfunnel] missing translation: \"${key}\" (${locale})`)\n return key\n }\n return interpolate(raw, params)\n }) as TFunction\n fn.plural = (n, forms, params) => {\n let rule: PluralCategory\n try {\n rule = new Intl.PluralRules(locale).select(n) as PluralCategory\n } catch {\n rule = 'other'\n }\n const form = forms[rule] ?? forms.other ?? ''\n return interpolate(form.replace(/#/g, String(n)), params)\n }\n return fn\n }, [catalog, chain, locale])\n\n // Like formatMoney: an invalid locale/options must degrade to a plain\n // rendering, never throw mid-render.\n const fmt = useMemo<Formatters>(\n () => ({\n number: (n, opts) => {\n try {\n return new Intl.NumberFormat(locale, opts).format(n)\n } catch {\n return String(n)\n }\n },\n date: (d, opts) => {\n try {\n return new Intl.DateTimeFormat(locale, opts).format(d)\n } catch {\n return String(d instanceof Date ? d.toISOString() : d)\n }\n },\n percent: (n, opts) => {\n try {\n return new Intl.NumberFormat(locale, { style: 'percent', ...opts }).format(n)\n } catch {\n return `${(n * 100).toFixed(0)}%`\n }\n },\n }),\n [locale],\n )\n\n return {\n t,\n fmt,\n locale,\n setLocale,\n dir: isRtl(locale) ? 'rtl' : 'ltr',\n locales: config?.supported ?? [locale],\n }\n}\n","/**\n * v2 `products` — the **read-only** product catalog.\n *\n * **AppFunnel does not manage currency.** Multi-currency is entirely the payment\n * provider's job: the provider (or its preview API) resolves the visitor's price,\n * and we receive a single resolved `{ amount, currency }` per product. No FX, no\n * currency selection, no conversion on our side. (FX appears only for frozen-USD\n * *reporting*, never display — phase-3 §3.6b.) A provider that doesn't localize\n * simply gives one currency.\n *\n * Our only job is **display**: pick the product by logical id and **format** its\n * amount. Formatting happens at read time in the funnel's **active locale** (so\n * switching language reformats `kr 79,00` ⇄ `$9.99`), while the **currency** is\n * whatever the provider resolved. Currency selection is the platform's; the\n * authoring funnel only ever names a product id.\n *\n * The math itself (resolve/format/exponents) is pure and lives in {@link ./money}\n * so the server/tooling entry can use it without React — this module re-exports\n * it and adds the React wiring (provider + hooks).\n */\n\nimport {\n createContext,\n createElement,\n useContext,\n useMemo,\n type ReactNode,\n} from 'react'\nimport { useActiveLocale } from '../i18n/translation'\nimport { formatProduct, type Product, type ResolvedProduct } from './money'\n\nexport {\n resolveProduct,\n buildCatalog,\n formatMoney,\n formatProduct,\n currencyExponent,\n} from './money'\nexport type { Product, ResolvedProduct, ProductInput, Money, Interval } from './money'\n\n// ── React wiring ─────────────────────────────────────────\n\nconst CatalogContext = createContext<Map<string, ResolvedProduct> | null>(null)\n\nexport function CatalogProvider({\n catalog,\n children,\n}: {\n catalog: Map<string, ResolvedProduct>\n children: ReactNode\n}): ReactNode {\n return createElement(CatalogContext.Provider, { value: catalog }, children)\n}\n\nfunction useCatalog(): Map<string, ResolvedProduct> {\n return useContext(CatalogContext) ?? EMPTY\n}\nconst EMPTY = new Map<string, ResolvedProduct>()\n\n/** `useProduct('monthly')` — one product, formatted in the active locale. */\nexport function useProduct(id: string | undefined): Product | undefined {\n const catalog = useCatalog()\n const locale = useActiveLocale()\n const resolved = id ? catalog.get(id) : undefined\n return useMemo(() => (resolved ? formatProduct(resolved, locale) : undefined), [resolved, locale])\n}\n\n/** `useProducts()` — every product, formatted in the active locale, in order. */\nexport function useProducts(): Product[] {\n const catalog = useCatalog()\n const locale = useActiveLocale()\n return useMemo(\n () => Array.from(catalog.values()).map((r) => formatProduct(r, locale)),\n [catalog, locale],\n )\n}\n","import {\n createContext,\n createElement,\n lazy,\n Suspense,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useTransition,\n type ComponentType,\n type ReactNode,\n} from 'react'\nimport { useFunnel } from '../state/namespaces'\nimport { exposurePayload, newEventId, useTrackerRef, type Tracker } from '../tracking/tracking'\nimport { entryGuard, evaluateGate, expectedPathLength, nextPage, outgoingKeys, type FlowPage, type PageMeta } from './spine'\nimport { bucketingSeed, resolveExperiments } from './experiments'\nimport type { PageContext } from '../state/context'\n\n/** What a page's `load` resolves to — a component, or a module default-exporting one. */\nexport type PageModule = ComponentType | { default: ComponentType }\n\n/**\n * A page wired into the runtime. Provide **either** an eager `Component` (small\n * funnels, tests) **or** a lazy `load` (code-split: the renderer hands a dynamic\n * `import()` so a big funnel ships one chunk per page, not the whole funnel).\n */\nexport interface RuntimePage {\n key: string\n meta?: PageMeta\n /** Eager component. Provide this or `load`. */\n Component?: ComponentType\n /** Lazy loader for a code-split chunk. Provide this or `Component`. */\n load?: () => Promise<PageModule>\n}\n\nexport interface NavigationState {\n /** The current page's read-only context (key, index, total, progress). */\n page: PageContext\n /** Advance via the current page's `next` predicate, else the linear next. */\n next: () => void\n /** Go to the previous page in history. */\n back: () => void\n /** Jump to a specific page key. */\n go: (key: string) => void\n /** Warm a page's code-split chunk ahead of navigation (e.g. on link hover). No-op for eager pages. */\n prefetch: (key: string) => void\n /**\n * The page keys the visitor could go to next, already resolved to the chunk that\n * would render (experiment variant applied). The **renderer** maps these to chunk\n * URLs and emits `<link rel=\"modulepreload\">` (the browser-native, non-executing,\n * SSR-able prefetch — see v0 `HeadlessFunnelRenderer`). The SDK's `load()`-based\n * `prefetch` is the fallback for mounts without a modulepreload manager.\n */\n nextCandidates: string[]\n canGoBack: boolean\n /**\n * True while a navigation's target page chunk is still resolving (a cold,\n * un-prefetched lazy chunk). The current page stays on screen during this window\n * (no Suspense-fallback flicker); read this to show a subtle \"working\" affordance\n * so a tapped button doesn't feel dead. Usually false/instant when the next chunk\n * was prefetched.\n */\n isNavigating: boolean\n}\n\nconst NavContext = createContext<NavigationState | null>(null)\n\n/** experiment id → the variant this visitor is bucketed into, for the live render. */\nconst ExperimentContext = createContext<Record<string, string>>({})\n\n/**\n * `const variant = useExperiment('welcome-headline')` — the variant key this\n * visitor is assigned in an experiment (`undefined` if not in one). Page-variant\n * swapping is automatic; this is for branching *within* a page or custom logging.\n */\nexport function useExperiment(id: string): string | undefined {\n return useContext(ExperimentContext)[id]\n}\n\n/**\n * Compute the read-only page context for a position in the flow. `total` is the\n * **expected** path length for the visitor's current answers (see\n * {@link expectedPathLength}) — not the raw file count — so progress reaches 100%\n * on whichever branch the funnel actually takes. Clamped so a visitor who jumped\n * past the traced path can't read above 100%.\n */\nfunction pageContextFor(\n currentKey: string,\n slug: string,\n index: number,\n total: number,\n startedAt: number,\n): PageContext {\n const denom = Math.max(total, index + 1)\n return {\n key: currentKey,\n slug,\n index,\n total: denom,\n progressPercentage: denom > 0 ? Math.min(100, Math.round(((index + 1) / denom) * 100)) : 0,\n startedAt,\n }\n}\n\n/** Page-timing clock (effects only, never render). */\nconst now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now())\n\n/**\n * `page.exit` timing — wall-clock duration on a page, minus time the tab was\n * hidden (active engagement). Emits for the page being LEFT on each page change;\n * the final page's exit fires on unmount.\n */\nfunction usePageExitTimer(tracker: Tracker, currentKey: string | undefined): void {\n const timer = useRef<{ key: string; enteredAt: number; hidden: number; hiddenSince: number | null } | null>(null)\n const emitExit = useCallback(() => {\n const t = timer.current\n if (!t) return\n const at = now()\n const hidden = t.hidden + (t.hiddenSince != null ? at - t.hiddenSince : 0)\n const durationMs = Math.round(at - t.enteredAt)\n tracker.track('page.exit', { pageId: t.key, durationMs, activeMs: Math.max(0, Math.round(durationMs - hidden)) })\n }, [tracker])\n\n // Track tab visibility so `activeMs` excludes backgrounded time.\n useEffect(() => {\n if (typeof document === 'undefined') return\n const onVis = () => {\n const t = timer.current\n if (!t) return\n if (document.visibilityState === 'hidden') t.hiddenSince = now()\n else if (t.hiddenSince != null) {\n t.hidden += now() - t.hiddenSince\n t.hiddenSince = null\n }\n }\n document.addEventListener('visibilitychange', onVis)\n return () => document.removeEventListener('visibilitychange', onVis)\n }, [])\n\n // On each page change emit page.exit for the page being left, then start the\n // new page's timer.\n useEffect(() => {\n if (!currentKey) return\n if (timer.current && timer.current.key !== currentKey) emitExit()\n const hidden = typeof document !== 'undefined' && document.visibilityState === 'hidden'\n timer.current = { key: currentKey, enteredAt: now(), hidden: 0, hiddenSince: hidden ? now() : null }\n }, [currentKey, emitExit])\n\n useEffect(() => () => emitExit(), [emitExit])\n}\n\n/**\n * Renders the funnel: shows the current page and drives navigation. `next()`\n * resolves the current page's `next` predicate against the live snapshot\n * (writable namespaces + read-only `context`), falling back to the linear next\n * page in file order (see {@link nextPage}).\n *\n * Auto-emits `funnel.start` on mount and `page.view` on each page change, and\n * keeps `context.page` in sync so predicates and `usePage()` see the live page.\n *\n * Pass a `layout` (a `{ children }` component) for **persistent chrome** — a\n * header, progress bar, background — rendered *inside* the nav context but\n * *outside* the page swap, so it mounts once and never remounts on navigation\n * (and can read `usePage`/`useNavigation`).\n *\n * Must live inside `<FunnelProvider>`.\n */\nexport function FunnelView({\n pages,\n initialKey,\n layout,\n fallback,\n prefetch: prefetchMode = 'auto',\n onNavigate,\n}: {\n pages: RuntimePage[]\n initialKey?: string\n layout?: ComponentType<{ children: ReactNode }>\n /** Shown in the page area while a lazy page's chunk loads (the layout persists around it). */\n fallback?: ReactNode\n /**\n * `'auto'` (default): the SDK warms next-likely chunks by calling `load()`.\n * `'off'`: the **renderer** owns prefetch (via `<link rel=\"modulepreload\">` over\n * `useNavigation().nextCandidates`) — avoids the redundant `load()` execution.\n */\n prefetch?: 'auto' | 'off'\n /**\n * Fires on every page change (incl. the initial page) with the current page key\n * + slug. The **renderer** uses it to sync the URL path (`history.replaceState`,\n * v0-style — funnel back is in-memory, not browser history). Fires for the\n * *resolved* page, so if an entry `guard` bounced a deep-link to the start, the\n * URL gets corrected.\n */\n onNavigate?: (key: string, slug: string) => void\n}): ReactNode {\n const funnel = useFunnel()\n const tracker = useTrackerRef()\n\n // Resolve each page to a renderable component: eager `Component` as-is, or a\n // stable `React.lazy` over `load` (memoized so the lazy element identity is\n // stable across renders → no remount). `loaders` keeps the raw `load` fns for\n // prefetch (dynamic import dedupes, so calling them early just warms the chunk).\n const components = useMemo(() => {\n const map = new Map<string, ComponentType>()\n for (const p of pages) {\n if (p.Component) map.set(p.key, p.Component)\n else if (p.load) {\n const load = p.load\n map.set(p.key, lazy(() => Promise.resolve(load()).then((m) =>\n typeof m === 'function' ? { default: m } : m,\n )))\n }\n }\n return map\n }, [pages])\n const loaders = useMemo(\n () => new Map(pages.filter((p) => p.load).map((p) => [p.key, p.load!])),\n [pages],\n )\n\n // Resolve page-level experiments once for this visitor: which variant of each\n // slot to show, and which variant pages drop out of the linear flow. The seed is\n // PINNED to the first non-null value for this mount (a ref, not the live context) so a\n // mid-session identify() that later populates context.identity can never flip an\n // in-progress visitor's variant — the comment's promise is now enforced, not incidental.\n const seedRef = useRef<string | null>(null)\n if (seedRef.current === null) seedRef.current = bucketingSeed(funnel.context)\n const seed = seedRef.current\n const experiments = useMemo(\n () => resolveExperiments(pages, funnel.experiments, seed),\n [pages, funnel.experiments, seed],\n )\n // The two key remaps every navigation touch point needs: a routing TARGET\n // collapses to its slot (variant keys never stand alone in the flow); a slot\n // resolves to the chunk its assigned variant renders.\n const toSlot = useCallback((k: string) => experiments.slotOf[k] ?? k, [experiments])\n const toRenderKey = useCallback((k: string) => experiments.render[k] ?? k, [experiments])\n const pageByKey = useMemo(() => new Map(pages.map((p) => [p.key, p])), [pages])\n // The effective flow: anchors + standalone pages, in order (losers removed).\n const flowPages = useMemo<RuntimePage[]>(\n () => experiments.activeKeys.map((k) => pageByKey.get(k)).filter((p): p is RuntimePage => p !== undefined),\n [experiments, pageByKey],\n )\n\n // The flow as plain {key, meta} for routing + path-length tracing.\n const flow = useMemo<FlowPage[]>(\n () => flowPages.map((p) => ({ key: p.key, meta: p.meta })),\n [flowPages],\n )\n\n // Resolve the starting page. A deep-link / reload `initialKey` is honored only if\n // the page's entry `guard` passes against the (restored) snapshot — else fall\n // back to the start page. (In-funnel navigation never hits this; routing gated it.)\n const [history, setHistory] = useState<string[]>(() => {\n const start = flowPages[0]?.key\n if (!initialKey || initialKey === start) return start ? [start] : []\n const target = toSlot(initialKey)\n const page = flowPages.find((p) => p.key === target)\n // Effective guard = the page-type default (paywall/upsell need email) AND any\n // explicit meta.guard.\n const guard = entryGuard(page?.meta)\n const ok = page && (!guard || evaluateGate(guard, funnel.snapshot()))\n const first = ok ? target : start\n return first ? [first] : []\n })\n const currentKey = history[history.length - 1]\n const index = history.length - 1\n const startKey = history[0]\n\n // Expected path length for the visitor's current answers — re-traced per\n // navigation so progress reaches 100% on whichever branch the funnel takes.\n const total = useMemo(\n () => expectedPathLength(flow, startKey, funnel.snapshot()),\n // currentKey in deps: re-trace as each step's answers settle the branch.\n [flow, startKey, currentKey, funnel],\n )\n\n // Keep the read-only context's `page` slice current so predicates + usePage see it.\n const slug = pageByKey.get(currentKey)?.meta?.slug ?? currentKey\n const page = useMemo(\n () => pageContextFor(currentKey, slug, index, total, funnel.context.system.now),\n [currentKey, slug, index, total, funnel.context.system.now],\n )\n // Keep the imperative handle's `context.page` in sync for snapshot()/predicates\n // and the window.appfunnel bus. Synced in a COMMIT effect, not during render —\n // mutating a shared object mid-render is unsafe under SSR/concurrent rendering\n // (two in-flight renders would race on it). Everything render-facing reads\n // `page` from the NavContext value below (React state), so this only serves\n // event-handler/effect readers, which always run after the commit.\n useEffect(() => {\n funnel.context.page = page\n }, [funnel, page])\n\n // funnel.start once, on mount.\n const started = useRef(false)\n useEffect(() => {\n if (started.current) return\n started.current = true\n tracker.track('funnel.start', {})\n }, [tracker])\n\n // page.view on every page change.\n useEffect(() => {\n if (!currentKey) return\n tracker.track('page.view', { pageId: currentKey, pageKey: currentKey, isInitial: index === 0, eventId: newEventId() })\n }, [tracker, currentKey, index])\n\n // Tell the renderer the live page (key + slug) so it can sync the URL path.\n useEffect(() => {\n if (currentKey && onNavigate) onNavigate(currentKey, slug)\n }, [onNavigate, currentKey, slug])\n\n // experiment.exposure the first time the visitor lands on an experiment slot.\n const exposed = useRef<Set<string>>(new Set())\n useEffect(() => {\n const expId = experiments.experimentOf[currentKey]\n if (!expId || exposed.current.has(expId)) return\n exposed.current.add(expId)\n tracker.track('experiment.exposure', exposurePayload(expId, experiments.assignments[expId], experiments.versionOf[expId]))\n }, [tracker, currentKey, experiments])\n\n usePageExitTimer(tracker, currentKey)\n\n // Navigation swaps a code-split page (a lazy chunk). Wrap the history update in a\n // transition so React keeps the CURRENT page on screen until the next page's chunk\n // is ready, instead of flashing the Suspense `fallback` (the inter-page flicker).\n // `isNavigating` is true while a cold chunk resolves → show a \"working\" affordance\n // so the button doesn't feel dead. Prefetch makes this window usually invisible.\n const [isNavigating, startNav] = useTransition()\n const next = useCallback(() => {\n // Route over the effective flow (slots); the slot page's `meta.next` governs\n // routing. Remap any target that points at a collapsed variant key to its slot.\n const target = nextPage(flow, currentKey, funnel.snapshot())\n const resolved = target ? toSlot(target) : target\n if (resolved) startNav(() => setHistory((h) => [...h, resolved]))\n }, [flow, currentKey, funnel, toSlot])\n\n const back = useCallback(\n () => startNav(() => setHistory((h) => (h.length > 1 ? h.slice(0, -1) : h))),\n [],\n )\n const go = useCallback(\n (key: string) => startNav(() => setHistory((h) => [...h, toSlot(key)])),\n [toSlot],\n )\n\n // Warm a slot's code-split chunk (the variant that would actually render). Idempotent.\n const prefetched = useRef<Set<string>>(new Set())\n const prefetch = useCallback(\n (key: string) => {\n const target = toRenderKey(key)\n const load = loaders.get(target)\n if (!load || prefetched.current.has(target)) return\n prefetched.current.add(target)\n load().catch(() => prefetched.current.delete(target)) // let a failed load retry later\n },\n [loaders, toRenderKey],\n )\n\n // The next-likely pages, resolved to the chunk that would actually render\n // (experiment variant applied) — the renderer modulepreloads these.\n const nextCandidates = useMemo(\n () => [...new Set(outgoingKeys(flow, currentKey).map(toRenderKey))],\n [flow, currentKey, toRenderKey],\n )\n\n // 'auto' mode: warm those chunks by calling load(). 'off': the renderer owns it.\n useEffect(() => {\n if (prefetchMode !== 'auto') return\n for (const key of nextCandidates) prefetch(key)\n }, [prefetchMode, nextCandidates, prefetch])\n\n const value: NavigationState = {\n page,\n next,\n back,\n go,\n prefetch,\n nextCandidates,\n canGoBack: history.length > 1,\n isNavigating,\n }\n // Render the assigned variant's component at the current slot (the anchor key\n // stays the flow position; only the component swaps). Lazy pages suspend, so the\n // page area shows `fallback` while the chunk loads — inside the layout, so the\n // persistent chrome stays put.\n const renderKey = toRenderKey(currentKey)\n const Current = components.get(renderKey)\n const pageEl = createElement(Suspense, { fallback: fallback ?? null }, Current ? createElement(Current) : null)\n // The layout wraps the page inside NavContext → it persists across navigation\n // (same element type, only the page child swaps) and can use nav/funnel hooks.\n const content = layout ? createElement(layout, null, pageEl) : pageEl\n\n return createElement(\n ExperimentContext.Provider,\n { value: experiments.assignments },\n createElement(NavContext.Provider, { value }, content),\n )\n}\n\n/** `const { next, back, go, page } = useNavigation()`. */\nexport function useNavigation(): NavigationState {\n const ctx = useContext(NavContext)\n if (!ctx) throw new Error('useNavigation must be used inside <FunnelView>')\n return ctx\n}\n\n/** `usePage()` — the current page's read-only context, reactive to navigation. */\nexport function usePage(): PageContext {\n return useNavigation().page\n}\n","/**\n * Imperative, promise-based modal registry — our trimmed adaptation of\n * eBay's `@ebay/nice-modal-react` (MIT). The model: a module-level registry +\n * a reducer-backed store, so any code can `showModal(MyModal)` from anywhere\n * (no prop-drilling, no rendering the modal where you trigger it) and get back a\n * **promise** that resolves when the modal calls `resolve()` — perfect for\n * confirm/upsell/detail flows.\n *\n * Every modal is keyed by a **stable id**, which also makes it natural to bind\n * analytics later (open/close per id, like pages).\n *\n * Pair it with the controlled chrome in {@link ./overlay}: a `defineModal`\n * component renders a `<Sheet open={m.visible} onClose={m.hide}>`/`<Modal>`.\n * The runtime ({@link ./namespaces}.FunnelProvider) mounts {@link ModalRoot} for\n * you, so there's no provider to wire.\n *\n * Trimmed vs upstream: dropped the antd/mui/bootstrap binding adapters and the\n * standalone `<Provider>` (folded into the funnel runtime).\n */\n\nimport {\n createContext,\n createElement,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n type ComponentType,\n type Dispatch,\n type ReactNode,\n} from 'react'\n\n// ── State ────────────────────────────────────────────────\n\nexport interface ModalState {\n id: string\n args?: Record<string, unknown>\n visible?: boolean\n delayVisible?: boolean\n keepMounted?: boolean\n}\nexport interface ModalStore {\n [id: string]: ModalState\n}\ninterface ModalAction {\n type: 'show' | 'hide' | 'remove' | 'set-flags'\n payload: { modalId: string; args?: Record<string, unknown>; flags?: Record<string, unknown> }\n}\ninterface ModalCallbacks {\n [id: string]: { resolve: (v: unknown) => void; reject: (v: unknown) => void; promise: Promise<unknown> }\n}\n\n/** The handle `useModal()` returns to control one modal. */\nexport interface ModalHandler<Props = Record<string, unknown>> {\n id: string\n args?: Record<string, unknown>\n visible: boolean\n keepMounted: boolean\n show: (args?: Props) => Promise<unknown>\n hide: () => Promise<unknown>\n remove: () => void\n /** Resolve the promise returned by `show()` (e.g. a confirm result). */\n resolve: (value?: unknown) => void\n /** Reject the promise returned by `show()`. */\n reject: (value?: unknown) => void\n /** Resolve the promise returned by `hide()` (after a close transition). */\n resolveHide: (value?: unknown) => void\n}\n\n// ── Registry + dispatch ──────────────────────────────────\n\nconst symModalId = Symbol('AppFunnelModalId')\nconst initialState: ModalStore = {}\nconst ModalStateContext = createContext<ModalStore>(initialState)\nconst ModalIdContext = createContext<string | null>(null)\n/** The provider-scoped dispatch — components/hooks always read this, never the module fallback. */\nconst ModalDispatchContext = createContext<Dispatch<ModalAction> | null>(null)\n\nconst REGISTRY: { [id: string]: { comp: ComponentType<any>; props?: Record<string, unknown> } } = {}\nconst ALREADY_MOUNTED: Record<string, boolean> = {}\nconst modalCallbacks: ModalCallbacks = {}\nconst hideCallbacks: ModalCallbacks = {}\n\nlet uid = 0\nconst getUid = () => `_af_modal_${uid++}`\n\n/**\n * Module-level **fallback** dispatch for the imperative API (`showModal` called\n * from plain code with no React context). Runtimes register on a stack in a\n * mount *effect* — never during render, so concurrent SSR renders can't race on\n * it, and a server render (where effects don't run) never touches module state.\n * The imperative API binds to the most recently mounted runtime; inside React,\n * hooks use the provider-scoped {@link ModalDispatchContext} instead.\n */\nconst runtimeStack: Dispatch<ModalAction>[] = []\n\nconst dispatch: Dispatch<ModalAction> = (action) => {\n const top = runtimeStack[runtimeStack.length - 1]\n if (!top) {\n throw new Error('No modal dispatch — render inside <FunnelProvider> (which mounts the modal runtime).')\n }\n top(action)\n}\n\nexport const modalReducer = (state: ModalStore = initialState, action: ModalAction): ModalStore => {\n const { modalId, args, flags } = action.payload\n switch (action.type) {\n case 'show':\n return {\n ...state,\n [modalId]: {\n ...state[modalId],\n id: modalId,\n args,\n // Mount first, then flip visible on the next effect → enter transition.\n visible: !!ALREADY_MOUNTED[modalId],\n delayVisible: !ALREADY_MOUNTED[modalId],\n },\n }\n case 'hide':\n return state[modalId] ? { ...state, [modalId]: { ...state[modalId], visible: false } } : state\n case 'remove': {\n const next = { ...state }\n delete next[modalId]\n return next\n }\n case 'set-flags':\n return { ...state, [modalId]: { ...state[modalId], ...flags } }\n default:\n return state\n }\n}\n\nfunction idOf(modal: string | ComponentType<any>): string {\n if (typeof modal === 'string') return modal\n const m = modal as ComponentType<any> & { [symModalId]?: string }\n if (!m[symModalId]) m[symModalId] = getUid()\n return m[symModalId] as string\n}\n\n// ── Imperative API (callable from anywhere) ──────────────\n\n/** Register a component as an id-keyed modal so the placeholder can render it. */\nexport function registerModal(id: string, comp: ComponentType<any>, props?: Record<string, unknown>): void {\n if (!REGISTRY[id]) REGISTRY[id] = { comp, props }\n else REGISTRY[id].props = props\n}\n\nexport function unregisterModal(id: string): void {\n delete REGISTRY[id]\n}\n\nfunction showModalVia<T = unknown>(\n d: Dispatch<ModalAction>,\n modal: string | ComponentType<any>,\n args?: Record<string, unknown>,\n): Promise<T> {\n const id = idOf(modal)\n if (typeof modal !== 'string' && !REGISTRY[id]) registerModal(id, modal)\n d({ type: 'show', payload: { modalId: id, args } })\n if (!modalCallbacks[id]) {\n let res!: (v: unknown) => void\n let rej!: (v: unknown) => void\n const promise = new Promise<unknown>((resolve, reject) => {\n res = resolve\n rej = reject\n })\n modalCallbacks[id] = { resolve: res, reject: rej, promise }\n }\n return modalCallbacks[id].promise as Promise<T>\n}\n\n/** Show a modal (by component or id). Returns a promise resolved by `resolve()`. */\nexport function showModal<T = unknown>(modal: string | ComponentType<any>, args?: Record<string, unknown>): Promise<T> {\n return showModalVia(dispatch, modal, args)\n}\n\nfunction hideModalVia<T = unknown>(d: Dispatch<ModalAction>, modal: string | ComponentType<any>): Promise<T> {\n const id = idOf(modal)\n d({ type: 'hide', payload: { modalId: id } })\n delete modalCallbacks[id]\n if (!hideCallbacks[id]) {\n let res!: (v: unknown) => void\n let rej!: (v: unknown) => void\n const promise = new Promise<unknown>((resolve, reject) => {\n res = resolve\n rej = reject\n })\n hideCallbacks[id] = { resolve: res, reject: rej, promise }\n }\n return hideCallbacks[id].promise as Promise<T>\n}\n\n/** Hide a modal. Returns a promise resolved by `resolveHide()` (post-transition). */\nexport function hideModal<T = unknown>(modal: string | ComponentType<any>): Promise<T> {\n return hideModalVia(dispatch, modal)\n}\n\nfunction removeModalVia(d: Dispatch<ModalAction>, modal: string | ComponentType<any>): void {\n const id = idOf(modal)\n d({ type: 'remove', payload: { modalId: id } })\n delete modalCallbacks[id]\n delete hideCallbacks[id]\n}\n\n/** Remove a modal from the tree (frees its state; better than just hiding). */\nexport function removeModal(modal: string | ComponentType<any>): void {\n removeModalVia(dispatch, modal)\n}\n\nfunction setFlags(d: Dispatch<ModalAction>, id: string, flags: Record<string, unknown>): void {\n d({ type: 'set-flags', payload: { modalId: id, flags } })\n}\n\n// ── Hook ─────────────────────────────────────────────────\n\nexport function useModal(): ModalHandler\nexport function useModal(modal: string, args?: Record<string, unknown>): ModalHandler\nexport function useModal<P extends object>(modal: ComponentType<P>, args?: Partial<P>): ModalHandler<P>\nexport function useModal(modal?: string | ComponentType<any>, args?: Record<string, unknown>): ModalHandler {\n const modals = useContext(ModalStateContext)\n const contextId = useContext(ModalIdContext)\n // Prefer the provider-scoped dispatch; the module fallback covers hook usage\n // outside <ModalRuntime> (which itself throws a descriptive error).\n const d = useContext(ModalDispatchContext) ?? dispatch\n const isComponent = !!modal && typeof modal !== 'string'\n const id = modal ? idOf(modal) : contextId\n if (!id) throw new Error('useModal: no modal id (call inside a defineModal component, or pass an id/component).')\n\n useEffect(() => {\n if (isComponent && !REGISTRY[id]) registerModal(id, modal as ComponentType<any>, args)\n }, [isComponent, id, modal, args])\n\n const info = modals[id]\n const show = useCallback((a?: Record<string, unknown>) => showModalVia(d, id, a), [d, id])\n const hide = useCallback(() => hideModalVia(d, id), [d, id])\n const remove = useCallback(() => removeModalVia(d, id), [d, id])\n const resolve = useCallback((v?: unknown) => {\n modalCallbacks[id]?.resolve(v)\n delete modalCallbacks[id]\n }, [id])\n const reject = useCallback((v?: unknown) => {\n modalCallbacks[id]?.reject(v)\n delete modalCallbacks[id]\n }, [id])\n const resolveHide = useCallback((v?: unknown) => {\n hideCallbacks[id]?.resolve(v)\n delete hideCallbacks[id]\n }, [id])\n\n return useMemo(\n () => ({\n id,\n args: info?.args,\n visible: !!info?.visible,\n keepMounted: !!info?.keepMounted,\n show,\n hide,\n remove,\n resolve,\n reject,\n resolveHide,\n }),\n [id, info?.args, info?.visible, info?.keepMounted, show, hide, remove, resolve, reject, resolveHide],\n )\n}\n\n// ── defineModal (HOC) ────────────────────────────────────\n\nexport interface ModalHocProps {\n id: string\n defaultVisible?: boolean\n keepMounted?: boolean\n}\n\n/**\n * Wrap a component into an id-keyed modal. Inside it, `useModal()` (no args)\n * gives the handle. Render a controlled `<Sheet>`/`<Modal>` with\n * `open={m.visible} onClose={m.hide}`.\n */\nexport function defineModal<P extends object>(Comp: ComponentType<P>): ComponentType<P & ModalHocProps> {\n return function Wrapped({ id, defaultVisible, keepMounted, ...props }: P & ModalHocProps): ReactNode {\n const { args, show } = useModal(id)\n const modals = useContext(ModalStateContext)\n const d = useContext(ModalDispatchContext) ?? dispatch\n const shouldMount = !!modals[id]\n\n useEffect(() => {\n if (defaultVisible) show()\n ALREADY_MOUNTED[id] = true\n return () => {\n delete ALREADY_MOUNTED[id]\n }\n }, [id, show, defaultVisible])\n\n useEffect(() => {\n if (keepMounted) setFlags(d, id, { keepMounted: true })\n }, [d, id, keepMounted])\n\n const delayVisible = modals[id]?.delayVisible\n useEffect(() => {\n if (delayVisible) show(args)\n }, [delayVisible, args, show])\n\n if (!shouldMount) return null\n return createElement(\n ModalIdContext.Provider,\n { value: id },\n createElement(Comp, { ...(props as P), ...args }),\n )\n }\n}\n\n// ── Runtime (mounted by FunnelProvider) ──────────────────\n\n/** Renders every visible registered modal. Mounted once by the funnel runtime. */\nexport function ModalRoot(): ReactNode {\n const modals = useContext(ModalStateContext)\n const toRender = Object.keys(modals)\n .filter((id) => REGISTRY[id])\n .map((id) => ({ id, ...REGISTRY[id] }))\n return createElement(\n 'div',\n { 'data-appfunnel-modal-root': '' },\n ...toRender.map((t) => createElement(t.comp, { key: t.id, id: t.id, ...t.props })),\n )\n}\n\n/**\n * Provides the modal store + dispatch (context-scoped) + renders {@link ModalRoot}.\n * Wrapped around the funnel tree by `FunnelProvider`.\n *\n * The module-level fallback dispatch (for the imperative `showModal()` API) is\n * bound in a mount **effect** — never during render — so SSR and concurrent\n * renders are safe. With multiple simultaneous providers the imperative API\n * binds to the **most recently mounted** one (a dev warning fires); hooks inside\n * each tree always use their own provider's dispatch via context.\n */\nexport function ModalRuntime({ children }: { children: ReactNode }): ReactNode {\n const [state, localDispatch] = useReducer(modalReducer, initialState)\n useEffect(() => {\n runtimeStack.push(localDispatch)\n if (runtimeStack.length > 1) {\n try {\n console.warn(\n `[appfunnel] ${runtimeStack.length} modal runtimes are mounted — the imperative showModal()/hideModal() API binds to the most recent one. Use the useModal() hook inside each tree instead.`,\n )\n } catch {\n /* no-op */\n }\n }\n return () => {\n const i = runtimeStack.indexOf(localDispatch)\n if (i !== -1) runtimeStack.splice(i, 1)\n }\n }, [])\n return createElement(\n ModalDispatchContext.Provider,\n { value: localDispatch },\n createElement(\n ModalStateContext.Provider,\n { value: state },\n children,\n createElement(ModalRoot, null),\n ),\n )\n}\n","/**\n * Raw, **controlled** overlay chrome — `<Sheet>` (a drawer) and `<Modal>` (a\n * centered dialog). Headless and styleable (className/portal/dismiss), the same\n * two-tier contract as `<Choice>`: thin wrappers you restyle or eject.\n *\n * These are the presentation layer. For *imperative*, promise-based modals\n * triggered from anywhere, wrap one in `defineModal` and `showModal(...)`\n * (see {@link ./modals}) — that registry drives these controlled primitives.\n * They're also used directly (no registry) where local state is simpler, e.g.\n * the checkout `sheet` surface.\n *\n * Deliberately minimal: portal to `document.body`, lock body scroll while open,\n * dismiss on Escape / backdrop. No animation engine, no focus-trap dependency.\n */\n\nimport {\n createElement,\n useEffect,\n type CSSProperties,\n type ReactNode,\n} from 'react'\nimport { createPortal } from 'react-dom'\nimport { useModal } from './registry'\n\nexport type SheetSide = 'bottom' | 'top' | 'left' | 'right'\n\n/**\n * `<Sheet>`/`<Modal>` bind themselves to the surrounding {@link defineModal} via\n * its context — so inside a modal you write just `<Sheet>…</Sheet>`, with no\n * open/onClose plumbing. They are therefore **only valid inside a `defineModal`**\n * (rendered through `showModal`); used anywhere else `useModal()` throws, which\n * is the correct signal. For an overlay driven by local state, wrap it in a\n * `defineModal` and `showModal` it — that's the one overlay path.\n */\nfunction useModalControl(): { open: boolean; onClose: () => void } {\n const m = useModal()\n return {\n open: m.visible,\n onClose: () => {\n m.hide()\n m.resolveHide()\n if (!m.keepMounted) m.remove()\n },\n }\n}\n\ninterface OverlayCommon {\n className?: string\n backdropClassName?: string\n dismissOnBackdrop?: boolean\n ariaLabel?: string\n children: ReactNode\n}\n\ninterface ShellProps {\n open: boolean\n onClose: () => void\n className?: string\n backdropClassName?: string\n dismissOnBackdrop?: boolean\n ariaLabel?: string\n /** Flexbox alignment of the panel within the viewport. */\n container: Pick<CSSProperties, 'justifyContent' | 'alignItems'>\n /** Panel layout (size + corners per variant). */\n panel: CSSProperties\n children: ReactNode\n}\n\n/** Shared overlay shell: portal, backdrop, scroll-lock, Escape — variant-agnostic. */\nfunction OverlayShell({\n open,\n onClose,\n className,\n backdropClassName,\n dismissOnBackdrop = true,\n ariaLabel,\n container,\n panel,\n children,\n}: ShellProps): ReactNode {\n useEffect(() => {\n if (!open || typeof document === 'undefined') return\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') onClose()\n }\n const prev = document.body.style.overflow\n document.body.style.overflow = 'hidden'\n document.addEventListener('keydown', onKey)\n return () => {\n document.body.style.overflow = prev\n document.removeEventListener('keydown', onKey)\n }\n }, [open, onClose])\n\n if (!open || typeof document === 'undefined') return null\n\n const overlay = createElement(\n 'div',\n {\n role: 'dialog',\n 'aria-modal': true,\n 'aria-label': ariaLabel,\n 'data-appfunnel-overlay': '',\n style: { position: 'fixed', inset: 0, zIndex: 1000, display: 'flex', ...container },\n },\n createElement('div', {\n 'data-appfunnel-overlay-backdrop': '',\n className: backdropClassName,\n onClick: dismissOnBackdrop ? onClose : undefined,\n style: { position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)' },\n }),\n createElement(\n 'div',\n { 'data-appfunnel-overlay-panel': '', className, style: { position: 'relative', background: '#fff', ...panel } },\n children,\n ),\n )\n\n return createPortal(overlay, document.body)\n}\n\nexport type SheetProps = OverlayCommon & {\n /** Edge the drawer slides from (default `bottom`). */\n side?: SheetSide\n}\n\nconst SHEET_LAYOUT: Record<SheetSide, { container: ShellProps['container']; panel: CSSProperties }> = {\n bottom: { container: { justifyContent: 'flex-end', alignItems: 'stretch' }, panel: { borderTopLeftRadius: 16, borderTopRightRadius: 16, padding: 16, maxHeight: '90vh', overflow: 'auto' } },\n top: { container: { justifyContent: 'flex-start', alignItems: 'stretch' }, panel: { borderBottomLeftRadius: 16, borderBottomRightRadius: 16, padding: 16, maxHeight: '90vh', overflow: 'auto' } },\n left: { container: { justifyContent: 'flex-start', alignItems: 'stretch' }, panel: { height: '100%', width: 'min(420px, 90vw)', padding: 16, overflow: 'auto' } },\n right: { container: { justifyContent: 'flex-end', alignItems: 'stretch' }, panel: { height: '100%', width: 'min(420px, 90vw)', padding: 16, overflow: 'auto' } },\n}\n\n/**\n * An edge-anchored drawer. Inside a `defineModal` it auto-binds — `<Sheet>…`;\n * outside one, control it with `open`/`onClose`.\n */\nexport function Sheet(props: SheetProps): ReactNode {\n const control = useModalControl()\n const layout = SHEET_LAYOUT[props.side ?? 'bottom']\n return createElement(OverlayShell, {\n ...control,\n className: props.className,\n backdropClassName: props.backdropClassName,\n dismissOnBackdrop: props.dismissOnBackdrop,\n ariaLabel: props.ariaLabel,\n container: layout.container,\n panel: layout.panel,\n children: props.children,\n })\n}\n\nexport type ModalProps = OverlayCommon\n\n/** A centered dialog. Auto-binds to its `defineModal` — `<Modal>…`. */\nexport function Modal(props: ModalProps): ReactNode {\n const control = useModalControl()\n return createElement(OverlayShell, {\n ...control,\n className: props.className,\n backdropClassName: props.backdropClassName,\n dismissOnBackdrop: props.dismissOnBackdrop,\n ariaLabel: props.ariaLabel,\n container: { justifyContent: 'center', alignItems: 'center' },\n panel: { borderRadius: 16, padding: 24, width: 'min(480px, 92vw)', maxHeight: '90vh', overflow: 'auto' },\n children: props.children,\n })\n}\n","/**\n * v2 commerce primitives — the two intents from phase-3, made trivial.\n *\n * - `<Checkout product surface>` — the **purchase** primitive. The `surface`\n * prop picks presentation; some surfaces render **inline** (express wallets,\n * inline card, provider iframe), some **open on click** (sheet/popup/redirect).\n * `<Checkout>` covers both: it renders inline surfaces and renders a trigger\n * button for the rest (`asChild` to use your own button).\n * - `<Upsell product>` — the **upsell** primitive. Off-session charge to the\n * saved method, no card re-entry, one tap.\n * - `useCheckout()` — the headless hook under both, always available for a\n * fully-custom CTA.\n *\n * The SDK never talks to a provider. It owns the state machine + the analytics\n * (`checkout.start` / `purchase.complete`) + post-charge navigation, and\n * delegates the actual charge/render to an injected {@link CheckoutDriver}\n * (the real one is platform-side; tests use {@link createMockDriver}).\n *\n * Which product is charged is the author's bound variable, captured at render\n * (inline surfaces) or at `open()` time (trigger surfaces).\n */\n\nimport {\n createContext,\n createElement,\n isValidElement,\n cloneElement,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n type ComponentType,\n type ReactElement,\n type ReactNode,\n} from 'react'\nimport { useTrackerRef } from '../tracking/tracking'\nimport { useNavigation } from '../flow/flow'\nimport { Sheet } from '../modals/sheet'\nimport { defineModal, useModal, showModal } from '../modals/registry'\nimport {\n checkoutError,\n isInlineSurface,\n PROVIDER_PROFILES,\n type CheckoutError,\n type CheckoutErrorCategory,\n type CheckoutIntent,\n type CheckoutProvider,\n type CheckoutSurface,\n type UpsellKind,\n} from './capabilities'\n\n// ── Capability matrix (pure — lives in ./capabilities, ships via the manifest\n// entry so the API/editor/AI run the SAME checks; re-exported here so every\n// existing import keeps working) ───────────────────────\nexport {\n INLINE_SURFACES,\n PROVIDER_PROFILES,\n checkoutError,\n isInlineSurface,\n isMerchantOfRecord,\n isOrchestrator,\n surfacesFor,\n validateCheckout,\n validateUpsell,\n} from './capabilities'\nexport type {\n CheckoutError,\n CheckoutErrorCategory,\n CheckoutIntent,\n CheckoutProvider,\n CheckoutSurface,\n OffSessionReliability,\n ProviderProfile,\n SurfaceCapability,\n UpsellKind,\n ValidationResult,\n} from './capabilities'\n\n// ── Driver seam ──────────────────────────────────────────\n\nexport type CheckoutStatus = 'idle' | 'loading' | 'requires_action' | 'success' | 'error'\n\nexport interface CheckoutRequest {\n product: string\n intent: CheckoutIntent\n surface?: CheckoutSurface\n /** For `upsell` intent — which kind of off-session charge (default `subscription`). */\n kind?: UpsellKind\n /**\n * Buyer email at attempt time, read from the funnel's `user.email` namespace value\n * (injected by `FunnelProvider` via {@link driverWithEmail} — no author wiring).\n * Drivers forward it into the wire `CheckoutSessionRequest.email` (Stripe Customer\n * creation / receipts / Paddle prefill).\n */\n email?: string\n}\n\nexport interface CheckoutResult {\n ok: boolean\n error?: CheckoutError\n /** Charged amount in minor units (for the purchase event). */\n amountMinor?: number\n currency?: string\n /**\n * The **server-minted** dedup id for the purchase event — the platform creates it\n * when the charge settles and fires CAPI with it; the SDK emits `purchase.complete`\n * with the same id so the browser pixel dedupes against the server. (Server is the\n * source of truth for payment events; the SDK doesn't mint these.)\n */\n eventId?: string\n}\n\nexport interface CheckoutCallbacks {\n onSuccess: (result: CheckoutResult) => void\n onError: (error: CheckoutError) => void\n /**\n * The buyer SUBMITTED an inline surface (Stripe confirm click / wallet\n * authorization; Paddle inline checkout opening). This is when `checkout.start`\n * fires and the status machine enters `loading` for inline attempts — trigger\n * surfaces fire it at click time instead. It also marks fresh user intent, so\n * the once-per-chain recovery guard resets. Optional: drivers that can't\n * observe submit simply never call it, and the SHEET host deliberately doesn't\n * forward it (the sheet's own open already began the attempt — re-firing would\n * double-count starts and un-arm the recovery guard mid-chain).\n */\n onStart?: () => void\n /**\n * The inline surface reports a valid payment method was entered (e.g. Stripe's\n * Payment Element became `complete`), before the charge. Drives the\n * `checkout.payment_added` analytics step; optional — drivers that can't observe\n * it (or off-session charges) simply never call it.\n */\n onPaymentAdded?: () => void\n}\n\n/**\n * What a driver factory (`stripeCheckoutDriver` et al. from the\n * `@appfunnel-dev/sdk/driver-*` entries) receives to construct a\n * {@link CheckoutDriver}. Derived by `createFunnelTree` from the SAME\n * renderer-injected mount data the platform tracker uses (tracking config +\n * identity), so checkout wire calls land on the exact campaign/funnel/session\n * the analytics do — there is no second config channel to drift.\n *\n * Serializable on purpose, and factories must be **construction-safe on the\n * server too**: a factory only closes over this ctx (no provider SDK, no\n * `window`) — all provider work belongs in effects/event handlers, so SSR can\n * render the driver's stable inline placeholder and hydration matches.\n */\nexport interface CheckoutDriverContext {\n /** Public API origin, e.g. `https://api.appfunnel.net` (no trailing slash). */\n apiBase: string\n /** Campaign DB id (the checkout route key, same as the ingestion route key). */\n campaignId: string\n /** WebFunnel DB id (NOT the funnel.ts config id). */\n funnelId: string\n /** Render-time mode — the server resolves the product binding + store credentials by it. */\n mode: 'test' | 'live'\n /** Funnel session id when one exists (analytics + customer continuity). */\n sessionId?: string | null\n /** Signed-cookie-verified bare visitor id, when known. */\n visitorId?: string | null\n}\n\n/**\n * The provider seam. The platform injects the real one (Stripe/Paddle/Whop/…);\n * tests use {@link createMockDriver}.\n *\n * Most providers ship their **own React SDK** (`@stripe/react-stripe-js`,\n * `@paddle/paddle-js`, Primer's React components, …). A driver's `renderInline`\n * returns exactly that: the provider's React element mounted in our chrome (inline,\n * or inside the `<Sheet>`). Those provider SDKs live in the **driver/platform**\n * package, not our core funnel SDK — which is why the driver is injected: the core\n * stays lean and provider-agnostic, and you only pull the SDK for the provider you use.\n */\nexport interface CheckoutDriver {\n provider: CheckoutProvider\n /** Trigger a charge (trigger surfaces + programmatic). Resolves when settled. */\n start(req: CheckoutRequest): Promise<CheckoutResult>\n /** Render an inline surface (e.g. the provider's React payment element); report via callbacks. */\n renderInline?(req: CheckoutRequest, cb: CheckoutCallbacks): ReactNode\n /**\n * Verify an EXISTING attempt with the server (`POST /complete`, bounded re-poll on\n * `pending`) — the redirect-return resume leg: hosted-checkout success URLs carry\n * `?af_checkout={correlationId}` back into the funnel, and {@link CheckoutResume}\n * hands the id here so the settlement (server-verified) resolves into the normal\n * success/failure paths. Never charges; only verifies.\n */\n resume?(correlationId: string): Promise<CheckoutResult>\n}\n\nexport interface MockDriverOptions {\n /** The result a successful charge resolves with. */\n result?: CheckoutResult\n /** Make **off-session** charges (no surface) fail — to exercise the upsell fallback. */\n failOffSession?: CheckoutError | boolean\n}\n\n/** A console/no-op driver — tests, preview, local dev. Succeeds unless configured to fail. */\nexport function createMockDriver(\n provider: CheckoutProvider = 'stripe',\n options: MockDriverOptions = {},\n): CheckoutDriver {\n const success: CheckoutResult = options.result ?? { ok: true, amountMinor: 0, currency: 'USD' }\n const offError: CheckoutError =\n typeof options.failOffSession === 'object'\n ? options.failOffSession\n : checkoutError('authentication_required', 'off-session charge declined (mock)')\n return {\n provider,\n start: (req) => {\n if (options.failOffSession && !req.surface) return Promise.resolve({ ok: false, error: offError })\n return Promise.resolve(success)\n },\n renderInline: (req, cb) =>\n createElement(\n 'button',\n {\n type: 'button',\n 'data-mock-surface': req.surface,\n onClick: () => {\n cb.onStart?.() // user submit — mirrors the real drivers (checkout.start for inline)\n if (success.ok) cb.onSuccess(success)\n else cb.onError(success.error ?? checkoutError('processing_error', 'failed (mock)'))\n },\n },\n `Pay (mock ${req.surface})`,\n ),\n resume: () => Promise.resolve(success),\n }\n}\n\n/**\n * Wrap a driver so every attempt carries the buyer email the funnel has collected\n * (`user.email`), read at ATTEMPT time — `start()` for trigger surfaces, the\n * `renderInline` request for mounted surfaces. Applied by `FunnelProvider` around\n * the injected driver, so `useCheckout`, `<Checkout>` inline branches and the\n * checkout sheet all forward it without wiring; drivers pass it into the wire's\n * `CheckoutSessionRequest.email`. An explicit `req.email` always wins.\n */\nexport function driverWithEmail(driver: CheckoutDriver, getEmail: () => string | undefined): CheckoutDriver {\n const enrich = (req: CheckoutRequest): CheckoutRequest =>\n req.email !== undefined ? req : { ...req, email: getEmail() }\n return {\n ...driver,\n start: (req) => driver.start(enrich(req)),\n renderInline: driver.renderInline ? (req, cb) => driver.renderInline!(enrich(req), cb) : undefined,\n }\n}\n\nconst DriverContext = createContext<CheckoutDriver | null>(null)\n\nexport function CheckoutDriverProvider({\n driver,\n children,\n}: {\n driver: CheckoutDriver\n children: ReactNode\n}): ReactNode {\n return createElement(DriverContext.Provider, { value: driver }, children)\n}\n\nfunction useDriver(): CheckoutDriver {\n return useContext(DriverContext) ?? FALLBACK_DRIVER\n}\nconst FALLBACK_DRIVER = createMockDriver()\n\n// ── Failure routing (the recovery \"magic\") ───────────────\n\n/** One declarative recovery route for a failure category. */\nexport type FailureRoute =\n | { go: string } // navigate the flow to a page key (e.g. a real-card recapture page)\n | { modal: string | ComponentType<any> } // show a registry modal — it receives {@link FailureModalProps}\n | { fallback: CheckoutSurface } // re-collect a card ON-SESSION on this surface and retry (once)\n | ((error: CheckoutError) => void) // full control\n\n/**\n * What a `{ modal }` failure route hands the modal — the error AND the actions,\n * because registry modals mount outside the flow's nav context and a recovery\n * modal that can't act is just an error toast. Type your modal with this:\n *\n * ```tsx\n * const Declined = defineModal<FailureModalProps>(({ error, go, retry }) => (\n * <Sheet>\n * <p>{error.category === 'prepaid_card' ? 'Prepaid cards can't start a trial.' : 'Payment didn't go through.'}</p>\n * <button onClick={() => retry('sheet')}>Try another card</button>\n * <button onClick={() => go('downsell')}>See the lite plan</button>\n * </Sheet>\n * ))\n * ```\n *\n * A modal can also host a whole `<Checkout product=\"…\" surface=\"element\" />` for\n * an inline downsell — the driver context is app-level, so checkout works inside\n * modals as-is.\n */\nexport interface FailureModalProps {\n error: CheckoutError\n /** The product whose charge failed (absent only for product-less failures). */\n product?: string\n /** Navigate the flow to a page key (modals can't call useNavigation themselves). */\n go: (pageKey: string) => void\n /**\n * Re-attempt the SAME product. `retry()` re-runs an upsell off-session; for a\n * purchase (which needs UI to re-collect) it opens the payment sheet.\n * `retry('sheet')` re-collects on the SDK sheet; an inline surface\n * (`element`/`express`/`embedded`) is COERCED to the sheet when the provider\n * supports it — a retry has no page slot to mount into, so the sheet hosts the\n * element. On sheet-less MoR providers (Paddle) inline retries run through the\n * driver, whose provider checkout opens its own overlay. `retry('popup')` /\n * `retry('redirect')` hand off to the provider. A failed retry routes through\n * `onFailed` again (the modal reopens) — the loop is user-driven, never\n * automatic. Hide the modal first (`useModal().hide()`) when retrying into a\n * surface that opens its own overlay.\n */\n retry: (surface?: CheckoutSurface) => void\n}\n\n/**\n * Declarative failure recovery — route each failure **category** to what happens\n * next, instead of hand-wiring `onError`:\n *\n * ```tsx\n * <Checkout product=\"monthly\" surface=\"element\" onFailed={{\n * prepaid_card: { go: 'real-card' },\n * insufficient_funds: { modal: DownsellModal },\n * default: { modal: TryAgainModal },\n * }} />\n * ```\n *\n * Resolution: exact category → `default` → nothing (the error state + `checkout.\n * failed` event stand, as today). Two built-in judgments:\n * - `canceled` only routes when mapped EXPLICITLY — a deliberately dismissed\n * sheet/popup is not a failure to recover from, so `default` never catches it;\n * - a `{ fallback }` recovery runs at most once per attempt chain (its own\n * failure routes through the non-fallback routes), so declines can't loop.\n *\n * `checkout.failed` fires with category + declineCode on every failure regardless\n * of routing — recovery pages are measurable, and being ordinary flow pages they\n * are A/B-able with page experiments like anything else.\n */\nexport type OnFailedMap = Partial<Record<CheckoutErrorCategory | 'default', FailureRoute>>\n\n// ── The headless hook ────────────────────────────────────\n\nexport interface UseCheckoutOptions {\n intent?: CheckoutIntent\n /** For `upsell` intent — which kind of off-session charge (default `subscription`). */\n kind?: UpsellKind\n /** Advance to the next page after a successful charge (default: true). */\n advanceOnSuccess?: boolean\n onSuccess?: (result: CheckoutResult) => void\n onError?: (error: CheckoutError) => void\n /** Declarative failure recovery — see {@link OnFailedMap}. Runs AFTER `onError`. */\n onFailed?: OnFailedMap\n /**\n * Try this surface ON-SESSION once on any first failure, before `onFailed`\n * routing — the generalized `<Upsell fallback>`: the off-session (or first)\n * charge fails, the surface re-collects a card, the retry's failure then goes\n * through `onFailed`. Never re-triggered by its own failure; never triggered\n * by a user-`canceled` checkout.\n */\n recoverySurface?: CheckoutSurface\n}\n\nexport interface CheckoutHandle {\n /** Start the charge for a product; resolves with the result (no surface = off-session). */\n open: (product: string, surface?: CheckoutSurface) => Promise<CheckoutResult>\n status: CheckoutStatus\n /** The last failure, structured so you can route/recover by `category`. */\n error: CheckoutError | null\n isLoading: boolean\n reset: () => void\n /** Build the callbacks an inline surface reports through (used by `<Checkout>`). */\n callbacksFor: (product?: string, surface?: CheckoutSurface) => CheckoutCallbacks & { onStart: () => void }\n}\n\n/**\n * The headless checkout hook. Owns the state machine + analytics + post-charge\n * navigation; delegates the charge to the injected {@link CheckoutDriver}.\n */\nexport function useCheckout(opts: UseCheckoutOptions = {}): CheckoutHandle {\n const driver = useDriver()\n const tracker = useTrackerRef()\n const nav = useNavigation()\n const [status, setStatus] = useState<CheckoutStatus>('idle')\n const [error, setError] = useState<CheckoutError | null>(null)\n\n const intent = opts.intent ?? 'purchase'\n const kind = opts.kind\n const advance = opts.advanceOnSuccess ?? true\n\n // True while an on-session recovery attempt (recoverySurface / a `{ fallback }`\n // route) is in flight — its own failure must not start ANOTHER re-collect, so\n // declines can't loop. Cleared on every fresh user-initiated attempt.\n const recovering = useRef(false)\n // fail → startRecovery → (sheet/attempt) → fail is mutually recursive; refs give\n // the cycle stable identities so the returned handle doesn't churn per render.\n const failRef = useRef<(err: CheckoutError, product?: string) => void>(() => {})\n const attemptRef = useRef<(product: string, surface?: CheckoutSurface) => Promise<CheckoutResult>>(\n async () => ({ ok: false }),\n )\n\n const succeed = useCallback(\n (result: CheckoutResult) => {\n setStatus('success')\n tracker.track('purchase.complete', {\n amount: result.amountMinor != null ? result.amountMinor / 100 : undefined,\n currency: result.currency,\n eventId: result.eventId, // server-minted (browser↔CAPI dedup); undefined if none\n })\n opts.onSuccess?.(result)\n if (advance) nav.next()\n },\n [tracker, nav, advance, opts],\n )\n const succeedRef = useRef(succeed)\n succeedRef.current = succeed\n\n const begin = useCallback(\n (product?: string, surface?: CheckoutSurface) => {\n setStatus('loading')\n setError(null)\n tracker.track('checkout.start', { productId: product, surface })\n },\n [tracker],\n )\n\n const paymentAdded = useCallback(() => tracker.track('checkout.payment_added', {}), [tracker])\n\n // Open the on-session recovery surface for a product. A recovery has no page slot\n // to mount UI into, so surfaces that need one route through our sheet: `sheet`\n // itself, and inline surfaces WHEN the provider supports the sheet (Stripe et al.\n // — an element/express recovery is the same client_confirm hosted in the sheet).\n // Everything else (popup/redirect, and inline on sheet-less MoR providers like\n // Paddle, whose provider_checkout opens its OWN overlay) runs through the driver.\n const hostInSheet = (surface: CheckoutSurface): boolean =>\n surface === 'sheet' ||\n (isInlineSurface(surface) && !!PROVIDER_PROFILES[driver.provider]?.surfaces.sheet)\n const startRecovery = (product: string, surface: CheckoutSurface) => {\n recovering.current = true\n if (hostInSheet(surface)) {\n begin(product, 'sheet')\n void showModal(CheckoutSheet, {\n product,\n surface: 'sheet',\n intent,\n kind,\n onSuccess: (r: CheckoutResult) => succeedRef.current(r),\n onError: (e: CheckoutError) => failRef.current(e, product),\n onPaymentAdded: () => paymentAdded(),\n })\n } else {\n void attemptRef.current(product, surface)\n }\n }\n\n failRef.current = (err: CheckoutError, product?: string) => {\n // 3DS/SCA that an off-session charge can't satisfy → flag for recovery.\n setStatus(err.category === 'authentication_required' ? 'requires_action' : 'error')\n setError(err)\n tracker.track('checkout.failed', {\n category: err.category,\n declineCode: err.declineCode,\n productId: product,\n intent,\n })\n opts.onError?.(err)\n\n // A deliberately dismissed checkout routes only when 'canceled' is mapped\n // EXPLICITLY — recovery machinery must not chase a user who closed the sheet.\n if (err.category === 'canceled' && !opts.onFailed?.canceled) return\n // First failure + a recovery surface → re-collect on-session, ONCE; the\n // retry's failure falls through to onFailed below.\n if (product && !recovering.current && opts.recoverySurface && err.category !== 'canceled') {\n startRecovery(product, opts.recoverySurface)\n return\n }\n let route = opts.onFailed?.[err.category] ?? (err.category === 'canceled' ? undefined : opts.onFailed?.default)\n // The documented `{ fallback }` fall-through: a fallback runs at most once per\n // attempt chain, so once a recovery is in flight the RECOVERY's own failure\n // resolves the DEFAULT route instead — unless the default is itself a fallback\n // (or was the resolved route), in which case the error state stands.\n if (route && typeof route === 'object' && 'fallback' in route && recovering.current) {\n const dflt = opts.onFailed?.default\n route =\n dflt && dflt !== route && !(typeof dflt === 'object' && 'fallback' in dflt) ? dflt : undefined\n }\n if (!route) return\n if (typeof route === 'function') route(err)\n else if ('go' in route) nav.go(route.go)\n else if ('modal' in route) {\n // Hand the modal the ACTIONS, not just the error (FailureModalProps) — the\n // registry host mounts outside the nav context, so these closures are the\n // modal's only way to move the flow or re-charge.\n const props: FailureModalProps = {\n error: err,\n product,\n go: (pageKey: string) => nav.go(pageKey),\n retry: (surface?: CheckoutSurface) => {\n if (!product) return\n recovering.current = true // a retry's failure routes again; it never auto-recovers on top\n if (!surface) {\n // Bare retry: an upsell re-runs off-session; a purchase needs UI to\n // re-collect a card — the sheet where the provider supports it, else\n // the provider's own overlay (popup).\n if (intent === 'upsell') void attemptRef.current(product)\n else startRecovery(product, PROVIDER_PROFILES[driver.provider]?.surfaces.sheet ? 'sheet' : 'popup')\n return\n }\n // startRecovery routes it: surfaces needing a MOUNTED UI go through the\n // SAME CheckoutSheet machinery the recovery path uses — driver.start\n // cannot mount React UI, so routing them there would dead-end and mint\n // orphan attempts. popup/redirect (and Paddle's own-overlay inline) are\n // driver-run hand-offs.\n startRecovery(product, surface)\n },\n }\n void showModal(route.modal, props as unknown as Record<string, unknown>)\n } else if ('fallback' in route) {\n if (product && !recovering.current) startRecovery(product, route.fallback)\n }\n }\n\n attemptRef.current = async (product: string, surface?: CheckoutSurface): Promise<CheckoutResult> => {\n begin(product, surface)\n try {\n const result = await driver.start({ product, intent, surface, kind })\n if (result.ok) succeedRef.current(result)\n else failRef.current(result.error ?? checkoutError('unknown', 'Checkout failed'), product)\n return result\n } catch (e) {\n const err = checkoutError('processing_error', e instanceof Error ? e.message : 'Checkout failed')\n failRef.current(err, product)\n return { ok: false, error: err }\n }\n }\n\n const open = useCallback(async (product: string, surface?: CheckoutSurface): Promise<CheckoutResult> => {\n recovering.current = false // fresh user-initiated attempt chain\n return attemptRef.current(product, surface)\n }, [])\n\n const callbacksFor = useCallback(\n (product?: string, surface?: CheckoutSurface) => ({\n onStart: () => {\n recovering.current = false // fresh user-initiated attempt chain\n begin(product, surface)\n },\n onSuccess: (result: CheckoutResult) => succeedRef.current(result),\n onError: (err: CheckoutError) => failRef.current(err, product),\n onPaymentAdded: () => paymentAdded(),\n }),\n [begin, paymentAdded],\n )\n\n const reset = useCallback(() => {\n recovering.current = false\n setStatus('idle')\n setError(null)\n }, [])\n\n return { open, status, error, isLoading: status === 'loading', reset, callbacksFor }\n}\n\n// ── The components ───────────────────────────────────────\n\nexport interface CheckoutProps extends UseCheckoutOptions {\n /** Logical product id (the author's bound selection). */\n product: string\n surface: CheckoutSurface\n /** Render your own trigger element instead of the default button (trigger surfaces). */\n asChild?: boolean\n /** Trigger label / your trigger element. */\n children?: ReactNode\n className?: string\n}\n\n/**\n * The `sheet` surface as a registry modal: our {@link Sheet} hosts the driver's\n * element. It resolves outcomes by invoking the callbacks passed via `showModal`\n * args — closures created in the `<Checkout>` trigger (which lives inside\n * `<FunnelView>`, so they carry navigation).\n *\n * EVERY exit resolves exactly once: success/failure through the driver callbacks,\n * and a dismissal (backdrop/Escape unmounts the modal) as `canceled` — otherwise\n * the attempt's status would sit in `loading` forever, permanently disabling the\n * trigger. `canceled` then follows the built-in judgment: status → `error`,\n * `checkout.failed` fires, but `onFailed` routes it only when mapped explicitly.\n * `onStart` is deliberately NOT forwarded to the hosted element — the sheet's\n * open already began the attempt (see {@link CheckoutCallbacks.onStart}).\n */\nconst CheckoutSheet = defineModal<{\n product: string\n surface: CheckoutSurface\n intent: CheckoutIntent\n kind?: UpsellKind\n onSuccess: (result: CheckoutResult) => void\n onError: (error: CheckoutError) => void\n onPaymentAdded?: () => void\n}>(({ product, surface, intent, kind, onSuccess, onError, onPaymentAdded }) => {\n const driver = useDriver()\n const modal = useModal()\n // True once ANY outcome was reported — the unmount cleanup below only converts a\n // silent dismissal into `canceled`, never doubles a real outcome.\n const resolved = useRef(false)\n const onErrorRef = useRef(onError)\n onErrorRef.current = onError\n const hostable = !!driver.renderInline\n useEffect(() => {\n if (!hostable) {\n // Defensive: a driver with no inline surface cannot host the sheet — resolve\n // the attempt instead of leaving the trigger stuck in `loading`.\n resolved.current = true\n onErrorRef.current(\n checkoutError('processing_error', 'This checkout driver has no inline surface to host in the sheet'),\n )\n void modal.hide()\n modal.remove()\n return\n }\n return () => {\n // Backdrop/Escape dismissal removes the modal (unmount) without an outcome.\n if (!resolved.current) {\n onErrorRef.current(checkoutError('canceled', 'Checkout was dismissed before completing'))\n }\n }\n // Mount-scoped by design: resolution is tracked through refs.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n if (!driver.renderInline) return null\n // Outcomes REMOVE the modal (not just hide it): the next show mounts fresh, so\n // the resolution ref can never leak a previous attempt's state into a new one.\n const close = () => {\n resolved.current = true\n void modal.hide()\n modal.remove()\n }\n return createElement(Sheet, {\n children: driver.renderInline(\n { product, intent, surface, kind },\n {\n onSuccess: (r) => { close(); onSuccess(r) },\n onError: (e) => { close(); onError(e) },\n onPaymentAdded,\n },\n ),\n })\n})\n\n/** Render the default trigger button, or clone the author's `asChild` element. */\nfunction trigger(\n onClick: () => void,\n { asChild, children, className, disabled }: { asChild?: boolean; children?: ReactNode; className?: string; disabled?: boolean },\n): ReactNode {\n if (asChild && isValidElement(children)) {\n const child = children as ReactElement<{ onClick?: () => void }>\n return cloneElement(child, { onClick })\n }\n return createElement('button', { type: 'button', className, disabled, onClick }, children ?? 'Continue')\n}\n\n/**\n * The purchase primitive. Three presentation modes by `surface`:\n * - **inline** (`express`/`element`/`embedded`) — the driver renders the\n * provider UI in place (keyed by product so a selection change remounts it);\n * - **SDK sheet** (`sheet`) — a trigger opens the AppFunnel-owned {@link Sheet}\n * and the driver renders the provider element inside it;\n * - **provider-hosted** (`popup`/`redirect`) — a trigger hands off to the\n * provider's own overlay/page.\n */\nexport function Checkout({\n product,\n surface,\n asChild,\n children,\n className,\n ...options\n}: CheckoutProps): ReactNode {\n const driver = useDriver()\n const checkout = useCheckout(options)\n const intent = options.intent ?? 'purchase'\n\n // Inline: driver renders the mounted UI; keyed by product so changing the\n // selected plan cleanly remounts the surface.\n if (isInlineSurface(surface)) {\n return driver.renderInline\n ? createElement(\n 'div',\n { key: product, className },\n driver.renderInline({ product, intent, surface }, checkout.callbacksFor(product, surface)),\n )\n : null\n }\n\n // SDK sheet: open our overlay (a registry modal) hosting the driver's element.\n if (surface === 'sheet') {\n const cb = checkout.callbacksFor(product, surface)\n const open = () => {\n cb.onStart()\n showModal(CheckoutSheet, {\n product,\n surface,\n intent,\n kind: options.kind,\n onSuccess: cb.onSuccess,\n onError: cb.onError,\n onPaymentAdded: cb.onPaymentAdded,\n })\n }\n return trigger(open, { asChild, children, className, disabled: checkout.isLoading })\n }\n\n // Provider-hosted (popup/redirect): trigger hands off to the provider.\n return trigger(() => checkout.open(product, surface), {\n asChild,\n children,\n className,\n disabled: checkout.isLoading,\n })\n}\n\nexport interface UpsellProps extends Omit<UseCheckoutOptions, 'intent'> {\n product: string\n /**\n * If the off-session charge fails, present this surface **on-session** to\n * re-collect a card and charge again — e.g. `fallback=\"sheet\"` opens the\n * payment sheet, `fallback=\"popup\"` the provider overlay. Omit to just report\n * the failure (via `onError` / the `checkout.failed` event).\n */\n fallback?: CheckoutSurface\n asChild?: boolean\n children?: ReactNode\n className?: string\n}\n\n/**\n * The upsell primitive — an off-session, one-tap charge to the saved method (no\n * surface, no card re-entry). On failure, optionally `fallback` to an on-session\n * surface to re-collect and retry — `fallback` IS the hook's `recoverySurface`,\n * so the retry's own failure routes through `onFailed` (e.g. prepaid_card → a\n * recapture page) instead of dead-ending.\n */\nexport function Upsell({ product, fallback, asChild, children, className, ...options }: UpsellProps): ReactNode {\n const checkout = useCheckout({\n ...options,\n intent: 'upsell',\n recoverySurface: fallback ?? options.recoverySurface,\n })\n\n return trigger(() => void checkout.open(product) /* off-session (no surface) */, {\n asChild,\n children: children ?? 'Add to my plan',\n className,\n disabled: checkout.isLoading,\n })\n}\n\n// ── Redirect-return resume (hosted checkout success URLs) ────────────────────\n\n/** correlationIds this page load already resumed — the leg runs once per attempt\n * even if the component remounts (StrictMode, page-experiment remounts). */\nconst consumedResumes = new Set<string>()\n\n/**\n * The dangling settle leg of the `redirect` surface. The server appends\n * `af_checkout={correlationId}` to hosted-checkout success URLs; when the buyer\n * lands back in the funnel this component detects the param, has the server\n * VERIFY the attempt (`driver.resume` → `POST /complete`, bounded re-poll while\n * `pending`), and resolves it into the normal machinery:\n *\n * - `settled` → `purchase.complete` fires with the settlement's server-minted\n * `eventId` (pixel↔CAPI dedup), the flow advances, and the param is stripped\n * (`history.replaceState`) so a reload can't re-run the leg;\n * - `failed` → the normal failure path (`checkout.failed` + status `error`;\n * any `onFailed` maps passed as props apply — product-less, so only\n * `go`/handler routes can act).\n *\n * SSR-safe (effect-only) and runs once per correlationId per page load. Mounted\n * automatically by `createFunnelTree` inside the nav context; needs a driver\n * with `resume` (both platform drivers ship it; the mock resolves its result).\n */\nexport function CheckoutResume(options: UseCheckoutOptions = {}): ReactNode {\n const driver = useDriver()\n const checkout = useCheckout(options)\n const callbacksRef = useRef(checkout.callbacksFor)\n callbacksRef.current = checkout.callbacksFor\n\n useEffect(() => {\n if (typeof window === 'undefined' || !driver.resume) return\n const url = new URL(window.location.href)\n const correlationId = url.searchParams.get('af_checkout')\n if (!correlationId || consumedResumes.has(correlationId)) return\n consumedResumes.add(correlationId)\n void driver.resume(correlationId).then((result) => {\n // Not a new attempt — no onStart/`checkout.start`; the charge already ran.\n const cb = callbacksRef.current()\n if (result.ok) {\n url.searchParams.delete('af_checkout')\n window.history.replaceState(window.history.state, '', url.toString())\n cb.onSuccess(result)\n } else {\n cb.onError(result.error ?? checkoutError('unknown', 'The checkout could not be verified'))\n }\n })\n // Mount-scoped by design (the URL param is a page-load fact).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n return null\n}\n","'use client';\nfunction __insertCSS(code) {\n if (!code || typeof document == 'undefined') return\n let head = document.head || document.getElementsByTagName('head')[0]\n let style = document.createElement('style')\n style.type = 'text/css'\n head.appendChild(style)\n ;style.styleSheet ? (style.styleSheet.cssText = code) : style.appendChild(document.createTextNode(code))\n}\n\nimport React from 'react';\nimport ReactDOM from 'react-dom';\n\nconst getAsset = (type)=>{\n switch(type){\n case 'success':\n return SuccessIcon;\n case 'info':\n return InfoIcon;\n case 'warning':\n return WarningIcon;\n case 'error':\n return ErrorIcon;\n default:\n return null;\n }\n};\nconst bars = Array(12).fill(0);\nconst Loader = ({ visible, className })=>{\n return /*#__PURE__*/ React.createElement(\"div\", {\n className: [\n 'sonner-loading-wrapper',\n className\n ].filter(Boolean).join(' '),\n \"data-visible\": visible\n }, /*#__PURE__*/ React.createElement(\"div\", {\n className: \"sonner-spinner\"\n }, bars.map((_, i)=>/*#__PURE__*/ React.createElement(\"div\", {\n className: \"sonner-loading-bar\",\n key: `spinner-bar-${i}`\n }))));\n};\nconst SuccessIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: \"0 0 20 20\",\n fill: \"currentColor\",\n height: \"20\",\n width: \"20\"\n}, /*#__PURE__*/ React.createElement(\"path\", {\n fillRule: \"evenodd\",\n d: \"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z\",\n clipRule: \"evenodd\"\n}));\nconst WarningIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: \"0 0 24 24\",\n fill: \"currentColor\",\n height: \"20\",\n width: \"20\"\n}, /*#__PURE__*/ React.createElement(\"path\", {\n fillRule: \"evenodd\",\n d: \"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z\",\n clipRule: \"evenodd\"\n}));\nconst InfoIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: \"0 0 20 20\",\n fill: \"currentColor\",\n height: \"20\",\n width: \"20\"\n}, /*#__PURE__*/ React.createElement(\"path\", {\n fillRule: \"evenodd\",\n d: \"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z\",\n clipRule: \"evenodd\"\n}));\nconst ErrorIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: \"0 0 20 20\",\n fill: \"currentColor\",\n height: \"20\",\n width: \"20\"\n}, /*#__PURE__*/ React.createElement(\"path\", {\n fillRule: \"evenodd\",\n d: \"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z\",\n clipRule: \"evenodd\"\n}));\nconst CloseIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n width: \"12\",\n height: \"12\",\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n strokeWidth: \"1.5\",\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\"\n}, /*#__PURE__*/ React.createElement(\"line\", {\n x1: \"18\",\n y1: \"6\",\n x2: \"6\",\n y2: \"18\"\n}), /*#__PURE__*/ React.createElement(\"line\", {\n x1: \"6\",\n y1: \"6\",\n x2: \"18\",\n y2: \"18\"\n}));\n\nconst useIsDocumentHidden = ()=>{\n const [isDocumentHidden, setIsDocumentHidden] = React.useState(document.hidden);\n React.useEffect(()=>{\n const callback = ()=>{\n setIsDocumentHidden(document.hidden);\n };\n document.addEventListener('visibilitychange', callback);\n return ()=>window.removeEventListener('visibilitychange', callback);\n }, []);\n return isDocumentHidden;\n};\n\nlet toastsCounter = 1;\nclass Observer {\n constructor(){\n // We use arrow functions to maintain the correct `this` reference\n this.subscribe = (subscriber)=>{\n this.subscribers.push(subscriber);\n return ()=>{\n const index = this.subscribers.indexOf(subscriber);\n this.subscribers.splice(index, 1);\n };\n };\n this.publish = (data)=>{\n this.subscribers.forEach((subscriber)=>subscriber(data));\n };\n this.addToast = (data)=>{\n this.publish(data);\n this.toasts = [\n ...this.toasts,\n data\n ];\n };\n this.create = (data)=>{\n var _data_id;\n const { message, ...rest } = data;\n const id = typeof (data == null ? void 0 : data.id) === 'number' || ((_data_id = data.id) == null ? void 0 : _data_id.length) > 0 ? data.id : toastsCounter++;\n const alreadyExists = this.toasts.find((toast)=>{\n return toast.id === id;\n });\n const dismissible = data.dismissible === undefined ? true : data.dismissible;\n if (this.dismissedToasts.has(id)) {\n this.dismissedToasts.delete(id);\n }\n if (alreadyExists) {\n this.toasts = this.toasts.map((toast)=>{\n if (toast.id === id) {\n this.publish({\n ...toast,\n ...data,\n id,\n title: message\n });\n return {\n ...toast,\n ...data,\n id,\n dismissible,\n title: message\n };\n }\n return toast;\n });\n } else {\n this.addToast({\n title: message,\n ...rest,\n dismissible,\n id\n });\n }\n return id;\n };\n this.dismiss = (id)=>{\n if (id) {\n this.dismissedToasts.add(id);\n requestAnimationFrame(()=>this.subscribers.forEach((subscriber)=>subscriber({\n id,\n dismiss: true\n })));\n } else {\n this.toasts.forEach((toast)=>{\n this.subscribers.forEach((subscriber)=>subscriber({\n id: toast.id,\n dismiss: true\n }));\n });\n }\n return id;\n };\n this.message = (message, data)=>{\n return this.create({\n ...data,\n message\n });\n };\n this.error = (message, data)=>{\n return this.create({\n ...data,\n message,\n type: 'error'\n });\n };\n this.success = (message, data)=>{\n return this.create({\n ...data,\n type: 'success',\n message\n });\n };\n this.info = (message, data)=>{\n return this.create({\n ...data,\n type: 'info',\n message\n });\n };\n this.warning = (message, data)=>{\n return this.create({\n ...data,\n type: 'warning',\n message\n });\n };\n this.loading = (message, data)=>{\n return this.create({\n ...data,\n type: 'loading',\n message\n });\n };\n this.promise = (promise, data)=>{\n if (!data) {\n // Nothing to show\n return;\n }\n let id = undefined;\n if (data.loading !== undefined) {\n id = this.create({\n ...data,\n promise,\n type: 'loading',\n message: data.loading,\n description: typeof data.description !== 'function' ? data.description : undefined\n });\n }\n const p = Promise.resolve(promise instanceof Function ? promise() : promise);\n let shouldDismiss = id !== undefined;\n let result;\n const originalPromise = p.then(async (response)=>{\n result = [\n 'resolve',\n response\n ];\n const isReactElementResponse = React.isValidElement(response);\n if (isReactElementResponse) {\n shouldDismiss = false;\n this.create({\n id,\n type: 'default',\n message: response\n });\n } else if (isHttpResponse(response) && !response.ok) {\n shouldDismiss = false;\n const promiseData = typeof data.error === 'function' ? await data.error(`HTTP error! status: ${response.status}`) : data.error;\n const description = typeof data.description === 'function' ? await data.description(`HTTP error! status: ${response.status}`) : data.description;\n const isExtendedResult = typeof promiseData === 'object' && !React.isValidElement(promiseData);\n const toastSettings = isExtendedResult ? promiseData : {\n message: promiseData\n };\n this.create({\n id,\n type: 'error',\n description,\n ...toastSettings\n });\n } else if (response instanceof Error) {\n shouldDismiss = false;\n const promiseData = typeof data.error === 'function' ? await data.error(response) : data.error;\n const description = typeof data.description === 'function' ? await data.description(response) : data.description;\n const isExtendedResult = typeof promiseData === 'object' && !React.isValidElement(promiseData);\n const toastSettings = isExtendedResult ? promiseData : {\n message: promiseData\n };\n this.create({\n id,\n type: 'error',\n description,\n ...toastSettings\n });\n } else if (data.success !== undefined) {\n shouldDismiss = false;\n const promiseData = typeof data.success === 'function' ? await data.success(response) : data.success;\n const description = typeof data.description === 'function' ? await data.description(response) : data.description;\n const isExtendedResult = typeof promiseData === 'object' && !React.isValidElement(promiseData);\n const toastSettings = isExtendedResult ? promiseData : {\n message: promiseData\n };\n this.create({\n id,\n type: 'success',\n description,\n ...toastSettings\n });\n }\n }).catch(async (error)=>{\n result = [\n 'reject',\n error\n ];\n if (data.error !== undefined) {\n shouldDismiss = false;\n const promiseData = typeof data.error === 'function' ? await data.error(error) : data.error;\n const description = typeof data.description === 'function' ? await data.description(error) : data.description;\n const isExtendedResult = typeof promiseData === 'object' && !React.isValidElement(promiseData);\n const toastSettings = isExtendedResult ? promiseData : {\n message: promiseData\n };\n this.create({\n id,\n type: 'error',\n description,\n ...toastSettings\n });\n }\n }).finally(()=>{\n if (shouldDismiss) {\n // Toast is still in load state (and will be indefinitely — dismiss it)\n this.dismiss(id);\n id = undefined;\n }\n data.finally == null ? void 0 : data.finally.call(data);\n });\n const unwrap = ()=>new Promise((resolve, reject)=>originalPromise.then(()=>result[0] === 'reject' ? reject(result[1]) : resolve(result[1])).catch(reject));\n if (typeof id !== 'string' && typeof id !== 'number') {\n // cannot Object.assign on undefined\n return {\n unwrap\n };\n } else {\n return Object.assign(id, {\n unwrap\n });\n }\n };\n this.custom = (jsx, data)=>{\n const id = (data == null ? void 0 : data.id) || toastsCounter++;\n this.create({\n jsx: jsx(id),\n id,\n ...data\n });\n return id;\n };\n this.getActiveToasts = ()=>{\n return this.toasts.filter((toast)=>!this.dismissedToasts.has(toast.id));\n };\n this.subscribers = [];\n this.toasts = [];\n this.dismissedToasts = new Set();\n }\n}\nconst ToastState = new Observer();\n// bind this to the toast function\nconst toastFunction = (message, data)=>{\n const id = (data == null ? void 0 : data.id) || toastsCounter++;\n ToastState.addToast({\n title: message,\n ...data,\n id\n });\n return id;\n};\nconst isHttpResponse = (data)=>{\n return data && typeof data === 'object' && 'ok' in data && typeof data.ok === 'boolean' && 'status' in data && typeof data.status === 'number';\n};\nconst basicToast = toastFunction;\nconst getHistory = ()=>ToastState.toasts;\nconst getToasts = ()=>ToastState.getActiveToasts();\n// We use `Object.assign` to maintain the correct types as we would lose them otherwise\nconst toast = Object.assign(basicToast, {\n success: ToastState.success,\n info: ToastState.info,\n warning: ToastState.warning,\n error: ToastState.error,\n custom: ToastState.custom,\n message: ToastState.message,\n promise: ToastState.promise,\n dismiss: ToastState.dismiss,\n loading: ToastState.loading\n}, {\n getHistory,\n getToasts\n});\n\n__insertCSS(\"[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}\");\n\nfunction isAction(action) {\n return action.label !== undefined;\n}\n\n// Visible toasts amount\nconst VISIBLE_TOASTS_AMOUNT = 3;\n// Viewport padding\nconst VIEWPORT_OFFSET = '24px';\n// Mobile viewport padding\nconst MOBILE_VIEWPORT_OFFSET = '16px';\n// Default lifetime of a toasts (in ms)\nconst TOAST_LIFETIME = 4000;\n// Default toast width\nconst TOAST_WIDTH = 356;\n// Default gap between toasts\nconst GAP = 14;\n// Threshold to dismiss a toast\nconst SWIPE_THRESHOLD = 45;\n// Equal to exit animation duration\nconst TIME_BEFORE_UNMOUNT = 200;\nfunction cn(...classes) {\n return classes.filter(Boolean).join(' ');\n}\nfunction getDefaultSwipeDirections(position) {\n const [y, x] = position.split('-');\n const directions = [];\n if (y) {\n directions.push(y);\n }\n if (x) {\n directions.push(x);\n }\n return directions;\n}\nconst Toast = (props)=>{\n var _toast_classNames, _toast_classNames1, _toast_classNames2, _toast_classNames3, _toast_classNames4, _toast_classNames5, _toast_classNames6, _toast_classNames7, _toast_classNames8;\n const { invert: ToasterInvert, toast, unstyled, interacting, setHeights, visibleToasts, heights, index, toasts, expanded, removeToast, defaultRichColors, closeButton: closeButtonFromToaster, style, cancelButtonStyle, actionButtonStyle, className = '', descriptionClassName = '', duration: durationFromToaster, position, gap, expandByDefault, classNames, icons, closeButtonAriaLabel = 'Close toast' } = props;\n const [swipeDirection, setSwipeDirection] = React.useState(null);\n const [swipeOutDirection, setSwipeOutDirection] = React.useState(null);\n const [mounted, setMounted] = React.useState(false);\n const [removed, setRemoved] = React.useState(false);\n const [swiping, setSwiping] = React.useState(false);\n const [swipeOut, setSwipeOut] = React.useState(false);\n const [isSwiped, setIsSwiped] = React.useState(false);\n const [offsetBeforeRemove, setOffsetBeforeRemove] = React.useState(0);\n const [initialHeight, setInitialHeight] = React.useState(0);\n const remainingTime = React.useRef(toast.duration || durationFromToaster || TOAST_LIFETIME);\n const dragStartTime = React.useRef(null);\n const toastRef = React.useRef(null);\n const isFront = index === 0;\n const isVisible = index + 1 <= visibleToasts;\n const toastType = toast.type;\n const dismissible = toast.dismissible !== false;\n const toastClassname = toast.className || '';\n const toastDescriptionClassname = toast.descriptionClassName || '';\n // Height index is used to calculate the offset as it gets updated before the toast array, which means we can calculate the new layout faster.\n const heightIndex = React.useMemo(()=>heights.findIndex((height)=>height.toastId === toast.id) || 0, [\n heights,\n toast.id\n ]);\n const closeButton = React.useMemo(()=>{\n var _toast_closeButton;\n return (_toast_closeButton = toast.closeButton) != null ? _toast_closeButton : closeButtonFromToaster;\n }, [\n toast.closeButton,\n closeButtonFromToaster\n ]);\n const duration = React.useMemo(()=>toast.duration || durationFromToaster || TOAST_LIFETIME, [\n toast.duration,\n durationFromToaster\n ]);\n const closeTimerStartTimeRef = React.useRef(0);\n const offset = React.useRef(0);\n const lastCloseTimerStartTimeRef = React.useRef(0);\n const pointerStartRef = React.useRef(null);\n const [y, x] = position.split('-');\n const toastsHeightBefore = React.useMemo(()=>{\n return heights.reduce((prev, curr, reducerIndex)=>{\n // Calculate offset up until current toast\n if (reducerIndex >= heightIndex) {\n return prev;\n }\n return prev + curr.height;\n }, 0);\n }, [\n heights,\n heightIndex\n ]);\n const isDocumentHidden = useIsDocumentHidden();\n const invert = toast.invert || ToasterInvert;\n const disabled = toastType === 'loading';\n offset.current = React.useMemo(()=>heightIndex * gap + toastsHeightBefore, [\n heightIndex,\n toastsHeightBefore\n ]);\n React.useEffect(()=>{\n remainingTime.current = duration;\n }, [\n duration\n ]);\n React.useEffect(()=>{\n // Trigger enter animation without using CSS animation\n setMounted(true);\n }, []);\n React.useEffect(()=>{\n const toastNode = toastRef.current;\n if (toastNode) {\n const height = toastNode.getBoundingClientRect().height;\n // Add toast height to heights array after the toast is mounted\n setInitialHeight(height);\n setHeights((h)=>[\n {\n toastId: toast.id,\n height,\n position: toast.position\n },\n ...h\n ]);\n return ()=>setHeights((h)=>h.filter((height)=>height.toastId !== toast.id));\n }\n }, [\n setHeights,\n toast.id\n ]);\n React.useLayoutEffect(()=>{\n // Keep height up to date with the content in case it updates\n if (!mounted) return;\n const toastNode = toastRef.current;\n const originalHeight = toastNode.style.height;\n toastNode.style.height = 'auto';\n const newHeight = toastNode.getBoundingClientRect().height;\n toastNode.style.height = originalHeight;\n setInitialHeight(newHeight);\n setHeights((heights)=>{\n const alreadyExists = heights.find((height)=>height.toastId === toast.id);\n if (!alreadyExists) {\n return [\n {\n toastId: toast.id,\n height: newHeight,\n position: toast.position\n },\n ...heights\n ];\n } else {\n return heights.map((height)=>height.toastId === toast.id ? {\n ...height,\n height: newHeight\n } : height);\n }\n });\n }, [\n mounted,\n toast.title,\n toast.description,\n setHeights,\n toast.id,\n toast.jsx,\n toast.action,\n toast.cancel\n ]);\n const deleteToast = React.useCallback(()=>{\n // Save the offset for the exit swipe animation\n setRemoved(true);\n setOffsetBeforeRemove(offset.current);\n setHeights((h)=>h.filter((height)=>height.toastId !== toast.id));\n setTimeout(()=>{\n removeToast(toast);\n }, TIME_BEFORE_UNMOUNT);\n }, [\n toast,\n removeToast,\n setHeights,\n offset\n ]);\n React.useEffect(()=>{\n if (toast.promise && toastType === 'loading' || toast.duration === Infinity || toast.type === 'loading') return;\n let timeoutId;\n // Pause the timer on each hover\n const pauseTimer = ()=>{\n if (lastCloseTimerStartTimeRef.current < closeTimerStartTimeRef.current) {\n // Get the elapsed time since the timer started\n const elapsedTime = new Date().getTime() - closeTimerStartTimeRef.current;\n remainingTime.current = remainingTime.current - elapsedTime;\n }\n lastCloseTimerStartTimeRef.current = new Date().getTime();\n };\n const startTimer = ()=>{\n // setTimeout(, Infinity) behaves as if the delay is 0.\n // As a result, the toast would be closed immediately, giving the appearance that it was never rendered.\n // See: https://github.com/denysdovhan/wtfjs?tab=readme-ov-file#an-infinite-timeout\n if (remainingTime.current === Infinity) return;\n closeTimerStartTimeRef.current = new Date().getTime();\n // Let the toast know it has started\n timeoutId = setTimeout(()=>{\n toast.onAutoClose == null ? void 0 : toast.onAutoClose.call(toast, toast);\n deleteToast();\n }, remainingTime.current);\n };\n if (expanded || interacting || isDocumentHidden) {\n pauseTimer();\n } else {\n startTimer();\n }\n return ()=>clearTimeout(timeoutId);\n }, [\n expanded,\n interacting,\n toast,\n toastType,\n isDocumentHidden,\n deleteToast\n ]);\n React.useEffect(()=>{\n if (toast.delete) {\n deleteToast();\n toast.onDismiss == null ? void 0 : toast.onDismiss.call(toast, toast);\n }\n }, [\n deleteToast,\n toast.delete\n ]);\n function getLoadingIcon() {\n var _toast_classNames;\n if (icons == null ? void 0 : icons.loading) {\n var _toast_classNames1;\n return /*#__PURE__*/ React.createElement(\"div\", {\n className: cn(classNames == null ? void 0 : classNames.loader, toast == null ? void 0 : (_toast_classNames1 = toast.classNames) == null ? void 0 : _toast_classNames1.loader, 'sonner-loader'),\n \"data-visible\": toastType === 'loading'\n }, icons.loading);\n }\n return /*#__PURE__*/ React.createElement(Loader, {\n className: cn(classNames == null ? void 0 : classNames.loader, toast == null ? void 0 : (_toast_classNames = toast.classNames) == null ? void 0 : _toast_classNames.loader),\n visible: toastType === 'loading'\n });\n }\n const icon = toast.icon || (icons == null ? void 0 : icons[toastType]) || getAsset(toastType);\n var _toast_richColors, _icons_close;\n return /*#__PURE__*/ React.createElement(\"li\", {\n tabIndex: 0,\n ref: toastRef,\n className: cn(className, toastClassname, classNames == null ? void 0 : classNames.toast, toast == null ? void 0 : (_toast_classNames = toast.classNames) == null ? void 0 : _toast_classNames.toast, classNames == null ? void 0 : classNames.default, classNames == null ? void 0 : classNames[toastType], toast == null ? void 0 : (_toast_classNames1 = toast.classNames) == null ? void 0 : _toast_classNames1[toastType]),\n \"data-sonner-toast\": \"\",\n \"data-rich-colors\": (_toast_richColors = toast.richColors) != null ? _toast_richColors : defaultRichColors,\n \"data-styled\": !Boolean(toast.jsx || toast.unstyled || unstyled),\n \"data-mounted\": mounted,\n \"data-promise\": Boolean(toast.promise),\n \"data-swiped\": isSwiped,\n \"data-removed\": removed,\n \"data-visible\": isVisible,\n \"data-y-position\": y,\n \"data-x-position\": x,\n \"data-index\": index,\n \"data-front\": isFront,\n \"data-swiping\": swiping,\n \"data-dismissible\": dismissible,\n \"data-type\": toastType,\n \"data-invert\": invert,\n \"data-swipe-out\": swipeOut,\n \"data-swipe-direction\": swipeOutDirection,\n \"data-expanded\": Boolean(expanded || expandByDefault && mounted),\n \"data-testid\": toast.testId,\n style: {\n '--index': index,\n '--toasts-before': index,\n '--z-index': toasts.length - index,\n '--offset': `${removed ? offsetBeforeRemove : offset.current}px`,\n '--initial-height': expandByDefault ? 'auto' : `${initialHeight}px`,\n ...style,\n ...toast.style\n },\n onDragEnd: ()=>{\n setSwiping(false);\n setSwipeDirection(null);\n pointerStartRef.current = null;\n },\n onPointerDown: (event)=>{\n if (event.button === 2) return; // Return early on right click\n if (disabled || !dismissible) return;\n dragStartTime.current = new Date();\n setOffsetBeforeRemove(offset.current);\n // Ensure we maintain correct pointer capture even when going outside of the toast (e.g. when swiping)\n event.target.setPointerCapture(event.pointerId);\n if (event.target.tagName === 'BUTTON') return;\n setSwiping(true);\n pointerStartRef.current = {\n x: event.clientX,\n y: event.clientY\n };\n },\n onPointerUp: ()=>{\n var _toastRef_current, _toastRef_current1, _dragStartTime_current;\n if (swipeOut || !dismissible) return;\n pointerStartRef.current = null;\n const swipeAmountX = Number(((_toastRef_current = toastRef.current) == null ? void 0 : _toastRef_current.style.getPropertyValue('--swipe-amount-x').replace('px', '')) || 0);\n const swipeAmountY = Number(((_toastRef_current1 = toastRef.current) == null ? void 0 : _toastRef_current1.style.getPropertyValue('--swipe-amount-y').replace('px', '')) || 0);\n const timeTaken = new Date().getTime() - ((_dragStartTime_current = dragStartTime.current) == null ? void 0 : _dragStartTime_current.getTime());\n const swipeAmount = swipeDirection === 'x' ? swipeAmountX : swipeAmountY;\n const velocity = Math.abs(swipeAmount) / timeTaken;\n if (Math.abs(swipeAmount) >= SWIPE_THRESHOLD || velocity > 0.11) {\n setOffsetBeforeRemove(offset.current);\n toast.onDismiss == null ? void 0 : toast.onDismiss.call(toast, toast);\n if (swipeDirection === 'x') {\n setSwipeOutDirection(swipeAmountX > 0 ? 'right' : 'left');\n } else {\n setSwipeOutDirection(swipeAmountY > 0 ? 'down' : 'up');\n }\n deleteToast();\n setSwipeOut(true);\n return;\n } else {\n var _toastRef_current2, _toastRef_current3;\n (_toastRef_current2 = toastRef.current) == null ? void 0 : _toastRef_current2.style.setProperty('--swipe-amount-x', `0px`);\n (_toastRef_current3 = toastRef.current) == null ? void 0 : _toastRef_current3.style.setProperty('--swipe-amount-y', `0px`);\n }\n setIsSwiped(false);\n setSwiping(false);\n setSwipeDirection(null);\n },\n onPointerMove: (event)=>{\n var _window_getSelection, // Apply transform using both x and y values\n _toastRef_current, _toastRef_current1;\n if (!pointerStartRef.current || !dismissible) return;\n const isHighlighted = ((_window_getSelection = window.getSelection()) == null ? void 0 : _window_getSelection.toString().length) > 0;\n if (isHighlighted) return;\n const yDelta = event.clientY - pointerStartRef.current.y;\n const xDelta = event.clientX - pointerStartRef.current.x;\n var _props_swipeDirections;\n const swipeDirections = (_props_swipeDirections = props.swipeDirections) != null ? _props_swipeDirections : getDefaultSwipeDirections(position);\n // Determine swipe direction if not already locked\n if (!swipeDirection && (Math.abs(xDelta) > 1 || Math.abs(yDelta) > 1)) {\n setSwipeDirection(Math.abs(xDelta) > Math.abs(yDelta) ? 'x' : 'y');\n }\n let swipeAmount = {\n x: 0,\n y: 0\n };\n const getDampening = (delta)=>{\n const factor = Math.abs(delta) / 20;\n return 1 / (1.5 + factor);\n };\n // Only apply swipe in the locked direction\n if (swipeDirection === 'y') {\n // Handle vertical swipes\n if (swipeDirections.includes('top') || swipeDirections.includes('bottom')) {\n if (swipeDirections.includes('top') && yDelta < 0 || swipeDirections.includes('bottom') && yDelta > 0) {\n swipeAmount.y = yDelta;\n } else {\n // Smoothly transition to dampened movement\n const dampenedDelta = yDelta * getDampening(yDelta);\n // Ensure we don't jump when transitioning to dampened movement\n swipeAmount.y = Math.abs(dampenedDelta) < Math.abs(yDelta) ? dampenedDelta : yDelta;\n }\n }\n } else if (swipeDirection === 'x') {\n // Handle horizontal swipes\n if (swipeDirections.includes('left') || swipeDirections.includes('right')) {\n if (swipeDirections.includes('left') && xDelta < 0 || swipeDirections.includes('right') && xDelta > 0) {\n swipeAmount.x = xDelta;\n } else {\n // Smoothly transition to dampened movement\n const dampenedDelta = xDelta * getDampening(xDelta);\n // Ensure we don't jump when transitioning to dampened movement\n swipeAmount.x = Math.abs(dampenedDelta) < Math.abs(xDelta) ? dampenedDelta : xDelta;\n }\n }\n }\n if (Math.abs(swipeAmount.x) > 0 || Math.abs(swipeAmount.y) > 0) {\n setIsSwiped(true);\n }\n (_toastRef_current = toastRef.current) == null ? void 0 : _toastRef_current.style.setProperty('--swipe-amount-x', `${swipeAmount.x}px`);\n (_toastRef_current1 = toastRef.current) == null ? void 0 : _toastRef_current1.style.setProperty('--swipe-amount-y', `${swipeAmount.y}px`);\n }\n }, closeButton && !toast.jsx && toastType !== 'loading' ? /*#__PURE__*/ React.createElement(\"button\", {\n \"aria-label\": closeButtonAriaLabel,\n \"data-disabled\": disabled,\n \"data-close-button\": true,\n onClick: disabled || !dismissible ? ()=>{} : ()=>{\n deleteToast();\n toast.onDismiss == null ? void 0 : toast.onDismiss.call(toast, toast);\n },\n className: cn(classNames == null ? void 0 : classNames.closeButton, toast == null ? void 0 : (_toast_classNames2 = toast.classNames) == null ? void 0 : _toast_classNames2.closeButton)\n }, (_icons_close = icons == null ? void 0 : icons.close) != null ? _icons_close : CloseIcon) : null, (toastType || toast.icon || toast.promise) && toast.icon !== null && ((icons == null ? void 0 : icons[toastType]) !== null || toast.icon) ? /*#__PURE__*/ React.createElement(\"div\", {\n \"data-icon\": \"\",\n className: cn(classNames == null ? void 0 : classNames.icon, toast == null ? void 0 : (_toast_classNames3 = toast.classNames) == null ? void 0 : _toast_classNames3.icon)\n }, toast.promise || toast.type === 'loading' && !toast.icon ? toast.icon || getLoadingIcon() : null, toast.type !== 'loading' ? icon : null) : null, /*#__PURE__*/ React.createElement(\"div\", {\n \"data-content\": \"\",\n className: cn(classNames == null ? void 0 : classNames.content, toast == null ? void 0 : (_toast_classNames4 = toast.classNames) == null ? void 0 : _toast_classNames4.content)\n }, /*#__PURE__*/ React.createElement(\"div\", {\n \"data-title\": \"\",\n className: cn(classNames == null ? void 0 : classNames.title, toast == null ? void 0 : (_toast_classNames5 = toast.classNames) == null ? void 0 : _toast_classNames5.title)\n }, toast.jsx ? toast.jsx : typeof toast.title === 'function' ? toast.title() : toast.title), toast.description ? /*#__PURE__*/ React.createElement(\"div\", {\n \"data-description\": \"\",\n className: cn(descriptionClassName, toastDescriptionClassname, classNames == null ? void 0 : classNames.description, toast == null ? void 0 : (_toast_classNames6 = toast.classNames) == null ? void 0 : _toast_classNames6.description)\n }, typeof toast.description === 'function' ? toast.description() : toast.description) : null), /*#__PURE__*/ React.isValidElement(toast.cancel) ? toast.cancel : toast.cancel && isAction(toast.cancel) ? /*#__PURE__*/ React.createElement(\"button\", {\n \"data-button\": true,\n \"data-cancel\": true,\n style: toast.cancelButtonStyle || cancelButtonStyle,\n onClick: (event)=>{\n // We need to check twice because typescript\n if (!isAction(toast.cancel)) return;\n if (!dismissible) return;\n toast.cancel.onClick == null ? void 0 : toast.cancel.onClick.call(toast.cancel, event);\n deleteToast();\n },\n className: cn(classNames == null ? void 0 : classNames.cancelButton, toast == null ? void 0 : (_toast_classNames7 = toast.classNames) == null ? void 0 : _toast_classNames7.cancelButton)\n }, toast.cancel.label) : null, /*#__PURE__*/ React.isValidElement(toast.action) ? toast.action : toast.action && isAction(toast.action) ? /*#__PURE__*/ React.createElement(\"button\", {\n \"data-button\": true,\n \"data-action\": true,\n style: toast.actionButtonStyle || actionButtonStyle,\n onClick: (event)=>{\n // We need to check twice because typescript\n if (!isAction(toast.action)) return;\n toast.action.onClick == null ? void 0 : toast.action.onClick.call(toast.action, event);\n if (event.defaultPrevented) return;\n deleteToast();\n },\n className: cn(classNames == null ? void 0 : classNames.actionButton, toast == null ? void 0 : (_toast_classNames8 = toast.classNames) == null ? void 0 : _toast_classNames8.actionButton)\n }, toast.action.label) : null);\n};\nfunction getDocumentDirection() {\n if (typeof window === 'undefined') return 'ltr';\n if (typeof document === 'undefined') return 'ltr'; // For Fresh purpose\n const dirAttribute = document.documentElement.getAttribute('dir');\n if (dirAttribute === 'auto' || !dirAttribute) {\n return window.getComputedStyle(document.documentElement).direction;\n }\n return dirAttribute;\n}\nfunction assignOffset(defaultOffset, mobileOffset) {\n const styles = {};\n [\n defaultOffset,\n mobileOffset\n ].forEach((offset, index)=>{\n const isMobile = index === 1;\n const prefix = isMobile ? '--mobile-offset' : '--offset';\n const defaultValue = isMobile ? MOBILE_VIEWPORT_OFFSET : VIEWPORT_OFFSET;\n function assignAll(offset) {\n [\n 'top',\n 'right',\n 'bottom',\n 'left'\n ].forEach((key)=>{\n styles[`${prefix}-${key}`] = typeof offset === 'number' ? `${offset}px` : offset;\n });\n }\n if (typeof offset === 'number' || typeof offset === 'string') {\n assignAll(offset);\n } else if (typeof offset === 'object') {\n [\n 'top',\n 'right',\n 'bottom',\n 'left'\n ].forEach((key)=>{\n if (offset[key] === undefined) {\n styles[`${prefix}-${key}`] = defaultValue;\n } else {\n styles[`${prefix}-${key}`] = typeof offset[key] === 'number' ? `${offset[key]}px` : offset[key];\n }\n });\n } else {\n assignAll(defaultValue);\n }\n });\n return styles;\n}\nfunction useSonner() {\n const [activeToasts, setActiveToasts] = React.useState([]);\n React.useEffect(()=>{\n return ToastState.subscribe((toast)=>{\n if (toast.dismiss) {\n setTimeout(()=>{\n ReactDOM.flushSync(()=>{\n setActiveToasts((toasts)=>toasts.filter((t)=>t.id !== toast.id));\n });\n });\n return;\n }\n // Prevent batching, temp solution.\n setTimeout(()=>{\n ReactDOM.flushSync(()=>{\n setActiveToasts((toasts)=>{\n const indexOfExistingToast = toasts.findIndex((t)=>t.id === toast.id);\n // Update the toast if it already exists\n if (indexOfExistingToast !== -1) {\n return [\n ...toasts.slice(0, indexOfExistingToast),\n {\n ...toasts[indexOfExistingToast],\n ...toast\n },\n ...toasts.slice(indexOfExistingToast + 1)\n ];\n }\n return [\n toast,\n ...toasts\n ];\n });\n });\n });\n });\n }, []);\n return {\n toasts: activeToasts\n };\n}\nconst Toaster = /*#__PURE__*/ React.forwardRef(function Toaster(props, ref) {\n const { id, invert, position = 'bottom-right', hotkey = [\n 'altKey',\n 'KeyT'\n ], expand, closeButton, className, offset, mobileOffset, theme = 'light', richColors, duration, style, visibleToasts = VISIBLE_TOASTS_AMOUNT, toastOptions, dir = getDocumentDirection(), gap = GAP, icons, containerAriaLabel = 'Notifications' } = props;\n const [toasts, setToasts] = React.useState([]);\n const filteredToasts = React.useMemo(()=>{\n if (id) {\n return toasts.filter((toast)=>toast.toasterId === id);\n }\n return toasts.filter((toast)=>!toast.toasterId);\n }, [\n toasts,\n id\n ]);\n const possiblePositions = React.useMemo(()=>{\n return Array.from(new Set([\n position\n ].concat(filteredToasts.filter((toast)=>toast.position).map((toast)=>toast.position))));\n }, [\n filteredToasts,\n position\n ]);\n const [heights, setHeights] = React.useState([]);\n const [expanded, setExpanded] = React.useState(false);\n const [interacting, setInteracting] = React.useState(false);\n const [actualTheme, setActualTheme] = React.useState(theme !== 'system' ? theme : typeof window !== 'undefined' ? window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' : 'light');\n const listRef = React.useRef(null);\n const hotkeyLabel = hotkey.join('+').replace(/Key/g, '').replace(/Digit/g, '');\n const lastFocusedElementRef = React.useRef(null);\n const isFocusWithinRef = React.useRef(false);\n const removeToast = React.useCallback((toastToRemove)=>{\n setToasts((toasts)=>{\n var _toasts_find;\n if (!((_toasts_find = toasts.find((toast)=>toast.id === toastToRemove.id)) == null ? void 0 : _toasts_find.delete)) {\n ToastState.dismiss(toastToRemove.id);\n }\n return toasts.filter(({ id })=>id !== toastToRemove.id);\n });\n }, []);\n React.useEffect(()=>{\n return ToastState.subscribe((toast)=>{\n if (toast.dismiss) {\n // Prevent batching of other state updates\n requestAnimationFrame(()=>{\n setToasts((toasts)=>toasts.map((t)=>t.id === toast.id ? {\n ...t,\n delete: true\n } : t));\n });\n return;\n }\n // Prevent batching, temp solution.\n setTimeout(()=>{\n ReactDOM.flushSync(()=>{\n setToasts((toasts)=>{\n const indexOfExistingToast = toasts.findIndex((t)=>t.id === toast.id);\n // Update the toast if it already exists\n if (indexOfExistingToast !== -1) {\n return [\n ...toasts.slice(0, indexOfExistingToast),\n {\n ...toasts[indexOfExistingToast],\n ...toast\n },\n ...toasts.slice(indexOfExistingToast + 1)\n ];\n }\n return [\n toast,\n ...toasts\n ];\n });\n });\n });\n });\n }, [\n toasts\n ]);\n React.useEffect(()=>{\n if (theme !== 'system') {\n setActualTheme(theme);\n return;\n }\n if (theme === 'system') {\n // check if current preference is dark\n if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {\n // it's currently dark\n setActualTheme('dark');\n } else {\n // it's not dark\n setActualTheme('light');\n }\n }\n if (typeof window === 'undefined') return;\n const darkMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');\n try {\n // Chrome & Firefox\n darkMediaQuery.addEventListener('change', ({ matches })=>{\n if (matches) {\n setActualTheme('dark');\n } else {\n setActualTheme('light');\n }\n });\n } catch (error) {\n // Safari < 14\n darkMediaQuery.addListener(({ matches })=>{\n try {\n if (matches) {\n setActualTheme('dark');\n } else {\n setActualTheme('light');\n }\n } catch (e) {\n console.error(e);\n }\n });\n }\n }, [\n theme\n ]);\n React.useEffect(()=>{\n // Ensure expanded is always false when no toasts are present / only one left\n if (toasts.length <= 1) {\n setExpanded(false);\n }\n }, [\n toasts\n ]);\n React.useEffect(()=>{\n const handleKeyDown = (event)=>{\n var _listRef_current;\n const isHotkeyPressed = hotkey.every((key)=>event[key] || event.code === key);\n if (isHotkeyPressed) {\n var _listRef_current1;\n setExpanded(true);\n (_listRef_current1 = listRef.current) == null ? void 0 : _listRef_current1.focus();\n }\n if (event.code === 'Escape' && (document.activeElement === listRef.current || ((_listRef_current = listRef.current) == null ? void 0 : _listRef_current.contains(document.activeElement)))) {\n setExpanded(false);\n }\n };\n document.addEventListener('keydown', handleKeyDown);\n return ()=>document.removeEventListener('keydown', handleKeyDown);\n }, [\n hotkey\n ]);\n React.useEffect(()=>{\n if (listRef.current) {\n return ()=>{\n if (lastFocusedElementRef.current) {\n lastFocusedElementRef.current.focus({\n preventScroll: true\n });\n lastFocusedElementRef.current = null;\n isFocusWithinRef.current = false;\n }\n };\n }\n }, [\n listRef.current\n ]);\n return(// Remove item from normal navigation flow, only available via hotkey\n /*#__PURE__*/ React.createElement(\"section\", {\n ref: ref,\n \"aria-label\": `${containerAriaLabel} ${hotkeyLabel}`,\n tabIndex: -1,\n \"aria-live\": \"polite\",\n \"aria-relevant\": \"additions text\",\n \"aria-atomic\": \"false\",\n suppressHydrationWarning: true\n }, possiblePositions.map((position, index)=>{\n var _heights_;\n const [y, x] = position.split('-');\n if (!filteredToasts.length) return null;\n return /*#__PURE__*/ React.createElement(\"ol\", {\n key: position,\n dir: dir === 'auto' ? getDocumentDirection() : dir,\n tabIndex: -1,\n ref: listRef,\n className: className,\n \"data-sonner-toaster\": true,\n \"data-sonner-theme\": actualTheme,\n \"data-y-position\": y,\n \"data-x-position\": x,\n style: {\n '--front-toast-height': `${((_heights_ = heights[0]) == null ? void 0 : _heights_.height) || 0}px`,\n '--width': `${TOAST_WIDTH}px`,\n '--gap': `${gap}px`,\n ...style,\n ...assignOffset(offset, mobileOffset)\n },\n onBlur: (event)=>{\n if (isFocusWithinRef.current && !event.currentTarget.contains(event.relatedTarget)) {\n isFocusWithinRef.current = false;\n if (lastFocusedElementRef.current) {\n lastFocusedElementRef.current.focus({\n preventScroll: true\n });\n lastFocusedElementRef.current = null;\n }\n }\n },\n onFocus: (event)=>{\n const isNotDismissible = event.target instanceof HTMLElement && event.target.dataset.dismissible === 'false';\n if (isNotDismissible) return;\n if (!isFocusWithinRef.current) {\n isFocusWithinRef.current = true;\n lastFocusedElementRef.current = event.relatedTarget;\n }\n },\n onMouseEnter: ()=>setExpanded(true),\n onMouseMove: ()=>setExpanded(true),\n onMouseLeave: ()=>{\n // Avoid setting expanded to false when interacting with a toast, e.g. swiping\n if (!interacting) {\n setExpanded(false);\n }\n },\n onDragEnd: ()=>setExpanded(false),\n onPointerDown: (event)=>{\n const isNotDismissible = event.target instanceof HTMLElement && event.target.dataset.dismissible === 'false';\n if (isNotDismissible) return;\n setInteracting(true);\n },\n onPointerUp: ()=>setInteracting(false)\n }, filteredToasts.filter((toast)=>!toast.position && index === 0 || toast.position === position).map((toast, index)=>{\n var _toastOptions_duration, _toastOptions_closeButton;\n return /*#__PURE__*/ React.createElement(Toast, {\n key: toast.id,\n icons: icons,\n index: index,\n toast: toast,\n defaultRichColors: richColors,\n duration: (_toastOptions_duration = toastOptions == null ? void 0 : toastOptions.duration) != null ? _toastOptions_duration : duration,\n className: toastOptions == null ? void 0 : toastOptions.className,\n descriptionClassName: toastOptions == null ? void 0 : toastOptions.descriptionClassName,\n invert: invert,\n visibleToasts: visibleToasts,\n closeButton: (_toastOptions_closeButton = toastOptions == null ? void 0 : toastOptions.closeButton) != null ? _toastOptions_closeButton : closeButton,\n interacting: interacting,\n position: position,\n style: toastOptions == null ? void 0 : toastOptions.style,\n unstyled: toastOptions == null ? void 0 : toastOptions.unstyled,\n classNames: toastOptions == null ? void 0 : toastOptions.classNames,\n cancelButtonStyle: toastOptions == null ? void 0 : toastOptions.cancelButtonStyle,\n actionButtonStyle: toastOptions == null ? void 0 : toastOptions.actionButtonStyle,\n closeButtonAriaLabel: toastOptions == null ? void 0 : toastOptions.closeButtonAriaLabel,\n removeToast: removeToast,\n toasts: filteredToasts.filter((t)=>t.position == toast.position),\n heights: heights.filter((h)=>h.position == toast.position),\n setHeights: setHeights,\n expandByDefault: expand,\n gap: gap,\n expanded: expanded,\n swipeDirections: props.swipeDirections\n });\n }));\n })));\n});\n\nexport { Toaster, toast, useSonner };\n","/**\n * Toast — a thin convenience over {@link https://sonner.emilkowal.ski | sonner}.\n *\n * Authors call `toast.success(...)` / `toast.error(...)` anywhere in their funnel.\n * `FunnelProvider` auto-mounts {@link FunnelToaster} (opt out with `toaster={false}`),\n * so toasts work with no setup; render it yourself if you want a custom location.\n *\n * **Dependency policy:** sonner is a direct dependency, imported statically (it's a small\n * lib that ships with every funnel — no lazy chunk, no forwarding proxy). `toaster={false}`\n * still renders no toaster markup; a funnel that never toasts just never calls `toast`.\n */\n\nimport { createElement, type ReactNode } from 'react'\nimport { Toaster, type ToasterProps } from 'sonner'\n\nexport type { ToasterProps }\n\n// sonner's imperative `toast` (`toast('hi')`, `toast.success(...)`, `toast.dismiss()`, …),\n// re-exported DIRECTLY. A re-export keeps the emitted .d.ts nameable — annotating an inferred\n// `const toast = sonnerToast` would drag in sonner's un-exported internal types (TS4023).\nexport { toast } from 'sonner'\n\n/**\n * Sonner's `<Toaster>` with funnel defaults (top-center); pass any `ToasterProps` to override.\n * SSR-safe — sonner renders an empty container server-side and hydrates cleanly on the client.\n */\nexport function FunnelToaster(props: ToasterProps = {}): ReactNode {\n return createElement(Toaster, { position: 'top-center', ...props })\n}\n\n/** Internal: resolve the `FunnelProvider` `toaster` prop to an element (or null). */\nexport function renderToaster(toaster: boolean | ToasterProps): ReactNode {\n if (toaster === false) return null\n return <FunnelToaster {...(toaster === true ? {} : toaster)} />\n}\n","import {\n createContext,\n createElement,\n Fragment,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n useSyncExternalStore,\n type ReactNode,\n} from 'react'\nimport type { VariableStore } from './variableStore'\nimport { createFunnelStore, NAMESPACE_PREFIX, type WritableNamespace } from './store'\nimport { buildAcquisition, buildContext, type FunnelContext } from './context'\nimport {\n TrackerProvider,\n createConsoleTracker,\n type Tracker,\n} from '../tracking/tracking'\nimport { attachBus, createBus, withBus, type FunnelBus } from '../tracking/bus'\nimport { CatalogProvider, buildCatalog, type ResolvedProduct, type ProductInput } from '../commerce/catalog'\nimport { CheckoutDriverProvider, createMockDriver, driverWithEmail, type CheckoutDriver } from '../commerce/checkout'\nimport { ModalRuntime } from '../modals/registry'\nimport { LocaleProvider, type MessageCatalog } from '../i18n/translation'\nimport { renderToaster, type ToasterProps } from '../toast/toast'\nimport type { FunnelDefinition, FunnelSnapshot } from '../flow/spine'\nimport type { RuntimeExperiment } from '../flow/experiments'\nimport type { VariableValue } from '../types'\n\n/**\n * v2 namespace layer over the flat {@link VariableStore}.\n *\n * **The public surface is hooks, not a god object.** Reactive reads use\n * `useState`-shaped tuple hooks (`const [goal, setGoal] = useResponse('goal')`);\n * read-only computed values use `useDevice()`/`useLocale()`/`usePage()`/`useUtm()`.\n * `useFunnel()` returns an **imperative, non-subscribing** handle for use in\n * handlers/effects only — it is not the documented primary API and carries no\n * `sdk` branding.\n *\n * Three writable namespaces (`user`/`responses`/`data`) + the read-only\n * `context`. Entitlements are **not** here — they're the separate app/IdentitySDK.\n *\n * All writes route through {@link Namespace.set}, so persistence + identify fire\n * from one place (the \"magic behind set()\", doc 07 §Layer 1).\n */\n\n// ── Writable namespace view ──────────────────────────────\n\n/** A typed view over one writable namespace's slice of the store. */\nexport class Namespace<\n T extends Record<string, VariableValue> = Record<string, VariableValue>,\n> {\n private readonly dot: string\n\n constructor(\n private readonly store: VariableStore,\n readonly name: WritableNamespace,\n /** Side-effect run after every write (persistence, identify). */\n private readonly onWrite: (ns: WritableNamespace, values: Partial<T>) => void,\n ) {\n this.dot = `${NAMESPACE_PREFIX[name]}.`\n }\n\n /** Fully-qualified store key for a namespace-relative key. */\n storeKey(key: string): string {\n return this.dot + key\n }\n\n /** The store-key prefix this namespace reads/writes (e.g. `user.`). */\n get prefix(): string {\n return this.dot\n }\n\n /** Read the whole namespace as a flat object (prefix stripped). */\n getAll(): T {\n const out: Record<string, VariableValue> = {}\n const all = this.store.getState()\n for (const key in all) {\n if (key.startsWith(this.dot)) out[key.slice(this.dot.length)] = all[key]\n }\n return out as T\n }\n\n /** Read one key, or the whole namespace when called with no argument. */\n get<K extends keyof T & string>(key: K): T[K]\n get(): T\n get(key?: string): VariableValue | T {\n return key === undefined ? this.getAll() : this.store.get(this.storeKey(key))\n }\n\n /** Write one or more keys from a plain object (batched + side-effected). */\n set(values: Partial<T>): void {\n const updates: Record<string, VariableValue> = {}\n for (const key in values) {\n updates[this.storeKey(key)] = values[key] as VariableValue\n }\n this.store.setMany(updates)\n this.onWrite(this.name, values)\n }\n}\n\n// ── The imperative handle ────────────────────────────────\n\n/**\n * The imperative funnel handle (`useFunnel()`). Non-reactive — for event\n * handlers and effects. Reactive render reads go through the hooks instead.\n */\nexport interface Funnel {\n user: Namespace\n responses: Namespace\n data: Namespace\n /** Read-only computed namespace. `page` reflects the latest navigation. */\n readonly context: FunnelContext\n /** Live page-level experiment records (platform/DB-sourced); the runtime buckets visitors into them. */\n readonly experiments: RuntimeExperiment[]\n /** Emit a custom analytics event. */\n track: Tracker['track']\n /** A point-in-time snapshot for predicates (routing/conditions). */\n snapshot(): FunnelSnapshot\n}\n\n/** Build the imperative handle over a store + context + tracker. */\nexport function createFunnel(\n store: VariableStore,\n context: FunnelContext,\n tracker: Tracker,\n experiments: RuntimeExperiment[] = [],\n): Funnel {\n // One write path → one place for the \"magic behind set()\".\n const onWrite = (ns: WritableNamespace, values: Record<string, VariableValue>) => {\n // Identify the moment a non-empty email is written.\n if (ns === 'user' && typeof values.email === 'string' && values.email) {\n tracker.identify(values.email)\n }\n // Push the writable snapshot for debounced persistence.\n tracker.setVariables?.(store.getState())\n }\n\n const user = new Namespace(store, 'user', onWrite)\n const responses = new Namespace(store, 'responses', onWrite)\n const data = new Namespace(store, 'data', onWrite)\n\n return {\n user,\n responses,\n data,\n context,\n experiments,\n track: (event: string, eventData?: never, userData?: Record<string, unknown>) =>\n tracker.track(event, eventData, userData),\n snapshot: () => ({\n user: user.getAll(),\n responses: responses.getAll(),\n data: data.getAll(),\n context,\n }),\n }\n}\n\n// ── React wiring ─────────────────────────────────────────\n\ninterface FunnelContextValue {\n funnel: Funnel\n store: VariableStore\n context: FunnelContext\n catalog: Map<string, ResolvedProduct>\n driver: CheckoutDriver\n /** Tracker composed with the client bus sink (every track() also hits window.appfunnel). */\n tracker: Tracker\n /** The window.appfunnel event bus (client-side integration surface). */\n bus: FunnelBus\n}\n\nconst FunnelCtx = createContext<FunnelContextValue | null>(null)\n\nexport interface FunnelProviderProps {\n /** Mount from a funnel definition (the normal case). */\n config?: FunnelDefinition\n /** Server / session-restored values overriding declared defaults. */\n sessionValues?: Record<string, VariableValue>\n /** The platform tracker; defaults to a silent console tracker (tests/dev). */\n tracker?: Tracker\n /** Computed-context seed (funnel id, test/live mode, server-hydrated utm/session). */\n context?: Parameters<typeof buildContext>[0]\n /** Products with their provider-resolved price (`{ amount, currency }`). */\n products?: ProductInput[]\n /** Live page-level experiment records, platform/DB-sourced (not authored in funnel code). */\n experiments?: RuntimeExperiment[]\n /** The platform checkout driver; defaults to a mock that resolves successfully. */\n checkout?: CheckoutDriver\n /** Message catalogs per locale (`messages/<locale>.json`) for translation. */\n messages?: MessageCatalog\n /** Explicit locale override (URL/param/geo); wins over the detected device locale. */\n locale?: string\n /** Auto-mount the toast `<Toaster>` (default true). Pass props to customize, or `false` to opt out. */\n toaster?: boolean | ToasterProps\n /** Advanced / testing: supply a pre-built store instead of a `config`. */\n store?: VariableStore\n children: ReactNode\n}\n\n/**\n * Mounts a funnel: builds the writable {@link VariableStore} + the read-only\n * {@link FunnelContext} (once) and provides the runtime to the tree via hooks.\n */\nexport function FunnelProvider({\n config,\n sessionValues,\n tracker,\n context: contextOpts,\n products,\n experiments,\n checkout,\n messages,\n locale: localeOverride,\n toaster = true,\n store,\n children,\n}: FunnelProviderProps): ReactNode {\n const resolvedTracker = tracker ?? FALLBACK_TRACKER\n const [value] = useState<FunnelContextValue>(() => {\n const s =\n store ??\n createFunnelStore(\n { responses: config?.responses, data: config?.data },\n sessionValues,\n )\n const ctx = buildContext({\n funnelId: config?.id,\n ...contextOpts,\n })\n // The client event bus (window.appfunnel), composed into the tracker so every\n // taxonomy event mirrors to it for on-page pixels. Read getters wire to store + context.\n const bus = createBus({\n getVariable: (key) => s.get(key),\n getVariables: () => s.getState(),\n getCurrentPageId: () => ctx.page.key || null,\n getCustomerId: () => ctx.identity.customerId,\n getVisitorId: () => ctx.identity.visitorId,\n })\n const busTracker = withBus(resolvedTracker, bus)\n // Every checkout attempt carries the buyer email the funnel collected — read\n // from the store at ATTEMPT time (`user.email`), loose-validated so a half-typed\n // value can't fail the wire's email validation (the server treats absent email\n // as an anonymous customer; a webhook/identify backfills it later).\n const emailForCheckout = (): string | undefined => {\n const value = s.get('user.email')\n return typeof value === 'string' && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/.test(value) ? value : undefined\n }\n return {\n funnel: createFunnel(s, ctx, busTracker, experiments ?? []),\n store: s,\n context: ctx,\n catalog: buildCatalog(products ?? []),\n driver: driverWithEmail(checkout ?? createMockDriver(), emailForCheckout),\n tracker: busTracker,\n bus,\n }\n })\n // Expose the bus on window.appfunnel for the funnel's lifetime (client-side only).\n useEffect(() => attachBus(value.bus), [value.bus])\n // Forward the acquisition snapshot once on entry → the platform persists it\n // first-class (session + first-touch Customer) + feeds CAPI.\n useEffect(() => {\n value.tracker.setAcquisition?.(buildAcquisition(value.context))\n }, [value])\n const tree = createElement(TrackerProvider, {\n tracker: value.tracker,\n children: createElement(CheckoutDriverProvider, {\n driver: value.driver,\n children: createElement(CatalogProvider, {\n catalog: value.catalog,\n children: createElement(FunnelCtx.Provider, {\n value,\n children: createElement(LocaleProvider, {\n config: config?.locales,\n catalog: messages,\n detected: value.context.locale.locale,\n override: localeOverride,\n children: createElement(ModalRuntime, { children }),\n }),\n }),\n }),\n }),\n })\n return createElement(Fragment, null, tree, renderToaster(toaster))\n}\n\nconst FALLBACK_TRACKER = createConsoleTracker({ silent: true })\n\nfunction useFunnelCtx(): FunnelContextValue {\n const ctx = useContext(FunnelCtx)\n if (!ctx) {\n throw new Error('useFunnel/useResponse/… must be used inside <FunnelProvider>')\n }\n return ctx\n}\n\n/**\n * The imperative handle. Does **not** subscribe — use it in event handlers and\n * effects (`useFunnel().responses.set({...})`). For reactive reads use the hooks.\n */\nexport function useFunnel(): Funnel {\n return useFunnelCtx().funnel\n}\n\n/** Internal: the raw {@link VariableStore} (for reactive condition/field hooks). */\nexport function useFunnelStore(): VariableStore {\n return useFunnelCtx().store\n}\n\n// ── Reactive field hooks ─────────────────────────────────\n\n/** Subscribe to a single flat store key; returns its reactive value. */\nfunction useStoreKey(store: VariableStore, key: string): VariableValue {\n const subscribe = useCallback(\n (cb: () => void) => store.subscribe(cb, { keys: [key] }),\n [store, key],\n )\n const getSnapshot = useCallback(() => store.get(key), [store, key])\n // Snapshot is the primitive value → stable by value, no caching needed.\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot)\n}\n\n/** Build a `useState`-shaped tuple hook bound to one writable namespace. */\nfunction makeFieldHook(ns: WritableNamespace) {\n return function useNamespaceField(\n key: string,\n ): [VariableValue, (value: VariableValue) => void] {\n const { funnel, store } = useFunnelCtx()\n const value = useStoreKey(store, `${NAMESPACE_PREFIX[ns]}.${key}`)\n const set = useCallback(\n (v: VariableValue) => funnel[ns].set({ [key]: v }),\n [funnel, key],\n )\n return [value, set]\n }\n}\n\n/**\n * `const [goal, setGoal] = useResponse('goal')` — one funnel answer,\n * `useState`-shaped and per-key reactive. Writing persists + (later) feeds\n * analytics aggregation.\n */\nexport const useResponse = makeFieldHook('responses')\n\n/**\n * `const [height, setHeight] = useUserAttribute('height')` — any field on the\n * user. The platform routes known fields → typed column, custom → attribute;\n * the author doesn't specify which. Writing `email` also identifies the visitor.\n */\nexport const useUserAttribute = makeFieldHook('user')\n\n/**\n * `const [score, setScore] = useData('score')` — working/scratch state. Persisted\n * (survives reload/return) but kept out of `responses` aggregation.\n */\nexport const useData = makeFieldHook('data')\n\n/**\n * The headless field hook — `useField('responses.goal')` — the building block\n * the styleable components (`<Choice>`) wrap. Takes a namespaced path and\n * returns `{ value, set }`. Accepts only writable namespaces.\n */\nexport function useField(path: string): {\n value: VariableValue\n set: (value: VariableValue) => void\n} {\n const dot = path.indexOf('.')\n const ns = path.slice(0, dot) as WritableNamespace\n const key = path.slice(dot + 1)\n const { funnel, store } = useFunnelCtx()\n if (!(ns in NAMESPACE_PREFIX)) {\n throw new Error(`useField: \"${path}\" is not a writable namespace (user/responses/data)`)\n }\n const value = useStoreKey(store, `${NAMESPACE_PREFIX[ns]}.${key}`)\n const set = useCallback(\n (v: VariableValue) => funnel[ns].set({ [key]: v }),\n [funnel, ns, key],\n )\n return { value, set }\n}\n\n// ── Read-only context hooks ──────────────────────────────\n\n/** The whole read-only computed namespace (non-reactive except `page`). */\nfunction useContextObject(): FunnelContext {\n return useFunnelCtx().context\n}\n\n/** `useDevice()` — viewport, device type, pixel ratio (read-only). */\nexport function useDevice(): FunnelContext['device'] {\n return useContextObject().device\n}\n\n/** `useLocale()` — resolved locale/language/region/timezone (read-only). */\nexport function useLocale(): FunnelContext['locale'] {\n return useContextObject().locale\n}\n\n/** `useUtm()` — the 5 utm params captured on entry (read-only). */\nexport function useUtm(): FunnelContext['utm'] {\n return useContextObject().utm\n}\n\n/** `useClickIds()` — per-network ad click-ids captured on entry (read-only). */\nexport function useClickIds(): FunnelContext['clickIds'] {\n return useContextObject().clickIds\n}\n\n/** `useSystem()` — funnel id, test/live mode, build clock (read-only). */\nexport function useSystem(): FunnelContext['system'] {\n return useContextObject().system\n}\n\n/** Read a dotted path out of context, e.g. `useContextValue('device.isMobile')`. */\nexport function useContextValue(path: string): unknown {\n const ctx = useContextObject()\n return useMemo(\n () => path.split('.').reduce<unknown>((acc, k) => (acc as Record<string, unknown>)?.[k], ctx),\n [ctx, path],\n )\n}\n","/**\n * The REAL platform tracker (phase-1 §1.4 / BREAKING-CHANGES B-1) — POSTs the taxonomy to\n * `POST {apiBase}/campaign/{campaignId}/event`, the SAME ingestion endpoint v1 funnels use, so\n * v2 sessions/customers/events land in the shared analytics graph with zero schema fork.\n *\n * Built INSIDE the sealed bundle from serializable config (`MountOpts.tracking`) — the renderer\n * can only pass data across the build boundary, never live objects. Wired automatically by\n * `createFunnelTree` when tracking config is present.\n *\n * Behavior:\n * - SSR-safe: on the server (or with no config) this is never constructed — `createFunnelTree`\n * only wires it client-side; the export also guards `window` for direct users.\n * - mode:'test' → console tracker (previews/QA never pollute shared analytics; the real\n * test-mode quarantine is phase-3 §3.1c).\n * - The FIRST event establishes the session: sends are SERIALIZED until the server returns a\n * `sessionId` (avoids N parallel first-events racing session creation), then fire-and-forget.\n * The sessionId is kept in sessionStorage (per-tab reload continuity) — durable cross-visit\n * identity is the `visitorId`'s job, not the session's.\n * - `visitorId` (bare id, SSR-injected from the af_vid cookie) rides on every event — the\n * ingestion side uses it for durable session lookup + anonymous-Customer continuity.\n * - Acquisition (utm + click-ids + fbp/fbc + referrer) is folded into the FIRST event's\n * `userData.query` bag — exactly where the v1 ingestion's `extractUtmParams`/attribution\n * upgrade logic already looks. Pushed once; never re-sent.\n * - Failures are swallowed (console.warn) — tracking must never break a funnel.\n */\nimport type { Tracker } from './tracking'\nimport type { Acquisition } from '../state/context'\nimport { createConsoleTracker, exposurePayload } from './tracking'\n\n/** The string-valued, non-empty click-ids — the only kind either attribution shape carries. */\nfunction validClickIds(acq: Acquisition): [string, string][] {\n return Object.entries(acq.clickIds ?? {}).filter(\n (e): e is [string, string] => typeof e[1] === 'string' && e[1] !== '',\n )\n}\n\nexport interface PlatformTrackingConfig {\n /** Public API origin, e.g. `https://api.appfunnel.net` (no trailing slash). */\n apiBase: string\n /** Campaign DB id (the ingestion route key). */\n campaignId: string\n /** WebFunnel DB id (NOT the funnel.ts config id). */\n funnelId: string\n /** Verified bare visitor id (phase-1 §1.2), SSR-injected. */\n visitorId?: string | null\n /** Server-resolved session id (renderer looked it up by visitorId for hydration) — a fallback\n * seed; a per-tab sessionStorage id wins over it (v1 tab semantics). */\n sessionId?: string | null\n /** FUNNEL-split experiment assignment (phase-4): the renderer picked this funnel for the\n * visitor — the tracker emits the experiment.exposure (page-level exposures come from the\n * flow runtime instead). Deduped per (session, experiment) in analytics. */\n experiment?: { id: string; variant: string; version?: number }\n mode?: 'test' | 'live'\n}\n\nfunction acquisitionQueryBag(acq: Acquisition): Record<string, string> {\n const q: Record<string, string> = {}\n const utm = acq.utm ?? {}\n for (const [k, v] of Object.entries({\n utm_source: utm.source, utm_medium: utm.medium, utm_campaign: utm.campaign,\n utm_term: utm.term, utm_content: utm.content,\n })) if (v) q[k] = v\n for (const [k, v] of validClickIds(acq)) q[k] = v\n if (acq.cookies?.fbp) q._fbp = acq.cookies.fbp\n if (acq.cookies?.fbc) q._fbc = acq.cookies.fbc\n return q\n}\n\n/**\n * The `adAttribution` body field in v1's EXACT shape (admin collectAdAttribution): click-ids by\n * their param names + `fbp`/`fbc`/`ttp` cookie values, with `fbc` synthesized from `fbclid` when\n * the cookie is absent (`fb.1.<ts>.<fbclid>` — Meta's documented format). Ingestion's existing\n * first-write-wins merge + traffic-source upgrade + typed-column extraction (phase-1 §1.3) all\n * key on these names — reusing the battle-tested path instead of forking it.\n */\nfunction acquisitionAdAttribution(acq: Acquisition): Record<string, string> {\n const a: Record<string, string> = {}\n for (const [k, v] of validClickIds(acq)) a[k] = v\n if (acq.cookies?.fbp) a.fbp = acq.cookies.fbp\n if (acq.cookies?.fbc) a.fbc = acq.cookies.fbc\n else if (acq.clickIds?.fbclid) a.fbc = `fb.1.${Date.now()}.${acq.clickIds.fbclid}`\n return a\n}\n\nexport function createPlatformTracker(cfg: PlatformTrackingConfig): Tracker {\n // Never on the server; never for test mode (preview/QA stays out of shared analytics).\n if (typeof window === 'undefined' || cfg.mode === 'test') return createConsoleTracker()\n\n const base = cfg.apiBase.replace(/\\/+$/, '')\n const url = `${base}/campaign/${encodeURIComponent(cfg.campaignId)}/event`\n const sidKey = `af_sid:${cfg.campaignId}`\n let sessionId: string | null = null\n try { sessionId = window.sessionStorage.getItem(sidKey) } catch { /* storage may be blocked */ }\n if (!sessionId && cfg.sessionId) sessionId = cfg.sessionId // server-resolved (visitorId) fallback\n\n let acquisition: Acquisition | null = null\n let acquisitionSent = false\n let chain: Promise<void> = Promise.resolve()\n\n const send = async (event: string, data?: Record<string, unknown>, userData?: Record<string, unknown>) => {\n let mergedUserData = userData\n let adAttribution: Record<string, string> | undefined\n // Acquisition (click-ids/UTMs) is the ONLY carrier of paid-attribution for v2 and rides the\n // FIRST event. `attachingAcquisition` marks that THIS send is carrying it — we only burn the\n // once-flag on SUCCESS (below), so a dropped first POST re-attaches on the next event instead\n // of reporting a paid session as direct (adversarial review P2).\n let attachingAcquisition = false\n if (acquisition && !acquisitionSent) {\n attachingAcquisition = true\n const query = acquisitionQueryBag(acquisition)\n mergedUserData = Object.keys(query).length ? { ...userData, query } : userData\n const ad = acquisitionAdAttribution(acquisition)\n if (Object.keys(ad).length) adAttribution = ad\n }\n const body = {\n campaignId: cfg.campaignId,\n funnelId: cfg.funnelId,\n event,\n sessionId: sessionId ?? undefined,\n visitorId: cfg.visitorId ?? undefined,\n eventId: typeof data?.eventId === 'string' ? (data.eventId as string) : undefined,\n data: data ?? {},\n metadata: {\n language: typeof navigator !== 'undefined' ? navigator.language : undefined,\n screen: typeof window.screen !== 'undefined' ? `${window.screen.width}x${window.screen.height}` : undefined,\n timezone: (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone } catch { return undefined } })(),\n referrer: typeof document !== 'undefined' && document.referrer ? document.referrer : undefined,\n },\n ...(mergedUserData ? { userData: mergedUserData } : {}),\n ...(adAttribution ? { adAttribution } : {}),\n }\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n keepalive: true, // survives page.exit / unload\n })\n // Only NOW commit the once-flag — a throw above (network drop) leaves it false so the next\n // event re-carries acquisition. keepalive caps the body at ~64KB; acquisition + one event is\n // far under that (variable snapshots use the separate session-data endpoint).\n if (attachingAcquisition) acquisitionSent = true\n const json = (await res.json().catch(() => null)) as { sessionId?: string } | null\n if (json?.sessionId && json.sessionId !== sessionId) {\n sessionId = json.sessionId\n try { window.sessionStorage.setItem(sidKey, sessionId) } catch { /* best-effort */ }\n }\n }\n\n const enqueue = (event: string, data?: Record<string, unknown>, userData?: Record<string, unknown>) => {\n const task = () =>\n send(event, data, userData).catch((e) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[appfunnel] track failed (${event}):`, e)\n })\n if (!sessionId) {\n // Serialize until the first response resolves the session — later events ride the chain.\n chain = chain.then(task)\n } else {\n void task()\n }\n }\n\n // ── Variable persistence (phase-1 §1.1: the server-backed namespace store) ──\n // Every namespace write pushes the FULL flat snapshot ({'user.email', 'responses.goal', …});\n // we debounce trailing-edge and POST the latest snapshot to the v1 session-data endpoint\n // (the API merges it into session.data and runs the normalizer's v2 extraction). Needs a\n // session — before one resolves, the flush rides the send chain. Flushed on pagehide.\n const VARS_DEBOUNCE_MS = 800\n let pendingVars: Record<string, unknown> | null = null\n let varsTimer: ReturnType<typeof setTimeout> | null = null\n\n const flushVars = () => {\n if (varsTimer) { clearTimeout(varsTimer); varsTimer = null }\n if (!pendingVars) return\n const doPost = () => {\n if (!pendingVars || !sessionId) return\n const userData = pendingVars\n pendingVars = null\n void fetch(`${base}/campaign/${encodeURIComponent(cfg.campaignId)}/event/session/data`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ sessionId, userData }),\n keepalive: true,\n }).catch((e) => {\n if (process.env.NODE_ENV !== 'production') console.warn('[appfunnel] variable persist failed:', e)\n })\n }\n if (sessionId) doPost()\n else chain = chain.then(doPost) // wait for the first event to establish the session\n }\n\n try {\n window.addEventListener('pagehide', flushVars)\n } catch { /* non-browser-ish environments */ }\n\n // FUNNEL-split exposure: the renderer made the assignment server-side; record it once per\n // page load (analytics dedupes by session+experiment) so the split's arms are measurable.\n if (cfg.experiment?.id && cfg.experiment.variant) {\n enqueue('experiment.exposure', exposurePayload(cfg.experiment.id, cfg.experiment.variant, cfg.experiment.version))\n }\n\n return {\n track: (event: string, data?: Record<string, unknown>, userData?: Record<string, unknown>) =>\n enqueue(event, data, userData),\n identify: (email: string, eventId?: string) =>\n enqueue('user.registered', { email, ...(eventId ? { eventId } : {}) }),\n setVariables: (variables: Record<string, unknown>) => {\n pendingVars = variables // full snapshot — latest wins\n if (varsTimer) clearTimeout(varsTimer)\n varsTimer = setTimeout(flushVars, VARS_DEBOUNCE_MS)\n },\n setAcquisition: (acq: Acquisition) => { acquisition = acq },\n }\n}\n","/**\n * The **mount contract** — `mount.tsx` is THE v2 convention for a funnel build.\n *\n * Every published funnel ships a `mount.tsx` that exports exactly two things\n * (the {@link MountModule} shape):\n *\n * - `pages: RuntimePage[]` — the code-split page list in file order (the\n * admin editor rewrites this array; the anchor\n * `export const pages: RuntimePage[] = [` must survive verbatim);\n * - `tree: (opts: MountOpts) => ReactNode` — built with\n * {@link createFunnelTree}, consumed identically by the server entry (SSR)\n * and the client entry (hydration) so both render the same tree.\n *\n * `createFunnelTree` packages the canonical provider stack so funnel builds\n * don't hand-roll it:\n *\n * AssetsProvider → FunnelProvider{config, products, locale, mode}\n * → FunnelView{pages, layout, initialKey, prefetch:'off'}\n *\n * (`prefetch: 'off'` because the renderer owns chunk warming via\n * `<link rel=\"modulepreload\">` over `useNavigation().nextCandidates`.)\n */\n\nimport {\n createContext,\n createElement,\n Fragment,\n useContext,\n type ComponentType,\n type ReactNode,\n} from 'react'\nimport { FunnelProvider } from '../state/namespaces'\nimport { FunnelView, type RuntimePage } from './flow'\nimport type { FunnelDefinition } from './spine'\nimport type { ProductInput } from '../commerce/money'\nimport { CheckoutResume, type CheckoutDriver, type CheckoutDriverContext } from '../commerce/checkout'\nimport type { RuntimeExperiment } from './experiments'\nimport { createPlatformTracker } from '../tracking/platformTracker'\n\n// ── Assets ───────────────────────────────────────────────\n\n/**\n * Funnel asset map: logical name (e.g. `logo.svg`) → content-addressed CDN URL,\n * injected by the renderer. Assets live in a SHARED content-addressed store\n * (`appfunnel/assets/<hash>`), so identical content is stored once across all\n * builds and funnels while staying immutable. Both SSR and client read the same\n * injected map → URLs match. Defaults to `{}` (no provider needed in tests).\n */\nexport const AssetsContext = createContext<Record<string, string>>({})\n\n/** Provides the funnel's asset map (mounted for you by {@link createFunnelTree}). */\nexport function AssetsProvider({\n assets,\n children,\n}: {\n assets?: Record<string, string>\n children: ReactNode\n}): ReactNode {\n return createElement(AssetsContext.Provider, { value: assets ?? {} }, children)\n}\n\n/** The whole asset map (logical name → CDN URL). `{}` outside a provider. */\nexport function useAssets(): Record<string, string> {\n return useContext(AssetsContext)\n}\n\n/** `useAsset('logo.svg')` — one asset's CDN URL, or `undefined` if not injected. */\nexport function useAsset(name: string): string | undefined {\n return useContext(AssetsContext)[name]\n}\n\n// ── Mount options ────────────────────────────────────────\n\n/** What the renderer injects when mounting a funnel build (SSR and hydration). */\nexport interface MountOpts {\n /** Platform-resolved product prices (one currency per visitor). */\n products?: ProductInput[]\n /** Explicit locale override (URL/param/geo); wins over the detected device locale. */\n locale?: string\n mode?: 'test' | 'live'\n /** Deep-link / reload entry page (honored only if its entry guard passes). */\n initialKey?: string\n /** Asset map: logical name → content-addressed CDN URL. */\n assets?: Record<string, string>\n /** The SIGNED anonymous visitor id (bare id, verified server-side; phase-1 §1.2) — the\n * renderer mints/reads the `af_vid` cookie and injects the value here. Feeds\n * `context.identity.visitorId` (experiment bucketing fallback seed, session continuity). */\n visitorId?: string | null\n /** Known customer id (identified visitor) — the preferred bucketing seed. */\n customerId?: string | null\n /** Platform tracking config (phase-1 §1.4). Present → `createFunnelTree` wires the real\n * platform tracker (events POST to the shared ingestion endpoint). Absent (preview, tests,\n * bare mounts) → the console tracker. Serializable on purpose — it crosses the sealed-build\n * boundary as data. */\n tracking?: {\n apiBase: string\n campaignId: string\n /** WebFunnel DB id (NOT the funnel.ts config id). */\n funnelId: string\n /** FUNNEL-split assignment (phase-4) — the tracker emits its exposure event. */\n experiment?: { id: string; variant: string; version?: number }\n }\n /** Server-hydrated namespace snapshot (phase-1 §1.1): flat namespaced keys\n * (`user.email`, `responses.goal`, …) from the visitor's latest session — the renderer\n * resolves it by visitorId so a returning visitor resumes with their answers. */\n sessionValues?: Record<string, string | number | boolean | null | string[]>\n /** RUNNING page-experiment records (phase-4): platform-owned wiring over the bundle's\n * `@variant` pages, injected at render time — no rebuild to start/stop/reweight. */\n experiments?: RuntimeExperiment[]\n /** The server-resolved session id backing `sessionValues` — seeds the tracker (fallback)\n * and `context.session.id`. */\n sessionId?: string | null\n}\n\n/**\n * The shape a funnel build's `mount.tsx` module must export — the named,\n * versioned contract between a build and the renderer/editor:\n * `import type { MountModule } from '@appfunnel-dev/sdk'`.\n */\nexport type MountModule = {\n pages: RuntimePage[]\n tree: (opts: MountOpts) => ReactNode\n}\n\n// ── createFunnelTree ─────────────────────────────────────\n\nexport interface CreateFunnelTreeInput {\n /** The funnel's spine (`defineFunnel(...)`). */\n config: FunnelDefinition\n /** Code-split pages in file order (the same array `mount.tsx` exports). */\n pages: RuntimePage[]\n /** Persistent chrome wrapped around the page area (mounted once). */\n layout?: ComponentType<{ children: ReactNode }>\n /**\n * The platform checkout driver factory — `mount.tsx` imports it from a driver\n * subpath entry (`import { stripeCheckoutDriver } from '@appfunnel-dev/sdk/driver-stripe'`)\n * and passes it here, so the provider choice stays in the SDK-owned authoring\n * contract while the ctx (apiBase/campaign/funnel/mode/identity) stays\n * renderer-injected. Called once per `tree()` mount, only when tracking config\n * is present — without it there is no API to charge against (preview, tests,\n * bare mounts) and the mock driver fallback stays in place. Test mode still\n * constructs the real driver: the wire contract carries `mode`, and the server\n * resolves the provider's TEST store from it (that's the quarantine, not the client).\n */\n checkoutDriver?: (ctx: CheckoutDriverContext) => CheckoutDriver\n}\n\n/**\n * Build a funnel's `tree(opts)` — the standard provider stack over your pages.\n *\n * ```tsx\n * export const pages: RuntimePage[] = [ ... ]\n * export const tree = createFunnelTree({ config, pages, layout: Layout })\n * ```\n */\nexport function createFunnelTree({\n config,\n pages,\n layout,\n checkoutDriver,\n}: CreateFunnelTreeInput): (opts: MountOpts) => ReactNode {\n return function tree(opts: MountOpts): ReactNode {\n const mode = opts.mode ?? 'live'\n // The real platform tracker when the renderer passed tracking config (live only — the\n // factory itself no-ops for SSR and test mode). One instance per tree() call: the entries\n // call tree() exactly once per mount (SSR render / hydration), so no memo hook is needed\n // and tree() stays callable outside React.\n const tracker = opts.tracking\n ? createPlatformTracker({\n ...opts.tracking,\n visitorId: opts.visitorId,\n sessionId: opts.sessionId,\n mode,\n })\n : undefined\n // The platform checkout driver when mount.tsx exported a factory AND the renderer passed\n // tracking config — the driver ctx derives from the SAME injected data the tracker uses,\n // so there is no second config channel. Unlike the tracker (whose factory no-ops on the\n // server), the driver IS constructed during SSR, deliberately: factories are\n // construction-safe closures over serializable ctx (provider SDKs load only in\n // effects/event handlers), and a driver's renderInline returns the same stable placeholder\n // on the server and the first client paint. Skipping construction server-side would SSR\n // the mock fallback's <button> into inline surfaces — a guaranteed hydration mismatch.\n const checkout = checkoutDriver && opts.tracking\n ? checkoutDriver({\n apiBase: opts.tracking.apiBase,\n campaignId: opts.tracking.campaignId,\n funnelId: opts.tracking.funnelId,\n mode,\n sessionId: opts.sessionId,\n visitorId: opts.visitorId,\n })\n : undefined\n // The redirect-return resume leg (hosted-checkout success URLs carry\n // `?af_checkout={correlationId}`) rides the persistent layout slot: it needs\n // tracker + navigation, which only exist INSIDE FunnelView's nav context, and\n // the layout is the one mount-once spot there. SSR-safe (renders null;\n // effect-only) and inert without the param.\n const layoutWithResume: ComponentType<{ children: ReactNode }> = function LayoutWithCheckoutResume({\n children,\n }: {\n children: ReactNode\n }): ReactNode {\n return createElement(\n Fragment,\n null,\n createElement(CheckoutResume, null),\n layout ? createElement(layout, null, children) : children,\n )\n }\n return createElement(AssetsProvider, {\n assets: opts.assets,\n children: createElement(FunnelProvider, {\n config,\n products: opts.products ?? [],\n locale: opts.locale,\n tracker,\n checkout,\n sessionValues: opts.sessionValues,\n experiments: opts.experiments,\n context: {\n mode,\n visitorId: opts.visitorId ?? null,\n customerId: opts.customerId ?? null,\n sessionId: opts.sessionId ?? null,\n },\n children: createElement(FunnelView, {\n pages,\n layout: layoutWithResume,\n initialKey: opts.initialKey,\n prefetch: 'off', // renderer background-modulepreloads all chunks\n }),\n }),\n })\n }\n}\n","import {\n createElement,\n type ButtonHTMLAttributes,\n type MouseEvent as ReactMouseEvent,\n type ReactNode,\n} from 'react'\nimport { useField } from '../state/namespaces'\nimport { useNavigation } from './flow'\n\n/**\n * The two-tier component model (doc 07 §\"magic ≠ black box\"): the magic lives in\n * headless hooks (`useField`, `useNavigation`); these styleable components are\n * thin, restyle-able wrappers over them. Every `<Choice>` reduces to `useField`\n * + your own JSX — eject any time. They pass `className`/DOM props straight\n * through and never dictate a pixel beyond the minimum.\n */\n\nexport interface ChoiceOption {\n value: string\n label?: ReactNode\n}\n\nexport interface ChoiceProps {\n /** Writable namespaced path to bind, e.g. `responses.goal`. */\n bind: string\n /** The selectable options (a bare string is shorthand for `{value, label}`). */\n options: (string | ChoiceOption)[]\n /** Class applied to each option button. */\n className?: string\n /** Class applied to the selected option button (in addition to `className`). */\n selectedClassName?: string\n /** Advance navigation after a choice (handy for single-tap question pages). */\n advanceOnSelect?: boolean\n}\n\n/**\n * Single-select bound to a writable field. `<Choice bind=\"responses.goal\"\n * options={[\"lose\", \"gain\"]} />` — selecting persists + (later) tracks; pass\n * `advanceOnSelect` to move to the next page on tap.\n */\nexport function Choice({\n bind,\n options,\n className,\n selectedClassName,\n advanceOnSelect,\n}: ChoiceProps): ReactNode {\n const { value, set } = useField(bind)\n const nav = useNavigation()\n\n return options.map((opt) => {\n const o: ChoiceOption = typeof opt === 'string' ? { value: opt } : opt\n const selected = value === o.value\n return createElement(\n 'button',\n {\n key: o.value,\n type: 'button',\n 'aria-pressed': selected,\n 'data-selected': selected || undefined,\n className: selected && selectedClassName ? `${className ?? ''} ${selectedClassName}`.trim() : className,\n onClick: () => {\n set(o.value)\n if (advanceOnSelect) nav.next()\n },\n },\n o.label ?? o.value,\n )\n })\n}\n\nexport interface NextProps extends ButtonHTMLAttributes<HTMLButtonElement> {\n children?: ReactNode\n}\n\n/** A button that advances the funnel (the current page's `next`, else linear). */\nexport function Next({ children, onClick, ...rest }: NextProps): ReactNode {\n const { next } = useNavigation()\n return createElement(\n 'button',\n {\n type: 'button',\n ...rest,\n onClick: (e: ReactMouseEvent<HTMLButtonElement>) => {\n onClick?.(e)\n if (!e.defaultPrevented) next()\n },\n },\n children ?? 'Continue',\n )\n}\n\nexport interface BackProps extends ButtonHTMLAttributes<HTMLButtonElement> {\n children?: ReactNode\n}\n\n/** A button that returns to the previous page; hidden when there's no history. */\nexport function Back({ children, onClick, ...rest }: BackProps): ReactNode {\n const { back, canGoBack } = useNavigation()\n if (!canGoBack) return null\n return createElement(\n 'button',\n {\n type: 'button',\n ...rest,\n onClick: (e: ReactMouseEvent<HTMLButtonElement>) => {\n onClick?.(e)\n if (!e.defaultPrevented) back()\n },\n },\n children ?? 'Back',\n )\n}\n","/**\n * The **event catalog** — the single source of truth for *which* events exist and\n * how each is routed (analytics vs. integrations vs. runtime-only). Pairs with the\n * typed payloads in {@link ./tracking}.`FunnelEventDataMap`.\n *\n * This replaces the duplication the monorepo flags (`shared/events/catalog.ts` is\n * \"documentation, not imported\" — the taxonomy is re-declared in\n * `admin/lib/funnel/tracking.ts`, each `admin/lib/integrations/*` EVENT_MAP, and\n * `api/src/integrations/constants`). In v2 the **SDK owns the taxonomy** (it emits\n * it), so the bus, the pixel loaders, and the platform all import *this*.\n */\n\nexport type EventSource = 'frontend' | 'backend'\n\nexport interface EventMeta {\n /** Where the event originates. `backend` = the server emits it (e.g. a settled charge). */\n sources: EventSource[]\n /** Persisted to analytics. */\n tracking: boolean\n /** Forwarded to ad/integration pixels (Meta/GTM/TikTok/…). */\n integrations: boolean\n /** Runtime-only JS subscription — not persisted, not sent to integrations. */\n runtime?: boolean\n}\n\n/**\n * Every event the system knows, with its routing metadata. Keys are the taxonomy\n * names (a superset of `FunnelEventDataMap`: it also lists the **backend-originated**\n * monetary events the platform pushes to the client bus for pixel firing).\n */\nexport const EVENT_CATALOG = {\n // ── Runtime / navigation (JS subscriptions; not persisted) ──\n 'funnel.start': { sources: ['frontend'], tracking: false, integrations: false, runtime: true },\n 'experiment.exposure': { sources: ['frontend'], tracking: true, integrations: false },\n\n // ── Frontend, tracked; some also go to pixels ──\n 'page.view': { sources: ['frontend'], tracking: true, integrations: true },\n 'page.exit': { sources: ['frontend'], tracking: true, integrations: false },\n 'user.registered': { sources: ['frontend'], tracking: true, integrations: true },\n 'checkout.start': { sources: ['frontend'], tracking: true, integrations: true },\n 'checkout.payment_added': { sources: ['frontend'], tracking: true, integrations: true },\n 'checkout.failed': { sources: ['frontend'], tracking: true, integrations: false },\n\n // ── Backend-originated money events (server mints the eventId; client fires the pixel) ──\n 'purchase.complete': { sources: ['backend'], tracking: true, integrations: true },\n 'customer.first_purchase': { sources: ['backend'], tracking: true, integrations: true },\n 'subscription.created': { sources: ['backend'], tracking: true, integrations: true },\n 'subscription.renewal': { sources: ['backend'], tracking: true, integrations: true },\n} as const satisfies Record<string, EventMeta>\n\n/** A catalog event name. */\nexport type CatalogEvent = keyof typeof EVENT_CATALOG\n\n/** True if the event is persisted to analytics. */\nexport function isTrackableEvent(name: string): boolean {\n return EVENT_CATALOG[name as CatalogEvent]?.tracking ?? false\n}\n\n/** True if the event is forwarded to ad/integration pixels. */\nexport function isIntegrationEvent(name: string): boolean {\n return EVENT_CATALOG[name as CatalogEvent]?.integrations ?? false\n}\n\n/** The events that feed integrations — the set a pixel loader subscribes to. */\nexport function integrationEvents(): CatalogEvent[] {\n return (Object.keys(EVENT_CATALOG) as CatalogEvent[]).filter((e) => EVENT_CATALOG[e].integrations)\n}\n","/**\n * `<Script>` — the **declared third-party embed** primitive (phase-2 §2.3d).\n *\n * The controlled escape hatch for runtime widgets/embeds that genuinely need\n * client code — Intercom, Trustpilot, a calendar embed, an operator pixel. Unlike\n * arbitrary `<script>` injection, it's **declared** (the funnel author writes\n * `<Script src=…/>`), **deduped** (injected at most once per id/src, even across\n * page navigation in the SPA — a chat widget must not reload on every page), and\n * **CSP-friendly** (accepts a `nonce`).\n *\n * CSP enforcement itself is the **renderer's** job: it scans the funnel's declared\n * `<Script src>`s (build-time) into the `script-src` allowlist and supplies the\n * `nonce`. This component just injects the tag at the right time.\n *\n * For *analytics* pixels, prefer subscribing to the `window.appfunnel` bus\n * ({@link ../tracking/bus}) — `<Script>` is for non-analytics third-party widgets\n * (and the pixel loader snippets, which then subscribe to the bus).\n */\n\nimport { useEffect } from 'react'\n\n/** Module-level registry so a given script injects once for the app's lifetime. */\nconst injected = new Set<string>()\n\nexport interface ScriptProps {\n /** The third-party script URL. */\n src: string\n /**\n * When to inject. `afterInteractive` (default) injects on mount (after hydration);\n * `lazyOnload` waits for idle/`load` so it never competes with the funnel's own JS.\n */\n strategy?: 'afterInteractive' | 'lazyOnload'\n /** Dedup key (defaults to `src`) — the script injects at most once per id. */\n id?: string\n /** Defaults to `true`. */\n async?: boolean\n defer?: boolean\n /** CSP nonce — supplied by the renderer. */\n nonce?: string\n /** Extra attributes (e.g. `data-*`). */\n attributes?: Record<string, string>\n onLoad?: () => void\n onError?: () => void\n}\n\n/**\n * Injects a third-party script once. Renders nothing. Persists across navigation\n * (the tag is never removed on unmount — third-party widgets should stay loaded).\n */\nexport function Script({\n src,\n strategy = 'afterInteractive',\n id,\n async = true,\n defer,\n nonce,\n attributes,\n onLoad,\n onError,\n}: ScriptProps): null {\n useEffect(() => {\n if (typeof document === 'undefined') return\n const key = id ?? src\n if (injected.has(key)) {\n onLoad?.() // already present from an earlier mount\n return\n }\n\n const inject = () => {\n if (injected.has(key)) return\n injected.add(key)\n const el = document.createElement('script')\n el.src = src\n if (id) el.id = id\n if (async) el.async = true\n if (defer) el.defer = true\n if (nonce) el.nonce = nonce\n if (attributes) for (const [k, v] of Object.entries(attributes)) el.setAttribute(k, v)\n el.addEventListener('load', () => onLoad?.())\n el.addEventListener('error', () => {\n injected.delete(key) // allow a later retry\n onError?.()\n })\n document.head.appendChild(el)\n }\n\n if (strategy === 'lazyOnload') {\n const ric = (window as unknown as { requestIdleCallback?: (cb: () => void) => number })\n .requestIdleCallback\n if (ric) {\n ric(inject)\n } else {\n const t = setTimeout(inject, 0)\n return () => clearTimeout(t)\n }\n return\n }\n inject()\n // src/id identify the script; injection is idempotent via the registry.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [src, id])\n\n return null\n}\n\n/** Internal: clear the injected-script registry (tests only). */\nexport function __resetScriptRegistry(): void {\n injected.clear()\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/state/variableStore.ts","../src/state/store.ts","../src/state/context.ts","../src/tracking/tracking.ts","../src/tracking/bus.ts","../src/i18n/translation.ts","../src/commerce/catalog.ts","../src/flow/flow.tsx","../src/modals/registry.tsx","../src/modals/sheet.tsx","../src/commerce/checkout.tsx","../../../node_modules/sonner/dist/index.mjs","../src/toast/toast.tsx","../src/state/namespaces.ts","../src/tracking/platformTracker.ts","../src/flow/mount.tsx","../src/flow/components.tsx","../src/tracking/catalog.ts","../src/embed/script.tsx"],"names":["now","createContext","createElement","useContext","useMemo","useCallback","useEffect","useState","page","useRef","toast","jsx","height","heights","_toast_classNames","_toast_classNames1","offset","Toaster","toasts","id","position","index","value","Fragment"],"mappings":";;;;;;;;;AAgBO,IAAM,gBAAN,MAAoB;AAAA,EAMzB,YAAY,OAAA,EAAwC;AAJpD,IAAA,IAAA,CAAQ,SAAA,uBAAgB,GAAA,EAAoB;AAE5C;AAAA,IAAA,IAAA,CAAQ,cAAwB,EAAC;AAG/B,IAAA,IAAA,CAAK,KAAA,GAAQ,EAAE,GAAG,OAAA,EAAQ;AAAA,EAC5B;AAAA,EAEA,QAAA,GAA0C;AACxC,IAAA,OAAO,IAAA,CAAK,KAAA;AAAA,EACd;AAAA,EAEA,IAAI,GAAA,EAA4B;AAC9B,IAAA,OAAO,IAAA,CAAK,MAAM,GAAG,CAAA;AAAA,EACvB;AAAA,EAEA,GAAA,CAAI,KAAa,KAAA,EAA4B;AAC3C,IAAA,IAAI,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA,KAAM,KAAA,EAAO;AAC/B,IAAA,IAAA,CAAK,KAAA,GAAQ,EAAE,GAAG,IAAA,CAAK,OAAO,CAAC,GAAG,GAAG,KAAA,EAAM;AAC3C,IAAA,IAAA,CAAK,WAAA,GAAc,CAAC,GAAG,CAAA;AACvB,IAAA,IAAA,CAAK,MAAA,EAAO;AAAA,EACd;AAAA,EAEA,SAAS,OAAA,EAAuF;AAC9F,IAAA,MAAM,OAAO,IAAA,CAAK,KAAA;AAClB,IAAA,MAAM,IAAA,GAAO,QAAQ,IAAI,CAAA;AACzB,IAAA,IAAI,SAAS,IAAA,EAAM;AACnB,IAAA,IAAA,CAAK,KAAA,GAAQ,IAAA;AAEb,IAAA,IAAA,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AAA,KAAU,KAAA,GAAQ,IAAA;AACtB,MAAA,IAAI,KAAA,KAAU,KAAA,GAAQ,IAAA;AACtB,MAAA,IAAI,KAAA,KAAU,KAAA,GAAQ,KAAA;AACtB,MAAA,IAAI,UAAA,EAAY,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,CAAA,IAAK,MAAA,CAAO,OAAA,CAAQ,UAAU,CAAA,EAAG,EAAA,CAAG,YAAA,CAAa,GAAG,CAAC,CAAA;AACrF,MAAA,EAAA,CAAG,gBAAA,CAAiB,MAAA,EAAQ,MAAM,MAAA,IAAU,CAAA;AAC5C,MAAA,EAAA,CAAG,gBAAA,CAAiB,SAAS,MAAM;AACjC,QAAA,QAAA,CAAS,OAAO,GAAG,CAAA;AACnB,QAAA,OAAA,IAAU;AAAA,MACZ,CAAC,CAAA;AACD,MAAA,QAAA,CAAS,IAAA,CAAK,YAAY,EAAE,CAAA;AAAA,IAC9B,CAAA;AAEA,IAAA,IAAI,aAAa,YAAA,EAAc;AAC7B,MAAA,MAAM,MAAO,MAAA,CACV,mBAAA;AACH,MAAA,IAAI,GAAA,EAAK;AACP,QAAA,GAAA,CAAI,MAAM,CAAA;AAAA,MACZ,CAAA,MAAO;AACL,QAAA,MAAM,CAAA,GAAI,UAAA,CAAW,MAAA,EAAQ,CAAC,CAAA;AAC9B,QAAA,OAAO,MAAM,aAAa,CAAC,CAAA;AAAA,MAC7B;AACA,MAAA;AAAA,IACF;AACA,IAAA,MAAA,EAAO;AAAA,EAGT,CAAA,EAAG,CAAC,GAAA,EAAK,EAAE,CAAC,CAAA;AAEZ,EAAA,OAAO,IAAA;AACT","file":"index.js","sourcesContent":["import type { VariableValue } from '../types'\n\n/**\n * External variable store for funnel variables — the flat, reactive key/value\n * store under the v2 namespaces. Components subscribe selectively via\n * `useSyncExternalStore`, so only components depending on changed keys re-render.\n * (Seeding lives in {@link ./store}.`createFunnelStore`.)\n */\ninterface ScopedListener {\n listener: () => void\n /** Exact keys to watch, or null for all changes */\n keys: string[] | null\n /** Prefix to watch (e.g. 'answers.'), or null for all */\n prefix: string | null\n}\n\nexport class VariableStore {\n private state: Record<string, VariableValue>\n private listeners = new Set<ScopedListener>()\n /** Tracks which keys changed in the last mutation — used by scoped notify */\n private changedKeys: string[] = []\n\n constructor(initial: Record<string, VariableValue>) {\n this.state = { ...initial }\n }\n\n getState(): Record<string, VariableValue> {\n return this.state\n }\n\n get(key: string): VariableValue {\n return this.state[key]\n }\n\n set(key: string, value: VariableValue): void {\n if (this.state[key] === value) return\n this.state = { ...this.state, [key]: value }\n this.changedKeys = [key]\n this.notify()\n }\n\n setState(updater: (prev: Record<string, VariableValue>) => Record<string, VariableValue>): void {\n const prev = this.state\n const next = updater(prev)\n if (next === prev) return\n this.state = next\n // Compute changed keys\n this.changedKeys = []\n for (const key of Object.keys(next)) {\n if (next[key] !== prev[key]) this.changedKeys.push(key)\n }\n for (const key of Object.keys(prev)) {\n if (!(key in next) && prev[key] !== undefined) this.changedKeys.push(key)\n }\n this.notify()\n }\n\n /** Batch set multiple variables at once */\n setMany(updates: Record<string, VariableValue>): void {\n const changed: string[] = []\n const next = { ...this.state }\n for (const [key, value] of Object.entries(updates)) {\n if (next[key] !== value) {\n next[key] = value\n changed.push(key)\n }\n }\n if (changed.length === 0) return\n this.state = next\n this.changedKeys = changed\n this.notify()\n }\n\n /**\n * Subscribe to store changes.\n *\n * @param listener - callback fired when relevant keys change\n * @param scope - optional scope to limit notifications:\n * - `{ keys: ['data.x', 'user.email'] }` — only fire when these exact keys change\n * - `{ prefix: 'answers.' }` — only fire when any key starting with this prefix changes\n * - omit or `{}` — fire on every change (global listener)\n */\n subscribe(\n listener: () => void,\n scope?: { keys?: string[]; prefix?: string },\n ): () => void {\n const entry: ScopedListener = {\n listener,\n keys: scope?.keys || null,\n prefix: scope?.prefix || null,\n }\n this.listeners.add(entry)\n return () => this.listeners.delete(entry)\n }\n\n private notify(): void {\n const changed = this.changedKeys\n for (const entry of this.listeners) {\n // Global listener — no scope\n if (!entry.keys && !entry.prefix) {\n entry.listener()\n continue\n }\n // Key-scoped listener\n if (entry.keys) {\n if (changed.some((k) => entry.keys!.includes(k))) {\n entry.listener()\n }\n continue\n }\n // Prefix-scoped listener\n if (entry.prefix) {\n if (changed.some((k) => k.startsWith(entry.prefix!))) {\n entry.listener()\n }\n }\n }\n }\n}\n","/**\n * v2 store seeding — builds a {@link VariableStore} holding only the **writable**\n * namespaces (`user` / `responses` / `data`), each persisted to the backend.\n *\n * Seeds the {@link VariableStore} with v2 prefixes (no legacy `answers.`/`query.`\n * aliasing). Read-only computed values do NOT live\n * here — see {@link ./context}. Three deliberate namespaces:\n *\n * - `user.*` persistent identity attributes (cross-session)\n * - `responses.*` the clean, aggregated funnel answers\n * - `data.*` working/scratch state — persisted (so reload + return survive)\n * but kept separate from responses so analytics aggregates only\n * real answers and `data` can hold intermediate garbage\n */\n\nimport type { VariableValue, VariableConfig } from '../types'\nimport { VariableStore } from './variableStore'\n\n/** v2 namespace → store-key prefix (sans trailing dot). 1:1, no legacy aliasing. */\nexport const NAMESPACE_PREFIX = {\n user: 'user',\n responses: 'responses',\n data: 'data',\n} as const\n\nexport type WritableNamespace = keyof typeof NAMESPACE_PREFIX\n\n/** Built-in user attributes — always present so reads never `undefined`. */\nconst BUILTIN_USER: Record<string, VariableValue> = {\n 'user.email': '',\n 'user.name': '',\n}\n\nexport interface FunnelStoreConfig {\n responses?: Record<string, VariableConfig>\n data?: Record<string, VariableConfig>\n}\n\nfunction defaultFor(type: string): VariableValue {\n switch (type) {\n case 'string': return ''\n case 'number': return 0\n case 'boolean': return false\n case 'stringArray': return []\n default: return ''\n }\n}\n\n/**\n * Seed a store from a funnel's declared `responses`/`data` defaults, then layer\n * server / session-restored values on top (highest priority).\n */\nexport function createFunnelStore(\n config: FunnelStoreConfig = {},\n sessionValues?: Record<string, VariableValue>,\n): VariableStore {\n const initial: Record<string, VariableValue> = { ...BUILTIN_USER }\n\n for (const [key, cfg] of Object.entries(config.responses ?? {})) {\n initial[`responses.${key}`] = cfg.default ?? defaultFor(cfg.type)\n }\n for (const [key, cfg] of Object.entries(config.data ?? {})) {\n initial[`data.${key}`] = cfg.default ?? defaultFor(cfg.type)\n }\n\n if (sessionValues) {\n for (const [key, value] of Object.entries(sessionValues)) {\n if (value !== undefined) initial[key] = value\n }\n }\n\n return new VariableStore(initial)\n}\n","/**\n * v2 `context` — the **read-only, computed** namespace.\n *\n * Everything the funnel can *read* but never *write*: the device, the visitor's\n * locale, the current page, acquisition params (UTM), the session, and system\n * facts (funnel id, test/live mode, clock). It supersedes the v0 flat\n * `page.*`/`device.*`/`browser.*`/`os.*`/`query.*`/`metadata.*` system variables\n * (see {@link ./systemVariables}) by folding them into one nested object.\n *\n * Why it's *not* in the {@link ./variableStore}: the store holds **writable**\n * state (`user`/`responses`/`data`) that persists + re-renders per key. Context\n * is derived and read-only, so it lives as a plain object on a React context —\n * no subscriptions, no churn. The one moving part (`page`) is merged into the\n * snapshot from navigation state at read time.\n *\n * Authors read it through hooks (`useDevice()`, `useLocale()`, `usePage()`,\n * `useUtm()`) or inside routing/condition predicates as `s.context.*`.\n */\n\n// ── Shape ────────────────────────────────────────────────\n\nexport interface DeviceContext {\n type: 'mobile' | 'tablet' | 'desktop'\n isMobile: boolean\n isTablet: boolean\n screenWidth: number\n screenHeight: number\n viewportWidth: number\n viewportHeight: number\n colorDepth: number\n pixelRatio: number\n}\n\nexport interface BrowserContext {\n name: string\n version: string\n userAgent: string\n language: string\n cookieEnabled: boolean\n online: boolean\n}\n\nexport interface OsContext {\n name: string\n timezone: string\n}\n\nexport interface LocaleContext {\n /** Full locale, e.g. `en-US`. */\n locale: string\n /** Language subtag, e.g. `en`. */\n language: string\n /** Region subtag, e.g. `US` (may be empty). */\n region: string\n /** IANA timezone, e.g. `America/New_York`. */\n timeZone: string\n}\n\nexport interface PageContext {\n /** Current page key. */\n key: string\n /** Current page URL slug (`meta.slug`, defaults to the key) — what the renderer puts in the path. */\n slug: string\n /** 0-based position in the visited history. */\n index: number\n /** Total pages in the (expected) flow. */\n total: number\n /** 0–100. */\n progressPercentage: number\n /** Epoch ms the current page was entered. */\n startedAt: number\n}\n\n/** Acquisition / ad params captured on entry (the old `query.*` utm slice). */\nexport interface UtmContext {\n source?: string\n medium?: string\n campaign?: string\n content?: string\n term?: string\n [key: string]: string | undefined\n}\n\n/**\n * Per-network ad **click-ids** captured from the entry URL — the matching signals\n * the server CAPI needs. Named per network (not a generic bag) so the platform +\n * each integration map them precisely; `[key]` catches any others.\n */\nexport interface ClickIdContext {\n /** Meta / Facebook */\n fbclid?: string\n /** Google Ads (+ gbraid/wbraid for app↔web) */\n gclid?: string\n gbraid?: string\n wbraid?: string\n /** Microsoft / Bing */\n msclkid?: string\n /** TikTok */\n ttclid?: string\n /** Twitter / X */\n twclid?: string\n /** Snapchat */\n sccid?: string\n /** LinkedIn */\n li_fat_id?: string\n /** Pinterest */\n epik?: string\n /** Reddit */\n rdt_cid?: string\n [key: string]: string | undefined\n}\n\n/**\n * The full acquisition snapshot captured once on entry — the funnel reads `utm` /\n * `clickIds` off {@link FunnelContext}; the SDK forwards this whole thing to the\n * tracker (`setAcquisition`) so the platform persists it **first-class**: per-visit\n * on the session + **first-touch (write-once) on the Customer**, and the click-ids /\n * `_fbp`/`_fbc` cookies feed CAPI. Not stored as a generic attribute/answer.\n */\nexport interface Acquisition {\n utm: UtmContext\n clickIds: ClickIdContext\n /** CAPI cookies (`_fbp`/`_fbc`) read from `document.cookie` (not funnel-readable). */\n cookies: { fbp?: string; fbc?: string }\n /** `document.referrer` at entry. */\n referrer: string\n /** Entry URL path (the landing page). */\n landingPath: string\n}\n\nexport interface SessionContext {\n /** Server session id; null until resolved. */\n id: string | null\n /** Epoch ms the session began. */\n startedAt: number\n /** `document.referrer` at entry. */\n referrer: string\n}\n\n/**\n * Durable identity for **stable experiment bucketing** (phase-4 §4.2). The\n * preferred seed is `customerId` once known; before identification it's the\n * signed anonymous `visitorId` (P1). It is deliberately **not** the session id or\n * fingerprint — a returning visitor (e.g. via winback) must keep their variant\n * across sessions/devices (landmine #4). Both null = unidentifiable traffic, and\n * the experiment layer falls back to control rather than bucket on nothing.\n */\nexport interface IdentityContext {\n /** Known customer id (post-identification). The preferred bucketing seed. */\n customerId: string | null\n /** Signed anonymous visitor id. The fallback bucketing seed. */\n visitorId: string | null\n}\n\nexport interface SystemContext {\n funnelId: string\n campaignId: string\n /** Render mode — `test` for preview/QA, `live` for public traffic. */\n mode: 'test' | 'live'\n /** Epoch ms captured at build time (stable per render, not a live clock). */\n now: number\n}\n\n/** The whole read-only computed namespace, as read in predicates: `s.context.*`. */\nexport interface FunnelContext {\n device: DeviceContext\n browser: BrowserContext\n os: OsContext\n locale: LocaleContext\n page: PageContext\n utm: UtmContext\n /** Per-network ad click-ids captured on entry (funnel-readable; also forwarded for CAPI). */\n clickIds: ClickIdContext\n session: SessionContext\n identity: IdentityContext\n system: SystemContext\n}\n\n// ── Detection ────────────────────────────────────────────\n\ninterface RawBrowser {\n device: DeviceContext\n browser: BrowserContext\n os: OsContext\n locale: LocaleContext\n}\n\nlet cached: RawBrowser | null = null\n\nfunction extractVersion(ua: string, regex: RegExp): string {\n return ua.match(regex)?.[1] ?? '0'\n}\n\n/**\n * Sniff device/browser/os/locale from the environment, once. SSR-safe: returns\n * neutral defaults when `window` is absent. (Self-contained v2 detector — the v0\n * {@link ./systemVariables} equivalent emits flat store keys; this returns the\n * nested shape.)\n */\nfunction detect(): RawBrowser {\n if (cached) return cached\n\n if (typeof window === 'undefined') {\n cached = {\n device: {\n type: 'desktop', isMobile: false, isTablet: false,\n screenWidth: 0, screenHeight: 0, viewportWidth: 0, viewportHeight: 0,\n colorDepth: 24, pixelRatio: 1,\n },\n browser: {\n name: 'Unknown', version: '0', userAgent: 'unknown',\n language: 'en', cookieEnabled: true, online: true,\n },\n os: { name: 'Unknown', timezone: 'UTC' },\n locale: { locale: 'en', language: 'en', region: '', timeZone: 'UTC' },\n }\n return cached\n }\n\n const ua = navigator.userAgent\n const l = ua.toLowerCase()\n\n let name = 'Unknown'\n let version = '0'\n if (l.includes('firefox')) { name = 'Firefox'; version = extractVersion(ua, /Firefox\\/(\\d+[\\d.]*)/) }\n else if (l.includes('edg')) { name = 'Edge'; version = extractVersion(ua, /Edg\\/(\\d+[\\d.]*)/) }\n else if (l.includes('chrome') && !l.includes('edg')) { name = 'Chrome'; version = extractVersion(ua, /Chrome\\/(\\d+[\\d.]*)/) }\n else if (l.includes('safari') && !l.includes('chrome')) { name = 'Safari'; version = extractVersion(ua, /Version\\/(\\d+[\\d.]*)/) }\n\n let osName = 'Unknown'\n if (l.includes('win')) osName = 'Windows'\n else if (l.includes('mac')) osName = 'macOS'\n else if (l.includes('linux') && !l.includes('android')) osName = 'Linux'\n else if (l.includes('android')) osName = 'Android'\n else if (/iphone|ipad|ipod/.test(l)) osName = 'iOS'\n\n let type: DeviceContext['type'] = 'desktop'\n if (/mobile|android(?!.*tablet)|iphone|ipod/.test(l)) type = 'mobile'\n else if (/tablet|ipad/.test(l)) type = 'tablet'\n\n const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'\n const fullLocale = navigator.language || 'en'\n const [language = 'en', region = ''] = fullLocale.split('-')\n\n cached = {\n device: {\n type, isMobile: type === 'mobile', isTablet: type === 'tablet',\n screenWidth: window.screen?.width || 0,\n screenHeight: window.screen?.height || 0,\n viewportWidth: window.innerWidth || 0,\n viewportHeight: window.innerHeight || 0,\n colorDepth: window.screen?.colorDepth || 24,\n pixelRatio: window.devicePixelRatio || 1,\n },\n browser: {\n name, version, userAgent: ua,\n language: fullLocale,\n cookieEnabled: navigator.cookieEnabled ?? true,\n online: navigator.onLine ?? true,\n },\n os: { name: osName, timezone: timeZone },\n locale: { locale: fullLocale, language, region, timeZone },\n }\n return cached\n}\n\n/** Collect `utm_*` params (and any extras) from the URL. SSR-safe. */\nfunction collectUtm(): UtmContext {\n if (typeof window === 'undefined') return {}\n const out: UtmContext = {}\n const params = new URLSearchParams(window.location.search)\n params.forEach((value, key) => {\n if (key.startsWith('utm_')) out[key.slice(4)] = value\n })\n return out\n}\n\n/** Known ad-network click-id params. Any present in the URL is captured. */\nconst CLICK_ID_PARAMS = [\n 'fbclid', 'gclid', 'gbraid', 'wbraid', 'msclkid', 'ttclid',\n 'twclid', 'sccid', 'li_fat_id', 'epik', 'rdt_cid', 'dclid', 'irclickid',\n]\n\n/** Collect ad-network click-ids from the entry URL. SSR-safe. */\nfunction collectClickIds(): ClickIdContext {\n if (typeof window === 'undefined') return {}\n const out: ClickIdContext = {}\n const params = new URLSearchParams(window.location.search)\n for (const key of CLICK_ID_PARAMS) {\n const v = params.get(key)\n if (v) out[key] = v\n }\n return out\n}\n\n/** Read a cookie value by name. SSR-safe AND sandbox-safe: in an opaque-origin sandboxed\n * iframe (e.g. the editor preview, which deliberately has no allow-same-origin) the native\n * `document.cookie` GETTER throws a SecurityError — degrade to \"no cookie\", never crash. */\nfunction readCookie(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined\n try {\n const m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'))\n return m ? decodeURIComponent(m[1]) : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Assemble the full {@link Acquisition} snapshot from the context + `document`\n * (cookies, referrer, path) — captured once on entry, forwarded to the tracker for\n * first-class persistence (session + first-touch Customer) + CAPI.\n */\nexport function buildAcquisition(context: FunnelContext): Acquisition {\n return {\n utm: context.utm,\n clickIds: context.clickIds,\n cookies: { fbp: readCookie('_fbp'), fbc: readCookie('_fbc') },\n referrer: context.session.referrer,\n landingPath: typeof window !== 'undefined' ? window.location.pathname : '',\n }\n}\n\nexport interface BuildContextOptions {\n funnelId?: string\n campaignId?: string\n mode?: 'test' | 'live'\n /** Stable build-time clock (avoids `Date.now()` churn in renders/tests). */\n now?: number\n sessionId?: string | null\n /** Known customer id — the preferred stable bucketing seed (phase-4 §4.2). */\n customerId?: string | null\n /** Signed anonymous visitor id — the fallback bucketing seed. */\n visitorId?: string | null\n /** Overrides for any slice — used by the server to hydrate `utm`/`session`. */\n overrides?: Partial<FunnelContext>\n}\n\n/**\n * Build the read-only {@link FunnelContext} once, at mount. `page` starts at the\n * first page and is replaced per navigation when assembling a snapshot.\n */\nexport function buildContext(opts: BuildContextOptions = {}): FunnelContext {\n const raw = detect()\n const now = opts.now ?? 0\n const referrer = typeof document !== 'undefined' ? document.referrer : ''\n\n const base: FunnelContext = {\n device: raw.device,\n browser: raw.browser,\n os: raw.os,\n locale: raw.locale,\n utm: collectUtm(),\n clickIds: collectClickIds(),\n page: { key: '', slug: '', index: 0, total: 0, progressPercentage: 0, startedAt: now },\n session: { id: opts.sessionId ?? null, startedAt: now, referrer },\n identity: { customerId: opts.customerId ?? null, visitorId: opts.visitorId ?? null },\n system: {\n funnelId: opts.funnelId ?? '',\n campaignId: opts.campaignId ?? '',\n mode: opts.mode ?? 'live',\n now,\n },\n }\n\n if (!opts.overrides) return base\n return {\n ...base,\n ...opts.overrides,\n device: { ...base.device, ...opts.overrides.device },\n browser: { ...base.browser, ...opts.overrides.browser },\n os: { ...base.os, ...opts.overrides.os },\n locale: { ...base.locale, ...opts.overrides.locale },\n utm: { ...base.utm, ...opts.overrides.utm },\n clickIds: { ...base.clickIds, ...opts.overrides.clickIds },\n page: { ...base.page, ...opts.overrides.page },\n session: { ...base.session, ...opts.overrides.session },\n identity: { ...base.identity, ...opts.overrides.identity },\n system: { ...base.system, ...opts.overrides.system },\n }\n}\n\n/** Internal: reset the detection cache (tests only). */\nexport function __resetContextCache(): void {\n cached = null\n}\n","/**\n * v2 tracking seam — the funnel runtime emits a **fixed event taxonomy**, but\n * never talks to the network itself. It calls a {@link Tracker} the platform/CLI\n * injects via {@link FunnelProvider}. The real implementation is the existing\n * {@link ./tracker}.`FunnelTracker` (session id, ad attribution, debounced\n * persistence, CAPI fan-out); tests and local dev use {@link createConsoleTracker}.\n *\n * The taxonomy is preserved verbatim from v0 so analytics keep working:\n * funnel.start · page.view · page.exit · user.registered · experiment.exposure ·\n * checkout.start · checkout.payment_added · checkout.failed · purchase.complete\n *\n * Where each fires (all from the SDK runtime):\n * - `funnel.start` / `page.view` / `page.exit` / `experiment.exposure` — navigation\n * ({@link ../flow/flow}.`FunnelView`); `page.exit` carries duration + active (visible) time.\n * - `user.registered` — `identify()`, the first time `user.email` is written.\n * - `checkout.*` / `purchase.complete` — the commerce primitives ({@link ../commerce/checkout}).\n * `checkout.payment_added` is reported by an inline driver via `onPaymentAdded` (optional).\n *\n * A `responses.set(...)` does **not** emit a discrete event — values are batched into\n * `userData` and persisted (debounced). Only the events above fire.\n */\n\nimport {\n createContext,\n createElement,\n useCallback,\n useContext,\n type ReactNode,\n} from 'react'\nimport type { Acquisition } from '../state/context'\n\n// ── Event taxonomy (typed, preserved from v0) ────────────\n\nexport interface FunnelEventDataMap {\n 'funnel.start': Record<string, never>\n 'page.view': { pageId: string; pageKey?: string; pageName?: string; isInitial?: boolean; eventId?: string }\n 'page.exit': { pageId: string; durationMs: number; activeMs: number }\n 'user.registered': { email: string; eventId?: string }\n 'checkout.start': { productId?: string; priceId?: string; productName?: string; surface?: string }\n 'checkout.payment_added': Record<string, never>\n 'checkout.failed': { category: string; declineCode?: string; productId?: string; intent?: string }\n 'purchase.complete': { amount?: number; currency?: string; email?: string; eventId?: string }\n 'experiment.exposure': { experimentId: string; variant: string; version?: number }\n}\n\n/**\n * Build the `experiment.exposure` payload — ONE constructor for both exposure\n * emitters (the PAGE path in flow.tsx and the FUNNEL path in platformTracker),\n * so the wire shape can't drift between them. `version` is the platform record\n * version results key on; omitted (not `undefined`) when the record has none.\n */\nexport function exposurePayload(\n experimentId: string,\n variant: string,\n version?: number,\n): FunnelEventDataMap['experiment.exposure'] {\n return { experimentId, variant, ...(version !== undefined ? { version } : {}) }\n}\n\n/**\n * A unique id for an analytics event, used as the **dedup key** between the\n * browser pixel (`fbq(..., { eventID })`) and the server CAPI call. Browser-\n * originated events (page.view, registration) mint one with this; **purchase /\n * subscription events carry the id the *server* minted** (the charge is the source\n * of truth) — see `CheckoutResult.eventId`.\n */\nlet _eventIdCounter = 0\nexport function newEventId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID()\n return `af_${Date.now().toString(36)}_${(_eventIdCounter++).toString(36)}`\n}\n\nexport type KnownFunnelEvent = keyof FunnelEventDataMap\n\n/**\n * The surface the runtime needs from a tracker. A subset of `FunnelTracker`, so\n * the real one satisfies it directly; the console tracker is a trivial stub.\n */\nexport interface Tracker {\n /** Emit a known event (typed) or any custom event name. */\n track<E extends KnownFunnelEvent>(event: E, data?: FunnelEventDataMap[E], userData?: Record<string, unknown>): void\n track(event: string, data?: Record<string, unknown>, userData?: Record<string, unknown>): void\n /**\n * Identify by email — fires `user.registered` (idempotent in the impl). The\n * optional `eventId` is the browser↔CAPI dedup key for the registration event.\n */\n identify(email: string, eventId?: string): void\n /** Push the latest variable snapshot for batched/debounced persistence. */\n setVariables?(variables: Record<string, unknown>): void\n /**\n * The acquisition snapshot (utm + click-ids + `_fbp`/`_fbc` + referrer), pushed\n * once on entry. The platform persists it first-class — per-visit on the session +\n * **first-touch (write-once) on the Customer** — and feeds it to CAPI. Optional;\n * the console/test trackers ignore it.\n */\n setAcquisition?(acquisition: Acquisition): void\n}\n\n/** A no-op-ish tracker that logs to the console — for tests, preview, local dev. */\nexport function createConsoleTracker(opts: { silent?: boolean } = {}): Tracker {\n const log = (label: string, ...args: unknown[]) => {\n if (!opts.silent) console.info(`[appfunnel] ${label}`, ...args)\n }\n return {\n track: (event: string, data?: unknown) => log(`track ${event}`, data ?? {}),\n identify: (email: string, eventId?: string) => log('identify', email, eventId),\n setVariables: (vars) => log('vars', vars),\n setAcquisition: (acq) => log('acquisition', acq),\n }\n}\n\n// ── React wiring ─────────────────────────────────────────\n\nconst TrackerContext = createContext<Tracker | null>(null)\n\nexport function TrackerProvider({\n tracker,\n children,\n}: {\n tracker: Tracker\n children: ReactNode\n}): ReactNode {\n return createElement(TrackerContext.Provider, { value: tracker }, children)\n}\n\n/** Internal: the raw tracker, or a silent console fallback if none provided. */\nexport function useTrackerRef(): Tracker {\n return useContext(TrackerContext) ?? FALLBACK\n}\n\nconst FALLBACK = createConsoleTracker({ silent: true })\n\n/**\n * `const { track } = useTracker()` — emit a custom event. Auto events\n * (page.view, identify, purchase, …) fire on their own; this is the escape\n * hatch for funnel-specific events (`track('quiz_skipped', { step: 3 })`).\n */\nexport function useTracker(): { track: Tracker['track'] } {\n const tracker = useTrackerRef()\n const track = useCallback(\n (event: string, data?: Record<string, unknown>, userData?: Record<string, unknown>) =>\n tracker.track(event, data as never, userData),\n [tracker],\n )\n return { track }\n}\n","/**\n * The **`window.appfunnel` event bus** — the client-side integration surface\n * (port of v0 `admin/lib/funnel/utils/appfunnelRuntime.ts`).\n *\n * Every taxonomy event the runtime emits is mirrored here, so on-page pixels and\n * custom scripts integrate by **subscribing** — `window.appfunnel.on('purchase.complete', …)`\n * — instead of the funnel hand-injecting pixel config per page. The pre-built pixel\n * loaders (Meta/TikTok/GTM/Clarity) are just subscribers; CAPI stays the server-side\n * default (this is the *client* sink of the same events). See doc 08 §3.\n *\n * Two deliberate properties vs. v0:\n * - **Replay history** (`events`): async pixels load *after* `funnel.start`/`page.view`\n * fire, so a late subscriber would miss them. The bus keeps a bounded history a\n * subscriber can replay (the GTM `dataLayer` trick) — no lost events.\n * - **Subscribe + read only.** The window surface exposes `on`/`off`/`events` + read\n * getters; it has **no `emit`** (third-party code can't forge events) and **no\n * mutating actions** (`setVariable`/navigation) — the funnel can't be driven through\n * it. (v0's full-control Custom-JS API is deferred pending the bus-control-scope\n * decision; doc 08 §3 + §4.)\n */\n\nimport { newEventId, type Tracker } from './tracking'\n\n/** Read accessors the bus exposes — wired to the funnel's store + context. */\nexport interface BusAccessors {\n getVariable: (key: string) => unknown\n getVariables: () => Record<string, unknown>\n getCurrentPageId: () => string | null\n getCustomerId: () => string | null\n getVisitorId: () => string | null\n}\n\nexport interface BusEvent {\n event: string\n data: unknown\n /** Epoch ms the event was emitted (for ordering / replay). */\n ts: number\n}\n\ntype Listener = (data: unknown) => void\n\n/** The public `window.appfunnel` surface — subscribe + read, never emit or mutate. */\nexport interface AppFunnelBusApi extends BusAccessors {\n /** Subscribe to an event (or `'*'` for all). Returns an unsubscribe fn. */\n on(event: string, cb: Listener): () => void\n off(event: string, cb: Listener): void\n /** Bounded replay history — read past events, then `on()` for future ones. */\n readonly events: BusEvent[]\n}\n\nconst MAX_HISTORY = 250\n\n/**\n * The internal bus: the public {@link AppFunnelBusApi} plus `emit` (SDK-only) and\n * `now` injection. The SDK holds this; only {@link AppFunnelBusApi} reaches `window`.\n */\nexport interface FunnelBus extends AppFunnelBusApi {\n emit(event: string, data?: unknown): void\n}\n\n/** Create a bus over the given read accessors. `now` is injectable for tests. */\nexport function createBus(accessors: BusAccessors, now: () => number = () => Date.now()): FunnelBus {\n const listeners = new Map<string, Set<Listener>>()\n const events: BusEvent[] = []\n\n const on: AppFunnelBusApi['on'] = (event, cb) => {\n let set = listeners.get(event)\n if (!set) listeners.set(event, (set = new Set()))\n set.add(cb)\n return () => off(event, cb)\n }\n const off: AppFunnelBusApi['off'] = (event, cb) => {\n listeners.get(event)?.delete(cb)\n }\n\n const emit = (event: string, data?: unknown) => {\n events.push({ event, data, ts: now() })\n if (events.length > MAX_HISTORY) events.shift()\n // Exact-event listeners, then wildcard. A throwing subscriber never breaks the rest.\n for (const cb of listeners.get(event) ?? []) {\n try { cb(data) } catch { /* a pixel error must not break the funnel */ }\n }\n for (const cb of listeners.get('*') ?? []) {\n try { cb({ event, data }) } catch { /* ignore */ }\n }\n }\n\n return { on, off, events, emit, ...accessors }\n}\n\n/**\n * Wrap a {@link Tracker} so every emitted taxonomy event is mirrored to the bus\n * (the client sink). `identify()` also surfaces a `user.registered` to the bus, so\n * pixels see registration. The server sink (the inner tracker → CAPI) is untouched.\n */\nexport function withBus(tracker: Tracker, bus: FunnelBus): Tracker {\n return {\n // Spread preserves the original call arity (don't append an undefined userData).\n track: ((...args: [string, unknown?, Record<string, unknown>?]) => {\n ;(tracker.track as (...a: unknown[]) => void)(...args)\n bus.emit(args[0], args[1])\n }) as Tracker['track'],\n identify: (email: string, eventId?: string) => {\n // One id shared by the server (inner.identify → CAPI) and the bus (pixel) so\n // CompleteRegistration dedupes across browser + server.\n const id = eventId ?? newEventId()\n tracker.identify(email, id)\n bus.emit('user.registered', { email, eventId: id })\n },\n setVariables: tracker.setVariables ? (v) => tracker.setVariables!(v) : undefined,\n // Acquisition is persistence (session + first-touch Customer), not a bus event.\n setAcquisition: tracker.setAcquisition ? (a) => tracker.setAcquisition!(a) : undefined,\n }\n}\n\ndeclare global {\n interface Window {\n appfunnel?: AppFunnelBusApi\n }\n}\n\n/**\n * Attach the bus's public surface to `window.appfunnel` (client-side only).\n * Returns a detach fn for unmount. No-op under SSR.\n */\nexport function attachBus(bus: FunnelBus): () => void {\n if (typeof window === 'undefined') return () => {}\n const { on, off, getVariable, getVariables, getCurrentPageId, getCustomerId, getVisitorId } = bus\n const api: AppFunnelBusApi = {\n on, off, getVariable, getVariables, getCurrentPageId, getCustomerId, getVisitorId,\n get events() { return bus.events },\n }\n window.appfunnel = api\n return () => {\n if (window.appfunnel === api) delete window.appfunnel\n }\n}\n","/**\n * v2 localization — translated **text** (prices already localize via `Intl` in\n * {@link ./catalog}). Per doc 05: locales live in the funnel source — supported\n * locales + default + fallback are funnel config ({@link FunnelLocales}), and\n * each locale is a flat `key → string` **catalog** (`messages/en.json`, …),\n * versioned + published with the funnel. The dashboard's manual translation\n * table edits exactly these catalogs.\n *\n * Lookup walks a **fallback chain** (active → fallback → default) so a missing\n * string never blanks — it falls through, and only as a last resort returns the\n * key (flagged in dev). Interpolation is simple `{{var}}`; plurals use the\n * built-in `Intl.PluralRules`; numbers/dates/percent use `Intl`. No ICU, no rich\n * markup (markup stays in TSX).\n */\n\nimport {\n createContext,\n createElement,\n useContext,\n useEffect,\n useMemo,\n useState,\n type ReactNode,\n} from 'react'\nimport type { FunnelLocales } from '../flow/spine'\nimport { isRtl, resolveLocale, type Direction } from './locale'\n\n// Pure locale resolution lives in ./locale (React-free, shared with the\n// server/tooling entry); re-exported here so existing imports keep working.\nexport { isRtl, resolveLocale } from './locale'\nexport type { Direction } from './locale'\n\n/** locale → (message key → string). The shape of `messages/<locale>.json`. */\nexport type MessageCatalog = Record<string, Record<string, string>>\n\nexport type PluralCategory = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other'\n\n/** Replace `{{name}}` placeholders; leaves unknown ones intact. */\nfunction interpolate(str: string, params?: Record<string, string | number>): string {\n if (!params) return str\n return str.replace(/\\{\\{(\\w+)\\}\\}/g, (_, k: string) => (k in params ? String(params[k]) : `{{${k}}}`))\n}\n\n/** Walk the fallback chain for a key; undefined if absent everywhere. */\nfunction lookup(catalog: MessageCatalog, chain: string[], key: string): string | undefined {\n for (const loc of chain) {\n const v = catalog[loc]?.[key]\n if (v !== undefined) return v\n }\n return undefined\n}\n\nfunction devWarn(message: string): void {\n const env = (globalThis as { process?: { env?: { NODE_ENV?: string } } }).process?.env?.NODE_ENV\n if (env === 'production') return\n try {\n console.warn(message)\n } catch {\n /* no-op */\n }\n}\n\n// ── Public types ─────────────────────────────────────────\n\nexport interface TFunction {\n /** Translate a key, with optional `{{var}}` params. Missing → fallback → key. */\n (key: string, params?: Record<string, string | number>): string\n /** Locale-correct plural: `t.plural(n, { one: '# day', other: '# days' })` (`#` → n). */\n plural: (\n n: number,\n forms: Partial<Record<PluralCategory, string>>,\n params?: Record<string, string | number>,\n ) => string\n}\n\nexport interface Formatters {\n number: (n: number, opts?: Intl.NumberFormatOptions) => string\n date: (d: Date | number, opts?: Intl.DateTimeFormatOptions) => string\n percent: (n: number, opts?: Intl.NumberFormatOptions) => string\n}\n\nexport interface Translation {\n t: TFunction\n fmt: Formatters\n /** The active (resolved) locale. */\n locale: string\n /** Switch locale at runtime (preview / language picker). */\n setLocale: (locale: string) => void\n /** Text direction for the active locale. */\n dir: Direction\n /** The funnel's supported locales. */\n locales: string[]\n}\n\n// ── React wiring ─────────────────────────────────────────\n\ninterface LocaleContextValue {\n locale: string\n setLocale: (locale: string) => void\n config?: FunnelLocales\n catalog: MessageCatalog\n}\n\nconst LocaleContext = createContext<LocaleContextValue | null>(null)\n\nexport interface LocaleProviderProps {\n config?: FunnelLocales\n catalog?: MessageCatalog\n /** Device/browser locale (from computed context) — the resolution input. */\n detected: string\n /** Explicit override (URL/param/geo), highest priority. */\n override?: string\n children: ReactNode\n}\n\n/** Resolves + holds the active locale and the message catalog. */\nexport function LocaleProvider({\n config,\n catalog = {},\n detected,\n override,\n children,\n}: LocaleProviderProps): ReactNode {\n const [locale, setLocale] = useState(() => resolveLocale(config, detected, override))\n // Re-resolve when the inputs change (SSR-hydrated override arriving late, a\n // preview switching `locale`, config swap). A runtime `setLocale` (language\n // picker) survives re-renders — this only fires when a *prop* changes; React\n // bails out when the re-resolved locale is unchanged.\n useEffect(() => {\n setLocale(resolveLocale(config, detected, override))\n }, [config, detected, override])\n const value = useMemo<LocaleContextValue>(\n () => ({ locale, setLocale, config, catalog }),\n [locale, config, catalog],\n )\n return createElement(LocaleContext.Provider, { value }, children)\n}\n\n/** The active (resolved) funnel locale, or `'en'` if no provider — for display\n * formatting (e.g. {@link ./catalog} prices) without building the full handle. */\nexport function useActiveLocale(): string {\n return useContext(LocaleContext)?.locale ?? 'en'\n}\n\n/**\n * `const { t, fmt, locale, dir } = useTranslation()` — translated text +\n * locale-aware `Intl` formatters for the active funnel locale.\n */\nexport function useTranslation(): Translation {\n const ctx = useContext(LocaleContext)\n if (!ctx) throw new Error('useTranslation must be used inside <FunnelProvider>')\n const { locale, setLocale, config, catalog } = ctx\n\n const chain = useMemo(() => {\n const def = config?.default\n const fb = config?.fallback\n return Array.from(new Set([locale, fb, def].filter(Boolean) as string[]))\n }, [locale, config])\n\n const t = useMemo<TFunction>(() => {\n const fn = ((key: string, params?: Record<string, string | number>) => {\n const raw = lookup(catalog, chain, key)\n if (raw === undefined) {\n devWarn(`[appfunnel] missing translation: \"${key}\" (${locale})`)\n return key\n }\n return interpolate(raw, params)\n }) as TFunction\n fn.plural = (n, forms, params) => {\n let rule: PluralCategory\n try {\n rule = new Intl.PluralRules(locale).select(n) as PluralCategory\n } catch {\n rule = 'other'\n }\n const form = forms[rule] ?? forms.other ?? ''\n return interpolate(form.replace(/#/g, String(n)), params)\n }\n return fn\n }, [catalog, chain, locale])\n\n // Like formatMoney: an invalid locale/options must degrade to a plain\n // rendering, never throw mid-render.\n const fmt = useMemo<Formatters>(\n () => ({\n number: (n, opts) => {\n try {\n return new Intl.NumberFormat(locale, opts).format(n)\n } catch {\n return String(n)\n }\n },\n date: (d, opts) => {\n try {\n return new Intl.DateTimeFormat(locale, opts).format(d)\n } catch {\n return String(d instanceof Date ? d.toISOString() : d)\n }\n },\n percent: (n, opts) => {\n try {\n return new Intl.NumberFormat(locale, { style: 'percent', ...opts }).format(n)\n } catch {\n return `${(n * 100).toFixed(0)}%`\n }\n },\n }),\n [locale],\n )\n\n return {\n t,\n fmt,\n locale,\n setLocale,\n dir: isRtl(locale) ? 'rtl' : 'ltr',\n locales: config?.supported ?? [locale],\n }\n}\n","/**\n * v2 `products` — the **read-only** product catalog.\n *\n * **AppFunnel does not manage currency.** Multi-currency is entirely the payment\n * provider's job: the provider (or its preview API) resolves the visitor's price,\n * and we receive a single resolved `{ amount, currency }` per product. No FX, no\n * currency selection, no conversion on our side. (FX appears only for frozen-USD\n * *reporting*, never display — phase-3 §3.6b.) A provider that doesn't localize\n * simply gives one currency.\n *\n * Our only job is **display**: pick the product by logical id and **format** its\n * amount. Formatting happens at read time in the funnel's **active locale** (so\n * switching language reformats `kr 79,00` ⇄ `$9.99`), while the **currency** is\n * whatever the provider resolved. Currency selection is the platform's; the\n * authoring funnel only ever names a product id.\n *\n * The math itself (resolve/format/exponents) is pure and lives in {@link ./money}\n * so the server/tooling entry can use it without React — this module re-exports\n * it and adds the React wiring (provider + hooks).\n */\n\nimport {\n createContext,\n createElement,\n useContext,\n useMemo,\n type ReactNode,\n} from 'react'\nimport { useActiveLocale } from '../i18n/translation'\nimport { formatProduct, type Product, type ResolvedProduct } from './money'\n\nexport {\n resolveProduct,\n buildCatalog,\n formatMoney,\n formatProduct,\n currencyExponent,\n} from './money'\nexport type { Product, ResolvedProduct, ProductInput, Money, Interval } from './money'\n\n// ── React wiring ─────────────────────────────────────────\n\nconst CatalogContext = createContext<Map<string, ResolvedProduct> | null>(null)\n\nexport function CatalogProvider({\n catalog,\n children,\n}: {\n catalog: Map<string, ResolvedProduct>\n children: ReactNode\n}): ReactNode {\n return createElement(CatalogContext.Provider, { value: catalog }, children)\n}\n\nfunction useCatalog(): Map<string, ResolvedProduct> {\n return useContext(CatalogContext) ?? EMPTY\n}\nconst EMPTY = new Map<string, ResolvedProduct>()\n\n/** `useProduct('monthly')` — one product, formatted in the active locale. */\nexport function useProduct(id: string | undefined): Product | undefined {\n const catalog = useCatalog()\n const locale = useActiveLocale()\n const resolved = id ? catalog.get(id) : undefined\n return useMemo(() => (resolved ? formatProduct(resolved, locale) : undefined), [resolved, locale])\n}\n\n/** `useProducts()` — every product, formatted in the active locale, in order. */\nexport function useProducts(): Product[] {\n const catalog = useCatalog()\n const locale = useActiveLocale()\n return useMemo(\n () => Array.from(catalog.values()).map((r) => formatProduct(r, locale)),\n [catalog, locale],\n )\n}\n","import {\n createContext,\n createElement,\n lazy,\n Suspense,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useTransition,\n type ComponentType,\n type ReactNode,\n} from 'react'\nimport { useFunnel } from '../state/namespaces'\nimport { exposurePayload, newEventId, useTrackerRef, type Tracker } from '../tracking/tracking'\nimport { entryGuard, evaluateGate, expectedPathLength, nextPage, outgoingKeys, type FlowPage, type PageMeta } from './spine'\nimport { bucketingSeed, resolveExperiments } from './experiments'\nimport type { PageContext } from '../state/context'\n\n/** What a page's `load` resolves to — a component, or a module default-exporting one. */\nexport type PageModule = ComponentType | { default: ComponentType }\n\n/**\n * A page wired into the runtime. Provide **either** an eager `Component` (small\n * funnels, tests) **or** a lazy `load` (code-split: the renderer hands a dynamic\n * `import()` so a big funnel ships one chunk per page, not the whole funnel).\n */\nexport interface RuntimePage {\n key: string\n meta?: PageMeta\n /** Eager component. Provide this or `load`. */\n Component?: ComponentType\n /** Lazy loader for a code-split chunk. Provide this or `Component`. */\n load?: () => Promise<PageModule>\n}\n\nexport interface NavigationState {\n /** The current page's read-only context (key, index, total, progress). */\n page: PageContext\n /** Advance via the current page's `next` predicate, else the linear next. */\n next: () => void\n /** Go to the previous page in history. */\n back: () => void\n /** Jump to a specific page key. */\n go: (key: string) => void\n /** Warm a page's code-split chunk ahead of navigation (e.g. on link hover). No-op for eager pages. */\n prefetch: (key: string) => void\n /**\n * The page keys the visitor could go to next, already resolved to the chunk that\n * would render (experiment variant applied). The **renderer** maps these to chunk\n * URLs and emits `<link rel=\"modulepreload\">` (the browser-native, non-executing,\n * SSR-able prefetch — see v0 `HeadlessFunnelRenderer`). The SDK's `load()`-based\n * `prefetch` is the fallback for mounts without a modulepreload manager.\n */\n nextCandidates: string[]\n canGoBack: boolean\n /**\n * True while a navigation's target page chunk is still resolving (a cold,\n * un-prefetched lazy chunk). The current page stays on screen during this window\n * (no Suspense-fallback flicker); read this to show a subtle \"working\" affordance\n * so a tapped button doesn't feel dead. Usually false/instant when the next chunk\n * was prefetched.\n */\n isNavigating: boolean\n}\n\nconst NavContext = createContext<NavigationState | null>(null)\n\n/** experiment id → the variant this visitor is bucketed into, for the live render. */\nconst ExperimentContext = createContext<Record<string, string>>({})\n\n/**\n * `const variant = useExperiment('welcome-headline')` — the variant key this\n * visitor is assigned in an experiment (`undefined` if not in one). Page-variant\n * swapping is automatic; this is for branching *within* a page or custom logging.\n */\nexport function useExperiment(id: string): string | undefined {\n return useContext(ExperimentContext)[id]\n}\n\n/**\n * Compute the read-only page context for a position in the flow. `total` is the\n * **expected** path length for the visitor's current answers (see\n * {@link expectedPathLength}) — not the raw file count — so progress reaches 100%\n * on whichever branch the funnel actually takes. Clamped so a visitor who jumped\n * past the traced path can't read above 100%.\n */\nfunction pageContextFor(\n currentKey: string,\n slug: string,\n index: number,\n total: number,\n startedAt: number,\n): PageContext {\n const denom = Math.max(total, index + 1)\n return {\n key: currentKey,\n slug,\n index,\n total: denom,\n progressPercentage: denom > 0 ? Math.min(100, Math.round(((index + 1) / denom) * 100)) : 0,\n startedAt,\n }\n}\n\n/** Page-timing clock (effects only, never render). */\nconst now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now())\n\n/**\n * `page.exit` timing — wall-clock duration on a page, minus time the tab was\n * hidden (active engagement). Emits for the page being LEFT on each page change;\n * the final page's exit fires on unmount.\n */\nfunction usePageExitTimer(tracker: Tracker, currentKey: string | undefined): void {\n const timer = useRef<{ key: string; enteredAt: number; hidden: number; hiddenSince: number | null } | null>(null)\n const emitExit = useCallback(() => {\n const t = timer.current\n if (!t) return\n const at = now()\n const hidden = t.hidden + (t.hiddenSince != null ? at - t.hiddenSince : 0)\n const durationMs = Math.round(at - t.enteredAt)\n tracker.track('page.exit', { pageId: t.key, durationMs, activeMs: Math.max(0, Math.round(durationMs - hidden)) })\n }, [tracker])\n\n // Track tab visibility so `activeMs` excludes backgrounded time.\n useEffect(() => {\n if (typeof document === 'undefined') return\n const onVis = () => {\n const t = timer.current\n if (!t) return\n if (document.visibilityState === 'hidden') t.hiddenSince = now()\n else if (t.hiddenSince != null) {\n t.hidden += now() - t.hiddenSince\n t.hiddenSince = null\n }\n }\n document.addEventListener('visibilitychange', onVis)\n return () => document.removeEventListener('visibilitychange', onVis)\n }, [])\n\n // On each page change emit page.exit for the page being left, then start the\n // new page's timer.\n useEffect(() => {\n if (!currentKey) return\n if (timer.current && timer.current.key !== currentKey) emitExit()\n const hidden = typeof document !== 'undefined' && document.visibilityState === 'hidden'\n timer.current = { key: currentKey, enteredAt: now(), hidden: 0, hiddenSince: hidden ? now() : null }\n }, [currentKey, emitExit])\n\n useEffect(() => () => emitExit(), [emitExit])\n}\n\n/**\n * Renders the funnel: shows the current page and drives navigation. `next()`\n * resolves the current page's `next` predicate against the live snapshot\n * (writable namespaces + read-only `context`), falling back to the linear next\n * page in file order (see {@link nextPage}).\n *\n * Auto-emits `funnel.start` on mount and `page.view` on each page change, and\n * keeps `context.page` in sync so predicates and `usePage()` see the live page.\n *\n * Pass a `layout` (a `{ children }` component) for **persistent chrome** — a\n * header, progress bar, background — rendered *inside* the nav context but\n * *outside* the page swap, so it mounts once and never remounts on navigation\n * (and can read `usePage`/`useNavigation`).\n *\n * Must live inside `<FunnelProvider>`.\n */\nexport function FunnelView({\n pages,\n initialKey,\n layout,\n fallback,\n prefetch: prefetchMode = 'auto',\n onNavigate,\n}: {\n pages: RuntimePage[]\n initialKey?: string\n layout?: ComponentType<{ children: ReactNode }>\n /** Shown in the page area while a lazy page's chunk loads (the layout persists around it). */\n fallback?: ReactNode\n /**\n * `'auto'` (default): the SDK warms next-likely chunks by calling `load()`.\n * `'off'`: the **renderer** owns prefetch (via `<link rel=\"modulepreload\">` over\n * `useNavigation().nextCandidates`) — avoids the redundant `load()` execution.\n */\n prefetch?: 'auto' | 'off'\n /**\n * Fires on every page change (incl. the initial page) with the current page key\n * + slug. The **renderer** uses it to sync the URL path (`history.replaceState`,\n * v0-style — funnel back is in-memory, not browser history). Fires for the\n * *resolved* page, so if an entry `guard` bounced a deep-link to the start, the\n * URL gets corrected.\n */\n onNavigate?: (key: string, slug: string) => void\n}): ReactNode {\n const funnel = useFunnel()\n const tracker = useTrackerRef()\n\n // Resolve each page to a renderable component: eager `Component` as-is, or a\n // stable `React.lazy` over `load` (memoized so the lazy element identity is\n // stable across renders → no remount). `loaders` keeps the raw `load` fns for\n // prefetch (dynamic import dedupes, so calling them early just warms the chunk).\n const components = useMemo(() => {\n const map = new Map<string, ComponentType>()\n for (const p of pages) {\n if (p.Component) map.set(p.key, p.Component)\n else if (p.load) {\n const load = p.load\n map.set(p.key, lazy(() => Promise.resolve(load()).then((m) =>\n typeof m === 'function' ? { default: m } : m,\n )))\n }\n }\n return map\n }, [pages])\n const loaders = useMemo(\n () => new Map(pages.filter((p) => p.load).map((p) => [p.key, p.load!])),\n [pages],\n )\n\n // Resolve page-level experiments once for this visitor: which variant of each\n // slot to show, and which variant pages drop out of the linear flow. The seed is\n // PINNED to the first non-null value for this mount (a ref, not the live context) so a\n // mid-session identify() that later populates context.identity can never flip an\n // in-progress visitor's variant — the comment's promise is now enforced, not incidental.\n const seedRef = useRef<string | null>(null)\n if (seedRef.current === null) seedRef.current = bucketingSeed(funnel.context)\n const seed = seedRef.current\n const experiments = useMemo(\n () => resolveExperiments(pages, funnel.experiments, seed),\n [pages, funnel.experiments, seed],\n )\n // The two key remaps every navigation touch point needs: a routing TARGET\n // collapses to its slot (variant keys never stand alone in the flow); a slot\n // resolves to the chunk its assigned variant renders.\n const toSlot = useCallback((k: string) => experiments.slotOf[k] ?? k, [experiments])\n const toRenderKey = useCallback((k: string) => experiments.render[k] ?? k, [experiments])\n const pageByKey = useMemo(() => new Map(pages.map((p) => [p.key, p])), [pages])\n // The effective flow: anchors + standalone pages, in order (losers removed).\n const flowPages = useMemo<RuntimePage[]>(\n () => experiments.activeKeys.map((k) => pageByKey.get(k)).filter((p): p is RuntimePage => p !== undefined),\n [experiments, pageByKey],\n )\n\n // The flow as plain {key, meta} for routing + path-length tracing.\n const flow = useMemo<FlowPage[]>(\n () => flowPages.map((p) => ({ key: p.key, meta: p.meta })),\n [flowPages],\n )\n\n // Resolve the starting page. A deep-link / reload `initialKey` is honored only if\n // the page's entry `guard` passes against the (restored) snapshot — else fall\n // back to the start page. (In-funnel navigation never hits this; routing gated it.)\n const [history, setHistory] = useState<string[]>(() => {\n const start = flowPages[0]?.key\n if (!initialKey || initialKey === start) return start ? [start] : []\n const target = toSlot(initialKey)\n const page = flowPages.find((p) => p.key === target)\n // Effective guard = the page-type default (paywall/upsell need email) AND any\n // explicit meta.guard.\n const guard = entryGuard(page?.meta)\n const ok = page && (!guard || evaluateGate(guard, funnel.snapshot()))\n const first = ok ? target : start\n return first ? [first] : []\n })\n const currentKey = history[history.length - 1]\n const index = history.length - 1\n const startKey = history[0]\n\n // Expected path length for the visitor's current answers — re-traced per\n // navigation so progress reaches 100% on whichever branch the funnel takes.\n const total = useMemo(\n () => expectedPathLength(flow, startKey, funnel.snapshot()),\n // currentKey in deps: re-trace as each step's answers settle the branch.\n [flow, startKey, currentKey, funnel],\n )\n\n // Keep the read-only context's `page` slice current so predicates + usePage see it.\n const slug = pageByKey.get(currentKey)?.meta?.slug ?? currentKey\n const page = useMemo(\n () => pageContextFor(currentKey, slug, index, total, funnel.context.system.now),\n [currentKey, slug, index, total, funnel.context.system.now],\n )\n // Keep the imperative handle's `context.page` in sync for snapshot()/predicates\n // and the window.appfunnel bus. Synced in a COMMIT effect, not during render —\n // mutating a shared object mid-render is unsafe under SSR/concurrent rendering\n // (two in-flight renders would race on it). Everything render-facing reads\n // `page` from the NavContext value below (React state), so this only serves\n // event-handler/effect readers, which always run after the commit.\n useEffect(() => {\n funnel.context.page = page\n }, [funnel, page])\n\n // funnel.start once, on mount.\n const started = useRef(false)\n useEffect(() => {\n if (started.current) return\n started.current = true\n tracker.track('funnel.start', {})\n }, [tracker])\n\n // page.view on every page change.\n useEffect(() => {\n if (!currentKey) return\n tracker.track('page.view', { pageId: currentKey, pageKey: currentKey, isInitial: index === 0, eventId: newEventId() })\n }, [tracker, currentKey, index])\n\n // Tell the renderer the live page (key + slug) so it can sync the URL path.\n useEffect(() => {\n if (currentKey && onNavigate) onNavigate(currentKey, slug)\n }, [onNavigate, currentKey, slug])\n\n // experiment.exposure the first time the visitor lands on an experiment slot.\n const exposed = useRef<Set<string>>(new Set())\n useEffect(() => {\n const expId = experiments.experimentOf[currentKey]\n if (!expId || exposed.current.has(expId)) return\n exposed.current.add(expId)\n tracker.track('experiment.exposure', exposurePayload(expId, experiments.assignments[expId], experiments.versionOf[expId]))\n }, [tracker, currentKey, experiments])\n\n usePageExitTimer(tracker, currentKey)\n\n // Navigation swaps a code-split page (a lazy chunk). Wrap the history update in a\n // transition so React keeps the CURRENT page on screen until the next page's chunk\n // is ready, instead of flashing the Suspense `fallback` (the inter-page flicker).\n // `isNavigating` is true while a cold chunk resolves → show a \"working\" affordance\n // so the button doesn't feel dead. Prefetch makes this window usually invisible.\n const [isNavigating, startNav] = useTransition()\n const next = useCallback(() => {\n // Route over the effective flow (slots); the slot page's `meta.next` governs\n // routing. Remap any target that points at a collapsed variant key to its slot.\n const target = nextPage(flow, currentKey, funnel.snapshot())\n const resolved = target ? toSlot(target) : target\n if (resolved) startNav(() => setHistory((h) => [...h, resolved]))\n }, [flow, currentKey, funnel, toSlot])\n\n const back = useCallback(\n () => startNav(() => setHistory((h) => (h.length > 1 ? h.slice(0, -1) : h))),\n [],\n )\n const go = useCallback(\n (key: string) => startNav(() => setHistory((h) => [...h, toSlot(key)])),\n [toSlot],\n )\n\n // Warm a slot's code-split chunk (the variant that would actually render). Idempotent.\n const prefetched = useRef<Set<string>>(new Set())\n const prefetch = useCallback(\n (key: string) => {\n const target = toRenderKey(key)\n const load = loaders.get(target)\n if (!load || prefetched.current.has(target)) return\n prefetched.current.add(target)\n load().catch(() => prefetched.current.delete(target)) // let a failed load retry later\n },\n [loaders, toRenderKey],\n )\n\n // The next-likely pages, resolved to the chunk that would actually render\n // (experiment variant applied) — the renderer modulepreloads these.\n const nextCandidates = useMemo(\n () => [...new Set(outgoingKeys(flow, currentKey).map(toRenderKey))],\n [flow, currentKey, toRenderKey],\n )\n\n // 'auto' mode: warm those chunks by calling load(). 'off': the renderer owns it.\n useEffect(() => {\n if (prefetchMode !== 'auto') return\n for (const key of nextCandidates) prefetch(key)\n }, [prefetchMode, nextCandidates, prefetch])\n\n const value: NavigationState = {\n page,\n next,\n back,\n go,\n prefetch,\n nextCandidates,\n canGoBack: history.length > 1,\n isNavigating,\n }\n // Render the assigned variant's component at the current slot (the anchor key\n // stays the flow position; only the component swaps). Lazy pages suspend, so the\n // page area shows `fallback` while the chunk loads — inside the layout, so the\n // persistent chrome stays put.\n const renderKey = toRenderKey(currentKey)\n const Current = components.get(renderKey)\n const pageEl = createElement(Suspense, { fallback: fallback ?? null }, Current ? createElement(Current) : null)\n // The layout wraps the page inside NavContext → it persists across navigation\n // (same element type, only the page child swaps) and can use nav/funnel hooks.\n const content = layout ? createElement(layout, null, pageEl) : pageEl\n\n return createElement(\n ExperimentContext.Provider,\n { value: experiments.assignments },\n createElement(NavContext.Provider, { value }, content),\n )\n}\n\n/** `const { next, back, go, page } = useNavigation()`. */\nexport function useNavigation(): NavigationState {\n const ctx = useContext(NavContext)\n if (!ctx) throw new Error('useNavigation must be used inside <FunnelView>')\n return ctx\n}\n\n/** `usePage()` — the current page's read-only context, reactive to navigation. */\nexport function usePage(): PageContext {\n return useNavigation().page\n}\n","/**\n * Imperative, promise-based modal registry — our trimmed adaptation of\n * eBay's `@ebay/nice-modal-react` (MIT). The model: a module-level registry +\n * a reducer-backed store, so any code can `showModal(MyModal)` from anywhere\n * (no prop-drilling, no rendering the modal where you trigger it) and get back a\n * **promise** that resolves when the modal calls `resolve()` — perfect for\n * confirm/upsell/detail flows.\n *\n * Every modal is keyed by a **stable id**, which also makes it natural to bind\n * analytics later (open/close per id, like pages).\n *\n * Pair it with the controlled chrome in {@link ./overlay}: a `defineModal`\n * component renders a `<Sheet open={m.visible} onClose={m.hide}>`/`<Modal>`.\n * The runtime ({@link ./namespaces}.FunnelProvider) mounts {@link ModalRoot} for\n * you, so there's no provider to wire.\n *\n * Trimmed vs upstream: dropped the antd/mui/bootstrap binding adapters and the\n * standalone `<Provider>` (folded into the funnel runtime).\n */\n\nimport {\n createContext,\n createElement,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n type ComponentType,\n type Dispatch,\n type ReactNode,\n} from 'react'\n\n// ── State ────────────────────────────────────────────────\n\nexport interface ModalState {\n id: string\n args?: Record<string, unknown>\n visible?: boolean\n delayVisible?: boolean\n keepMounted?: boolean\n}\nexport interface ModalStore {\n [id: string]: ModalState\n}\ninterface ModalAction {\n type: 'show' | 'hide' | 'remove' | 'set-flags'\n payload: { modalId: string; args?: Record<string, unknown>; flags?: Record<string, unknown> }\n}\ninterface ModalCallbacks {\n [id: string]: { resolve: (v: unknown) => void; reject: (v: unknown) => void; promise: Promise<unknown> }\n}\n\n/** The handle `useModal()` returns to control one modal. */\nexport interface ModalHandler<Props = Record<string, unknown>> {\n id: string\n args?: Record<string, unknown>\n visible: boolean\n keepMounted: boolean\n show: (args?: Props) => Promise<unknown>\n hide: () => Promise<unknown>\n remove: () => void\n /** Resolve the promise returned by `show()` (e.g. a confirm result). */\n resolve: (value?: unknown) => void\n /** Reject the promise returned by `show()`. */\n reject: (value?: unknown) => void\n /** Resolve the promise returned by `hide()` (after a close transition). */\n resolveHide: (value?: unknown) => void\n}\n\n// ── Registry + dispatch ──────────────────────────────────\n\nconst symModalId = Symbol('AppFunnelModalId')\nconst initialState: ModalStore = {}\nconst ModalStateContext = createContext<ModalStore>(initialState)\nconst ModalIdContext = createContext<string | null>(null)\n/** The provider-scoped dispatch — components/hooks always read this, never the module fallback. */\nconst ModalDispatchContext = createContext<Dispatch<ModalAction> | null>(null)\n\nconst REGISTRY: { [id: string]: { comp: ComponentType<any>; props?: Record<string, unknown> } } = {}\nconst ALREADY_MOUNTED: Record<string, boolean> = {}\nconst modalCallbacks: ModalCallbacks = {}\nconst hideCallbacks: ModalCallbacks = {}\n\nlet uid = 0\nconst getUid = () => `_af_modal_${uid++}`\n\n/**\n * Module-level **fallback** dispatch for the imperative API (`showModal` called\n * from plain code with no React context). Runtimes register on a stack in a\n * mount *effect* — never during render, so concurrent SSR renders can't race on\n * it, and a server render (where effects don't run) never touches module state.\n * The imperative API binds to the most recently mounted runtime; inside React,\n * hooks use the provider-scoped {@link ModalDispatchContext} instead.\n */\nconst runtimeStack: Dispatch<ModalAction>[] = []\n\nconst dispatch: Dispatch<ModalAction> = (action) => {\n const top = runtimeStack[runtimeStack.length - 1]\n if (!top) {\n throw new Error('No modal dispatch — render inside <FunnelProvider> (which mounts the modal runtime).')\n }\n top(action)\n}\n\nexport const modalReducer = (state: ModalStore = initialState, action: ModalAction): ModalStore => {\n const { modalId, args, flags } = action.payload\n switch (action.type) {\n case 'show':\n return {\n ...state,\n [modalId]: {\n ...state[modalId],\n id: modalId,\n args,\n // Mount first, then flip visible on the next effect → enter transition.\n visible: !!ALREADY_MOUNTED[modalId],\n delayVisible: !ALREADY_MOUNTED[modalId],\n },\n }\n case 'hide':\n return state[modalId] ? { ...state, [modalId]: { ...state[modalId], visible: false } } : state\n case 'remove': {\n const next = { ...state }\n delete next[modalId]\n return next\n }\n case 'set-flags':\n return { ...state, [modalId]: { ...state[modalId], ...flags } }\n default:\n return state\n }\n}\n\nfunction idOf(modal: string | ComponentType<any>): string {\n if (typeof modal === 'string') return modal\n const m = modal as ComponentType<any> & { [symModalId]?: string }\n if (!m[symModalId]) m[symModalId] = getUid()\n return m[symModalId] as string\n}\n\n// ── Imperative API (callable from anywhere) ──────────────\n\n/** Register a component as an id-keyed modal so the placeholder can render it. */\nexport function registerModal(id: string, comp: ComponentType<any>, props?: Record<string, unknown>): void {\n if (!REGISTRY[id]) REGISTRY[id] = { comp, props }\n else REGISTRY[id].props = props\n}\n\nexport function unregisterModal(id: string): void {\n delete REGISTRY[id]\n}\n\nfunction showModalVia<T = unknown>(\n d: Dispatch<ModalAction>,\n modal: string | ComponentType<any>,\n args?: Record<string, unknown>,\n): Promise<T> {\n const id = idOf(modal)\n if (typeof modal !== 'string' && !REGISTRY[id]) registerModal(id, modal)\n d({ type: 'show', payload: { modalId: id, args } })\n if (!modalCallbacks[id]) {\n let res!: (v: unknown) => void\n let rej!: (v: unknown) => void\n const promise = new Promise<unknown>((resolve, reject) => {\n res = resolve\n rej = reject\n })\n modalCallbacks[id] = { resolve: res, reject: rej, promise }\n }\n return modalCallbacks[id].promise as Promise<T>\n}\n\n/** Show a modal (by component or id). Returns a promise resolved by `resolve()`. */\nexport function showModal<T = unknown>(modal: string | ComponentType<any>, args?: Record<string, unknown>): Promise<T> {\n return showModalVia(dispatch, modal, args)\n}\n\nfunction hideModalVia<T = unknown>(d: Dispatch<ModalAction>, modal: string | ComponentType<any>): Promise<T> {\n const id = idOf(modal)\n d({ type: 'hide', payload: { modalId: id } })\n delete modalCallbacks[id]\n if (!hideCallbacks[id]) {\n let res!: (v: unknown) => void\n let rej!: (v: unknown) => void\n const promise = new Promise<unknown>((resolve, reject) => {\n res = resolve\n rej = reject\n })\n hideCallbacks[id] = { resolve: res, reject: rej, promise }\n }\n return hideCallbacks[id].promise as Promise<T>\n}\n\n/** Hide a modal. Returns a promise resolved by `resolveHide()` (post-transition). */\nexport function hideModal<T = unknown>(modal: string | ComponentType<any>): Promise<T> {\n return hideModalVia(dispatch, modal)\n}\n\nfunction removeModalVia(d: Dispatch<ModalAction>, modal: string | ComponentType<any>): void {\n const id = idOf(modal)\n d({ type: 'remove', payload: { modalId: id } })\n delete modalCallbacks[id]\n delete hideCallbacks[id]\n}\n\n/** Remove a modal from the tree (frees its state; better than just hiding). */\nexport function removeModal(modal: string | ComponentType<any>): void {\n removeModalVia(dispatch, modal)\n}\n\nfunction setFlags(d: Dispatch<ModalAction>, id: string, flags: Record<string, unknown>): void {\n d({ type: 'set-flags', payload: { modalId: id, flags } })\n}\n\n// ── Hook ─────────────────────────────────────────────────\n\nexport function useModal(): ModalHandler\nexport function useModal(modal: string, args?: Record<string, unknown>): ModalHandler\nexport function useModal<P extends object>(modal: ComponentType<P>, args?: Partial<P>): ModalHandler<P>\nexport function useModal(modal?: string | ComponentType<any>, args?: Record<string, unknown>): ModalHandler {\n const modals = useContext(ModalStateContext)\n const contextId = useContext(ModalIdContext)\n // Prefer the provider-scoped dispatch; the module fallback covers hook usage\n // outside <ModalRuntime> (which itself throws a descriptive error).\n const d = useContext(ModalDispatchContext) ?? dispatch\n const isComponent = !!modal && typeof modal !== 'string'\n const id = modal ? idOf(modal) : contextId\n if (!id) throw new Error('useModal: no modal id (call inside a defineModal component, or pass an id/component).')\n\n useEffect(() => {\n if (isComponent && !REGISTRY[id]) registerModal(id, modal as ComponentType<any>, args)\n }, [isComponent, id, modal, args])\n\n const info = modals[id]\n const show = useCallback((a?: Record<string, unknown>) => showModalVia(d, id, a), [d, id])\n const hide = useCallback(() => hideModalVia(d, id), [d, id])\n const remove = useCallback(() => removeModalVia(d, id), [d, id])\n const resolve = useCallback((v?: unknown) => {\n modalCallbacks[id]?.resolve(v)\n delete modalCallbacks[id]\n }, [id])\n const reject = useCallback((v?: unknown) => {\n modalCallbacks[id]?.reject(v)\n delete modalCallbacks[id]\n }, [id])\n const resolveHide = useCallback((v?: unknown) => {\n hideCallbacks[id]?.resolve(v)\n delete hideCallbacks[id]\n }, [id])\n\n return useMemo(\n () => ({\n id,\n args: info?.args,\n visible: !!info?.visible,\n keepMounted: !!info?.keepMounted,\n show,\n hide,\n remove,\n resolve,\n reject,\n resolveHide,\n }),\n [id, info?.args, info?.visible, info?.keepMounted, show, hide, remove, resolve, reject, resolveHide],\n )\n}\n\n// ── defineModal (HOC) ────────────────────────────────────\n\nexport interface ModalHocProps {\n id: string\n defaultVisible?: boolean\n keepMounted?: boolean\n}\n\n/**\n * Wrap a component into an id-keyed modal. Inside it, `useModal()` (no args)\n * gives the handle. Render a controlled `<Sheet>`/`<Modal>` with\n * `open={m.visible} onClose={m.hide}`.\n */\nexport function defineModal<P extends object>(Comp: ComponentType<P>): ComponentType<P & ModalHocProps> {\n return function Wrapped({ id, defaultVisible, keepMounted, ...props }: P & ModalHocProps): ReactNode {\n const { args, show } = useModal(id)\n const modals = useContext(ModalStateContext)\n const d = useContext(ModalDispatchContext) ?? dispatch\n const shouldMount = !!modals[id]\n\n useEffect(() => {\n if (defaultVisible) show()\n ALREADY_MOUNTED[id] = true\n return () => {\n delete ALREADY_MOUNTED[id]\n }\n }, [id, show, defaultVisible])\n\n useEffect(() => {\n if (keepMounted) setFlags(d, id, { keepMounted: true })\n }, [d, id, keepMounted])\n\n const delayVisible = modals[id]?.delayVisible\n useEffect(() => {\n if (delayVisible) show(args)\n }, [delayVisible, args, show])\n\n if (!shouldMount) return null\n return createElement(\n ModalIdContext.Provider,\n { value: id },\n createElement(Comp, { ...(props as P), ...args }),\n )\n }\n}\n\n// ── Runtime (mounted by FunnelProvider) ──────────────────\n\n/** Renders every visible registered modal. Mounted once by the funnel runtime. */\nexport function ModalRoot(): ReactNode {\n const modals = useContext(ModalStateContext)\n const toRender = Object.keys(modals)\n .filter((id) => REGISTRY[id])\n .map((id) => ({ id, ...REGISTRY[id] }))\n return createElement(\n 'div',\n { 'data-appfunnel-modal-root': '' },\n ...toRender.map((t) => createElement(t.comp, { key: t.id, id: t.id, ...t.props })),\n )\n}\n\n/**\n * Provides the modal store + dispatch (context-scoped) + renders {@link ModalRoot}.\n * Wrapped around the funnel tree by `FunnelProvider`.\n *\n * The module-level fallback dispatch (for the imperative `showModal()` API) is\n * bound in a mount **effect** — never during render — so SSR and concurrent\n * renders are safe. With multiple simultaneous providers the imperative API\n * binds to the **most recently mounted** one (a dev warning fires); hooks inside\n * each tree always use their own provider's dispatch via context.\n */\nexport function ModalRuntime({ children }: { children: ReactNode }): ReactNode {\n const [state, localDispatch] = useReducer(modalReducer, initialState)\n useEffect(() => {\n runtimeStack.push(localDispatch)\n if (runtimeStack.length > 1) {\n try {\n console.warn(\n `[appfunnel] ${runtimeStack.length} modal runtimes are mounted — the imperative showModal()/hideModal() API binds to the most recent one. Use the useModal() hook inside each tree instead.`,\n )\n } catch {\n /* no-op */\n }\n }\n return () => {\n const i = runtimeStack.indexOf(localDispatch)\n if (i !== -1) runtimeStack.splice(i, 1)\n }\n }, [])\n return createElement(\n ModalDispatchContext.Provider,\n { value: localDispatch },\n createElement(\n ModalStateContext.Provider,\n { value: state },\n children,\n createElement(ModalRoot, null),\n ),\n )\n}\n","/**\n * Raw, **controlled** overlay chrome — `<Sheet>` (a drawer) and `<Modal>` (a\n * centered dialog). Headless and styleable (className/portal/dismiss), the same\n * two-tier contract as `<Choice>`: thin wrappers you restyle or eject.\n *\n * These are the presentation layer. For *imperative*, promise-based modals\n * triggered from anywhere, wrap one in `defineModal` and `showModal(...)`\n * (see {@link ./modals}) — that registry drives these controlled primitives.\n * They're also used directly (no registry) where local state is simpler, e.g.\n * the checkout `sheet` surface.\n *\n * Deliberately minimal: portal to `document.body`, lock body scroll while open,\n * dismiss on Escape / backdrop. No animation engine, no focus-trap dependency.\n */\n\nimport {\n createElement,\n useEffect,\n type CSSProperties,\n type ReactNode,\n} from 'react'\nimport { createPortal } from 'react-dom'\nimport { useModal } from './registry'\n\nexport type SheetSide = 'bottom' | 'top' | 'left' | 'right'\n\n/**\n * `<Sheet>`/`<Modal>` bind themselves to the surrounding {@link defineModal} via\n * its context — so inside a modal you write just `<Sheet>…</Sheet>`, with no\n * open/onClose plumbing. They are therefore **only valid inside a `defineModal`**\n * (rendered through `showModal`); used anywhere else `useModal()` throws, which\n * is the correct signal. For an overlay driven by local state, wrap it in a\n * `defineModal` and `showModal` it — that's the one overlay path.\n */\nfunction useModalControl(): { open: boolean; onClose: () => void } {\n const m = useModal()\n return {\n open: m.visible,\n onClose: () => {\n m.hide()\n m.resolveHide()\n if (!m.keepMounted) m.remove()\n },\n }\n}\n\ninterface OverlayCommon {\n className?: string\n backdropClassName?: string\n dismissOnBackdrop?: boolean\n ariaLabel?: string\n children: ReactNode\n}\n\ninterface ShellProps {\n open: boolean\n onClose: () => void\n className?: string\n backdropClassName?: string\n dismissOnBackdrop?: boolean\n ariaLabel?: string\n /** Flexbox alignment of the panel within the viewport. */\n container: Pick<CSSProperties, 'justifyContent' | 'alignItems'>\n /** Panel layout (size + corners per variant). */\n panel: CSSProperties\n children: ReactNode\n}\n\n/** Shared overlay shell: portal, backdrop, scroll-lock, Escape — variant-agnostic. */\nfunction OverlayShell({\n open,\n onClose,\n className,\n backdropClassName,\n dismissOnBackdrop = true,\n ariaLabel,\n container,\n panel,\n children,\n}: ShellProps): ReactNode {\n useEffect(() => {\n if (!open || typeof document === 'undefined') return\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') onClose()\n }\n const prev = document.body.style.overflow\n document.body.style.overflow = 'hidden'\n document.addEventListener('keydown', onKey)\n return () => {\n document.body.style.overflow = prev\n document.removeEventListener('keydown', onKey)\n }\n }, [open, onClose])\n\n if (!open || typeof document === 'undefined') return null\n\n const overlay = createElement(\n 'div',\n {\n role: 'dialog',\n 'aria-modal': true,\n 'aria-label': ariaLabel,\n 'data-appfunnel-overlay': '',\n style: { position: 'fixed', inset: 0, zIndex: 1000, display: 'flex', ...container },\n },\n createElement('div', {\n 'data-appfunnel-overlay-backdrop': '',\n className: backdropClassName,\n onClick: dismissOnBackdrop ? onClose : undefined,\n style: { position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)' },\n }),\n createElement(\n 'div',\n { 'data-appfunnel-overlay-panel': '', className, style: { position: 'relative', background: '#fff', ...panel } },\n children,\n ),\n )\n\n return createPortal(overlay, document.body)\n}\n\nexport type SheetProps = OverlayCommon & {\n /** Edge the drawer slides from (default `bottom`). */\n side?: SheetSide\n}\n\nconst SHEET_LAYOUT: Record<SheetSide, { container: ShellProps['container']; panel: CSSProperties }> = {\n bottom: { container: { justifyContent: 'flex-end', alignItems: 'stretch' }, panel: { borderTopLeftRadius: 16, borderTopRightRadius: 16, padding: 16, maxHeight: '90vh', overflow: 'auto' } },\n top: { container: { justifyContent: 'flex-start', alignItems: 'stretch' }, panel: { borderBottomLeftRadius: 16, borderBottomRightRadius: 16, padding: 16, maxHeight: '90vh', overflow: 'auto' } },\n left: { container: { justifyContent: 'flex-start', alignItems: 'stretch' }, panel: { height: '100%', width: 'min(420px, 90vw)', padding: 16, overflow: 'auto' } },\n right: { container: { justifyContent: 'flex-end', alignItems: 'stretch' }, panel: { height: '100%', width: 'min(420px, 90vw)', padding: 16, overflow: 'auto' } },\n}\n\n/**\n * An edge-anchored drawer. Inside a `defineModal` it auto-binds — `<Sheet>…`;\n * outside one, control it with `open`/`onClose`.\n */\nexport function Sheet(props: SheetProps): ReactNode {\n const control = useModalControl()\n const layout = SHEET_LAYOUT[props.side ?? 'bottom']\n return createElement(OverlayShell, {\n ...control,\n className: props.className,\n backdropClassName: props.backdropClassName,\n dismissOnBackdrop: props.dismissOnBackdrop,\n ariaLabel: props.ariaLabel,\n container: layout.container,\n panel: layout.panel,\n children: props.children,\n })\n}\n\nexport type ModalProps = OverlayCommon\n\n/** A centered dialog. Auto-binds to its `defineModal` — `<Modal>…`. */\nexport function Modal(props: ModalProps): ReactNode {\n const control = useModalControl()\n return createElement(OverlayShell, {\n ...control,\n className: props.className,\n backdropClassName: props.backdropClassName,\n dismissOnBackdrop: props.dismissOnBackdrop,\n ariaLabel: props.ariaLabel,\n container: { justifyContent: 'center', alignItems: 'center' },\n panel: { borderRadius: 16, padding: 24, width: 'min(480px, 92vw)', maxHeight: '90vh', overflow: 'auto' },\n children: props.children,\n })\n}\n","/**\n * v2 commerce primitives — the two intents from phase-3, made trivial.\n *\n * - `<Checkout product surface>` — the **purchase** primitive. The `surface`\n * prop picks presentation; some surfaces render **inline** (express wallets,\n * inline card, provider iframe), some **open on click** (sheet/popup/redirect).\n * `<Checkout>` covers both: it renders inline surfaces and renders a trigger\n * button for the rest (`asChild` to use your own button).\n * - `<Upsell product>` — the **upsell** primitive. Off-session charge to the\n * saved method, no card re-entry, one tap.\n * - `useCheckout()` — the headless hook under both, always available for a\n * fully-custom CTA.\n *\n * The SDK never talks to a provider. It owns the state machine + the analytics\n * (`checkout.start` / `purchase.complete`) + post-charge navigation, and\n * delegates the actual charge/render to an injected {@link CheckoutDriver}\n * (the real one is platform-side; tests use {@link createMockDriver}).\n *\n * Which product is charged is the author's bound variable, captured at render\n * (inline surfaces) or at `open()` time (trigger surfaces).\n */\n\nimport {\n createContext,\n createElement,\n isValidElement,\n cloneElement,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n type ComponentType,\n type ReactElement,\n type ReactNode,\n} from 'react'\nimport { useTrackerRef } from '../tracking/tracking'\nimport { useNavigation } from '../flow/flow'\nimport { Sheet } from '../modals/sheet'\nimport { defineModal, useModal, showModal } from '../modals/registry'\nimport {\n checkoutError,\n isInlineSurface,\n PROVIDER_PROFILES,\n type CheckoutError,\n type CheckoutErrorCategory,\n type CheckoutIntent,\n type CheckoutProvider,\n type CheckoutSurface,\n type UpsellKind,\n} from './capabilities'\n\n// ── Capability matrix (pure — lives in ./capabilities, ships via the manifest\n// entry so the API/editor/AI run the SAME checks; re-exported here so every\n// existing import keeps working) ───────────────────────\nexport {\n INLINE_SURFACES,\n PROVIDER_PROFILES,\n checkoutError,\n isInlineSurface,\n isMerchantOfRecord,\n isOrchestrator,\n surfacesFor,\n validateCheckout,\n validateUpsell,\n} from './capabilities'\nexport type {\n CheckoutError,\n CheckoutErrorCategory,\n CheckoutIntent,\n CheckoutProvider,\n CheckoutSurface,\n OffSessionReliability,\n ProviderProfile,\n SurfaceCapability,\n UpsellKind,\n ValidationResult,\n} from './capabilities'\n\n// ── Driver seam ──────────────────────────────────────────\n\nexport type CheckoutStatus = 'idle' | 'loading' | 'requires_action' | 'success' | 'error'\n\nexport interface CheckoutRequest {\n /** The product SLOT the page named (`<Checkout product=\"primary\">`) — the display/analytics identity. */\n product: string\n /** The catalog product KEY charged — the CHARGE identity, resolved from `product` by {@link driverWithCatalog}. */\n catalogKey?: string\n intent: CheckoutIntent\n surface?: CheckoutSurface\n /** For `upsell` intent — which kind of off-session charge (default `subscription`). */\n kind?: UpsellKind\n /**\n * Buyer email at attempt time, read from the funnel's `user.email` namespace value\n * (injected by `FunnelProvider` via {@link driverWithEmail} — no author wiring).\n * Drivers forward it into the wire `CheckoutSessionRequest.email` (Stripe Customer\n * creation / receipts / Paddle prefill).\n */\n email?: string\n}\n\nexport interface CheckoutResult {\n ok: boolean\n error?: CheckoutError\n /** Charged amount in minor units (for the purchase event). */\n amountMinor?: number\n currency?: string\n /**\n * The **server-minted** dedup id for the purchase event — the platform creates it\n * when the charge settles and fires CAPI with it; the SDK emits `purchase.complete`\n * with the same id so the browser pixel dedupes against the server. (Server is the\n * source of truth for payment events; the SDK doesn't mint these.)\n */\n eventId?: string\n}\n\nexport interface CheckoutCallbacks {\n onSuccess: (result: CheckoutResult) => void\n onError: (error: CheckoutError) => void\n /**\n * The buyer SUBMITTED an inline surface (Stripe confirm click / wallet\n * authorization; Paddle inline checkout opening). This is when `checkout.start`\n * fires and the status machine enters `loading` for inline attempts — trigger\n * surfaces fire it at click time instead. It also marks fresh user intent, so\n * the once-per-chain recovery guard resets. Optional: drivers that can't\n * observe submit simply never call it, and the SHEET host deliberately doesn't\n * forward it (the sheet's own open already began the attempt — re-firing would\n * double-count starts and un-arm the recovery guard mid-chain).\n */\n onStart?: () => void\n /**\n * The inline surface reports a valid payment method was entered (e.g. Stripe's\n * Payment Element became `complete`), before the charge. Drives the\n * `checkout.payment_added` analytics step; optional — drivers that can't observe\n * it (or off-session charges) simply never call it.\n */\n onPaymentAdded?: () => void\n}\n\n/**\n * What a driver factory (`stripeCheckoutDriver` et al. from the\n * `@appfunnel-dev/sdk/driver-*` entries) receives to construct a\n * {@link CheckoutDriver}. Derived by `createFunnelTree` from the SAME\n * renderer-injected mount data the platform tracker uses (tracking config +\n * identity), so checkout wire calls land on the exact campaign/funnel/session\n * the analytics do — there is no second config channel to drift.\n *\n * Serializable on purpose, and factories must be **construction-safe on the\n * server too**: a factory only closes over this ctx (no provider SDK, no\n * `window`) — all provider work belongs in effects/event handlers, so SSR can\n * render the driver's stable inline placeholder and hydration matches.\n */\nexport interface CheckoutDriverContext {\n /** Public API origin, e.g. `https://api.appfunnel.net` (no trailing slash). */\n apiBase: string\n /** Campaign DB id (the checkout route key, same as the ingestion route key). */\n campaignId: string\n /** WebFunnel DB id (NOT the funnel.ts config id). */\n funnelId: string\n /** Render-time mode — the server resolves the product binding + store credentials by it. */\n mode: 'test' | 'live'\n /** Funnel session id when one exists (analytics + customer continuity). */\n sessionId?: string | null\n /** Signed-cookie-verified bare visitor id, when known. */\n visitorId?: string | null\n}\n\n/**\n * The provider seam. The platform injects the real one (Stripe/Paddle/Whop/…);\n * tests use {@link createMockDriver}.\n *\n * Most providers ship their **own React SDK** (`@stripe/react-stripe-js`,\n * `@paddle/paddle-js`, Primer's React components, …). A driver's `renderInline`\n * returns exactly that: the provider's React element mounted in our chrome (inline,\n * or inside the `<Sheet>`). Those provider SDKs live in the **driver/platform**\n * package, not our core funnel SDK — which is why the driver is injected: the core\n * stays lean and provider-agnostic, and you only pull the SDK for the provider you use.\n */\nexport interface CheckoutDriver {\n provider: CheckoutProvider\n /** Trigger a charge (trigger surfaces + programmatic). Resolves when settled. */\n start(req: CheckoutRequest): Promise<CheckoutResult>\n /** Render an inline surface (e.g. the provider's React payment element); report via callbacks. */\n renderInline?(req: CheckoutRequest, cb: CheckoutCallbacks): ReactNode\n /**\n * Verify an EXISTING attempt with the server (`POST /complete`, bounded re-poll on\n * `pending`) — the redirect-return resume leg: hosted-checkout success URLs carry\n * `?af_checkout={correlationId}` back into the funnel, and {@link CheckoutResume}\n * hands the id here so the settlement (server-verified) resolves into the normal\n * success/failure paths. Never charges; only verifies.\n */\n resume?(correlationId: string): Promise<CheckoutResult>\n}\n\nexport interface MockDriverOptions {\n /** The result a successful charge resolves with. */\n result?: CheckoutResult\n /** Make **off-session** charges (no surface) fail — to exercise the upsell fallback. */\n failOffSession?: CheckoutError | boolean\n}\n\n/** A console/no-op driver — tests, preview, local dev. Succeeds unless configured to fail. */\nexport function createMockDriver(\n provider: CheckoutProvider = 'stripe',\n options: MockDriverOptions = {},\n): CheckoutDriver {\n const success: CheckoutResult = options.result ?? { ok: true, amountMinor: 0, currency: 'USD' }\n const offError: CheckoutError =\n typeof options.failOffSession === 'object'\n ? options.failOffSession\n : checkoutError('authentication_required', 'off-session charge declined (mock)')\n return {\n provider,\n start: (req) => {\n if (options.failOffSession && !req.surface) return Promise.resolve({ ok: false, error: offError })\n return Promise.resolve(success)\n },\n renderInline: (req, cb) =>\n createElement(\n 'button',\n {\n type: 'button',\n 'data-mock-surface': req.surface,\n onClick: () => {\n cb.onStart?.() // user submit — mirrors the real drivers (checkout.start for inline)\n if (success.ok) cb.onSuccess(success)\n else cb.onError(success.error ?? checkoutError('processing_error', 'failed (mock)'))\n },\n },\n `Pay (mock ${req.surface})`,\n ),\n resume: () => Promise.resolve(success),\n }\n}\n\n/**\n * Wrap a driver so every attempt carries the buyer email the funnel has collected\n * (`user.email`), read at ATTEMPT time — `start()` for trigger surfaces, the\n * `renderInline` request for mounted surfaces. Applied by `FunnelProvider` around\n * the injected driver, so `useCheckout`, `<Checkout>` inline branches and the\n * checkout sheet all forward it without wiring; drivers pass it into the wire's\n * `CheckoutSessionRequest.email`. An explicit `req.email` always wins.\n */\nexport function driverWithEmail(driver: CheckoutDriver, getEmail: () => string | undefined): CheckoutDriver {\n const enrich = (req: CheckoutRequest): CheckoutRequest =>\n req.email !== undefined ? req : { ...req, email: getEmail() }\n return {\n ...driver,\n start: (req) => driver.start(enrich(req)),\n renderInline: driver.renderInline ? (req, cb) => driver.renderInline!(enrich(req), cb) : undefined,\n }\n}\n\n/**\n * Resolve the product SLOT (`req.product`, e.g. `'primary'`) to its assigned catalog KEY\n * (`req.catalogKey`, e.g. `'pro-monthly'`) on every attempt, from the funnel's resolved catalog map.\n * Applied by `FunnelProvider` around the driver so `<Checkout product=\"primary\">` puts the slot on\n * the wire while the driver charges the real catalog key — the driver never learns what a slot is,\n * and page code can only name a slot the funnel declares (the server can't be handed an arbitrary\n * catalog key). An explicit `req.catalogKey` always wins.\n */\nexport function driverWithCatalog(\n driver: CheckoutDriver,\n catalog: ReadonlyMap<string, { catalogKey: string }>,\n): CheckoutDriver {\n const enrich = (req: CheckoutRequest): CheckoutRequest =>\n req.catalogKey !== undefined ? req : { ...req, catalogKey: catalog.get(req.product)?.catalogKey }\n return {\n ...driver,\n start: (req) => driver.start(enrich(req)),\n renderInline: driver.renderInline ? (req, cb) => driver.renderInline!(enrich(req), cb) : undefined,\n }\n}\n\nconst DriverContext = createContext<CheckoutDriver | null>(null)\n\nexport function CheckoutDriverProvider({\n driver,\n children,\n}: {\n driver: CheckoutDriver\n children: ReactNode\n}): ReactNode {\n return createElement(DriverContext.Provider, { value: driver }, children)\n}\n\nfunction useDriver(): CheckoutDriver {\n return useContext(DriverContext) ?? FALLBACK_DRIVER\n}\nconst FALLBACK_DRIVER = createMockDriver()\n\n// ── Failure routing (the recovery \"magic\") ───────────────\n\n/** One declarative recovery route for a failure category. */\nexport type FailureRoute =\n | { go: string } // navigate the flow to a page key (e.g. a real-card recapture page)\n | { modal: string | ComponentType<any> } // show a registry modal — it receives {@link FailureModalProps}\n | { fallback: CheckoutSurface } // re-collect a card ON-SESSION on this surface and retry (once)\n | ((error: CheckoutError) => void) // full control\n\n/**\n * What a `{ modal }` failure route hands the modal — the error AND the actions,\n * because registry modals mount outside the flow's nav context and a recovery\n * modal that can't act is just an error toast. Type your modal with this:\n *\n * ```tsx\n * const Declined = defineModal<FailureModalProps>(({ error, go, retry }) => (\n * <Sheet>\n * <p>{error.category === 'prepaid_card' ? 'Prepaid cards can't start a trial.' : 'Payment didn't go through.'}</p>\n * <button onClick={() => retry('sheet')}>Try another card</button>\n * <button onClick={() => go('downsell')}>See the lite plan</button>\n * </Sheet>\n * ))\n * ```\n *\n * A modal can also host a whole `<Checkout product=\"…\" surface=\"element\" />` for\n * an inline downsell — the driver context is app-level, so checkout works inside\n * modals as-is.\n */\nexport interface FailureModalProps {\n error: CheckoutError\n /** The product whose charge failed (absent only for product-less failures). */\n product?: string\n /** Navigate the flow to a page key (modals can't call useNavigation themselves). */\n go: (pageKey: string) => void\n /**\n * Re-attempt the SAME product. `retry()` re-runs an upsell off-session; for a\n * purchase (which needs UI to re-collect) it opens the payment sheet.\n * `retry('sheet')` re-collects on the SDK sheet; an inline surface\n * (`element`/`express`/`embedded`) is COERCED to the sheet when the provider\n * supports it — a retry has no page slot to mount into, so the sheet hosts the\n * element. On sheet-less MoR providers (Paddle) inline retries run through the\n * driver, whose provider checkout opens its own overlay. `retry('popup')` /\n * `retry('redirect')` hand off to the provider. A failed retry routes through\n * `onFailed` again (the modal reopens) — the loop is user-driven, never\n * automatic. Hide the modal first (`useModal().hide()`) when retrying into a\n * surface that opens its own overlay.\n */\n retry: (surface?: CheckoutSurface) => void\n}\n\n/**\n * Declarative failure recovery — route each failure **category** to what happens\n * next, instead of hand-wiring `onError`:\n *\n * ```tsx\n * <Checkout product=\"monthly\" surface=\"element\" onFailed={{\n * prepaid_card: { go: 'real-card' },\n * insufficient_funds: { modal: DownsellModal },\n * default: { modal: TryAgainModal },\n * }} />\n * ```\n *\n * Resolution: exact category → `default` → nothing (the error state + `checkout.\n * failed` event stand, as today). Two built-in judgments:\n * - `canceled` only routes when mapped EXPLICITLY — a deliberately dismissed\n * sheet/popup is not a failure to recover from, so `default` never catches it;\n * - a `{ fallback }` recovery runs at most once per attempt chain (its own\n * failure routes through the non-fallback routes), so declines can't loop.\n *\n * `checkout.failed` fires with category + declineCode on every failure regardless\n * of routing — recovery pages are measurable, and being ordinary flow pages they\n * are A/B-able with page experiments like anything else.\n */\nexport type OnFailedMap = Partial<Record<CheckoutErrorCategory | 'default', FailureRoute>>\n\n// ── The headless hook ────────────────────────────────────\n\nexport interface UseCheckoutOptions {\n intent?: CheckoutIntent\n /** For `upsell` intent — which kind of off-session charge (default `subscription`). */\n kind?: UpsellKind\n /** Advance to the next page after a successful charge (default: true). */\n advanceOnSuccess?: boolean\n onSuccess?: (result: CheckoutResult) => void\n onError?: (error: CheckoutError) => void\n /** Declarative failure recovery — see {@link OnFailedMap}. Runs AFTER `onError`. */\n onFailed?: OnFailedMap\n /**\n * Try this surface ON-SESSION once on any first failure, before `onFailed`\n * routing — the generalized `<Upsell fallback>`: the off-session (or first)\n * charge fails, the surface re-collects a card, the retry's failure then goes\n * through `onFailed`. Never re-triggered by its own failure; never triggered\n * by a user-`canceled` checkout.\n */\n recoverySurface?: CheckoutSurface\n}\n\nexport interface CheckoutHandle {\n /** Start the charge for a product; resolves with the result (no surface = off-session). */\n open: (product: string, surface?: CheckoutSurface) => Promise<CheckoutResult>\n status: CheckoutStatus\n /** The last failure, structured so you can route/recover by `category`. */\n error: CheckoutError | null\n isLoading: boolean\n reset: () => void\n /** Build the callbacks an inline surface reports through (used by `<Checkout>`). */\n callbacksFor: (product?: string, surface?: CheckoutSurface) => CheckoutCallbacks & { onStart: () => void }\n}\n\n/**\n * The headless checkout hook. Owns the state machine + analytics + post-charge\n * navigation; delegates the charge to the injected {@link CheckoutDriver}.\n */\nexport function useCheckout(opts: UseCheckoutOptions = {}): CheckoutHandle {\n const driver = useDriver()\n const tracker = useTrackerRef()\n const nav = useNavigation()\n const [status, setStatus] = useState<CheckoutStatus>('idle')\n const [error, setError] = useState<CheckoutError | null>(null)\n\n const intent = opts.intent ?? 'purchase'\n const kind = opts.kind\n const advance = opts.advanceOnSuccess ?? true\n\n // True while an on-session recovery attempt (recoverySurface / a `{ fallback }`\n // route) is in flight — its own failure must not start ANOTHER re-collect, so\n // declines can't loop. Cleared on every fresh user-initiated attempt.\n const recovering = useRef(false)\n // fail → startRecovery → (sheet/attempt) → fail is mutually recursive; refs give\n // the cycle stable identities so the returned handle doesn't churn per render.\n const failRef = useRef<(err: CheckoutError, product?: string) => void>(() => {})\n const attemptRef = useRef<(product: string, surface?: CheckoutSurface) => Promise<CheckoutResult>>(\n async () => ({ ok: false }),\n )\n\n const succeed = useCallback(\n (result: CheckoutResult) => {\n setStatus('success')\n tracker.track('purchase.complete', {\n amount: result.amountMinor != null ? result.amountMinor / 100 : undefined,\n currency: result.currency,\n eventId: result.eventId, // server-minted (browser↔CAPI dedup); undefined if none\n })\n opts.onSuccess?.(result)\n if (advance) nav.next()\n },\n [tracker, nav, advance, opts],\n )\n const succeedRef = useRef(succeed)\n succeedRef.current = succeed\n\n const begin = useCallback(\n (product?: string, surface?: CheckoutSurface) => {\n setStatus('loading')\n setError(null)\n tracker.track('checkout.start', { productId: product, surface })\n },\n [tracker],\n )\n\n const paymentAdded = useCallback(() => tracker.track('checkout.payment_added', {}), [tracker])\n\n // Open the on-session recovery surface for a product. A recovery has no page slot\n // to mount UI into, so surfaces that need one route through our sheet: `sheet`\n // itself, and inline surfaces WHEN the provider supports the sheet (Stripe et al.\n // — an element/express recovery is the same client_confirm hosted in the sheet).\n // Everything else (popup/redirect, and inline on sheet-less MoR providers like\n // Paddle, whose provider_checkout opens its OWN overlay) runs through the driver.\n const hostInSheet = (surface: CheckoutSurface): boolean =>\n surface === 'sheet' ||\n (isInlineSurface(surface) && !!PROVIDER_PROFILES[driver.provider]?.surfaces.sheet)\n const startRecovery = (product: string, surface: CheckoutSurface) => {\n recovering.current = true\n if (hostInSheet(surface)) {\n begin(product, 'sheet')\n void showModal(CheckoutSheet, {\n product,\n surface: 'sheet',\n intent,\n kind,\n onSuccess: (r: CheckoutResult) => succeedRef.current(r),\n onError: (e: CheckoutError) => failRef.current(e, product),\n onPaymentAdded: () => paymentAdded(),\n })\n } else {\n void attemptRef.current(product, surface)\n }\n }\n\n failRef.current = (err: CheckoutError, product?: string) => {\n // 3DS/SCA that an off-session charge can't satisfy → flag for recovery.\n setStatus(err.category === 'authentication_required' ? 'requires_action' : 'error')\n setError(err)\n tracker.track('checkout.failed', {\n category: err.category,\n declineCode: err.declineCode,\n productId: product,\n intent,\n })\n opts.onError?.(err)\n\n // A deliberately dismissed checkout routes only when 'canceled' is mapped\n // EXPLICITLY — recovery machinery must not chase a user who closed the sheet.\n if (err.category === 'canceled' && !opts.onFailed?.canceled) return\n // First failure + a recovery surface → re-collect on-session, ONCE; the\n // retry's failure falls through to onFailed below.\n if (product && !recovering.current && opts.recoverySurface && err.category !== 'canceled') {\n startRecovery(product, opts.recoverySurface)\n return\n }\n let route = opts.onFailed?.[err.category] ?? (err.category === 'canceled' ? undefined : opts.onFailed?.default)\n // The documented `{ fallback }` fall-through: a fallback runs at most once per\n // attempt chain, so once a recovery is in flight the RECOVERY's own failure\n // resolves the DEFAULT route instead — unless the default is itself a fallback\n // (or was the resolved route), in which case the error state stands.\n if (route && typeof route === 'object' && 'fallback' in route && recovering.current) {\n const dflt = opts.onFailed?.default\n route =\n dflt && dflt !== route && !(typeof dflt === 'object' && 'fallback' in dflt) ? dflt : undefined\n }\n if (!route) return\n if (typeof route === 'function') route(err)\n else if ('go' in route) nav.go(route.go)\n else if ('modal' in route) {\n // Hand the modal the ACTIONS, not just the error (FailureModalProps) — the\n // registry host mounts outside the nav context, so these closures are the\n // modal's only way to move the flow or re-charge.\n const props: FailureModalProps = {\n error: err,\n product,\n go: (pageKey: string) => nav.go(pageKey),\n retry: (surface?: CheckoutSurface) => {\n if (!product) return\n recovering.current = true // a retry's failure routes again; it never auto-recovers on top\n if (!surface) {\n // Bare retry: an upsell re-runs off-session; a purchase needs UI to\n // re-collect a card — the sheet where the provider supports it, else\n // the provider's own overlay (popup).\n if (intent === 'upsell') void attemptRef.current(product)\n else startRecovery(product, PROVIDER_PROFILES[driver.provider]?.surfaces.sheet ? 'sheet' : 'popup')\n return\n }\n // startRecovery routes it: surfaces needing a MOUNTED UI go through the\n // SAME CheckoutSheet machinery the recovery path uses — driver.start\n // cannot mount React UI, so routing them there would dead-end and mint\n // orphan attempts. popup/redirect (and Paddle's own-overlay inline) are\n // driver-run hand-offs.\n startRecovery(product, surface)\n },\n }\n void showModal(route.modal, props as unknown as Record<string, unknown>)\n } else if ('fallback' in route) {\n if (product && !recovering.current) startRecovery(product, route.fallback)\n }\n }\n\n attemptRef.current = async (product: string, surface?: CheckoutSurface): Promise<CheckoutResult> => {\n begin(product, surface)\n try {\n const result = await driver.start({ product, intent, surface, kind })\n if (result.ok) succeedRef.current(result)\n else failRef.current(result.error ?? checkoutError('unknown', 'Checkout failed'), product)\n return result\n } catch (e) {\n const err = checkoutError('processing_error', e instanceof Error ? e.message : 'Checkout failed')\n failRef.current(err, product)\n return { ok: false, error: err }\n }\n }\n\n const open = useCallback(async (product: string, surface?: CheckoutSurface): Promise<CheckoutResult> => {\n recovering.current = false // fresh user-initiated attempt chain\n return attemptRef.current(product, surface)\n }, [])\n\n const callbacksFor = useCallback(\n (product?: string, surface?: CheckoutSurface) => ({\n onStart: () => {\n recovering.current = false // fresh user-initiated attempt chain\n begin(product, surface)\n },\n onSuccess: (result: CheckoutResult) => succeedRef.current(result),\n onError: (err: CheckoutError) => failRef.current(err, product),\n onPaymentAdded: () => paymentAdded(),\n }),\n [begin, paymentAdded],\n )\n\n const reset = useCallback(() => {\n recovering.current = false\n setStatus('idle')\n setError(null)\n }, [])\n\n return { open, status, error, isLoading: status === 'loading', reset, callbacksFor }\n}\n\n// ── The components ───────────────────────────────────────\n\nexport interface CheckoutProps extends UseCheckoutOptions {\n /** Logical product id (the author's bound selection). */\n product: string\n surface: CheckoutSurface\n /** Render your own trigger element instead of the default button (trigger surfaces). */\n asChild?: boolean\n /** Trigger label / your trigger element. */\n children?: ReactNode\n className?: string\n}\n\n/**\n * The `sheet` surface as a registry modal: our {@link Sheet} hosts the driver's\n * element. It resolves outcomes by invoking the callbacks passed via `showModal`\n * args — closures created in the `<Checkout>` trigger (which lives inside\n * `<FunnelView>`, so they carry navigation).\n *\n * EVERY exit resolves exactly once: success/failure through the driver callbacks,\n * and a dismissal (backdrop/Escape unmounts the modal) as `canceled` — otherwise\n * the attempt's status would sit in `loading` forever, permanently disabling the\n * trigger. `canceled` then follows the built-in judgment: status → `error`,\n * `checkout.failed` fires, but `onFailed` routes it only when mapped explicitly.\n * `onStart` is deliberately NOT forwarded to the hosted element — the sheet's\n * open already began the attempt (see {@link CheckoutCallbacks.onStart}).\n */\nconst CheckoutSheet = defineModal<{\n product: string\n surface: CheckoutSurface\n intent: CheckoutIntent\n kind?: UpsellKind\n onSuccess: (result: CheckoutResult) => void\n onError: (error: CheckoutError) => void\n onPaymentAdded?: () => void\n}>(({ product, surface, intent, kind, onSuccess, onError, onPaymentAdded }) => {\n const driver = useDriver()\n const modal = useModal()\n // True once ANY outcome was reported — the unmount cleanup below only converts a\n // silent dismissal into `canceled`, never doubles a real outcome.\n const resolved = useRef(false)\n const onErrorRef = useRef(onError)\n onErrorRef.current = onError\n const hostable = !!driver.renderInline\n useEffect(() => {\n if (!hostable) {\n // Defensive: a driver with no inline surface cannot host the sheet — resolve\n // the attempt instead of leaving the trigger stuck in `loading`.\n resolved.current = true\n onErrorRef.current(\n checkoutError('processing_error', 'This checkout driver has no inline surface to host in the sheet'),\n )\n void modal.hide()\n modal.remove()\n return\n }\n return () => {\n // Backdrop/Escape dismissal removes the modal (unmount) without an outcome.\n if (!resolved.current) {\n onErrorRef.current(checkoutError('canceled', 'Checkout was dismissed before completing'))\n }\n }\n // Mount-scoped by design: resolution is tracked through refs.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n if (!driver.renderInline) return null\n // Outcomes REMOVE the modal (not just hide it): the next show mounts fresh, so\n // the resolution ref can never leak a previous attempt's state into a new one.\n const close = () => {\n resolved.current = true\n void modal.hide()\n modal.remove()\n }\n return createElement(Sheet, {\n children: driver.renderInline(\n { product, intent, surface, kind },\n {\n onSuccess: (r) => { close(); onSuccess(r) },\n onError: (e) => { close(); onError(e) },\n onPaymentAdded,\n },\n ),\n })\n})\n\n/** Render the default trigger button, or clone the author's `asChild` element. */\nfunction trigger(\n onClick: () => void,\n { asChild, children, className, disabled }: { asChild?: boolean; children?: ReactNode; className?: string; disabled?: boolean },\n): ReactNode {\n if (asChild && isValidElement(children)) {\n const child = children as ReactElement<{ onClick?: () => void }>\n return cloneElement(child, { onClick })\n }\n return createElement('button', { type: 'button', className, disabled, onClick }, children ?? 'Continue')\n}\n\n/**\n * The purchase primitive. Three presentation modes by `surface`:\n * - **inline** (`express`/`element`/`embedded`) — the driver renders the\n * provider UI in place (keyed by product so a selection change remounts it);\n * - **SDK sheet** (`sheet`) — a trigger opens the AppFunnel-owned {@link Sheet}\n * and the driver renders the provider element inside it;\n * - **provider-hosted** (`popup`/`redirect`) — a trigger hands off to the\n * provider's own overlay/page.\n */\nexport function Checkout({\n product,\n surface,\n asChild,\n children,\n className,\n ...options\n}: CheckoutProps): ReactNode {\n const driver = useDriver()\n const checkout = useCheckout(options)\n const intent = options.intent ?? 'purchase'\n\n // Inline: driver renders the mounted UI; keyed by product so changing the\n // selected plan cleanly remounts the surface.\n if (isInlineSurface(surface)) {\n return driver.renderInline\n ? createElement(\n 'div',\n { key: product, className },\n driver.renderInline({ product, intent, surface }, checkout.callbacksFor(product, surface)),\n )\n : null\n }\n\n // SDK sheet: open our overlay (a registry modal) hosting the driver's element.\n if (surface === 'sheet') {\n const cb = checkout.callbacksFor(product, surface)\n const open = () => {\n cb.onStart()\n showModal(CheckoutSheet, {\n product,\n surface,\n intent,\n kind: options.kind,\n onSuccess: cb.onSuccess,\n onError: cb.onError,\n onPaymentAdded: cb.onPaymentAdded,\n })\n }\n return trigger(open, { asChild, children, className, disabled: checkout.isLoading })\n }\n\n // Provider-hosted (popup/redirect): trigger hands off to the provider.\n return trigger(() => checkout.open(product, surface), {\n asChild,\n children,\n className,\n disabled: checkout.isLoading,\n })\n}\n\nexport interface UpsellProps extends Omit<UseCheckoutOptions, 'intent'> {\n product: string\n /**\n * If the off-session charge fails, present this surface **on-session** to\n * re-collect a card and charge again — e.g. `fallback=\"sheet\"` opens the\n * payment sheet, `fallback=\"popup\"` the provider overlay. Omit to just report\n * the failure (via `onError` / the `checkout.failed` event).\n */\n fallback?: CheckoutSurface\n asChild?: boolean\n children?: ReactNode\n className?: string\n}\n\n/**\n * The upsell primitive — an off-session, one-tap charge to the saved method (no\n * surface, no card re-entry). On failure, optionally `fallback` to an on-session\n * surface to re-collect and retry — `fallback` IS the hook's `recoverySurface`,\n * so the retry's own failure routes through `onFailed` (e.g. prepaid_card → a\n * recapture page) instead of dead-ending.\n */\nexport function Upsell({ product, fallback, asChild, children, className, ...options }: UpsellProps): ReactNode {\n const checkout = useCheckout({\n ...options,\n intent: 'upsell',\n recoverySurface: fallback ?? options.recoverySurface,\n })\n\n return trigger(() => void checkout.open(product) /* off-session (no surface) */, {\n asChild,\n children: children ?? 'Add to my plan',\n className,\n disabled: checkout.isLoading,\n })\n}\n\n// ── Redirect-return resume (hosted checkout success URLs) ────────────────────\n\n/** correlationIds this page load already resumed — the leg runs once per attempt\n * even if the component remounts (StrictMode, page-experiment remounts). */\nconst consumedResumes = new Set<string>()\n\n/**\n * The dangling settle leg of the `redirect` surface. The server appends\n * `af_checkout={correlationId}` to hosted-checkout success URLs; when the buyer\n * lands back in the funnel this component detects the param, has the server\n * VERIFY the attempt (`driver.resume` → `POST /complete`, bounded re-poll while\n * `pending`), and resolves it into the normal machinery:\n *\n * - `settled` → `purchase.complete` fires with the settlement's server-minted\n * `eventId` (pixel↔CAPI dedup), the flow advances, and the param is stripped\n * (`history.replaceState`) so a reload can't re-run the leg;\n * - `failed` → the normal failure path (`checkout.failed` + status `error`;\n * any `onFailed` maps passed as props apply — product-less, so only\n * `go`/handler routes can act).\n *\n * SSR-safe (effect-only) and runs once per correlationId per page load. Mounted\n * automatically by `createFunnelTree` inside the nav context; needs a driver\n * with `resume` (both platform drivers ship it; the mock resolves its result).\n */\nexport function CheckoutResume(options: UseCheckoutOptions = {}): ReactNode {\n const driver = useDriver()\n const checkout = useCheckout(options)\n const callbacksRef = useRef(checkout.callbacksFor)\n callbacksRef.current = checkout.callbacksFor\n\n useEffect(() => {\n if (typeof window === 'undefined' || !driver.resume) return\n const url = new URL(window.location.href)\n const correlationId = url.searchParams.get('af_checkout')\n if (!correlationId || consumedResumes.has(correlationId)) return\n consumedResumes.add(correlationId)\n void driver.resume(correlationId).then((result) => {\n // Not a new attempt — no onStart/`checkout.start`; the charge already ran.\n const cb = callbacksRef.current()\n if (result.ok) {\n url.searchParams.delete('af_checkout')\n window.history.replaceState(window.history.state, '', url.toString())\n cb.onSuccess(result)\n } else {\n cb.onError(result.error ?? checkoutError('unknown', 'The checkout could not be verified'))\n }\n })\n // Mount-scoped by design (the URL param is a page-load fact).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n return null\n}\n","'use client';\nfunction __insertCSS(code) {\n if (!code || typeof document == 'undefined') return\n let head = document.head || document.getElementsByTagName('head')[0]\n let style = document.createElement('style')\n style.type = 'text/css'\n head.appendChild(style)\n ;style.styleSheet ? (style.styleSheet.cssText = code) : style.appendChild(document.createTextNode(code))\n}\n\nimport React from 'react';\nimport ReactDOM from 'react-dom';\n\nconst getAsset = (type)=>{\n switch(type){\n case 'success':\n return SuccessIcon;\n case 'info':\n return InfoIcon;\n case 'warning':\n return WarningIcon;\n case 'error':\n return ErrorIcon;\n default:\n return null;\n }\n};\nconst bars = Array(12).fill(0);\nconst Loader = ({ visible, className })=>{\n return /*#__PURE__*/ React.createElement(\"div\", {\n className: [\n 'sonner-loading-wrapper',\n className\n ].filter(Boolean).join(' '),\n \"data-visible\": visible\n }, /*#__PURE__*/ React.createElement(\"div\", {\n className: \"sonner-spinner\"\n }, bars.map((_, i)=>/*#__PURE__*/ React.createElement(\"div\", {\n className: \"sonner-loading-bar\",\n key: `spinner-bar-${i}`\n }))));\n};\nconst SuccessIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: \"0 0 20 20\",\n fill: \"currentColor\",\n height: \"20\",\n width: \"20\"\n}, /*#__PURE__*/ React.createElement(\"path\", {\n fillRule: \"evenodd\",\n d: \"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z\",\n clipRule: \"evenodd\"\n}));\nconst WarningIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: \"0 0 24 24\",\n fill: \"currentColor\",\n height: \"20\",\n width: \"20\"\n}, /*#__PURE__*/ React.createElement(\"path\", {\n fillRule: \"evenodd\",\n d: \"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z\",\n clipRule: \"evenodd\"\n}));\nconst InfoIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: \"0 0 20 20\",\n fill: \"currentColor\",\n height: \"20\",\n width: \"20\"\n}, /*#__PURE__*/ React.createElement(\"path\", {\n fillRule: \"evenodd\",\n d: \"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z\",\n clipRule: \"evenodd\"\n}));\nconst ErrorIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: \"0 0 20 20\",\n fill: \"currentColor\",\n height: \"20\",\n width: \"20\"\n}, /*#__PURE__*/ React.createElement(\"path\", {\n fillRule: \"evenodd\",\n d: \"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z\",\n clipRule: \"evenodd\"\n}));\nconst CloseIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n width: \"12\",\n height: \"12\",\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n strokeWidth: \"1.5\",\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\"\n}, /*#__PURE__*/ React.createElement(\"line\", {\n x1: \"18\",\n y1: \"6\",\n x2: \"6\",\n y2: \"18\"\n}), /*#__PURE__*/ React.createElement(\"line\", {\n x1: \"6\",\n y1: \"6\",\n x2: \"18\",\n y2: \"18\"\n}));\n\nconst useIsDocumentHidden = ()=>{\n const [isDocumentHidden, setIsDocumentHidden] = React.useState(document.hidden);\n React.useEffect(()=>{\n const callback = ()=>{\n setIsDocumentHidden(document.hidden);\n };\n document.addEventListener('visibilitychange', callback);\n return ()=>window.removeEventListener('visibilitychange', callback);\n }, []);\n return isDocumentHidden;\n};\n\nlet toastsCounter = 1;\nclass Observer {\n constructor(){\n // We use arrow functions to maintain the correct `this` reference\n this.subscribe = (subscriber)=>{\n this.subscribers.push(subscriber);\n return ()=>{\n const index = this.subscribers.indexOf(subscriber);\n this.subscribers.splice(index, 1);\n };\n };\n this.publish = (data)=>{\n this.subscribers.forEach((subscriber)=>subscriber(data));\n };\n this.addToast = (data)=>{\n this.publish(data);\n this.toasts = [\n ...this.toasts,\n data\n ];\n };\n this.create = (data)=>{\n var _data_id;\n const { message, ...rest } = data;\n const id = typeof (data == null ? void 0 : data.id) === 'number' || ((_data_id = data.id) == null ? void 0 : _data_id.length) > 0 ? data.id : toastsCounter++;\n const alreadyExists = this.toasts.find((toast)=>{\n return toast.id === id;\n });\n const dismissible = data.dismissible === undefined ? true : data.dismissible;\n if (this.dismissedToasts.has(id)) {\n this.dismissedToasts.delete(id);\n }\n if (alreadyExists) {\n this.toasts = this.toasts.map((toast)=>{\n if (toast.id === id) {\n this.publish({\n ...toast,\n ...data,\n id,\n title: message\n });\n return {\n ...toast,\n ...data,\n id,\n dismissible,\n title: message\n };\n }\n return toast;\n });\n } else {\n this.addToast({\n title: message,\n ...rest,\n dismissible,\n id\n });\n }\n return id;\n };\n this.dismiss = (id)=>{\n if (id) {\n this.dismissedToasts.add(id);\n requestAnimationFrame(()=>this.subscribers.forEach((subscriber)=>subscriber({\n id,\n dismiss: true\n })));\n } else {\n this.toasts.forEach((toast)=>{\n this.subscribers.forEach((subscriber)=>subscriber({\n id: toast.id,\n dismiss: true\n }));\n });\n }\n return id;\n };\n this.message = (message, data)=>{\n return this.create({\n ...data,\n message\n });\n };\n this.error = (message, data)=>{\n return this.create({\n ...data,\n message,\n type: 'error'\n });\n };\n this.success = (message, data)=>{\n return this.create({\n ...data,\n type: 'success',\n message\n });\n };\n this.info = (message, data)=>{\n return this.create({\n ...data,\n type: 'info',\n message\n });\n };\n this.warning = (message, data)=>{\n return this.create({\n ...data,\n type: 'warning',\n message\n });\n };\n this.loading = (message, data)=>{\n return this.create({\n ...data,\n type: 'loading',\n message\n });\n };\n this.promise = (promise, data)=>{\n if (!data) {\n // Nothing to show\n return;\n }\n let id = undefined;\n if (data.loading !== undefined) {\n id = this.create({\n ...data,\n promise,\n type: 'loading',\n message: data.loading,\n description: typeof data.description !== 'function' ? data.description : undefined\n });\n }\n const p = Promise.resolve(promise instanceof Function ? promise() : promise);\n let shouldDismiss = id !== undefined;\n let result;\n const originalPromise = p.then(async (response)=>{\n result = [\n 'resolve',\n response\n ];\n const isReactElementResponse = React.isValidElement(response);\n if (isReactElementResponse) {\n shouldDismiss = false;\n this.create({\n id,\n type: 'default',\n message: response\n });\n } else if (isHttpResponse(response) && !response.ok) {\n shouldDismiss = false;\n const promiseData = typeof data.error === 'function' ? await data.error(`HTTP error! status: ${response.status}`) : data.error;\n const description = typeof data.description === 'function' ? await data.description(`HTTP error! status: ${response.status}`) : data.description;\n const isExtendedResult = typeof promiseData === 'object' && !React.isValidElement(promiseData);\n const toastSettings = isExtendedResult ? promiseData : {\n message: promiseData\n };\n this.create({\n id,\n type: 'error',\n description,\n ...toastSettings\n });\n } else if (response instanceof Error) {\n shouldDismiss = false;\n const promiseData = typeof data.error === 'function' ? await data.error(response) : data.error;\n const description = typeof data.description === 'function' ? await data.description(response) : data.description;\n const isExtendedResult = typeof promiseData === 'object' && !React.isValidElement(promiseData);\n const toastSettings = isExtendedResult ? promiseData : {\n message: promiseData\n };\n this.create({\n id,\n type: 'error',\n description,\n ...toastSettings\n });\n } else if (data.success !== undefined) {\n shouldDismiss = false;\n const promiseData = typeof data.success === 'function' ? await data.success(response) : data.success;\n const description = typeof data.description === 'function' ? await data.description(response) : data.description;\n const isExtendedResult = typeof promiseData === 'object' && !React.isValidElement(promiseData);\n const toastSettings = isExtendedResult ? promiseData : {\n message: promiseData\n };\n this.create({\n id,\n type: 'success',\n description,\n ...toastSettings\n });\n }\n }).catch(async (error)=>{\n result = [\n 'reject',\n error\n ];\n if (data.error !== undefined) {\n shouldDismiss = false;\n const promiseData = typeof data.error === 'function' ? await data.error(error) : data.error;\n const description = typeof data.description === 'function' ? await data.description(error) : data.description;\n const isExtendedResult = typeof promiseData === 'object' && !React.isValidElement(promiseData);\n const toastSettings = isExtendedResult ? promiseData : {\n message: promiseData\n };\n this.create({\n id,\n type: 'error',\n description,\n ...toastSettings\n });\n }\n }).finally(()=>{\n if (shouldDismiss) {\n // Toast is still in load state (and will be indefinitely — dismiss it)\n this.dismiss(id);\n id = undefined;\n }\n data.finally == null ? void 0 : data.finally.call(data);\n });\n const unwrap = ()=>new Promise((resolve, reject)=>originalPromise.then(()=>result[0] === 'reject' ? reject(result[1]) : resolve(result[1])).catch(reject));\n if (typeof id !== 'string' && typeof id !== 'number') {\n // cannot Object.assign on undefined\n return {\n unwrap\n };\n } else {\n return Object.assign(id, {\n unwrap\n });\n }\n };\n this.custom = (jsx, data)=>{\n const id = (data == null ? void 0 : data.id) || toastsCounter++;\n this.create({\n jsx: jsx(id),\n id,\n ...data\n });\n return id;\n };\n this.getActiveToasts = ()=>{\n return this.toasts.filter((toast)=>!this.dismissedToasts.has(toast.id));\n };\n this.subscribers = [];\n this.toasts = [];\n this.dismissedToasts = new Set();\n }\n}\nconst ToastState = new Observer();\n// bind this to the toast function\nconst toastFunction = (message, data)=>{\n const id = (data == null ? void 0 : data.id) || toastsCounter++;\n ToastState.addToast({\n title: message,\n ...data,\n id\n });\n return id;\n};\nconst isHttpResponse = (data)=>{\n return data && typeof data === 'object' && 'ok' in data && typeof data.ok === 'boolean' && 'status' in data && typeof data.status === 'number';\n};\nconst basicToast = toastFunction;\nconst getHistory = ()=>ToastState.toasts;\nconst getToasts = ()=>ToastState.getActiveToasts();\n// We use `Object.assign` to maintain the correct types as we would lose them otherwise\nconst toast = Object.assign(basicToast, {\n success: ToastState.success,\n info: ToastState.info,\n warning: ToastState.warning,\n error: ToastState.error,\n custom: ToastState.custom,\n message: ToastState.message,\n promise: ToastState.promise,\n dismiss: ToastState.dismiss,\n loading: ToastState.loading\n}, {\n getHistory,\n getToasts\n});\n\n__insertCSS(\"[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}\");\n\nfunction isAction(action) {\n return action.label !== undefined;\n}\n\n// Visible toasts amount\nconst VISIBLE_TOASTS_AMOUNT = 3;\n// Viewport padding\nconst VIEWPORT_OFFSET = '24px';\n// Mobile viewport padding\nconst MOBILE_VIEWPORT_OFFSET = '16px';\n// Default lifetime of a toasts (in ms)\nconst TOAST_LIFETIME = 4000;\n// Default toast width\nconst TOAST_WIDTH = 356;\n// Default gap between toasts\nconst GAP = 14;\n// Threshold to dismiss a toast\nconst SWIPE_THRESHOLD = 45;\n// Equal to exit animation duration\nconst TIME_BEFORE_UNMOUNT = 200;\nfunction cn(...classes) {\n return classes.filter(Boolean).join(' ');\n}\nfunction getDefaultSwipeDirections(position) {\n const [y, x] = position.split('-');\n const directions = [];\n if (y) {\n directions.push(y);\n }\n if (x) {\n directions.push(x);\n }\n return directions;\n}\nconst Toast = (props)=>{\n var _toast_classNames, _toast_classNames1, _toast_classNames2, _toast_classNames3, _toast_classNames4, _toast_classNames5, _toast_classNames6, _toast_classNames7, _toast_classNames8;\n const { invert: ToasterInvert, toast, unstyled, interacting, setHeights, visibleToasts, heights, index, toasts, expanded, removeToast, defaultRichColors, closeButton: closeButtonFromToaster, style, cancelButtonStyle, actionButtonStyle, className = '', descriptionClassName = '', duration: durationFromToaster, position, gap, expandByDefault, classNames, icons, closeButtonAriaLabel = 'Close toast' } = props;\n const [swipeDirection, setSwipeDirection] = React.useState(null);\n const [swipeOutDirection, setSwipeOutDirection] = React.useState(null);\n const [mounted, setMounted] = React.useState(false);\n const [removed, setRemoved] = React.useState(false);\n const [swiping, setSwiping] = React.useState(false);\n const [swipeOut, setSwipeOut] = React.useState(false);\n const [isSwiped, setIsSwiped] = React.useState(false);\n const [offsetBeforeRemove, setOffsetBeforeRemove] = React.useState(0);\n const [initialHeight, setInitialHeight] = React.useState(0);\n const remainingTime = React.useRef(toast.duration || durationFromToaster || TOAST_LIFETIME);\n const dragStartTime = React.useRef(null);\n const toastRef = React.useRef(null);\n const isFront = index === 0;\n const isVisible = index + 1 <= visibleToasts;\n const toastType = toast.type;\n const dismissible = toast.dismissible !== false;\n const toastClassname = toast.className || '';\n const toastDescriptionClassname = toast.descriptionClassName || '';\n // Height index is used to calculate the offset as it gets updated before the toast array, which means we can calculate the new layout faster.\n const heightIndex = React.useMemo(()=>heights.findIndex((height)=>height.toastId === toast.id) || 0, [\n heights,\n toast.id\n ]);\n const closeButton = React.useMemo(()=>{\n var _toast_closeButton;\n return (_toast_closeButton = toast.closeButton) != null ? _toast_closeButton : closeButtonFromToaster;\n }, [\n toast.closeButton,\n closeButtonFromToaster\n ]);\n const duration = React.useMemo(()=>toast.duration || durationFromToaster || TOAST_LIFETIME, [\n toast.duration,\n durationFromToaster\n ]);\n const closeTimerStartTimeRef = React.useRef(0);\n const offset = React.useRef(0);\n const lastCloseTimerStartTimeRef = React.useRef(0);\n const pointerStartRef = React.useRef(null);\n const [y, x] = position.split('-');\n const toastsHeightBefore = React.useMemo(()=>{\n return heights.reduce((prev, curr, reducerIndex)=>{\n // Calculate offset up until current toast\n if (reducerIndex >= heightIndex) {\n return prev;\n }\n return prev + curr.height;\n }, 0);\n }, [\n heights,\n heightIndex\n ]);\n const isDocumentHidden = useIsDocumentHidden();\n const invert = toast.invert || ToasterInvert;\n const disabled = toastType === 'loading';\n offset.current = React.useMemo(()=>heightIndex * gap + toastsHeightBefore, [\n heightIndex,\n toastsHeightBefore\n ]);\n React.useEffect(()=>{\n remainingTime.current = duration;\n }, [\n duration\n ]);\n React.useEffect(()=>{\n // Trigger enter animation without using CSS animation\n setMounted(true);\n }, []);\n React.useEffect(()=>{\n const toastNode = toastRef.current;\n if (toastNode) {\n const height = toastNode.getBoundingClientRect().height;\n // Add toast height to heights array after the toast is mounted\n setInitialHeight(height);\n setHeights((h)=>[\n {\n toastId: toast.id,\n height,\n position: toast.position\n },\n ...h\n ]);\n return ()=>setHeights((h)=>h.filter((height)=>height.toastId !== toast.id));\n }\n }, [\n setHeights,\n toast.id\n ]);\n React.useLayoutEffect(()=>{\n // Keep height up to date with the content in case it updates\n if (!mounted) return;\n const toastNode = toastRef.current;\n const originalHeight = toastNode.style.height;\n toastNode.style.height = 'auto';\n const newHeight = toastNode.getBoundingClientRect().height;\n toastNode.style.height = originalHeight;\n setInitialHeight(newHeight);\n setHeights((heights)=>{\n const alreadyExists = heights.find((height)=>height.toastId === toast.id);\n if (!alreadyExists) {\n return [\n {\n toastId: toast.id,\n height: newHeight,\n position: toast.position\n },\n ...heights\n ];\n } else {\n return heights.map((height)=>height.toastId === toast.id ? {\n ...height,\n height: newHeight\n } : height);\n }\n });\n }, [\n mounted,\n toast.title,\n toast.description,\n setHeights,\n toast.id,\n toast.jsx,\n toast.action,\n toast.cancel\n ]);\n const deleteToast = React.useCallback(()=>{\n // Save the offset for the exit swipe animation\n setRemoved(true);\n setOffsetBeforeRemove(offset.current);\n setHeights((h)=>h.filter((height)=>height.toastId !== toast.id));\n setTimeout(()=>{\n removeToast(toast);\n }, TIME_BEFORE_UNMOUNT);\n }, [\n toast,\n removeToast,\n setHeights,\n offset\n ]);\n React.useEffect(()=>{\n if (toast.promise && toastType === 'loading' || toast.duration === Infinity || toast.type === 'loading') return;\n let timeoutId;\n // Pause the timer on each hover\n const pauseTimer = ()=>{\n if (lastCloseTimerStartTimeRef.current < closeTimerStartTimeRef.current) {\n // Get the elapsed time since the timer started\n const elapsedTime = new Date().getTime() - closeTimerStartTimeRef.current;\n remainingTime.current = remainingTime.current - elapsedTime;\n }\n lastCloseTimerStartTimeRef.current = new Date().getTime();\n };\n const startTimer = ()=>{\n // setTimeout(, Infinity) behaves as if the delay is 0.\n // As a result, the toast would be closed immediately, giving the appearance that it was never rendered.\n // See: https://github.com/denysdovhan/wtfjs?tab=readme-ov-file#an-infinite-timeout\n if (remainingTime.current === Infinity) return;\n closeTimerStartTimeRef.current = new Date().getTime();\n // Let the toast know it has started\n timeoutId = setTimeout(()=>{\n toast.onAutoClose == null ? void 0 : toast.onAutoClose.call(toast, toast);\n deleteToast();\n }, remainingTime.current);\n };\n if (expanded || interacting || isDocumentHidden) {\n pauseTimer();\n } else {\n startTimer();\n }\n return ()=>clearTimeout(timeoutId);\n }, [\n expanded,\n interacting,\n toast,\n toastType,\n isDocumentHidden,\n deleteToast\n ]);\n React.useEffect(()=>{\n if (toast.delete) {\n deleteToast();\n toast.onDismiss == null ? void 0 : toast.onDismiss.call(toast, toast);\n }\n }, [\n deleteToast,\n toast.delete\n ]);\n function getLoadingIcon() {\n var _toast_classNames;\n if (icons == null ? void 0 : icons.loading) {\n var _toast_classNames1;\n return /*#__PURE__*/ React.createElement(\"div\", {\n className: cn(classNames == null ? void 0 : classNames.loader, toast == null ? void 0 : (_toast_classNames1 = toast.classNames) == null ? void 0 : _toast_classNames1.loader, 'sonner-loader'),\n \"data-visible\": toastType === 'loading'\n }, icons.loading);\n }\n return /*#__PURE__*/ React.createElement(Loader, {\n className: cn(classNames == null ? void 0 : classNames.loader, toast == null ? void 0 : (_toast_classNames = toast.classNames) == null ? void 0 : _toast_classNames.loader),\n visible: toastType === 'loading'\n });\n }\n const icon = toast.icon || (icons == null ? void 0 : icons[toastType]) || getAsset(toastType);\n var _toast_richColors, _icons_close;\n return /*#__PURE__*/ React.createElement(\"li\", {\n tabIndex: 0,\n ref: toastRef,\n className: cn(className, toastClassname, classNames == null ? void 0 : classNames.toast, toast == null ? void 0 : (_toast_classNames = toast.classNames) == null ? void 0 : _toast_classNames.toast, classNames == null ? void 0 : classNames.default, classNames == null ? void 0 : classNames[toastType], toast == null ? void 0 : (_toast_classNames1 = toast.classNames) == null ? void 0 : _toast_classNames1[toastType]),\n \"data-sonner-toast\": \"\",\n \"data-rich-colors\": (_toast_richColors = toast.richColors) != null ? _toast_richColors : defaultRichColors,\n \"data-styled\": !Boolean(toast.jsx || toast.unstyled || unstyled),\n \"data-mounted\": mounted,\n \"data-promise\": Boolean(toast.promise),\n \"data-swiped\": isSwiped,\n \"data-removed\": removed,\n \"data-visible\": isVisible,\n \"data-y-position\": y,\n \"data-x-position\": x,\n \"data-index\": index,\n \"data-front\": isFront,\n \"data-swiping\": swiping,\n \"data-dismissible\": dismissible,\n \"data-type\": toastType,\n \"data-invert\": invert,\n \"data-swipe-out\": swipeOut,\n \"data-swipe-direction\": swipeOutDirection,\n \"data-expanded\": Boolean(expanded || expandByDefault && mounted),\n \"data-testid\": toast.testId,\n style: {\n '--index': index,\n '--toasts-before': index,\n '--z-index': toasts.length - index,\n '--offset': `${removed ? offsetBeforeRemove : offset.current}px`,\n '--initial-height': expandByDefault ? 'auto' : `${initialHeight}px`,\n ...style,\n ...toast.style\n },\n onDragEnd: ()=>{\n setSwiping(false);\n setSwipeDirection(null);\n pointerStartRef.current = null;\n },\n onPointerDown: (event)=>{\n if (event.button === 2) return; // Return early on right click\n if (disabled || !dismissible) return;\n dragStartTime.current = new Date();\n setOffsetBeforeRemove(offset.current);\n // Ensure we maintain correct pointer capture even when going outside of the toast (e.g. when swiping)\n event.target.setPointerCapture(event.pointerId);\n if (event.target.tagName === 'BUTTON') return;\n setSwiping(true);\n pointerStartRef.current = {\n x: event.clientX,\n y: event.clientY\n };\n },\n onPointerUp: ()=>{\n var _toastRef_current, _toastRef_current1, _dragStartTime_current;\n if (swipeOut || !dismissible) return;\n pointerStartRef.current = null;\n const swipeAmountX = Number(((_toastRef_current = toastRef.current) == null ? void 0 : _toastRef_current.style.getPropertyValue('--swipe-amount-x').replace('px', '')) || 0);\n const swipeAmountY = Number(((_toastRef_current1 = toastRef.current) == null ? void 0 : _toastRef_current1.style.getPropertyValue('--swipe-amount-y').replace('px', '')) || 0);\n const timeTaken = new Date().getTime() - ((_dragStartTime_current = dragStartTime.current) == null ? void 0 : _dragStartTime_current.getTime());\n const swipeAmount = swipeDirection === 'x' ? swipeAmountX : swipeAmountY;\n const velocity = Math.abs(swipeAmount) / timeTaken;\n if (Math.abs(swipeAmount) >= SWIPE_THRESHOLD || velocity > 0.11) {\n setOffsetBeforeRemove(offset.current);\n toast.onDismiss == null ? void 0 : toast.onDismiss.call(toast, toast);\n if (swipeDirection === 'x') {\n setSwipeOutDirection(swipeAmountX > 0 ? 'right' : 'left');\n } else {\n setSwipeOutDirection(swipeAmountY > 0 ? 'down' : 'up');\n }\n deleteToast();\n setSwipeOut(true);\n return;\n } else {\n var _toastRef_current2, _toastRef_current3;\n (_toastRef_current2 = toastRef.current) == null ? void 0 : _toastRef_current2.style.setProperty('--swipe-amount-x', `0px`);\n (_toastRef_current3 = toastRef.current) == null ? void 0 : _toastRef_current3.style.setProperty('--swipe-amount-y', `0px`);\n }\n setIsSwiped(false);\n setSwiping(false);\n setSwipeDirection(null);\n },\n onPointerMove: (event)=>{\n var _window_getSelection, // Apply transform using both x and y values\n _toastRef_current, _toastRef_current1;\n if (!pointerStartRef.current || !dismissible) return;\n const isHighlighted = ((_window_getSelection = window.getSelection()) == null ? void 0 : _window_getSelection.toString().length) > 0;\n if (isHighlighted) return;\n const yDelta = event.clientY - pointerStartRef.current.y;\n const xDelta = event.clientX - pointerStartRef.current.x;\n var _props_swipeDirections;\n const swipeDirections = (_props_swipeDirections = props.swipeDirections) != null ? _props_swipeDirections : getDefaultSwipeDirections(position);\n // Determine swipe direction if not already locked\n if (!swipeDirection && (Math.abs(xDelta) > 1 || Math.abs(yDelta) > 1)) {\n setSwipeDirection(Math.abs(xDelta) > Math.abs(yDelta) ? 'x' : 'y');\n }\n let swipeAmount = {\n x: 0,\n y: 0\n };\n const getDampening = (delta)=>{\n const factor = Math.abs(delta) / 20;\n return 1 / (1.5 + factor);\n };\n // Only apply swipe in the locked direction\n if (swipeDirection === 'y') {\n // Handle vertical swipes\n if (swipeDirections.includes('top') || swipeDirections.includes('bottom')) {\n if (swipeDirections.includes('top') && yDelta < 0 || swipeDirections.includes('bottom') && yDelta > 0) {\n swipeAmount.y = yDelta;\n } else {\n // Smoothly transition to dampened movement\n const dampenedDelta = yDelta * getDampening(yDelta);\n // Ensure we don't jump when transitioning to dampened movement\n swipeAmount.y = Math.abs(dampenedDelta) < Math.abs(yDelta) ? dampenedDelta : yDelta;\n }\n }\n } else if (swipeDirection === 'x') {\n // Handle horizontal swipes\n if (swipeDirections.includes('left') || swipeDirections.includes('right')) {\n if (swipeDirections.includes('left') && xDelta < 0 || swipeDirections.includes('right') && xDelta > 0) {\n swipeAmount.x = xDelta;\n } else {\n // Smoothly transition to dampened movement\n const dampenedDelta = xDelta * getDampening(xDelta);\n // Ensure we don't jump when transitioning to dampened movement\n swipeAmount.x = Math.abs(dampenedDelta) < Math.abs(xDelta) ? dampenedDelta : xDelta;\n }\n }\n }\n if (Math.abs(swipeAmount.x) > 0 || Math.abs(swipeAmount.y) > 0) {\n setIsSwiped(true);\n }\n (_toastRef_current = toastRef.current) == null ? void 0 : _toastRef_current.style.setProperty('--swipe-amount-x', `${swipeAmount.x}px`);\n (_toastRef_current1 = toastRef.current) == null ? void 0 : _toastRef_current1.style.setProperty('--swipe-amount-y', `${swipeAmount.y}px`);\n }\n }, closeButton && !toast.jsx && toastType !== 'loading' ? /*#__PURE__*/ React.createElement(\"button\", {\n \"aria-label\": closeButtonAriaLabel,\n \"data-disabled\": disabled,\n \"data-close-button\": true,\n onClick: disabled || !dismissible ? ()=>{} : ()=>{\n deleteToast();\n toast.onDismiss == null ? void 0 : toast.onDismiss.call(toast, toast);\n },\n className: cn(classNames == null ? void 0 : classNames.closeButton, toast == null ? void 0 : (_toast_classNames2 = toast.classNames) == null ? void 0 : _toast_classNames2.closeButton)\n }, (_icons_close = icons == null ? void 0 : icons.close) != null ? _icons_close : CloseIcon) : null, (toastType || toast.icon || toast.promise) && toast.icon !== null && ((icons == null ? void 0 : icons[toastType]) !== null || toast.icon) ? /*#__PURE__*/ React.createElement(\"div\", {\n \"data-icon\": \"\",\n className: cn(classNames == null ? void 0 : classNames.icon, toast == null ? void 0 : (_toast_classNames3 = toast.classNames) == null ? void 0 : _toast_classNames3.icon)\n }, toast.promise || toast.type === 'loading' && !toast.icon ? toast.icon || getLoadingIcon() : null, toast.type !== 'loading' ? icon : null) : null, /*#__PURE__*/ React.createElement(\"div\", {\n \"data-content\": \"\",\n className: cn(classNames == null ? void 0 : classNames.content, toast == null ? void 0 : (_toast_classNames4 = toast.classNames) == null ? void 0 : _toast_classNames4.content)\n }, /*#__PURE__*/ React.createElement(\"div\", {\n \"data-title\": \"\",\n className: cn(classNames == null ? void 0 : classNames.title, toast == null ? void 0 : (_toast_classNames5 = toast.classNames) == null ? void 0 : _toast_classNames5.title)\n }, toast.jsx ? toast.jsx : typeof toast.title === 'function' ? toast.title() : toast.title), toast.description ? /*#__PURE__*/ React.createElement(\"div\", {\n \"data-description\": \"\",\n className: cn(descriptionClassName, toastDescriptionClassname, classNames == null ? void 0 : classNames.description, toast == null ? void 0 : (_toast_classNames6 = toast.classNames) == null ? void 0 : _toast_classNames6.description)\n }, typeof toast.description === 'function' ? toast.description() : toast.description) : null), /*#__PURE__*/ React.isValidElement(toast.cancel) ? toast.cancel : toast.cancel && isAction(toast.cancel) ? /*#__PURE__*/ React.createElement(\"button\", {\n \"data-button\": true,\n \"data-cancel\": true,\n style: toast.cancelButtonStyle || cancelButtonStyle,\n onClick: (event)=>{\n // We need to check twice because typescript\n if (!isAction(toast.cancel)) return;\n if (!dismissible) return;\n toast.cancel.onClick == null ? void 0 : toast.cancel.onClick.call(toast.cancel, event);\n deleteToast();\n },\n className: cn(classNames == null ? void 0 : classNames.cancelButton, toast == null ? void 0 : (_toast_classNames7 = toast.classNames) == null ? void 0 : _toast_classNames7.cancelButton)\n }, toast.cancel.label) : null, /*#__PURE__*/ React.isValidElement(toast.action) ? toast.action : toast.action && isAction(toast.action) ? /*#__PURE__*/ React.createElement(\"button\", {\n \"data-button\": true,\n \"data-action\": true,\n style: toast.actionButtonStyle || actionButtonStyle,\n onClick: (event)=>{\n // We need to check twice because typescript\n if (!isAction(toast.action)) return;\n toast.action.onClick == null ? void 0 : toast.action.onClick.call(toast.action, event);\n if (event.defaultPrevented) return;\n deleteToast();\n },\n className: cn(classNames == null ? void 0 : classNames.actionButton, toast == null ? void 0 : (_toast_classNames8 = toast.classNames) == null ? void 0 : _toast_classNames8.actionButton)\n }, toast.action.label) : null);\n};\nfunction getDocumentDirection() {\n if (typeof window === 'undefined') return 'ltr';\n if (typeof document === 'undefined') return 'ltr'; // For Fresh purpose\n const dirAttribute = document.documentElement.getAttribute('dir');\n if (dirAttribute === 'auto' || !dirAttribute) {\n return window.getComputedStyle(document.documentElement).direction;\n }\n return dirAttribute;\n}\nfunction assignOffset(defaultOffset, mobileOffset) {\n const styles = {};\n [\n defaultOffset,\n mobileOffset\n ].forEach((offset, index)=>{\n const isMobile = index === 1;\n const prefix = isMobile ? '--mobile-offset' : '--offset';\n const defaultValue = isMobile ? MOBILE_VIEWPORT_OFFSET : VIEWPORT_OFFSET;\n function assignAll(offset) {\n [\n 'top',\n 'right',\n 'bottom',\n 'left'\n ].forEach((key)=>{\n styles[`${prefix}-${key}`] = typeof offset === 'number' ? `${offset}px` : offset;\n });\n }\n if (typeof offset === 'number' || typeof offset === 'string') {\n assignAll(offset);\n } else if (typeof offset === 'object') {\n [\n 'top',\n 'right',\n 'bottom',\n 'left'\n ].forEach((key)=>{\n if (offset[key] === undefined) {\n styles[`${prefix}-${key}`] = defaultValue;\n } else {\n styles[`${prefix}-${key}`] = typeof offset[key] === 'number' ? `${offset[key]}px` : offset[key];\n }\n });\n } else {\n assignAll(defaultValue);\n }\n });\n return styles;\n}\nfunction useSonner() {\n const [activeToasts, setActiveToasts] = React.useState([]);\n React.useEffect(()=>{\n return ToastState.subscribe((toast)=>{\n if (toast.dismiss) {\n setTimeout(()=>{\n ReactDOM.flushSync(()=>{\n setActiveToasts((toasts)=>toasts.filter((t)=>t.id !== toast.id));\n });\n });\n return;\n }\n // Prevent batching, temp solution.\n setTimeout(()=>{\n ReactDOM.flushSync(()=>{\n setActiveToasts((toasts)=>{\n const indexOfExistingToast = toasts.findIndex((t)=>t.id === toast.id);\n // Update the toast if it already exists\n if (indexOfExistingToast !== -1) {\n return [\n ...toasts.slice(0, indexOfExistingToast),\n {\n ...toasts[indexOfExistingToast],\n ...toast\n },\n ...toasts.slice(indexOfExistingToast + 1)\n ];\n }\n return [\n toast,\n ...toasts\n ];\n });\n });\n });\n });\n }, []);\n return {\n toasts: activeToasts\n };\n}\nconst Toaster = /*#__PURE__*/ React.forwardRef(function Toaster(props, ref) {\n const { id, invert, position = 'bottom-right', hotkey = [\n 'altKey',\n 'KeyT'\n ], expand, closeButton, className, offset, mobileOffset, theme = 'light', richColors, duration, style, visibleToasts = VISIBLE_TOASTS_AMOUNT, toastOptions, dir = getDocumentDirection(), gap = GAP, icons, containerAriaLabel = 'Notifications' } = props;\n const [toasts, setToasts] = React.useState([]);\n const filteredToasts = React.useMemo(()=>{\n if (id) {\n return toasts.filter((toast)=>toast.toasterId === id);\n }\n return toasts.filter((toast)=>!toast.toasterId);\n }, [\n toasts,\n id\n ]);\n const possiblePositions = React.useMemo(()=>{\n return Array.from(new Set([\n position\n ].concat(filteredToasts.filter((toast)=>toast.position).map((toast)=>toast.position))));\n }, [\n filteredToasts,\n position\n ]);\n const [heights, setHeights] = React.useState([]);\n const [expanded, setExpanded] = React.useState(false);\n const [interacting, setInteracting] = React.useState(false);\n const [actualTheme, setActualTheme] = React.useState(theme !== 'system' ? theme : typeof window !== 'undefined' ? window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' : 'light');\n const listRef = React.useRef(null);\n const hotkeyLabel = hotkey.join('+').replace(/Key/g, '').replace(/Digit/g, '');\n const lastFocusedElementRef = React.useRef(null);\n const isFocusWithinRef = React.useRef(false);\n const removeToast = React.useCallback((toastToRemove)=>{\n setToasts((toasts)=>{\n var _toasts_find;\n if (!((_toasts_find = toasts.find((toast)=>toast.id === toastToRemove.id)) == null ? void 0 : _toasts_find.delete)) {\n ToastState.dismiss(toastToRemove.id);\n }\n return toasts.filter(({ id })=>id !== toastToRemove.id);\n });\n }, []);\n React.useEffect(()=>{\n return ToastState.subscribe((toast)=>{\n if (toast.dismiss) {\n // Prevent batching of other state updates\n requestAnimationFrame(()=>{\n setToasts((toasts)=>toasts.map((t)=>t.id === toast.id ? {\n ...t,\n delete: true\n } : t));\n });\n return;\n }\n // Prevent batching, temp solution.\n setTimeout(()=>{\n ReactDOM.flushSync(()=>{\n setToasts((toasts)=>{\n const indexOfExistingToast = toasts.findIndex((t)=>t.id === toast.id);\n // Update the toast if it already exists\n if (indexOfExistingToast !== -1) {\n return [\n ...toasts.slice(0, indexOfExistingToast),\n {\n ...toasts[indexOfExistingToast],\n ...toast\n },\n ...toasts.slice(indexOfExistingToast + 1)\n ];\n }\n return [\n toast,\n ...toasts\n ];\n });\n });\n });\n });\n }, [\n toasts\n ]);\n React.useEffect(()=>{\n if (theme !== 'system') {\n setActualTheme(theme);\n return;\n }\n if (theme === 'system') {\n // check if current preference is dark\n if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {\n // it's currently dark\n setActualTheme('dark');\n } else {\n // it's not dark\n setActualTheme('light');\n }\n }\n if (typeof window === 'undefined') return;\n const darkMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');\n try {\n // Chrome & Firefox\n darkMediaQuery.addEventListener('change', ({ matches })=>{\n if (matches) {\n setActualTheme('dark');\n } else {\n setActualTheme('light');\n }\n });\n } catch (error) {\n // Safari < 14\n darkMediaQuery.addListener(({ matches })=>{\n try {\n if (matches) {\n setActualTheme('dark');\n } else {\n setActualTheme('light');\n }\n } catch (e) {\n console.error(e);\n }\n });\n }\n }, [\n theme\n ]);\n React.useEffect(()=>{\n // Ensure expanded is always false when no toasts are present / only one left\n if (toasts.length <= 1) {\n setExpanded(false);\n }\n }, [\n toasts\n ]);\n React.useEffect(()=>{\n const handleKeyDown = (event)=>{\n var _listRef_current;\n const isHotkeyPressed = hotkey.every((key)=>event[key] || event.code === key);\n if (isHotkeyPressed) {\n var _listRef_current1;\n setExpanded(true);\n (_listRef_current1 = listRef.current) == null ? void 0 : _listRef_current1.focus();\n }\n if (event.code === 'Escape' && (document.activeElement === listRef.current || ((_listRef_current = listRef.current) == null ? void 0 : _listRef_current.contains(document.activeElement)))) {\n setExpanded(false);\n }\n };\n document.addEventListener('keydown', handleKeyDown);\n return ()=>document.removeEventListener('keydown', handleKeyDown);\n }, [\n hotkey\n ]);\n React.useEffect(()=>{\n if (listRef.current) {\n return ()=>{\n if (lastFocusedElementRef.current) {\n lastFocusedElementRef.current.focus({\n preventScroll: true\n });\n lastFocusedElementRef.current = null;\n isFocusWithinRef.current = false;\n }\n };\n }\n }, [\n listRef.current\n ]);\n return(// Remove item from normal navigation flow, only available via hotkey\n /*#__PURE__*/ React.createElement(\"section\", {\n ref: ref,\n \"aria-label\": `${containerAriaLabel} ${hotkeyLabel}`,\n tabIndex: -1,\n \"aria-live\": \"polite\",\n \"aria-relevant\": \"additions text\",\n \"aria-atomic\": \"false\",\n suppressHydrationWarning: true\n }, possiblePositions.map((position, index)=>{\n var _heights_;\n const [y, x] = position.split('-');\n if (!filteredToasts.length) return null;\n return /*#__PURE__*/ React.createElement(\"ol\", {\n key: position,\n dir: dir === 'auto' ? getDocumentDirection() : dir,\n tabIndex: -1,\n ref: listRef,\n className: className,\n \"data-sonner-toaster\": true,\n \"data-sonner-theme\": actualTheme,\n \"data-y-position\": y,\n \"data-x-position\": x,\n style: {\n '--front-toast-height': `${((_heights_ = heights[0]) == null ? void 0 : _heights_.height) || 0}px`,\n '--width': `${TOAST_WIDTH}px`,\n '--gap': `${gap}px`,\n ...style,\n ...assignOffset(offset, mobileOffset)\n },\n onBlur: (event)=>{\n if (isFocusWithinRef.current && !event.currentTarget.contains(event.relatedTarget)) {\n isFocusWithinRef.current = false;\n if (lastFocusedElementRef.current) {\n lastFocusedElementRef.current.focus({\n preventScroll: true\n });\n lastFocusedElementRef.current = null;\n }\n }\n },\n onFocus: (event)=>{\n const isNotDismissible = event.target instanceof HTMLElement && event.target.dataset.dismissible === 'false';\n if (isNotDismissible) return;\n if (!isFocusWithinRef.current) {\n isFocusWithinRef.current = true;\n lastFocusedElementRef.current = event.relatedTarget;\n }\n },\n onMouseEnter: ()=>setExpanded(true),\n onMouseMove: ()=>setExpanded(true),\n onMouseLeave: ()=>{\n // Avoid setting expanded to false when interacting with a toast, e.g. swiping\n if (!interacting) {\n setExpanded(false);\n }\n },\n onDragEnd: ()=>setExpanded(false),\n onPointerDown: (event)=>{\n const isNotDismissible = event.target instanceof HTMLElement && event.target.dataset.dismissible === 'false';\n if (isNotDismissible) return;\n setInteracting(true);\n },\n onPointerUp: ()=>setInteracting(false)\n }, filteredToasts.filter((toast)=>!toast.position && index === 0 || toast.position === position).map((toast, index)=>{\n var _toastOptions_duration, _toastOptions_closeButton;\n return /*#__PURE__*/ React.createElement(Toast, {\n key: toast.id,\n icons: icons,\n index: index,\n toast: toast,\n defaultRichColors: richColors,\n duration: (_toastOptions_duration = toastOptions == null ? void 0 : toastOptions.duration) != null ? _toastOptions_duration : duration,\n className: toastOptions == null ? void 0 : toastOptions.className,\n descriptionClassName: toastOptions == null ? void 0 : toastOptions.descriptionClassName,\n invert: invert,\n visibleToasts: visibleToasts,\n closeButton: (_toastOptions_closeButton = toastOptions == null ? void 0 : toastOptions.closeButton) != null ? _toastOptions_closeButton : closeButton,\n interacting: interacting,\n position: position,\n style: toastOptions == null ? void 0 : toastOptions.style,\n unstyled: toastOptions == null ? void 0 : toastOptions.unstyled,\n classNames: toastOptions == null ? void 0 : toastOptions.classNames,\n cancelButtonStyle: toastOptions == null ? void 0 : toastOptions.cancelButtonStyle,\n actionButtonStyle: toastOptions == null ? void 0 : toastOptions.actionButtonStyle,\n closeButtonAriaLabel: toastOptions == null ? void 0 : toastOptions.closeButtonAriaLabel,\n removeToast: removeToast,\n toasts: filteredToasts.filter((t)=>t.position == toast.position),\n heights: heights.filter((h)=>h.position == toast.position),\n setHeights: setHeights,\n expandByDefault: expand,\n gap: gap,\n expanded: expanded,\n swipeDirections: props.swipeDirections\n });\n }));\n })));\n});\n\nexport { Toaster, toast, useSonner };\n","/**\n * Toast — a thin convenience over {@link https://sonner.emilkowal.ski | sonner}.\n *\n * Authors call `toast.success(...)` / `toast.error(...)` anywhere in their funnel.\n * `FunnelProvider` auto-mounts {@link FunnelToaster} (opt out with `toaster={false}`),\n * so toasts work with no setup; render it yourself if you want a custom location.\n *\n * **Dependency policy:** sonner is a direct dependency, imported statically (it's a small\n * lib that ships with every funnel — no lazy chunk, no forwarding proxy). `toaster={false}`\n * still renders no toaster markup; a funnel that never toasts just never calls `toast`.\n */\n\nimport { createElement, type ReactNode } from 'react'\nimport { Toaster, type ToasterProps } from 'sonner'\n\nexport type { ToasterProps }\n\n// sonner's imperative `toast` (`toast('hi')`, `toast.success(...)`, `toast.dismiss()`, …),\n// re-exported DIRECTLY. A re-export keeps the emitted .d.ts nameable — annotating an inferred\n// `const toast = sonnerToast` would drag in sonner's un-exported internal types (TS4023).\nexport { toast } from 'sonner'\n\n/**\n * Sonner's `<Toaster>` with funnel defaults (top-center); pass any `ToasterProps` to override.\n * SSR-safe — sonner renders an empty container server-side and hydrates cleanly on the client.\n */\nexport function FunnelToaster(props: ToasterProps = {}): ReactNode {\n return createElement(Toaster, { position: 'top-center', ...props })\n}\n\n/** Internal: resolve the `FunnelProvider` `toaster` prop to an element (or null). */\nexport function renderToaster(toaster: boolean | ToasterProps): ReactNode {\n if (toaster === false) return null\n return <FunnelToaster {...(toaster === true ? {} : toaster)} />\n}\n","import {\n createContext,\n createElement,\n Fragment,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n useSyncExternalStore,\n type ReactNode,\n} from 'react'\nimport type { VariableStore } from './variableStore'\nimport { createFunnelStore, NAMESPACE_PREFIX, type WritableNamespace } from './store'\nimport { buildAcquisition, buildContext, type FunnelContext } from './context'\nimport {\n TrackerProvider,\n createConsoleTracker,\n type Tracker,\n} from '../tracking/tracking'\nimport { attachBus, createBus, withBus, type FunnelBus } from '../tracking/bus'\nimport { CatalogProvider, buildCatalog, type ResolvedProduct, type ProductInput } from '../commerce/catalog'\nimport { CheckoutDriverProvider, createMockDriver, driverWithEmail, driverWithCatalog, type CheckoutDriver } from '../commerce/checkout'\nimport { ModalRuntime } from '../modals/registry'\nimport { LocaleProvider, type MessageCatalog } from '../i18n/translation'\nimport { renderToaster, type ToasterProps } from '../toast/toast'\nimport type { FunnelDefinition, FunnelSnapshot } from '../flow/spine'\nimport type { RuntimeExperiment } from '../flow/experiments'\nimport type { VariableValue } from '../types'\n\n/**\n * v2 namespace layer over the flat {@link VariableStore}.\n *\n * **The public surface is hooks, not a god object.** Reactive reads use\n * `useState`-shaped tuple hooks (`const [goal, setGoal] = useResponse('goal')`);\n * read-only computed values use `useDevice()`/`useLocale()`/`usePage()`/`useUtm()`.\n * `useFunnel()` returns an **imperative, non-subscribing** handle for use in\n * handlers/effects only — it is not the documented primary API and carries no\n * `sdk` branding.\n *\n * Three writable namespaces (`user`/`responses`/`data`) + the read-only\n * `context`. Entitlements are **not** here — they're the separate app/IdentitySDK.\n *\n * All writes route through {@link Namespace.set}, so persistence + identify fire\n * from one place (the \"magic behind set()\", doc 07 §Layer 1).\n */\n\n// ── Writable namespace view ──────────────────────────────\n\n/** A typed view over one writable namespace's slice of the store. */\nexport class Namespace<\n T extends Record<string, VariableValue> = Record<string, VariableValue>,\n> {\n private readonly dot: string\n\n constructor(\n private readonly store: VariableStore,\n readonly name: WritableNamespace,\n /** Side-effect run after every write (persistence, identify). */\n private readonly onWrite: (ns: WritableNamespace, values: Partial<T>) => void,\n ) {\n this.dot = `${NAMESPACE_PREFIX[name]}.`\n }\n\n /** Fully-qualified store key for a namespace-relative key. */\n storeKey(key: string): string {\n return this.dot + key\n }\n\n /** The store-key prefix this namespace reads/writes (e.g. `user.`). */\n get prefix(): string {\n return this.dot\n }\n\n /** Read the whole namespace as a flat object (prefix stripped). */\n getAll(): T {\n const out: Record<string, VariableValue> = {}\n const all = this.store.getState()\n for (const key in all) {\n if (key.startsWith(this.dot)) out[key.slice(this.dot.length)] = all[key]\n }\n return out as T\n }\n\n /** Read one key, or the whole namespace when called with no argument. */\n get<K extends keyof T & string>(key: K): T[K]\n get(): T\n get(key?: string): VariableValue | T {\n return key === undefined ? this.getAll() : this.store.get(this.storeKey(key))\n }\n\n /** Write one or more keys from a plain object (batched + side-effected). */\n set(values: Partial<T>): void {\n const updates: Record<string, VariableValue> = {}\n for (const key in values) {\n updates[this.storeKey(key)] = values[key] as VariableValue\n }\n this.store.setMany(updates)\n this.onWrite(this.name, values)\n }\n}\n\n// ── The imperative handle ────────────────────────────────\n\n/**\n * The imperative funnel handle (`useFunnel()`). Non-reactive — for event\n * handlers and effects. Reactive render reads go through the hooks instead.\n */\nexport interface Funnel {\n user: Namespace\n responses: Namespace\n data: Namespace\n /** Read-only computed namespace. `page` reflects the latest navigation. */\n readonly context: FunnelContext\n /** Live page-level experiment records (platform/DB-sourced); the runtime buckets visitors into them. */\n readonly experiments: RuntimeExperiment[]\n /** Emit a custom analytics event. */\n track: Tracker['track']\n /** A point-in-time snapshot for predicates (routing/conditions). */\n snapshot(): FunnelSnapshot\n}\n\n/** Build the imperative handle over a store + context + tracker. */\nexport function createFunnel(\n store: VariableStore,\n context: FunnelContext,\n tracker: Tracker,\n experiments: RuntimeExperiment[] = [],\n): Funnel {\n // One write path → one place for the \"magic behind set()\".\n const onWrite = (ns: WritableNamespace, values: Record<string, VariableValue>) => {\n // Identify the moment a non-empty email is written.\n if (ns === 'user' && typeof values.email === 'string' && values.email) {\n tracker.identify(values.email)\n }\n // Push the writable snapshot for debounced persistence.\n tracker.setVariables?.(store.getState())\n }\n\n const user = new Namespace(store, 'user', onWrite)\n const responses = new Namespace(store, 'responses', onWrite)\n const data = new Namespace(store, 'data', onWrite)\n\n return {\n user,\n responses,\n data,\n context,\n experiments,\n track: (event: string, eventData?: never, userData?: Record<string, unknown>) =>\n tracker.track(event, eventData, userData),\n snapshot: () => ({\n user: user.getAll(),\n responses: responses.getAll(),\n data: data.getAll(),\n context,\n }),\n }\n}\n\n// ── React wiring ─────────────────────────────────────────\n\ninterface FunnelContextValue {\n funnel: Funnel\n store: VariableStore\n context: FunnelContext\n catalog: Map<string, ResolvedProduct>\n driver: CheckoutDriver\n /** Tracker composed with the client bus sink (every track() also hits window.appfunnel). */\n tracker: Tracker\n /** The window.appfunnel event bus (client-side integration surface). */\n bus: FunnelBus\n}\n\nconst FunnelCtx = createContext<FunnelContextValue | null>(null)\n\nexport interface FunnelProviderProps {\n /** Mount from a funnel definition (the normal case). */\n config?: FunnelDefinition\n /** Server / session-restored values overriding declared defaults. */\n sessionValues?: Record<string, VariableValue>\n /** The platform tracker; defaults to a silent console tracker (tests/dev). */\n tracker?: Tracker\n /** Computed-context seed (funnel id, test/live mode, server-hydrated utm/session). */\n context?: Parameters<typeof buildContext>[0]\n /** Products with their provider-resolved price (`{ amount, currency }`). */\n products?: ProductInput[]\n /** Live page-level experiment records, platform/DB-sourced (not authored in funnel code). */\n experiments?: RuntimeExperiment[]\n /** The platform checkout driver; defaults to a mock that resolves successfully. */\n checkout?: CheckoutDriver\n /** Message catalogs per locale (`messages/<locale>.json`) for translation. */\n messages?: MessageCatalog\n /** Explicit locale override (URL/param/geo); wins over the detected device locale. */\n locale?: string\n /** Auto-mount the toast `<Toaster>` (default true). Pass props to customize, or `false` to opt out. */\n toaster?: boolean | ToasterProps\n /** Advanced / testing: supply a pre-built store instead of a `config`. */\n store?: VariableStore\n children: ReactNode\n}\n\n/**\n * Mounts a funnel: builds the writable {@link VariableStore} + the read-only\n * {@link FunnelContext} (once) and provides the runtime to the tree via hooks.\n */\nexport function FunnelProvider({\n config,\n sessionValues,\n tracker,\n context: contextOpts,\n products,\n experiments,\n checkout,\n messages,\n locale: localeOverride,\n toaster = true,\n store,\n children,\n}: FunnelProviderProps): ReactNode {\n const resolvedTracker = tracker ?? FALLBACK_TRACKER\n const [value] = useState<FunnelContextValue>(() => {\n const s =\n store ??\n createFunnelStore(\n { responses: config?.responses, data: config?.data },\n sessionValues,\n )\n const ctx = buildContext({\n funnelId: config?.id,\n ...contextOpts,\n })\n // The client event bus (window.appfunnel), composed into the tracker so every\n // taxonomy event mirrors to it for on-page pixels. Read getters wire to store + context.\n const bus = createBus({\n getVariable: (key) => s.get(key),\n getVariables: () => s.getState(),\n getCurrentPageId: () => ctx.page.key || null,\n getCustomerId: () => ctx.identity.customerId,\n getVisitorId: () => ctx.identity.visitorId,\n })\n const busTracker = withBus(resolvedTracker, bus)\n // Every checkout attempt carries the buyer email the funnel collected — read\n // from the store at ATTEMPT time (`user.email`), loose-validated so a half-typed\n // value can't fail the wire's email validation (the server treats absent email\n // as an anonymous customer; a webhook/identify backfills it later).\n const emailForCheckout = (): string | undefined => {\n const value = s.get('user.email')\n return typeof value === 'string' && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/.test(value) ? value : undefined\n }\n const catalog = buildCatalog(products ?? [])\n return {\n funnel: createFunnel(s, ctx, busTracker, experiments ?? []),\n store: s,\n context: ctx,\n catalog,\n // Slot → catalog-key resolution wraps the email-enriching driver, so the wire charges the real\n // catalog key while pages + analytics keep the durable SLOT identity (req.product).\n driver: driverWithCatalog(driverWithEmail(checkout ?? createMockDriver(), emailForCheckout), catalog),\n tracker: busTracker,\n bus,\n }\n })\n // Expose the bus on window.appfunnel for the funnel's lifetime (client-side only).\n useEffect(() => attachBus(value.bus), [value.bus])\n // Forward the acquisition snapshot once on entry → the platform persists it\n // first-class (session + first-touch Customer) + feeds CAPI.\n useEffect(() => {\n value.tracker.setAcquisition?.(buildAcquisition(value.context))\n }, [value])\n const tree = createElement(TrackerProvider, {\n tracker: value.tracker,\n children: createElement(CheckoutDriverProvider, {\n driver: value.driver,\n children: createElement(CatalogProvider, {\n catalog: value.catalog,\n children: createElement(FunnelCtx.Provider, {\n value,\n children: createElement(LocaleProvider, {\n config: config?.locales,\n catalog: messages,\n detected: value.context.locale.locale,\n override: localeOverride,\n children: createElement(ModalRuntime, { children }),\n }),\n }),\n }),\n }),\n })\n return createElement(Fragment, null, tree, renderToaster(toaster))\n}\n\nconst FALLBACK_TRACKER = createConsoleTracker({ silent: true })\n\nfunction useFunnelCtx(): FunnelContextValue {\n const ctx = useContext(FunnelCtx)\n if (!ctx) {\n throw new Error('useFunnel/useResponse/… must be used inside <FunnelProvider>')\n }\n return ctx\n}\n\n/**\n * The imperative handle. Does **not** subscribe — use it in event handlers and\n * effects (`useFunnel().responses.set({...})`). For reactive reads use the hooks.\n */\nexport function useFunnel(): Funnel {\n return useFunnelCtx().funnel\n}\n\n/** Internal: the raw {@link VariableStore} (for reactive condition/field hooks). */\nexport function useFunnelStore(): VariableStore {\n return useFunnelCtx().store\n}\n\n// ── Reactive field hooks ─────────────────────────────────\n\n/** Subscribe to a single flat store key; returns its reactive value. */\nfunction useStoreKey(store: VariableStore, key: string): VariableValue {\n const subscribe = useCallback(\n (cb: () => void) => store.subscribe(cb, { keys: [key] }),\n [store, key],\n )\n const getSnapshot = useCallback(() => store.get(key), [store, key])\n // Snapshot is the primitive value → stable by value, no caching needed.\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot)\n}\n\n/** Build a `useState`-shaped tuple hook bound to one writable namespace. */\nfunction makeFieldHook(ns: WritableNamespace) {\n return function useNamespaceField(\n key: string,\n ): [VariableValue, (value: VariableValue) => void] {\n const { funnel, store } = useFunnelCtx()\n const value = useStoreKey(store, `${NAMESPACE_PREFIX[ns]}.${key}`)\n const set = useCallback(\n (v: VariableValue) => funnel[ns].set({ [key]: v }),\n [funnel, key],\n )\n return [value, set]\n }\n}\n\n/**\n * `const [goal, setGoal] = useResponse('goal')` — one funnel answer,\n * `useState`-shaped and per-key reactive. Writing persists + (later) feeds\n * analytics aggregation.\n */\nexport const useResponse = makeFieldHook('responses')\n\n/**\n * `const [height, setHeight] = useUserAttribute('height')` — any field on the\n * user. The platform routes known fields → typed column, custom → attribute;\n * the author doesn't specify which. Writing `email` also identifies the visitor.\n */\nexport const useUserAttribute = makeFieldHook('user')\n\n/**\n * `const [score, setScore] = useData('score')` — working/scratch state. Persisted\n * (survives reload/return) but kept out of `responses` aggregation.\n */\nexport const useData = makeFieldHook('data')\n\n/**\n * The headless field hook — `useField('responses.goal')` — the building block\n * the styleable components (`<Choice>`) wrap. Takes a namespaced path and\n * returns `{ value, set }`. Accepts only writable namespaces.\n */\nexport function useField(path: string): {\n value: VariableValue\n set: (value: VariableValue) => void\n} {\n const dot = path.indexOf('.')\n const ns = path.slice(0, dot) as WritableNamespace\n const key = path.slice(dot + 1)\n const { funnel, store } = useFunnelCtx()\n if (!(ns in NAMESPACE_PREFIX)) {\n throw new Error(`useField: \"${path}\" is not a writable namespace (user/responses/data)`)\n }\n const value = useStoreKey(store, `${NAMESPACE_PREFIX[ns]}.${key}`)\n const set = useCallback(\n (v: VariableValue) => funnel[ns].set({ [key]: v }),\n [funnel, ns, key],\n )\n return { value, set }\n}\n\n// ── Read-only context hooks ──────────────────────────────\n\n/** The whole read-only computed namespace (non-reactive except `page`). */\nfunction useContextObject(): FunnelContext {\n return useFunnelCtx().context\n}\n\n/** `useDevice()` — viewport, device type, pixel ratio (read-only). */\nexport function useDevice(): FunnelContext['device'] {\n return useContextObject().device\n}\n\n/** `useLocale()` — resolved locale/language/region/timezone (read-only). */\nexport function useLocale(): FunnelContext['locale'] {\n return useContextObject().locale\n}\n\n/** `useUtm()` — the 5 utm params captured on entry (read-only). */\nexport function useUtm(): FunnelContext['utm'] {\n return useContextObject().utm\n}\n\n/** `useClickIds()` — per-network ad click-ids captured on entry (read-only). */\nexport function useClickIds(): FunnelContext['clickIds'] {\n return useContextObject().clickIds\n}\n\n/** `useSystem()` — funnel id, test/live mode, build clock (read-only). */\nexport function useSystem(): FunnelContext['system'] {\n return useContextObject().system\n}\n\n/** Read a dotted path out of context, e.g. `useContextValue('device.isMobile')`. */\nexport function useContextValue(path: string): unknown {\n const ctx = useContextObject()\n return useMemo(\n () => path.split('.').reduce<unknown>((acc, k) => (acc as Record<string, unknown>)?.[k], ctx),\n [ctx, path],\n )\n}\n","/**\n * The REAL platform tracker (phase-1 §1.4 / BREAKING-CHANGES B-1) — POSTs the taxonomy to\n * `POST {apiBase}/campaign/{campaignId}/event`, the SAME ingestion endpoint v1 funnels use, so\n * v2 sessions/customers/events land in the shared analytics graph with zero schema fork.\n *\n * Built INSIDE the sealed bundle from serializable config (`MountOpts.tracking`) — the renderer\n * can only pass data across the build boundary, never live objects. Wired automatically by\n * `createFunnelTree` when tracking config is present.\n *\n * Behavior:\n * - SSR-safe: on the server (or with no config) this is never constructed — `createFunnelTree`\n * only wires it client-side; the export also guards `window` for direct users.\n * - mode:'test' → console tracker (previews/QA never pollute shared analytics; the real\n * test-mode quarantine is phase-3 §3.1c).\n * - The FIRST event establishes the session: sends are SERIALIZED until the server returns a\n * `sessionId` (avoids N parallel first-events racing session creation), then fire-and-forget.\n * The sessionId is kept in sessionStorage (per-tab reload continuity) — durable cross-visit\n * identity is the `visitorId`'s job, not the session's.\n * - `visitorId` (bare id, SSR-injected from the af_vid cookie) rides on every event — the\n * ingestion side uses it for durable session lookup + anonymous-Customer continuity.\n * - Acquisition (utm + click-ids + fbp/fbc + referrer) is folded into the FIRST event's\n * `userData.query` bag — exactly where the v1 ingestion's `extractUtmParams`/attribution\n * upgrade logic already looks. Pushed once; never re-sent.\n * - Failures are swallowed (console.warn) — tracking must never break a funnel.\n */\nimport type { Tracker } from './tracking'\nimport type { Acquisition } from '../state/context'\nimport { createConsoleTracker, exposurePayload } from './tracking'\n\n/** The string-valued, non-empty click-ids — the only kind either attribution shape carries. */\nfunction validClickIds(acq: Acquisition): [string, string][] {\n return Object.entries(acq.clickIds ?? {}).filter(\n (e): e is [string, string] => typeof e[1] === 'string' && e[1] !== '',\n )\n}\n\nexport interface PlatformTrackingConfig {\n /** Public API origin, e.g. `https://api.appfunnel.net` (no trailing slash). */\n apiBase: string\n /** Campaign DB id (the ingestion route key). */\n campaignId: string\n /** WebFunnel DB id (NOT the funnel.ts config id). */\n funnelId: string\n /** Verified bare visitor id (phase-1 §1.2), SSR-injected. */\n visitorId?: string | null\n /** Server-resolved session id (renderer looked it up by visitorId for hydration) — a fallback\n * seed; a per-tab sessionStorage id wins over it (v1 tab semantics). */\n sessionId?: string | null\n /** FUNNEL-split experiment assignment (phase-4): the renderer picked this funnel for the\n * visitor — the tracker emits the experiment.exposure (page-level exposures come from the\n * flow runtime instead). Deduped per (session, experiment) in analytics. */\n experiment?: { id: string; variant: string; version?: number }\n mode?: 'test' | 'live'\n}\n\nfunction acquisitionQueryBag(acq: Acquisition): Record<string, string> {\n const q: Record<string, string> = {}\n const utm = acq.utm ?? {}\n for (const [k, v] of Object.entries({\n utm_source: utm.source, utm_medium: utm.medium, utm_campaign: utm.campaign,\n utm_term: utm.term, utm_content: utm.content,\n })) if (v) q[k] = v\n for (const [k, v] of validClickIds(acq)) q[k] = v\n if (acq.cookies?.fbp) q._fbp = acq.cookies.fbp\n if (acq.cookies?.fbc) q._fbc = acq.cookies.fbc\n return q\n}\n\n/**\n * The `adAttribution` body field in v1's EXACT shape (admin collectAdAttribution): click-ids by\n * their param names + `fbp`/`fbc`/`ttp` cookie values, with `fbc` synthesized from `fbclid` when\n * the cookie is absent (`fb.1.<ts>.<fbclid>` — Meta's documented format). Ingestion's existing\n * first-write-wins merge + traffic-source upgrade + typed-column extraction (phase-1 §1.3) all\n * key on these names — reusing the battle-tested path instead of forking it.\n */\nfunction acquisitionAdAttribution(acq: Acquisition): Record<string, string> {\n const a: Record<string, string> = {}\n for (const [k, v] of validClickIds(acq)) a[k] = v\n if (acq.cookies?.fbp) a.fbp = acq.cookies.fbp\n if (acq.cookies?.fbc) a.fbc = acq.cookies.fbc\n else if (acq.clickIds?.fbclid) a.fbc = `fb.1.${Date.now()}.${acq.clickIds.fbclid}`\n return a\n}\n\nexport function createPlatformTracker(cfg: PlatformTrackingConfig): Tracker {\n // Never on the server; never for test mode (preview/QA stays out of shared analytics).\n if (typeof window === 'undefined' || cfg.mode === 'test') return createConsoleTracker()\n\n const base = cfg.apiBase.replace(/\\/+$/, '')\n const url = `${base}/campaign/${encodeURIComponent(cfg.campaignId)}/event`\n const sidKey = `af_sid:${cfg.campaignId}`\n let sessionId: string | null = null\n try { sessionId = window.sessionStorage.getItem(sidKey) } catch { /* storage may be blocked */ }\n if (!sessionId && cfg.sessionId) sessionId = cfg.sessionId // server-resolved (visitorId) fallback\n\n let acquisition: Acquisition | null = null\n let acquisitionSent = false\n let chain: Promise<void> = Promise.resolve()\n\n const send = async (event: string, data?: Record<string, unknown>, userData?: Record<string, unknown>) => {\n let mergedUserData = userData\n let adAttribution: Record<string, string> | undefined\n // Acquisition (click-ids/UTMs) is the ONLY carrier of paid-attribution for v2 and rides the\n // FIRST event. `attachingAcquisition` marks that THIS send is carrying it — we only burn the\n // once-flag on SUCCESS (below), so a dropped first POST re-attaches on the next event instead\n // of reporting a paid session as direct (adversarial review P2).\n let attachingAcquisition = false\n if (acquisition && !acquisitionSent) {\n attachingAcquisition = true\n const query = acquisitionQueryBag(acquisition)\n mergedUserData = Object.keys(query).length ? { ...userData, query } : userData\n const ad = acquisitionAdAttribution(acquisition)\n if (Object.keys(ad).length) adAttribution = ad\n }\n const body = {\n campaignId: cfg.campaignId,\n funnelId: cfg.funnelId,\n event,\n sessionId: sessionId ?? undefined,\n visitorId: cfg.visitorId ?? undefined,\n eventId: typeof data?.eventId === 'string' ? (data.eventId as string) : undefined,\n data: data ?? {},\n metadata: {\n language: typeof navigator !== 'undefined' ? navigator.language : undefined,\n screen: typeof window.screen !== 'undefined' ? `${window.screen.width}x${window.screen.height}` : undefined,\n timezone: (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone } catch { return undefined } })(),\n referrer: typeof document !== 'undefined' && document.referrer ? document.referrer : undefined,\n },\n ...(mergedUserData ? { userData: mergedUserData } : {}),\n ...(adAttribution ? { adAttribution } : {}),\n }\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n keepalive: true, // survives page.exit / unload\n })\n // Only NOW commit the once-flag — a throw above (network drop) leaves it false so the next\n // event re-carries acquisition. keepalive caps the body at ~64KB; acquisition + one event is\n // far under that (variable snapshots use the separate session-data endpoint).\n if (attachingAcquisition) acquisitionSent = true\n const json = (await res.json().catch(() => null)) as { sessionId?: string } | null\n if (json?.sessionId && json.sessionId !== sessionId) {\n sessionId = json.sessionId\n try { window.sessionStorage.setItem(sidKey, sessionId) } catch { /* best-effort */ }\n }\n }\n\n const enqueue = (event: string, data?: Record<string, unknown>, userData?: Record<string, unknown>) => {\n const task = () =>\n send(event, data, userData).catch((e) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[appfunnel] track failed (${event}):`, e)\n })\n if (!sessionId) {\n // Serialize until the first response resolves the session — later events ride the chain.\n chain = chain.then(task)\n } else {\n void task()\n }\n }\n\n // ── Variable persistence (phase-1 §1.1: the server-backed namespace store) ──\n // Every namespace write pushes the FULL flat snapshot ({'user.email', 'responses.goal', …});\n // we debounce trailing-edge and POST the latest snapshot to the v1 session-data endpoint\n // (the API merges it into session.data and runs the normalizer's v2 extraction). Needs a\n // session — before one resolves, the flush rides the send chain. Flushed on pagehide.\n const VARS_DEBOUNCE_MS = 800\n let pendingVars: Record<string, unknown> | null = null\n let varsTimer: ReturnType<typeof setTimeout> | null = null\n\n const flushVars = () => {\n if (varsTimer) { clearTimeout(varsTimer); varsTimer = null }\n if (!pendingVars) return\n const doPost = () => {\n if (!pendingVars || !sessionId) return\n const userData = pendingVars\n pendingVars = null\n void fetch(`${base}/campaign/${encodeURIComponent(cfg.campaignId)}/event/session/data`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ sessionId, userData }),\n keepalive: true,\n }).catch((e) => {\n if (process.env.NODE_ENV !== 'production') console.warn('[appfunnel] variable persist failed:', e)\n })\n }\n if (sessionId) doPost()\n else chain = chain.then(doPost) // wait for the first event to establish the session\n }\n\n try {\n window.addEventListener('pagehide', flushVars)\n } catch { /* non-browser-ish environments */ }\n\n // FUNNEL-split exposure: the renderer made the assignment server-side; record it once per\n // page load (analytics dedupes by session+experiment) so the split's arms are measurable.\n if (cfg.experiment?.id && cfg.experiment.variant) {\n enqueue('experiment.exposure', exposurePayload(cfg.experiment.id, cfg.experiment.variant, cfg.experiment.version))\n }\n\n return {\n track: (event: string, data?: Record<string, unknown>, userData?: Record<string, unknown>) =>\n enqueue(event, data, userData),\n identify: (email: string, eventId?: string) =>\n enqueue('user.registered', { email, ...(eventId ? { eventId } : {}) }),\n setVariables: (variables: Record<string, unknown>) => {\n pendingVars = variables // full snapshot — latest wins\n if (varsTimer) clearTimeout(varsTimer)\n varsTimer = setTimeout(flushVars, VARS_DEBOUNCE_MS)\n },\n setAcquisition: (acq: Acquisition) => { acquisition = acq },\n }\n}\n","/**\n * The **mount contract** — `mount.tsx` is THE v2 convention for a funnel build.\n *\n * Every published funnel ships a `mount.tsx` that exports exactly two things\n * (the {@link MountModule} shape):\n *\n * - `pages: RuntimePage[]` — the code-split page list in file order (the\n * admin editor rewrites this array; the anchor\n * `export const pages: RuntimePage[] = [` must survive verbatim);\n * - `tree: (opts: MountOpts) => ReactNode` — built with\n * {@link createFunnelTree}, consumed identically by the server entry (SSR)\n * and the client entry (hydration) so both render the same tree.\n *\n * `createFunnelTree` packages the canonical provider stack so funnel builds\n * don't hand-roll it:\n *\n * AssetsProvider → FunnelProvider{config, products, locale, mode}\n * → FunnelView{pages, layout, initialKey, prefetch:'off'}\n *\n * (`prefetch: 'off'` because the renderer owns chunk warming via\n * `<link rel=\"modulepreload\">` over `useNavigation().nextCandidates`.)\n */\n\nimport {\n createContext,\n createElement,\n Fragment,\n useContext,\n type ComponentType,\n type ReactNode,\n} from 'react'\nimport { FunnelProvider } from '../state/namespaces'\nimport { FunnelView, type RuntimePage } from './flow'\nimport type { FunnelDefinition } from './spine'\nimport type { ProductInput } from '../commerce/money'\nimport { CheckoutResume, type CheckoutDriver, type CheckoutDriverContext } from '../commerce/checkout'\nimport type { RuntimeExperiment } from './experiments'\nimport type { MessageCatalog } from '../i18n/translation'\nimport { createPlatformTracker } from '../tracking/platformTracker'\n\n// ── Assets ───────────────────────────────────────────────\n\n/**\n * Funnel asset map: logical name (e.g. `logo.svg`) → content-addressed CDN URL,\n * injected by the renderer. Assets live in a SHARED content-addressed store\n * (`appfunnel/assets/<hash>`), so identical content is stored once across all\n * builds and funnels while staying immutable. Both SSR and client read the same\n * injected map → URLs match. Defaults to `{}` (no provider needed in tests).\n */\nexport const AssetsContext = createContext<Record<string, string>>({})\n\n/** Provides the funnel's asset map (mounted for you by {@link createFunnelTree}). */\nexport function AssetsProvider({\n assets,\n children,\n}: {\n assets?: Record<string, string>\n children: ReactNode\n}): ReactNode {\n return createElement(AssetsContext.Provider, { value: assets ?? {} }, children)\n}\n\n/** The whole asset map (logical name → CDN URL). `{}` outside a provider. */\nexport function useAssets(): Record<string, string> {\n return useContext(AssetsContext)\n}\n\n/** `useAsset('logo.svg')` — one asset's CDN URL, or `undefined` if not injected. */\nexport function useAsset(name: string): string | undefined {\n return useContext(AssetsContext)[name]\n}\n\n// ── Mount options ────────────────────────────────────────\n\n/** What the renderer injects when mounting a funnel build (SSR and hydration). */\nexport interface MountOpts {\n /** Platform-resolved product prices (one currency per visitor). */\n products?: ProductInput[]\n /** Explicit locale override (URL/param/geo); wins over the detected device locale. */\n locale?: string\n mode?: 'test' | 'live'\n /** Deep-link / reload entry page (honored only if its entry guard passes). */\n initialKey?: string\n /** Asset map: logical name → content-addressed CDN URL. */\n assets?: Record<string, string>\n /** Per-locale message catalogs (`messages/<locale>.json`) — overrides the mount's baked-in ones. */\n messages?: MessageCatalog\n /** The SIGNED anonymous visitor id (bare id, verified server-side; phase-1 §1.2) — the\n * renderer mints/reads the `af_vid` cookie and injects the value here. Feeds\n * `context.identity.visitorId` (experiment bucketing fallback seed, session continuity). */\n visitorId?: string | null\n /** Known customer id (identified visitor) — the preferred bucketing seed. */\n customerId?: string | null\n /** Platform tracking config (phase-1 §1.4). Present → `createFunnelTree` wires the real\n * platform tracker (events POST to the shared ingestion endpoint). Absent (preview, tests,\n * bare mounts) → the console tracker. Serializable on purpose — it crosses the sealed-build\n * boundary as data. */\n tracking?: {\n apiBase: string\n campaignId: string\n /** WebFunnel DB id (NOT the funnel.ts config id). */\n funnelId: string\n /** FUNNEL-split assignment (phase-4) — the tracker emits its exposure event. */\n experiment?: { id: string; variant: string; version?: number }\n }\n /** Server-hydrated namespace snapshot (phase-1 §1.1): flat namespaced keys\n * (`user.email`, `responses.goal`, …) from the visitor's latest session — the renderer\n * resolves it by visitorId so a returning visitor resumes with their answers. */\n sessionValues?: Record<string, string | number | boolean | null | string[]>\n /** RUNNING page-experiment records (phase-4): platform-owned wiring over the bundle's\n * `@variant` pages, injected at render time — no rebuild to start/stop/reweight. */\n experiments?: RuntimeExperiment[]\n /** The server-resolved session id backing `sessionValues` — seeds the tracker (fallback)\n * and `context.session.id`. */\n sessionId?: string | null\n}\n\n/**\n * The shape a funnel build's `mount.tsx` module must export — the named,\n * versioned contract between a build and the renderer/editor:\n * `import type { MountModule } from '@appfunnel-dev/sdk'`.\n */\nexport type MountModule = {\n pages: RuntimePage[]\n tree: (opts: MountOpts) => ReactNode\n}\n\n// ── createFunnelTree ─────────────────────────────────────\n\nexport interface CreateFunnelTreeInput {\n /** The funnel's spine (`defineFunnel(...)`). */\n config: FunnelDefinition\n /** Code-split pages in file order (the same array `mount.tsx` exports). */\n pages: RuntimePage[]\n /** Persistent chrome wrapped around the page area (mounted once). */\n layout?: ComponentType<{ children: ReactNode }>\n /**\n * The platform checkout driver factory — `mount.tsx` imports it from a driver\n * subpath entry (`import { stripeCheckoutDriver } from '@appfunnel-dev/sdk/driver-stripe'`)\n * and passes it here, so the provider choice stays in the SDK-owned authoring\n * contract while the ctx (apiBase/campaign/funnel/mode/identity) stays\n * renderer-injected. Called once per `tree()` mount, only when tracking config\n * is present — without it there is no API to charge against (preview, tests,\n * bare mounts) and the mock driver fallback stays in place. Test mode still\n * constructs the real driver: the wire contract carries `mode`, and the server\n * resolves the provider's TEST store from it (that's the quarantine, not the client).\n */\n checkoutDriver?: (ctx: CheckoutDriverContext) => CheckoutDriver\n /**\n * The funnel's message catalogs (`messages/<locale>.json`), keyed by locale. The generated\n * `mount.tsx` imports the catalogs and passes them here so `t()` resolves at render (SSR + client);\n * `MountOpts.messages` can still override per-request. Omit for funnels with no translations.\n */\n messages?: MessageCatalog\n}\n\n/**\n * Build a funnel's `tree(opts)` — the standard provider stack over your pages.\n *\n * ```tsx\n * export const pages: RuntimePage[] = [ ... ]\n * export const tree = createFunnelTree({ config, pages, layout: Layout })\n * ```\n */\nexport function createFunnelTree({\n config,\n pages,\n layout,\n checkoutDriver,\n messages,\n}: CreateFunnelTreeInput): (opts: MountOpts) => ReactNode {\n return function tree(opts: MountOpts): ReactNode {\n const mode = opts.mode ?? 'live'\n // The real platform tracker when the renderer passed tracking config (live only — the\n // factory itself no-ops for SSR and test mode). One instance per tree() call: the entries\n // call tree() exactly once per mount (SSR render / hydration), so no memo hook is needed\n // and tree() stays callable outside React.\n const tracker = opts.tracking\n ? createPlatformTracker({\n ...opts.tracking,\n visitorId: opts.visitorId,\n sessionId: opts.sessionId,\n mode,\n })\n : undefined\n // The platform checkout driver when mount.tsx exported a factory AND the renderer passed\n // tracking config — the driver ctx derives from the SAME injected data the tracker uses,\n // so there is no second config channel. Unlike the tracker (whose factory no-ops on the\n // server), the driver IS constructed during SSR, deliberately: factories are\n // construction-safe closures over serializable ctx (provider SDKs load only in\n // effects/event handlers), and a driver's renderInline returns the same stable placeholder\n // on the server and the first client paint. Skipping construction server-side would SSR\n // the mock fallback's <button> into inline surfaces — a guaranteed hydration mismatch.\n const checkout = checkoutDriver && opts.tracking\n ? checkoutDriver({\n apiBase: opts.tracking.apiBase,\n campaignId: opts.tracking.campaignId,\n funnelId: opts.tracking.funnelId,\n mode,\n sessionId: opts.sessionId,\n visitorId: opts.visitorId,\n })\n : undefined\n // The redirect-return resume leg (hosted-checkout success URLs carry\n // `?af_checkout={correlationId}`) rides the persistent layout slot: it needs\n // tracker + navigation, which only exist INSIDE FunnelView's nav context, and\n // the layout is the one mount-once spot there. SSR-safe (renders null;\n // effect-only) and inert without the param.\n const layoutWithResume: ComponentType<{ children: ReactNode }> = function LayoutWithCheckoutResume({\n children,\n }: {\n children: ReactNode\n }): ReactNode {\n return createElement(\n Fragment,\n null,\n createElement(CheckoutResume, null),\n layout ? createElement(layout, null, children) : children,\n )\n }\n return createElement(AssetsProvider, {\n assets: opts.assets,\n children: createElement(FunnelProvider, {\n config,\n products: opts.products ?? [],\n messages: opts.messages ?? messages,\n locale: opts.locale,\n tracker,\n checkout,\n sessionValues: opts.sessionValues,\n experiments: opts.experiments,\n context: {\n mode,\n visitorId: opts.visitorId ?? null,\n customerId: opts.customerId ?? null,\n sessionId: opts.sessionId ?? null,\n },\n children: createElement(FunnelView, {\n pages,\n layout: layoutWithResume,\n initialKey: opts.initialKey,\n prefetch: 'off', // renderer background-modulepreloads all chunks\n }),\n }),\n })\n }\n}\n","import {\n createElement,\n type ButtonHTMLAttributes,\n type MouseEvent as ReactMouseEvent,\n type ReactNode,\n} from 'react'\nimport { useField } from '../state/namespaces'\nimport { useNavigation } from './flow'\n\n/**\n * The two-tier component model (doc 07 §\"magic ≠ black box\"): the magic lives in\n * headless hooks (`useField`, `useNavigation`); these styleable components are\n * thin, restyle-able wrappers over them. Every `<Choice>` reduces to `useField`\n * + your own JSX — eject any time. They pass `className`/DOM props straight\n * through and never dictate a pixel beyond the minimum.\n */\n\nexport interface ChoiceOption {\n value: string\n label?: ReactNode\n}\n\nexport interface ChoiceProps {\n /** Writable namespaced path to bind, e.g. `responses.goal`. */\n bind: string\n /** The selectable options (a bare string is shorthand for `{value, label}`). */\n options: (string | ChoiceOption)[]\n /** Class applied to each option button. */\n className?: string\n /** Class applied to the selected option button (in addition to `className`). */\n selectedClassName?: string\n /** Advance navigation after a choice (handy for single-tap question pages). */\n advanceOnSelect?: boolean\n}\n\n/**\n * Single-select bound to a writable field. `<Choice bind=\"responses.goal\"\n * options={[\"lose\", \"gain\"]} />` — selecting persists + (later) tracks; pass\n * `advanceOnSelect` to move to the next page on tap.\n */\nexport function Choice({\n bind,\n options,\n className,\n selectedClassName,\n advanceOnSelect,\n}: ChoiceProps): ReactNode {\n const { value, set } = useField(bind)\n const nav = useNavigation()\n\n return options.map((opt) => {\n const o: ChoiceOption = typeof opt === 'string' ? { value: opt } : opt\n const selected = value === o.value\n return createElement(\n 'button',\n {\n key: o.value,\n type: 'button',\n 'aria-pressed': selected,\n 'data-selected': selected || undefined,\n className: selected && selectedClassName ? `${className ?? ''} ${selectedClassName}`.trim() : className,\n onClick: () => {\n set(o.value)\n if (advanceOnSelect) nav.next()\n },\n },\n o.label ?? o.value,\n )\n })\n}\n\nexport interface NextProps extends ButtonHTMLAttributes<HTMLButtonElement> {\n children?: ReactNode\n}\n\n/** A button that advances the funnel (the current page's `next`, else linear). */\nexport function Next({ children, onClick, ...rest }: NextProps): ReactNode {\n const { next } = useNavigation()\n return createElement(\n 'button',\n {\n type: 'button',\n ...rest,\n onClick: (e: ReactMouseEvent<HTMLButtonElement>) => {\n onClick?.(e)\n if (!e.defaultPrevented) next()\n },\n },\n children ?? 'Continue',\n )\n}\n\nexport interface BackProps extends ButtonHTMLAttributes<HTMLButtonElement> {\n children?: ReactNode\n}\n\n/** A button that returns to the previous page; hidden when there's no history. */\nexport function Back({ children, onClick, ...rest }: BackProps): ReactNode {\n const { back, canGoBack } = useNavigation()\n if (!canGoBack) return null\n return createElement(\n 'button',\n {\n type: 'button',\n ...rest,\n onClick: (e: ReactMouseEvent<HTMLButtonElement>) => {\n onClick?.(e)\n if (!e.defaultPrevented) back()\n },\n },\n children ?? 'Back',\n )\n}\n","/**\n * The **event catalog** — the single source of truth for *which* events exist and\n * how each is routed (analytics vs. integrations vs. runtime-only). Pairs with the\n * typed payloads in {@link ./tracking}.`FunnelEventDataMap`.\n *\n * This replaces the duplication the monorepo flags (`shared/events/catalog.ts` is\n * \"documentation, not imported\" — the taxonomy is re-declared in\n * `admin/lib/funnel/tracking.ts`, each `admin/lib/integrations/*` EVENT_MAP, and\n * `api/src/integrations/constants`). In v2 the **SDK owns the taxonomy** (it emits\n * it), so the bus, the pixel loaders, and the platform all import *this*.\n */\n\nexport type EventSource = 'frontend' | 'backend'\n\nexport interface EventMeta {\n /** Where the event originates. `backend` = the server emits it (e.g. a settled charge). */\n sources: EventSource[]\n /** Persisted to analytics. */\n tracking: boolean\n /** Forwarded to ad/integration pixels (Meta/GTM/TikTok/…). */\n integrations: boolean\n /** Runtime-only JS subscription — not persisted, not sent to integrations. */\n runtime?: boolean\n}\n\n/**\n * Every event the system knows, with its routing metadata. Keys are the taxonomy\n * names (a superset of `FunnelEventDataMap`: it also lists the **backend-originated**\n * monetary events the platform pushes to the client bus for pixel firing).\n */\nexport const EVENT_CATALOG = {\n // ── Runtime / navigation (JS subscriptions; not persisted) ──\n 'funnel.start': { sources: ['frontend'], tracking: false, integrations: false, runtime: true },\n 'experiment.exposure': { sources: ['frontend'], tracking: true, integrations: false },\n\n // ── Frontend, tracked; some also go to pixels ──\n 'page.view': { sources: ['frontend'], tracking: true, integrations: true },\n 'page.exit': { sources: ['frontend'], tracking: true, integrations: false },\n 'user.registered': { sources: ['frontend'], tracking: true, integrations: true },\n 'checkout.start': { sources: ['frontend'], tracking: true, integrations: true },\n 'checkout.payment_added': { sources: ['frontend'], tracking: true, integrations: true },\n 'checkout.failed': { sources: ['frontend'], tracking: true, integrations: false },\n\n // ── Backend-originated money events (server mints the eventId; client fires the pixel) ──\n 'purchase.complete': { sources: ['backend'], tracking: true, integrations: true },\n 'customer.first_purchase': { sources: ['backend'], tracking: true, integrations: true },\n 'subscription.created': { sources: ['backend'], tracking: true, integrations: true },\n 'subscription.renewal': { sources: ['backend'], tracking: true, integrations: true },\n} as const satisfies Record<string, EventMeta>\n\n/** A catalog event name. */\nexport type CatalogEvent = keyof typeof EVENT_CATALOG\n\n/** True if the event is persisted to analytics. */\nexport function isTrackableEvent(name: string): boolean {\n return EVENT_CATALOG[name as CatalogEvent]?.tracking ?? false\n}\n\n/** True if the event is forwarded to ad/integration pixels. */\nexport function isIntegrationEvent(name: string): boolean {\n return EVENT_CATALOG[name as CatalogEvent]?.integrations ?? false\n}\n\n/** The events that feed integrations — the set a pixel loader subscribes to. */\nexport function integrationEvents(): CatalogEvent[] {\n return (Object.keys(EVENT_CATALOG) as CatalogEvent[]).filter((e) => EVENT_CATALOG[e].integrations)\n}\n","/**\n * `<Script>` — the **declared third-party embed** primitive (phase-2 §2.3d).\n *\n * The controlled escape hatch for runtime widgets/embeds that genuinely need\n * client code — Intercom, Trustpilot, a calendar embed, an operator pixel. Unlike\n * arbitrary `<script>` injection, it's **declared** (the funnel author writes\n * `<Script src=…/>`), **deduped** (injected at most once per id/src, even across\n * page navigation in the SPA — a chat widget must not reload on every page), and\n * **CSP-friendly** (accepts a `nonce`).\n *\n * CSP enforcement itself is the **renderer's** job: it scans the funnel's declared\n * `<Script src>`s (build-time) into the `script-src` allowlist and supplies the\n * `nonce`. This component just injects the tag at the right time.\n *\n * For *analytics* pixels, prefer subscribing to the `window.appfunnel` bus\n * ({@link ../tracking/bus}) — `<Script>` is for non-analytics third-party widgets\n * (and the pixel loader snippets, which then subscribe to the bus).\n */\n\nimport { useEffect } from 'react'\n\n/** Module-level registry so a given script injects once for the app's lifetime. */\nconst injected = new Set<string>()\n\nexport interface ScriptProps {\n /** The third-party script URL. */\n src: string\n /**\n * When to inject. `afterInteractive` (default) injects on mount (after hydration);\n * `lazyOnload` waits for idle/`load` so it never competes with the funnel's own JS.\n */\n strategy?: 'afterInteractive' | 'lazyOnload'\n /** Dedup key (defaults to `src`) — the script injects at most once per id. */\n id?: string\n /** Defaults to `true`. */\n async?: boolean\n defer?: boolean\n /** CSP nonce — supplied by the renderer. */\n nonce?: string\n /** Extra attributes (e.g. `data-*`). */\n attributes?: Record<string, string>\n onLoad?: () => void\n onError?: () => void\n}\n\n/**\n * Injects a third-party script once. Renders nothing. Persists across navigation\n * (the tag is never removed on unmount — third-party widgets should stay loaded).\n */\nexport function Script({\n src,\n strategy = 'afterInteractive',\n id,\n async = true,\n defer,\n nonce,\n attributes,\n onLoad,\n onError,\n}: ScriptProps): null {\n useEffect(() => {\n if (typeof document === 'undefined') return\n const key = id ?? src\n if (injected.has(key)) {\n onLoad?.() // already present from an earlier mount\n return\n }\n\n const inject = () => {\n if (injected.has(key)) return\n injected.add(key)\n const el = document.createElement('script')\n el.src = src\n if (id) el.id = id\n if (async) el.async = true\n if (defer) el.defer = true\n if (nonce) el.nonce = nonce\n if (attributes) for (const [k, v] of Object.entries(attributes)) el.setAttribute(k, v)\n el.addEventListener('load', () => onLoad?.())\n el.addEventListener('error', () => {\n injected.delete(key) // allow a later retry\n onError?.()\n })\n document.head.appendChild(el)\n }\n\n if (strategy === 'lazyOnload') {\n const ric = (window as unknown as { requestIdleCallback?: (cb: () => void) => number })\n .requestIdleCallback\n if (ric) {\n ric(inject)\n } else {\n const t = setTimeout(inject, 0)\n return () => clearTimeout(t)\n }\n return\n }\n inject()\n // src/id identify the script; injection is idempotent via the registry.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [src, id])\n\n return null\n}\n\n/** Internal: clear the injected-script registry (tests only). */\nexport function __resetScriptRegistry(): void {\n injected.clear()\n}\n"]}
|