@appfunnel-dev/sdk 2.0.0-canary.4 → 2.0.0-canary.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/{chunk-AKO6XKXP.js → chunk-AXXG3ODP.js} +10 -3
  2. package/dist/chunk-AXXG3ODP.js.map +1 -0
  3. package/dist/{chunk-M6U3FNRW.js → chunk-CFFMZYPE.js} +3 -3
  4. package/dist/{chunk-M6U3FNRW.js.map → chunk-CFFMZYPE.js.map} +1 -1
  5. package/dist/chunk-EMMSS5I5.cjs +37 -0
  6. package/dist/chunk-EMMSS5I5.cjs.map +1 -0
  7. package/dist/chunk-G3PMV62Z.js +33 -0
  8. package/dist/chunk-G3PMV62Z.js.map +1 -0
  9. package/dist/{chunk-JSRKA375.cjs → chunk-G44BUG6G.cjs} +10 -3
  10. package/dist/chunk-G44BUG6G.cjs.map +1 -0
  11. package/dist/{chunk-LJYLGLFS.cjs → chunk-QMAZGLGV.cjs} +2 -35
  12. package/dist/chunk-QMAZGLGV.cjs.map +1 -0
  13. package/dist/{chunk-YY375F2B.js → chunk-TNLRQPVY.js} +3 -33
  14. package/dist/chunk-TNLRQPVY.js.map +1 -0
  15. package/dist/{chunk-CY4VBSMX.cjs → chunk-VAOR77NW.cjs} +7 -7
  16. package/dist/{chunk-CY4VBSMX.cjs.map → chunk-VAOR77NW.cjs.map} +1 -1
  17. package/dist/chunk-WYUDL4FI.cjs +8 -0
  18. package/dist/chunk-WYUDL4FI.cjs.map +1 -0
  19. package/dist/chunk-ZZJG4EYL.js +6 -0
  20. package/dist/chunk-ZZJG4EYL.js.map +1 -0
  21. package/dist/driver-paddle.cjs +23 -22
  22. package/dist/driver-paddle.cjs.map +1 -1
  23. package/dist/driver-paddle.js +3 -2
  24. package/dist/driver-paddle.js.map +1 -1
  25. package/dist/driver-stripe.cjs +37 -36
  26. package/dist/driver-stripe.cjs.map +1 -1
  27. package/dist/driver-stripe.js +3 -2
  28. package/dist/driver-stripe.js.map +1 -1
  29. package/dist/index.cjs +504 -80
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +135 -74
  32. package/dist/index.d.ts +135 -74
  33. package/dist/index.js +447 -23
  34. package/dist/index.js.map +1 -1
  35. package/dist/{manifest-Cr2y1op6.d.cts → manifest-Dl7faaKe.d.cts} +34 -0
  36. package/dist/{manifest-Cr2y1op6.d.ts → manifest-Dl7faaKe.d.ts} +34 -0
  37. package/dist/manifest-entry.cjs +45 -30
  38. package/dist/manifest-entry.cjs.map +1 -1
  39. package/dist/manifest-entry.d.cts +1 -1
  40. package/dist/manifest-entry.d.ts +1 -1
  41. package/dist/manifest-entry.js +10 -3
  42. package/dist/manifest-entry.js.map +1 -1
  43. package/dist/protocol.cjs +13 -0
  44. package/dist/protocol.cjs.map +1 -0
  45. package/dist/protocol.d.cts +182 -0
  46. package/dist/protocol.d.ts +182 -0
  47. package/dist/protocol.js +4 -0
  48. package/dist/protocol.js.map +1 -0
  49. package/package.json +14 -2
  50. package/dist/chunk-AKO6XKXP.js.map +0 -1
  51. package/dist/chunk-JSRKA375.cjs.map +0 -1
  52. package/dist/chunk-LJYLGLFS.cjs.map +0 -1
  53. package/dist/chunk-YY375F2B.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/i18n/locale.ts","../src/commerce/money.ts","../src/flow/spine.ts","../src/flow/experiments.ts","../src/manifest/manifest.ts"],"names":[],"mappings":";;;AAUA,IAAM,SAAA,mBAAY,IAAI,GAAA,CAAI,CAAC,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,IAAI,CAAC,CAAA;AAGnE,SAAS,MAAM,MAAA,EAAyB;AAC7C,EAAA,OAAO,UAAU,GAAA,CAAI,MAAA,CAAO,MAAM,GAAG,CAAA,CAAE,CAAC,CAAC,CAAA;AAC3C;AAEA,IAAM,OAAO,CAAC,CAAA,KAA8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Ac,GAAA,CAAI,CAAC,KAAK,CAAC,aAAA,CAAc,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;AAEtG,EAAA,OAAO;AAAA;AAAA,IAEL,EAAA,EACE,QAAA,CAAS,MAAA,KAAW,CAAA,IACpB,WAAA,CAAY,WAAW,CAAA,IACvB,UAAA,CAAW,MAAA,KAAW,CAAA,IACtB,CAAC,mBAAA,IACD,cAAc,MAAA,KAAW,CAAA,IACzB,cAAA,CAAe,MAAA,KAAW,CAAA,IAC1B,CAAC,qBACD,kBAAA,CAAmB,MAAA,KAAW,CAAA,IAC9B,eAAA,CAAgB,MAAA,KAAW,CAAA;AAAA,IAC7B,QAAA;AAAA,IACA,WAAA;AAAA,IACA,UAAA;AAAA,IACA,mBAAA;AAAA,IACA,aAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA;AAAA,IACA,iBAAA;AAAA,IACA,kBAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-JSRKA375.cjs","sourcesContent":["/**\n * Pure locale resolution — no React. Split out of {@link ./translation} so the\n * server/tooling entry (`@appfunnel-dev/sdk/manifest`) can resolve a visitor's\n * locale without pulling component code. {@link ./translation} re-exports it.\n */\n\nimport type { FunnelLocales } from '../flow/spine'\n\nexport type Direction = 'ltr' | 'rtl'\n\nconst RTL_LANGS = new Set(['ar', 'he', 'fa', 'ur', 'ps', 'sd', 'dv', 'yi'])\n\n/** Whether a locale is right-to-left (by language subtag). */\nexport function isRtl(locale: string): boolean {\n return RTL_LANGS.has(locale.split('-')[0])\n}\n\nconst base = (l: string | undefined): string | undefined => l?.split('-')[0]\n\n/**\n * Resolve the active locale: `override` (URL/param) → `detected` (device) →\n * funnel default, each only if supported (matched by exact tag or language\n * subtag). Mirrors doc 05's resolution chain (the geo/header steps happen\n * server-side and arrive via `override`/`detected`).\n */\nexport function resolveLocale(\n config: FunnelLocales | undefined,\n detected: string,\n override?: string,\n): string {\n const supported = config?.supported ?? (config?.default ? [config.default] : ['en'])\n const def = config?.default ?? supported[0] ?? 'en'\n const pick = (l?: string): string | undefined => {\n if (!l) return undefined\n if (supported.includes(l)) return l\n return supported.find((s) => base(s) === base(l))\n }\n return pick(override) ?? pick(detected) ?? def\n}\n","/**\n * Pure catalog math — no React, no I/O. Split out of {@link ./catalog} so the\n * server/tooling entry (`@appfunnel-dev/sdk/manifest`) can compile/resolve\n * products without pulling react-dom or any component code into its graph.\n * {@link ./catalog} re-exports everything here and adds the React wiring.\n */\n\n// ── Shape ────────────────────────────────────────────────\n\nexport type Interval = 'day' | 'week' | 'month' | 'year' | 'one_time'\n\n/** What the platform hands the funnel per product (a single provider-resolved price). */\nexport interface ProductInput {\n id: string\n /** The catalog product KEY this input charges (the slot's assignment). Defaults to `id` (legacy/identity slots). */\n catalogKey?: string\n name?: string\n displayName?: string\n /** Provider-resolved price in **minor units** (the provider chose the currency). */\n amount: number\n /** Currency of `amount`, as the provider resolved it (e.g. `DKK`). */\n currency: string\n interval?: Interval\n intervalCount?: number\n trialDays?: number\n /** Trial price in minor units (omit/0 = free trial). */\n trialAmount?: number\n /** Settlement provider — opaque to the author, used by the checkout driver. */\n provider?: string\n}\n\n/** A money value with a locale-formatted string. */\nexport interface Money {\n /** Major units, e.g. `79`. */\n amount: number\n /** Minor units, e.g. `7900`. */\n minor: number\n currency: string\n /** Locale-formatted, e.g. `kr 79,00` / `€9,99` / `$9.99`. */\n formatted: string\n}\n\n/**\n * The product with its amounts resolved (currency + period math), **before**\n * locale formatting — what the catalog stores. `useProduct` formats it.\n */\nexport interface ResolvedProduct {\n id: string\n /** The catalog product KEY charged (the CHARGE identity; `id` is the SLOT/display identity). */\n catalogKey: string\n name: string\n displayName: string\n provider: string\n currency: string\n priceMinor: number\n perDayMinor: number\n perWeekMinor: number\n perMonthMinor: number\n perYearMinor: number\n period: string\n periodly: string\n hasTrial: boolean\n trialDays: number\n trialMinor: number\n}\n\n/** Display-ready product the author reads (every amount locale-formatted). */\nexport interface Product {\n id: string\n /** The catalog product KEY charged (the CHARGE identity; `id` is the SLOT/display identity). */\n catalogKey: string\n name: string\n displayName: string\n provider: string\n price: Money\n /** e.g. `month`, `quarter`, `one-time`. */\n period: string\n /** e.g. `monthly`, `quarterly`, `one-time`. */\n periodly: string\n /** Period-normalized prices (for \"just $0.27/day\" style copy). */\n perDay: Money\n perWeek: Money\n perMonth: Money\n perYear: Money\n hasTrial: boolean\n trialDays: number\n trialPrice: Money | null\n}\n\n// ── Resolve (currency-agnostic) ──────────────────────────\n\n/**\n * The period model: the **day is the canonical unit** and every interval is a\n * consistent number of days — `year = 365`, `month = 365/12` (~30.42),\n * `week = 7`. Consistent means the derived periods are exact multiples of each\n * other: a monthly product's `perMonthMinor` is its price, its `perYearMinor`\n * is exactly `12×` the price, and a yearly product's `perMonthMinor` is exactly\n * `price / 12` — no 360-vs-365 drift (the old `month = 30` model made a yearly\n * plan's \"per month\" ~1.4% off).\n */\nconst PERIOD_DAYS: Record<Interval, number> = {\n day: 1, week: 7, month: 365 / 12, year: 365, one_time: 0,\n}\n\nfunction periodDays(interval: Interval, count: number): number {\n return PERIOD_DAYS[interval] * count\n}\n\nfunction intervalLabel(interval: Interval, count: number): { period: string; periodly: string } {\n if (interval === 'one_time') return { period: 'one-time', periodly: 'one-time' }\n if (interval === 'month' && count === 3) return { period: 'quarter', periodly: 'quarterly' }\n if (interval === 'month' && count === 6) return { period: '6 months', periodly: 'semiannually' }\n if (interval === 'week' && count === 2) return { period: '2 weeks', periodly: 'biweekly' }\n if (count === 1) {\n const periodly = { day: 'daily', week: 'weekly', month: 'monthly', year: 'yearly' }[interval]\n return { period: interval, periodly }\n }\n return { period: `${count} ${interval}s`, periodly: `every ${count} ${interval}s` }\n}\n\n/**\n * Resolve a {@link ProductInput} into amounts + period math (no formatting yet).\n * Per-period amounts are **integer minor units** (each derived from the exact\n * daily rate, then rounded — never round-then-multiply, so error doesn't compound).\n */\nexport function resolveProduct(input: ProductInput): ResolvedProduct {\n const interval = input.interval ?? 'one_time'\n const count = input.intervalCount ?? 1\n const days = periodDays(interval, count)\n // Derive each period from the exact price/days ratio, rounding each result\n // independently to whole minor units.\n const per = (targetDays: number): number =>\n days > 0 ? Math.round((input.amount * targetDays) / days) : input.amount\n const label = intervalLabel(interval, count)\n // A paid trial can be \"N days for X\" OR an intro price with no day count —\n // a set trialAmount alone still makes it a trial (trialDays: 0 must not\n // swallow the trial price).\n const trialDays = input.trialDays ?? 0\n const trialMinor = input.trialAmount ?? 0\n\n return {\n id: input.id,\n catalogKey: input.catalogKey ?? input.id,\n name: input.name ?? input.id,\n displayName: input.displayName ?? input.name ?? input.id,\n provider: input.provider ?? 'stripe',\n currency: input.currency,\n priceMinor: input.amount,\n perDayMinor: per(1),\n perWeekMinor: per(7),\n perMonthMinor: per(365 / 12),\n perYearMinor: per(365),\n period: label.period,\n periodly: label.periodly,\n hasTrial: trialDays > 0 || trialMinor > 0,\n trialDays,\n trialMinor,\n }\n}\n\n/** Build the id → {@link ResolvedProduct} catalog. Formatting happens at read time. */\nexport function buildCatalog(inputs: ProductInput[]): Map<string, ResolvedProduct> {\n return new Map(inputs.map((i) => [i.id, resolveProduct(i)]))\n}\n\n// ── Format (locale-dependent) ────────────────────────────\n\n/** currency code → minor-unit exponent, resolved once via Intl (JPY→0, KWD→3, …). */\nconst EXPONENT_CACHE = new Map<string, number>()\n\n/**\n * The minor-unit exponent for a currency (`USD`→2, `JPY`→0, `KWD`/`BHD`→3),\n * derived from `Intl.NumberFormat(...).resolvedOptions().maximumFractionDigits`\n * with a fallback of 2 for unknown/invalid codes.\n */\nexport function currencyExponent(currency: string): number {\n const code = currency.toUpperCase()\n const hit = EXPONENT_CACHE.get(code)\n if (hit !== undefined) return hit\n let exp = 2\n try {\n exp = new Intl.NumberFormat('en', { style: 'currency', currency: code })\n .resolvedOptions().maximumFractionDigits ?? 2\n } catch {\n exp = 2\n }\n EXPONENT_CACHE.set(code, exp)\n return exp\n}\n\n/** Format minor units of `currency` in `locale` (exponent-aware: 7900 JPY = ¥7,900). */\nexport function formatMoney(minor: number, currency: string, locale: string): Money {\n const code = currency.toUpperCase()\n const exp = currencyExponent(code)\n const amount = minor / 10 ** exp\n let formatted: string\n try {\n formatted = new Intl.NumberFormat(locale, { style: 'currency', currency: code }).format(amount)\n } catch {\n formatted = `${code} ${amount.toFixed(exp)}`\n }\n return { amount, minor, currency: code, formatted }\n}\n\n/** Format a {@link ResolvedProduct} into a display {@link Product} in `locale`. */\nexport function formatProduct(r: ResolvedProduct, locale: string): Product {\n const m = (minor: number): Money => formatMoney(minor, r.currency, locale)\n return {\n id: r.id,\n catalogKey: r.catalogKey,\n name: r.name,\n displayName: r.displayName,\n provider: r.provider,\n price: m(r.priceMinor),\n period: r.period,\n periodly: r.periodly,\n perDay: m(r.perDayMinor),\n perWeek: m(r.perWeekMinor),\n perMonth: m(r.perMonthMinor),\n perYear: m(r.perYearMinor),\n hasTrial: r.hasTrial,\n trialDays: r.trialDays,\n trialPrice: r.hasTrial ? m(r.trialMinor) : null,\n }\n}\n","import type { ComponentType } from 'react'\nimport type { VariableConfig, VariableValue } from '../types'\nimport type { FunnelContext } from '../state/context'\n\n/**\n * The funnel **spine** — the constrained, declarative configuration authored as\n * code (`defineFunnel` / `pageMeta` / `definePage`) yet **dashboard-editable**\n * (static AST parse → pretty UI → codegen) and compiled to the manifest IR.\n *\n * Principle: **presentation = code** (the page components), **configuration =\n * data** (this spine). See docs/platform-v2/06-funnel-project-model.md.\n *\n * Routing is **declarative nodes + code predicates** (decided — doc 06): a\n * page's `next` is an ordered list of {@link Route}s, each with a **static `to`\n * page key** (so the dashboard can draw every possible edge without executing\n * anything) and an optional `when` **gate** that returns true/false. The gate is\n * either a declarative {@link Condition} (one field — UI-editable data) or a code\n * {@link Predicate} (`s => boolean` — the escape hatch, opaque body but the edge\n * is still visible). First matching route wins; a route with no `when` is the\n * fallback. Multiple conditions = multiple routes (or boolean logic in one\n * predicate). Omit `next` entirely for the default linear flow.\n */\n\n// ── Snapshot (what a predicate sees) ─────────────────────\n\n/**\n * Read-only view of every namespace a routing/condition predicate can branch\n * on. `user`/`responses`/`data` are the writable namespaces; `context` is the\n * read-only computed one ({@link FunnelContext}).\n */\nexport interface FunnelSnapshot {\n user: Record<string, VariableValue>\n responses: Record<string, VariableValue>\n data: Record<string, VariableValue>\n context: FunnelContext\n}\n\n/** A code-predicate gate — `s => s.responses.goal === 'gain'`. */\nexport type Predicate = (s: FunnelSnapshot) => boolean\n\nexport type ConditionOp =\n | 'eq' | 'neq' | 'in' | 'gt' | 'gte' | 'lt' | 'lte'\n | 'exists' | 'empty' | 'contains'\n\n/**\n * A declarative gate over **one** namespaced field — UI-editable data the\n * dashboard renders as a condition row (`field` `op` `value`). `field` is a\n * dotted path into the snapshot: `responses.goal`, `user.country`,\n * `context.device.isMobile`.\n */\nexport interface Condition {\n field: string\n op: ConditionOp\n value?: VariableValue | VariableValue[]\n}\n\n/** An edge gate: either declarative data ({@link Condition}) or a {@link Predicate}. */\nexport type Gate = Condition | Predicate\n\n/**\n * One routing edge out of a page. `to` is a **static** target key (the dashboard\n * reads these to draw the flow graph); `when` gates the edge (omit = fallback).\n */\nexport interface Route {\n to: string\n when?: Gate\n}\n\n/** Read a dotted path out of the snapshot (flat namespaces + nested `context`). */\nfunction readField(s: FunnelSnapshot, field: string): VariableValue {\n let cur: unknown = s\n for (const part of field.split('.')) {\n if (cur == null) return undefined\n cur = (cur as Record<string, unknown>)[part]\n }\n return cur as VariableValue\n}\n\n/** Evaluate a declarative {@link Condition} against a snapshot. */\nexport function evaluateCondition(cond: Condition, s: FunnelSnapshot): boolean {\n const val = readField(s, cond.field)\n const { op, value } = cond\n switch (op) {\n case 'eq': return val === value\n case 'neq': return val !== value\n case 'in': return Array.isArray(value) && (value as VariableValue[]).includes(val as VariableValue)\n case 'gt': return typeof val === 'number' && typeof value === 'number' && val > value\n case 'gte': return typeof val === 'number' && typeof value === 'number' && val >= value\n case 'lt': return typeof val === 'number' && typeof value === 'number' && val < value\n case 'lte': return typeof val === 'number' && typeof value === 'number' && val <= value\n case 'contains':\n if (typeof val === 'string') return val.includes(String(value))\n if (Array.isArray(val)) return (val as VariableValue[]).includes(value as VariableValue)\n return false\n case 'exists': return val !== undefined && val !== null && val !== ''\n case 'empty':\n return val === undefined || val === null || val === '' ||\n (Array.isArray(val) && val.length === 0)\n default: return false\n }\n}\n\n/** Evaluate either gate kind to a boolean. */\nexport function evaluateGate(gate: Gate, s: FunnelSnapshot): boolean {\n return typeof gate === 'function' ? gate(s) : evaluateCondition(gate, s)\n}\n\n/**\n * Resolve an ordered list of routes to a target page key, or `undefined` to fall\n * through to the linear next. First route whose gate passes (or has no `when`)\n * wins.\n */\nexport function resolveRoute(\n routes: Route[] | undefined,\n s: FunnelSnapshot,\n): string | undefined {\n if (!routes) return undefined\n for (const route of routes) {\n if (!route.when || evaluateGate(route.when, s)) return route.to\n }\n return undefined\n}\n\n// ── Pages ────────────────────────────────────────────────\n\nexport type PageType =\n | 'default' // plain content/step page (the baseline)\n | 'email-capture' // collects user.email — the mandatory identity step (validated)\n | 'paywall' // the offer/pricing page → drives paywall-view + paywall-CR\n | 'upsell' // post-purchase one-click → drives Upsell Rate + off-session charge\n | 'finish' // terminal success/thank-you page → completion analytics, ends the flow\n\nexport interface PageMeta {\n /** Page kind — drives behavior + analytics (e.g. `paywall`, `upsell`). */\n type?: PageType\n /** URL slug; defaults to the page key. */\n slug?: string\n /**\n * Ordered routing edges out of this page (first match wins). Each has a static\n * `to` key + an optional `when` gate. Omit for the default linear flow.\n */\n next?: Route[]\n /**\n * Entry precondition for **deep-link / reload** restoration. When the runtime is\n * asked to start *on this page* (not via in-funnel navigation), it restores there\n * only if `guard` passes against the restored snapshot — otherwise it falls back\n * to the start page. e.g. an upsell page: `guard: s => s.data.purchased === true`.\n * Reaching the page via `next()` is unaffected (routing already gated it). Omit =\n * always restorable. Same gate kind as routing (`Condition` or predicate).\n */\n guard?: Gate\n}\n\n/**\n * Identity helper for a page's co-located metadata.\n * `export const meta = pageMeta({ type: 'paywall', next: s => … })`.\n */\nexport function pageMeta(meta: PageMeta): PageMeta {\n return meta\n}\n\n/**\n * Default entry guard implied by a page **type** — a built-in precondition every\n * funnel inherits. `paywall` and `upsell` require a captured `user.email` (the\n * mandatory identity step), so a deep-link / reload straight into them without\n * email bounces to the start. Authors don't write this; an explicit `meta.guard`\n * **overrides** it (see {@link entryGuard}).\n */\nconst TYPE_GUARDS: Partial<Record<PageType, Gate>> = {\n paywall: { field: 'user.email', op: 'exists' },\n upsell: { field: 'user.email', op: 'exists' },\n}\n\n/**\n * The effective entry guard for a page: an explicit `meta.guard` if the author set\n * one, **otherwise** the page-type default (e.g. paywall/upsell need email). The\n * explicit guard fully **overrides** the default — it's not combined. Returns\n * `undefined` when neither applies.\n */\nexport function entryGuard(meta?: PageMeta): Gate | undefined {\n return meta?.guard ?? (meta?.type ? TYPE_GUARDS[meta.type] : undefined)\n}\n\n/**\n * Identity helper for a page component. The page is plain React that reaches the\n * runtime through hooks (`useResponse`, `useNavigation`, …) — there is no `sdk`\n * prop. `export default definePage(function Welcome() { … })`.\n */\nexport function definePage<P extends object = Record<string, never>>(\n component: ComponentType<P>,\n): ComponentType<P> {\n return component\n}\n\n// ── Flow resolution ──────────────────────────────────────\n\n/** A page in the flow: its key + (optional) co-located meta. */\nexport interface FlowPage {\n key: string\n meta?: PageMeta\n}\n\n/**\n * A page as declared in `funnel.ts` — the key + its metadata, flattened. This is the\n * AUTHORED shape (funnel.ts owns the page list, order, and routing); the build generates\n * the code-split `mount.tsx` from it. Routing (`next`) must stay DECLARATIVE (Route[] with\n * `{ to, when }` conditions, no predicate functions) so the web builder UI can edit it.\n */\nexport interface FunnelPage extends PageMeta {\n key: string\n}\n\n/**\n * Decide the next page from `currentKey`:\n * 1. the current page's `next` routes ({@link resolveRoute}), if one matches, else\n * 2. the next page in file order (the default linear flow), else\n * 3. `undefined` (end of funnel / current key not found).\n */\nexport function nextPage(\n pages: FlowPage[],\n currentKey: string,\n s: FunnelSnapshot,\n): string | undefined {\n const idx = pages.findIndex((p) => p.key === currentKey)\n if (idx === -1) return undefined\n const routed = resolveRoute(pages[idx].meta?.next, s)\n if (routed) return routed\n return pages[idx + 1]?.key\n}\n\n/**\n * Every page a visitor *could* go to next from `currentKey` — all route targets\n * (regardless of gate, since we don't know which will pass) plus the linear next.\n * Used to **prefetch** the likely-next page chunks; not for navigation.\n */\nexport function outgoingKeys(pages: FlowPage[], currentKey: string): string[] {\n const idx = pages.findIndex((p) => p.key === currentKey)\n if (idx === -1) return []\n const out = new Set<string>()\n for (const route of pages[idx].meta?.next ?? []) out.add(route.to)\n const linear = pages[idx + 1]?.key\n if (linear) out.add(linear)\n return [...out]\n}\n\n/**\n * The number of pages on the path from `startKey` to a `finish` (or the end of\n * the flow) **given the current state** — the denominator for progress. It walks\n * the actual routing ({@link nextPage}) rather than counting all files, so a\n * branched funnel reaches 100% on whichever path the visitor's answers select.\n * Re-traced per navigation; a visited set guards against routing cycles.\n */\nexport function expectedPathLength(\n pages: FlowPage[],\n startKey: string,\n s: FunnelSnapshot,\n): number {\n const seen = new Set<string>()\n let key: string | undefined = startKey\n let count = 0\n while (key && !seen.has(key)) {\n seen.add(key)\n count++\n if (pages.find((p) => p.key === key)?.meta?.type === 'finish') break\n key = nextPage(pages, key, s)\n }\n return count\n}\n\n// ── Funnel definition ────────────────────────────────────\n\nexport interface FunnelLocales {\n default: string\n supported: string[]\n fallback?: string\n}\n\n/**\n * The funnel-level spine. Flow is mostly inferred from page file order + each\n * page's `next`; this holds the funnel-wide config. Stays **thin** — routing\n * lives co-located on pages (doc 06: \"funnel.ts stays thin\").\n */\nexport interface FunnelDefinition {\n id: string\n /**\n * The funnel's pages — order, type, and declarative routing — the source of truth the\n * web builder edits and the build generates `mount.tsx` from. Each `key` maps to a\n * `pages/<key>.tsx` component. Omit `pages` on hand-written funnels that still ship their\n * own `mount.tsx` (back-compat); new/generated funnels declare them here.\n */\n pages?: FunnelPage[]\n /** Which checkout provider the paywall/checkout uses. The build wires the driver. */\n checkout?: 'stripe' | 'paddle'\n /** `responses.*` runtime variables (default values). */\n responses?: Record<string, VariableConfig>\n /** `data.*` working/scratch variables (default values). */\n data?: Record<string, VariableConfig>\n /**\n * The catalog products this funnel sells, as SLOTS: a local, stable key each PAGE\n * references (`useProduct('primary')`, `<Checkout product=\"primary\">`) → the catalog product\n * KEY it's assigned to. Swap the assignment to change the offer WITHOUT touching page code;\n * `null` = a declared-but-unassigned slot. A bare `string[]` is legacy sugar for IDENTITY\n * slots (`['pro'] ≡ { pro: 'pro' }`) — every existing funnel keeps working. Prices resolve\n * from the project catalog per environment (Live/Test) at render.\n */\n products?: string[] | Record<string, string | null>\n locales?: FunnelLocales\n /**\n * When `true`, the funnel shows the **geo-specific** currency/price the payment\n * provider resolves (Stripe `currency_options`, Paddle preview, Whop, SolidGate,\n * …). When `false` (default), a single fixed currency is used. AppFunnel does no\n * FX — this only toggles whether the platform asks the provider for the geo\n * price; the SDK just displays whatever resolved `{amount, currency}` it's handed.\n * (See docs/platform-v2 phase-3 §3.6.)\n */\n locationAwareCurrency?: boolean\n}\n\n/** Identity helper for a funnel definition. */\nexport function defineFunnel(def: FunnelDefinition): FunnelDefinition {\n return def\n}\n\n/** A funnel product SLOT: the local key pages reference → the assigned catalog product key (null = unassigned). */\nexport interface ProductSlot {\n slot: string\n catalogKey: string | null\n}\n\n/**\n * Normalize `FunnelDefinition.products` to a slot list. A legacy `string[]` becomes IDENTITY\n * slots (`['pro'] → [{ slot:'pro', catalogKey:'pro' }]`); a `{ slot: key|null }` map becomes its\n * entries (insertion order preserved, so `useProducts()` is deterministic).\n */\nexport function normalizeProducts(products: FunnelDefinition['products']): ProductSlot[] {\n if (!products) return []\n if (Array.isArray(products)) return products.map((k) => ({ slot: k, catalogKey: k }))\n return Object.entries(products).map(([slot, catalogKey]) => ({ slot, catalogKey: catalogKey ?? null }))\n}\n\n/** The unique, ASSIGNED catalog keys a funnel charges — for the promote gate + catalog reverse-lookup. */\nexport function funnelCatalogKeys(products: FunnelDefinition['products']): string[] {\n return [...new Set(normalizeProducts(products).map((s) => s.catalogKey).filter((k): k is string => !!k))]\n}\n","/**\n * **Runtime page-level experiments** — A/B/n on a *single page inside one funnel*,\n * resolved at render time (phase-4). No funnel duplication: a slot (e.g. the page\n * `welcome`) has alternate versions filed as siblings (`welcome@b.tsx`), and the\n * runtime shows **one** of them per visitor, collapsing the losers out of the\n * linear flow. The flow keeps stable **slot keys** (the control's key); only the\n * rendered component swaps — so routing, the manifest, and analytics all key on the\n * slot, not the variant.\n *\n * **Where the wiring lives:** the *variant pages* are code (compiled into the\n * bundle). The *experiment wiring* — slot, variant→page map, weights, status — is\n * **operational data the platform owns** (a DB record, edited by the dashboard,\n * changed without recompiling the funnel). The SDK is storage-agnostic: the\n * platform hands the runtime experiment records to `FunnelProvider`, the same way\n * it hands in resolved product prices. This module just resolves them.\n *\n * **The only source-side marker** is the `@` in a variant file's key\n * (`welcome@b`): it tells the *build* (manifest, flow graph) that a page is an\n * off-flow variant of its slot, so the structure is correct without the DB. The\n * label/weight/experiment-id are not in source.\n *\n * Bucketing is a deterministic FNV-1a hash, **namespaced by experiment id** so\n * independent experiments bucket orthogonally (the basis for layering 100+ tests,\n * §4.3). The seed is the durable identity ({@link bucketingSeed}) — never the\n * session/fingerprint — so a returning visitor keeps their variant (landmine #4).\n * Stability across an *add-a-variant* edit is the platform's job: an experiment's\n * variant set is immutable while running (reweighting / adding an arm = a new\n * experiment version), so within one record the assignment never moves.\n *\n * This module is pure (no React, no I/O) → it unit-tests trivially and the\n * dashboard/server can reuse the same assignment math.\n */\n\nimport type { FunnelContext } from '../state/context'\n\n// ── Hashing ──────────────────────────────────────────────\n\n/**\n * FNV-1a 32-bit hash → unsigned int. Deterministic and isomorphic (no `crypto`,\n * runs the same in the browser, a worker, and a build). The same math v0 used,\n * kept because it's sound — only the *seed* changes (identity, not session).\n */\nexport function fnv1a(input: string): number {\n let h = 0x811c9dc5\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i)\n // h *= 16777619, in uint32, via shift-adds.\n h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0\n }\n return h >>> 0\n}\n\n/** Map a seed string to a stable float in `[0, 1)`. */\nexport function hashToUnit(seed: string): number {\n return fnv1a(seed) / 0x1_0000_0000\n}\n\n/**\n * Pick a variant key by weight from a stable unit position `u ∈ [0,1)`. Variants\n * are walked in declaration order and the first whose cumulative weight band\n * contains `u` wins, so the same `u` always lands in the same variant.\n */\nexport function pickByWeight(weights: Record<string, number>, u: number): string {\n const entries = Object.entries(weights).filter(([, w]) => w > 0)\n if (entries.length === 0) return Object.keys(weights)[0] ?? ''\n const total = entries.reduce((sum, [, w]) => sum + w, 0)\n const target = u * total\n let acc = 0\n for (const [key, w] of entries) {\n acc += w\n if (target < acc) return key\n }\n return entries[entries.length - 1][0]\n}\n\n/**\n * Deterministically assign a visitor (`seed`) to a variant of one experiment.\n * The hash is **namespaced by `experimentId`** so two experiments on the same\n * traffic don't correlate (orthogonal layering).\n */\nexport function assignVariant(\n experimentId: string,\n seed: string,\n weights: Record<string, number>,\n): string {\n return pickByWeight(weights, hashToUnit(`${experimentId}:${seed}`))\n}\n\n// ── Seed + slot parsing ──────────────────────────────────\n\n/**\n * The stable bucketing seed: the signed `visitorId`, else the known `customerId`.\n * Never the session id or fingerprint (landmine #4). `null` when neither is known\n * — the caller then serves control instead of bucketing on nothing.\n *\n * visitorId-FIRST (not customerId-first) is deliberate: the customerId injected for an\n * anonymous visitor is minted server-side AFTER the first tracked event, so it is absent on\n * visit 1 and present on visit 2 — seeding on it would flip a returning visitor's arm and\n * count them in two arms of the same version. The signed `af_vid` cookie is the durable\n * identity that's stable from the first pageload, so it seeds; customerId is only the fallback\n * for cookieless SDK embeds. This matches the server-side FUNNEL split, which already seeds on\n * the verified visitorId (resolve.ts). (Cross-device stable bucketing for IDENTIFIED customers\n * is P3's IdentitySDK job, not this anonymous path.)\n */\nexport function bucketingSeed(context: FunnelContext): string | null {\n return context.identity.visitorId ?? context.identity.customerId ?? null\n}\n\n/** Split a page key into its slot + optional variant: `welcome@b` → `{ slot, variant: 'b' }`. */\nexport function parseSlotKey(key: string): { slot: string; variant?: string } {\n const at = key.indexOf('@')\n return at === -1 ? { slot: key } : { slot: key.slice(0, at), variant: key.slice(at + 1) }\n}\n\n/** True if a page key is an off-flow variant (`welcome@b`), by the source-side `@` marker. */\nexport function isVariantKey(key: string): boolean {\n return parseSlotKey(key).variant !== undefined\n}\n\n// ── Runtime experiment records (platform/DB-sourced) ─────\n\n/** One arm of an experiment: which page renders, at what weight. */\nexport interface ExperimentVariant {\n /** The page key this arm renders (the slot's control, or a `@variant` sibling). */\n page: string\n /** Relative weight in the split (need not sum to 100; zero = paused arm). */\n weight: number\n}\n\n/**\n * A runtime experiment record — the operational wiring the **platform** owns and\n * hands to the SDK (not authored in the funnel source). The variant *pages* are\n * code in the bundle; this is the live config over them.\n */\nexport interface RuntimeExperiment {\n id: string\n /** The page key holding the flow position (the anchor / control). */\n slot: string\n /** label → arm. One arm's `page` is the `slot` (control); others are `@variant` siblings. */\n variants: Record<string, ExperimentVariant>\n /** Lifecycle. Absent = running. */\n status?: 'running' | 'paused' | 'stopped'\n /** When stopped, the variant label everyone sees until promotion bakes it into the slot. */\n winner?: string\n /** Primary metric (analytics only; not used for resolution). */\n metric?: string\n /** Platform record version (immutable-while-running; reweight = new version). Rides on\n * exposure events so results key on (experimentId, version, variant). */\n version?: number\n}\n\n// ── Flow resolution ──────────────────────────────────────\n\nexport interface ExperimentResolution {\n /** experiment id → assigned variant label. */\n assignments: Record<string, string>\n /** Page keys forming the effective linear flow (variant siblings removed), in order. */\n activeKeys: string[]\n /** Slot key → the page key whose component should render there. */\n render: Record<string, string>\n /** Variant page key → its slot key. For remapping a route that targets a variant. */\n slotOf: Record<string, string>\n /** Slot key → the experiment id it hosts (drives the exposure event). */\n experimentOf: Record<string, string>\n /** Experiment id → platform record version (rides on exposure events). */\n versionOf: Record<string, number>\n}\n\n/**\n * Weights map (label → weight) for one experiment's arms. Exported (via the pure\n * manifest entry) so the server-side FUNNEL split (renderer resolve) projects arms\n * the same way before calling {@link assignVariant}, instead of re-inlining it.\n */\nexport function weightsOf(variants: Record<string, { weight: number }>): Record<string, number> {\n const out: Record<string, number> = {}\n for (const [label, v] of Object.entries(variants)) out[label] = v.weight\n return out\n}\n\n/** Effective lifecycle — an absent `status` means running. */\nfunction statusOf(exp: RuntimeExperiment): 'running' | 'paused' | 'stopped' {\n return exp.status ?? 'running'\n}\n\n/**\n * Resolve which page version each experiment slot shows for this visitor, and\n * which page keys remain in the linear flow.\n *\n * Variant pages are detected structurally by the `@` in their key, so they\n * collapse out of the linear flow even for a slot with no active experiment.\n * For each *running* experiment the visitor is bucketed (stable on `seed`); a\n * *stopped* one serves its `winner`; a *paused* one (or no seed) serves the slot.\n */\nexport function resolveExperiments(\n pages: { key: string }[],\n experiments: RuntimeExperiment[],\n seed: string | null,\n): ExperimentResolution {\n const assignments: Record<string, string> = {}\n const render: Record<string, string> = {}\n const experimentOf: Record<string, string> = {}\n const versionOf: Record<string, number> = {}\n // Servable-arm guard: an experiment record can outlive the build it points at (a rollback,\n // a running-reweight to a never-published page, an AI edit that deletes a variant file). If\n // the assigned arm's page isn't in THIS bundle, serving it renders a blank step AND would\n // still record an exposure — so fall back to the slot's control and record NOTHING for the\n // experiment (mirrors the FUNNEL-split candidate check in resolve.ts).\n const pageKeys = new Set(pages.map((p) => p.key))\n\n for (const exp of experiments) {\n const status = statusOf(exp)\n let label: string\n if (status === 'stopped' && exp.winner) label = exp.winner\n else if (status === 'running' && seed) label = assignVariant(exp.id, seed, weightsOf(exp.variants))\n else continue // paused, or no seed → the slot renders its own (control) page\n\n const arm = exp.variants[label]\n if (!arm) continue\n if (!pageKeys.has(arm.page) || !pageKeys.has(exp.slot)) continue // arm/slot not in the bundle → serve control, no exposure\n assignments[exp.id] = label\n experimentOf[exp.slot] = exp.id\n if (exp.version !== undefined) versionOf[exp.id] = exp.version\n if (arm.page !== exp.slot) render[exp.slot] = arm.page // swap only when a non-control arm won\n }\n\n // Variant siblings (`@`) never stand alone in the linear flow.\n const slotOf: Record<string, string> = {}\n const activeKeys: string[] = []\n for (const p of pages) {\n const { slot, variant } = parseSlotKey(p.key)\n if (variant !== undefined) slotOf[p.key] = slot\n else activeKeys.push(p.key)\n }\n\n return { assignments, activeKeys, render, slotOf, experimentOf, versionOf }\n}\n\n// ── Validation ───────────────────────────────────────────\n\n/** One referential problem with an experiment record. */\nexport interface ExperimentIssue {\n /** The offending experiment id (`'*'` for a cross-experiment issue). */\n experimentId: string\n code:\n | 'slot_missing' // slot is not a page in the funnel\n | 'slot_is_variant' // slot points at an `@variant`, not a real flow page\n | 'slot_conflict' // two experiments target the same slot\n | 'duplicate_id' // two experiments share an id (bucketing namespace collision)\n | 'variant_page_missing' // a variant references a page that doesn't exist (dangling)\n | 'variant_slot_mismatch' // a variant's `@`-page belongs to a different slot\n | 'no_control' // no arm renders the slot itself (the baseline)\n | 'no_traffic' // every arm has weight ≤ 0\n | 'negative_weight' // an arm has a negative weight\n | 'bad_winner' // a stopped experiment's winner isn't one of its variants\n | 'single_arm' // only one variant — nothing to test (warning)\n | 'orphan_variant' // a `@variant` page no running experiment renders (warning)\n message: string\n}\n\nexport interface ExperimentValidation {\n ok: boolean\n errors: ExperimentIssue[]\n warnings: ExperimentIssue[]\n}\n\n/**\n * Cross-check experiment records against the funnel's pages — the publish-time /\n * experiment-edit gate that catches the dangling references the runtime can't see\n * (the experiment wiring lives in the DB; the pages live in the build, so they can\n * drift). Pure: hand it the runtime experiments + the funnel's page keys (e.g.\n * `manifest.pages`).\n *\n * Errors block; warnings inform. `orphan_variant` is a warning, not an error — a\n * `@variant` file with no running experiment is dead-but-harmless (a paused test, or\n * one not wired yet).\n */\nexport function validateExperiments(\n experiments: RuntimeExperiment[],\n pages: { key: string }[],\n): ExperimentValidation {\n const errors: ExperimentIssue[] = []\n const warnings: ExperimentIssue[] = []\n const pageKeys = new Set(pages.map((p) => p.key))\n\n const seenIds = new Set<string>()\n const slotOwner = new Map<string, string>()\n\n for (const exp of experiments) {\n const err = (code: ExperimentIssue['code'], message: string) =>\n errors.push({ experimentId: exp.id, code, message })\n const warn = (code: ExperimentIssue['code'], message: string) =>\n warnings.push({ experimentId: exp.id, code, message })\n\n if (seenIds.has(exp.id)) err('duplicate_id', `Experiment id \"${exp.id}\" is used more than once.`)\n seenIds.add(exp.id)\n\n // Slot must be a real flow page (not missing, not itself a variant).\n if (!pageKeys.has(exp.slot)) err('slot_missing', `Slot \"${exp.slot}\" is not a page in the funnel.`)\n if (isVariantKey(exp.slot)) err('slot_is_variant', `Slot \"${exp.slot}\" is a variant page; a slot must be a real flow page.`)\n if (slotOwner.has(exp.slot)) {\n err('slot_conflict', `Slot \"${exp.slot}\" is already targeted by experiment \"${slotOwner.get(exp.slot)}\".`)\n } else {\n slotOwner.set(exp.slot, exp.id)\n }\n\n const arms = Object.entries(exp.variants)\n if (arms.length < 2) warn('single_arm', `Experiment \"${exp.id}\" has fewer than two variants — nothing to test.`)\n\n let hasControl = false\n let totalWeight = 0\n for (const [label, arm] of arms) {\n if (!pageKeys.has(arm.page)) {\n err('variant_page_missing', `Variant \"${label}\" references page \"${arm.page}\", which doesn't exist.`)\n }\n if (arm.page === exp.slot) hasControl = true\n else if (isVariantKey(arm.page) && parseSlotKey(arm.page).slot !== exp.slot) {\n err('variant_slot_mismatch', `Variant \"${label}\" page \"${arm.page}\" belongs to a different slot than \"${exp.slot}\".`)\n }\n if (arm.weight < 0) err('negative_weight', `Variant \"${label}\" has a negative weight (${arm.weight}).`)\n totalWeight += arm.weight\n }\n if (!hasControl) err('no_control', `No variant of \"${exp.id}\" renders the slot \"${exp.slot}\" itself (the control/baseline).`)\n if (totalWeight <= 0) err('no_traffic', `Experiment \"${exp.id}\" has no positive weight — no traffic would enter it.`)\n\n if (statusOf(exp) === 'stopped' && exp.winner && !exp.variants[exp.winner]) {\n err('bad_winner', `Stopped experiment \"${exp.id}\" names winner \"${exp.winner}\", which isn't one of its variants.`)\n }\n }\n\n // A `@variant` page that no running experiment renders is dead (but harmless).\n const running = new Set(experiments.filter((e) => statusOf(e) === 'running').flatMap((e) =>\n Object.values(e.variants).map((v) => v.page),\n ))\n for (const p of pages) {\n if (isVariantKey(p.key) && !running.has(p.key)) {\n warnings.push({ experimentId: '*', code: 'orphan_variant', message: `Variant page \"${p.key}\" is rendered by no running experiment.` })\n }\n }\n\n return { ok: errors.length === 0, errors, warnings }\n}\n","/**\n * The **manifest** — the declarative IR a funnel project compiles to (doc 06).\n * It's the machine-readable artifact the platform operates on without executing\n * the funnel: the dashboard draws the flow graph from it, analytics binds to its\n * **stable ids**, validation runs against it, and the renderer reads it to resolve\n * routing.\n *\n * `compileManifest` evaluates the spine (the funnel config + each page's co-located\n * `meta`) into that IR. It's pure — no I/O — so it unit-tests trivially. **It runs\n * server-side**, as the IR step of the publish build over the canonical files in our\n * storage (R2). The client/CLI never produces the authoritative manifest — R2 is the\n * source of truth, the server compiles. (A local dev preview may run it for itself,\n * but that output is never published.)\n *\n * Edge model mirrors the runtime ({@link ../flow/spine}.`nextPage`): a page's\n * `meta.next` routes become **branch** edges (with a serialized condition — a\n * declarative {@link Condition}, or an opaque marker for a code predicate), and the\n * implicit file-order fall-through becomes a **linear** edge (unless an\n * unconditional route already covers it, or the page is a `finish`).\n *\n * Experiments are **not** compiled here. A variant page is recognised structurally\n * by the `@` in its key (`welcome@b`) and tagged `variantOf` + collapsed out of the\n * linear flow; the experiment *wiring* (labels/weights/status) is operational data\n * the platform owns and overlays at render time, not part of the funnel build.\n *\n * Stable ids: the page **key** is the source anchor, so `id === key` here. The\n * durable analytics id is the semantic page name (a slot survives a winner being\n * promoted into it); transient `@variant` pages only ever key analytics by\n * `(experimentId, variant)` in immutable results — a platform concern.\n */\n\nimport type {\n Condition,\n FunnelDefinition,\n FunnelLocales,\n Gate,\n PageMeta,\n PageType,\n} from '../flow/spine'\nimport { normalizeProducts, funnelCatalogKeys, type ProductSlot } from '../flow/spine'\nimport { isVariantKey, parseSlotKey } from '../flow/experiments'\n\nexport interface ManifestPage {\n id: string\n key: string\n type: PageType\n slug: string\n index: number\n /**\n * Set on a variant page (`welcome@b`) to its **slot** (`welcome`) — a structural\n * marker that this node is an off-flow alternate, not a linear step. The\n * experiment *wiring* (label/weight/id) is operational data the platform owns,\n * not the manifest.\n */\n variantOf?: string\n}\n\nexport type EdgeCondition =\n | { kind: 'declarative'; condition: Condition }\n /** A code predicate — opaque body; `label` may be supplied later by AST parsing. */\n | { kind: 'predicate'; label?: string }\n\nexport interface ManifestEdge {\n from: string\n to: string\n kind: 'branch' | 'linear'\n /** Absent = unconditional (a fallback route, or the linear fall-through). */\n condition?: EdgeCondition\n}\n\nexport interface ManifestValidation {\n /**\n * `ok` = none of the hard errors: the original set (dead ends, unreachable\n * pages, bad targets, missing email capture) AND the structural errors added\n * later (duplicate keys, orphan variants, no reachable finish). Slug\n * collisions are a **warning** — reported but not folded into `ok` (slugs are\n * display/URL sugar; keys are the routing identity).\n */\n ok: boolean\n /** Page ids you can't proceed from (and that aren't a `finish`). */\n deadEnds: string[]\n /** Page ids not reachable from the start. */\n unreachable: string[]\n /** Routes whose target page key doesn't exist. */\n badTargets: { from: string; to: string }[]\n /** True if the funnel never writes `user.email` (the mandatory identity step). */\n missingEmailCapture: boolean\n /** Page keys that appear more than once (keys are the stable ids — hard error). */\n duplicateKeys: string[]\n /** Flow pages sharing a slug (URL ambiguity — warning, not folded into `ok`). */\n slugCollisions: { slug: string; pages: string[] }[]\n /** Variant pages (`x@b`) whose slot (`x`) doesn't exist as a flow page (hard error). */\n orphanVariants: string[]\n /**\n * True when no `finish` page is reachable from the start — e.g. the flow loops\n * (a cycle with no exit) or every path stalls before a terminal page. Dead ends\n * catch pages with no outgoing edge; this catches funnels that *never end* even\n * though every page can proceed. Hard error.\n */\n noReachableFinish: boolean\n /** Slot names a PAGE references (`useProduct`/`<Checkout product>`) that the funnel doesn't declare — hard error. */\n unknownProductRefs: string[]\n /** Declared slots a page references but which have no catalog product assigned (map value `null`) — hard error. */\n unassignedSlots: string[]\n}\n\nexport interface FunnelManifest {\n id: string\n pages: ManifestPage[]\n flow: { start: string | null; nodes: string[]; edges: ManifestEdge[] }\n /** The unique, ASSIGNED catalog keys the funnel charges (for the promote gate + catalog reverse-lookup). */\n products: string[]\n /** Product SLOTS: slot → assigned catalog key|null. `products` above is the unique assigned keys. */\n productSlots: ProductSlot[]\n /** Slot names PAGES reference (from the build's scan); validated against `productSlots`. Absent = no scan ran. */\n productRefs?: string[]\n locales?: FunnelLocales\n validation: ManifestValidation\n}\n\nexport interface CompileInput {\n funnel: FunnelDefinition\n /** Pages in file order (the default flow); `meta` holds type/slug/next. */\n pages: { key: string; meta?: PageMeta }[]\n /** Slot names the funnel's PAGES reference (from `scanProductRefs`) — cross-checked against the declared slots. */\n productRefs?: string[]\n}\n\n/**\n * A **variant** node — a page filed with an `@variant` key (e.g. `welcome@b`).\n * It's an alternate of its slot, not a step in the linear spine, so it gets no\n * linear edge and is excluded from dead-end/reachability checks (the runtime\n * resolves it by bucketing, not by an edge). The `@` is the only source-side\n * signal; the experiment wiring is the platform's operational data. The slot's\n * control (no `@`) stays the flow node. Mirrors {@link resolveExperiments}.\n */\nfunction isVariantNode(page: { key: string }): boolean {\n return isVariantKey(page.key)\n}\n\n/** Serialize a route gate for the manifest (declarative → data; predicate → opaque). */\nfunction serializeGate(when: Gate | undefined): EdgeCondition | undefined {\n if (!when) return undefined\n if (typeof when === 'function') return { kind: 'predicate' }\n return { kind: 'declarative', condition: when }\n}\n\n/** Compile a funnel's spine into its declarative {@link FunnelManifest} IR. */\nexport function compileManifest(input: CompileInput): FunnelManifest {\n const { funnel, pages } = input\n const keys = new Set(pages.map((p) => p.key))\n\n const manifestPages: ManifestPage[] = pages.map((p, index) => ({\n id: p.key,\n key: p.key,\n type: p.meta?.type ?? 'default',\n slug: p.meta?.slug ?? p.key,\n index,\n variantOf: isVariantKey(p.key) ? parseSlotKey(p.key).slot : undefined,\n }))\n\n const edges: ManifestEdge[] = []\n const badTargets: { from: string; to: string }[] = []\n\n // The next page in file order that is a real flow node (skip `@variant` siblings).\n const nextAnchor = (from: number) => {\n for (let j = from + 1; j < pages.length; j++) {\n if (!isVariantNode(pages[j])) return pages[j]\n }\n return undefined\n }\n\n pages.forEach((p, i) => {\n // Variant nodes are alternates of their slot, resolved at runtime by bucketing\n // — they carry no flow edges (routing lives on the slot's control/anchor).\n if (isVariantNode(p)) return\n\n const routes = p.meta?.next ?? []\n let hasUnconditional = false\n for (const route of routes) {\n if (!keys.has(route.to)) {\n badTargets.push({ from: p.key, to: route.to })\n continue\n }\n edges.push({ from: p.key, to: route.to, kind: 'branch', condition: serializeGate(route.when) })\n if (!route.when) hasUnconditional = true\n }\n // Linear fall-through, unless an unconditional route already covers it,\n // this is a `finish` page, or there is no next page.\n const next = nextAnchor(i)\n if (!hasUnconditional && next && p.meta?.type !== 'finish') {\n edges.push({ from: p.key, to: next.key, kind: 'linear' })\n }\n })\n\n // The start is the first real flow node (a leading variant can't be the entry).\n const startPage = pages.find((p) => !isVariantNode(p))\n const start = startPage?.key ?? null\n const variantKeys = new Set(pages.filter(isVariantNode).map((p) => p.key))\n const productSlots = normalizeProducts(funnel.products)\n const validation = validate(manifestPages, edges, badTargets, start, variantKeys, productSlots, input.productRefs)\n\n return {\n id: funnel.id,\n pages: manifestPages,\n flow: { start, nodes: manifestPages.map((p) => p.id), edges },\n products: funnelCatalogKeys(funnel.products),\n productSlots,\n productRefs: input.productRefs,\n locales: funnel.locales,\n validation,\n }\n}\n\nfunction validate(\n pages: ManifestPage[],\n edges: ManifestEdge[],\n badTargets: { from: string; to: string }[],\n start: string | null,\n variantKeys: Set<string>,\n slots: ProductSlot[],\n productRefs: string[] | undefined,\n): ManifestValidation {\n const outgoing = new Map<string, number>()\n for (const e of edges) outgoing.set(e.from, (outgoing.get(e.from) ?? 0) + 1)\n\n // Variant nodes are resolved by bucketing, not edges — they're neither dead\n // ends nor unreachable in the flow-graph sense, so exclude them from both.\n const deadEnds = pages\n .filter((p) => p.type !== 'finish' && !variantKeys.has(p.id) && !(outgoing.get(p.id)! > 0))\n .map((p) => p.id)\n\n // Reachability from the start over the edge set.\n const reachable = new Set<string>()\n if (start) {\n const adj = new Map<string, string[]>()\n for (const e of edges) {\n const list = adj.get(e.from)\n if (list) list.push(e.to)\n else adj.set(e.from, [e.to])\n }\n const stack = [start]\n while (stack.length) {\n const id = stack.pop()!\n if (reachable.has(id)) continue\n reachable.add(id)\n for (const to of adj.get(id) ?? []) stack.push(to)\n }\n }\n const unreachable = pages\n .filter((p) => !variantKeys.has(p.id) && !reachable.has(p.id))\n .map((p) => p.id)\n\n // The funnel must capture user.email somewhere (doc 06). We can see the typed\n // `email-capture` page; deeper detection (any user.email write) is a build-time\n // AST concern. Treat presence of an `email-capture` page as satisfying it.\n const missingEmailCapture = !pages.some((p) => p.type === 'email-capture')\n\n // Duplicate page keys — keys are the stable analytics/routing ids, so two\n // pages sharing one is a hard error (edges/experiments become ambiguous).\n const seen = new Set<string>()\n const duplicateKeys: string[] = []\n for (const p of pages) {\n if (seen.has(p.key) && !duplicateKeys.includes(p.key)) duplicateKeys.push(p.key)\n seen.add(p.key)\n }\n\n // Slug collisions among FLOW pages (variants never route by their own slug —\n // they render under their slot's URL). Warning: keys stay unambiguous.\n const bySlug = new Map<string, string[]>()\n for (const p of pages) {\n if (variantKeys.has(p.id)) continue\n const list = bySlug.get(p.slug)\n if (list) list.push(p.id)\n else bySlug.set(p.slug, [p.id])\n }\n const slugCollisions = [...bySlug.entries()]\n .filter(([, ids]) => ids.length > 1)\n .map(([slug, ids]) => ({ slug, pages: ids }))\n\n // Orphan variants — a `x@b` page whose slot `x` doesn't exist as a flow page.\n // The runtime could never bucket into it (no anchor in the flow) → hard error.\n const flowKeys = new Set(pages.filter((p) => !variantKeys.has(p.id)).map((p) => p.key))\n const orphanVariants = pages\n .filter((p) => p.variantOf !== undefined && !flowKeys.has(p.variantOf))\n .map((p) => p.id)\n\n // A funnel must be able to END: at least one `finish` page reachable from the\n // start. Catches cycles with no exit (every page proceeds — so no dead end —\n // but no path ever terminates).\n const noReachableFinish =\n start !== null && !pages.some((p) => p.type === 'finish' && reachable.has(p.id))\n\n // Product-ref validation: a page referencing a slot the funnel doesn't declare (unknown) or one\n // with no assigned catalog product (unassigned) can never resolve → hard error. Only runs when the\n // build passed a page scan (`productRefs`); absent scan = skip (back-compat, no false positives).\n const declaredSlots = new Set(slots.map((s) => s.slot))\n const assignedSlots = new Set(slots.filter((s) => s.catalogKey).map((s) => s.slot))\n const refs = productRefs ?? []\n const unknownProductRefs = [...new Set(refs.filter((r) => !declaredSlots.has(r)))]\n const unassignedSlots = [...new Set(refs.filter((r) => declaredSlots.has(r) && !assignedSlots.has(r)))]\n\n return {\n // Original hard errors AND the structural ones; slug collisions stay a warning.\n ok:\n deadEnds.length === 0 &&\n unreachable.length === 0 &&\n badTargets.length === 0 &&\n !missingEmailCapture &&\n duplicateKeys.length === 0 &&\n orphanVariants.length === 0 &&\n !noReachableFinish &&\n unknownProductRefs.length === 0 &&\n unassignedSlots.length === 0,\n deadEnds,\n unreachable,\n badTargets,\n missingEmailCapture,\n duplicateKeys,\n slugCollisions,\n orphanVariants,\n noReachableFinish,\n unknownProductRefs,\n unassignedSlots,\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commerce/capabilities.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBO,IAAM,eAAA,uBAAoD,GAAA,CAAqB;AAAA,EACpF,SAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF,CAAC;AAEM,SAAS,gBAAgB,OAAA,EAAmC;AACjE,EAAA,OAAO,eAAA,CAAgB,IAAI,OAAO,CAAA;AACpC;AAgDA,IAAM,KAAwB,EAAE,QAAA,EAAU,MAAM,OAAA,EAAS,IAAA,EAAM,YAAY,UAAA,EAAW;AA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AAI,KAAA,EAAO,MAAA,EAAQ,CAAA,eAAA,EAAkB,cAAc,CAAA,4CAAA,CAAA,EAA+C;AAAA,EAC7G;AACA,EAAA,IAAI,GAAA,CAAI,eAAe,aAAA,EAAe;AACpC,IAAA,OAAO,EAAE,IAAI,IAAA,EAAM,IAAA,EAAM,4BAA4B,QAAQ,CAAA,EAAA,EAAK,cAAc,CAAA,6EAAA,CAAA,EAA2E;AAAA,EAC7J;AACA,EAAA,OAAO,EAAE,IAAI,IAAA,EAAK;AACpB;AA+BO,SAAS,aAAA,CACd,QAAA,EACA,OAAA,EACA,KAAA,GAAuD,EAAC,EACzC;AACf,EAAA,MAAM,YAAY,KAAA,CAAM,SAAA,KAAc,aAAa,yBAAA,IAA6B,QAAA,KAAa,6BAA6B,QAAA,KAAa,kBAAA,CAAA;AACvI,EAAA,OAAO,EAAE,QAAA,EAAU,OAAA,EAAS,WAAA,EAAa,KAAA,CAAM,aAAa,SAAA,EAAU;AACxE","file":"chunk-LJYLGLFS.cjs","sourcesContent":["/**\n * The provider capability matrix + checkout error taxonomy — the PURE half of the\n * checkout seam, extracted from checkout.tsx so it ships through the **manifest\n * entry** (no React): the API's publish validation, the editor, AI authoring, and\n * local dev all run the SAME checks the runtime primitives use (phase-3 §3.1b —\n * \"the SDK ships this as data\"). The React half (driver seam, `useCheckout`,\n * `<Checkout>`/`<Upsell>`) stays in ./checkout, which re-exports everything here.\n */\n\nexport type CheckoutSurface =\n | 'express' // wallet quick-buttons (Apple/Google Pay) — inline\n | 'element' // inline card form — inline\n | 'embedded' // provider-managed inline checkout — inline\n | 'sheet' // bottom-sheet popup — opens on click\n | 'popup' // provider-hosted overlay — opens on click\n | 'redirect' // provider-hosted page — opens on click\n\nexport type CheckoutProvider = 'stripe' | 'paddle' | 'whop' | 'primer' | 'solidgate'\nexport type CheckoutIntent = 'purchase' | 'upsell'\n\n/** Surfaces that render inline (vs. those that open on click). */\nexport const INLINE_SURFACES: ReadonlySet<CheckoutSurface> = new Set<CheckoutSurface>([\n 'express',\n 'element',\n 'embedded',\n])\n\nexport function isInlineSurface(surface: CheckoutSurface): boolean {\n return INLINE_SURFACES.has(surface)\n}\n\n/**\n * The kind of off-session upsell (researched against Funnelfox's changelog, which\n * ships these as distinct features). The discriminating real-world constraint is\n * **stacking a 2nd concurrent subscription** — Paddle can't, SolidGate/Stripe can.\n */\nexport type UpsellKind =\n | 'subscription' // charge a NEW, 2nd concurrent subscription off-session (stacking)\n | 'one-time' // charge a one-time add-on off-session\n | 'upgrade' // change the existing subscription's plan\n\n/** Reliability of an off-session upsell charge AFTER a purchase on a surface. */\nexport type OffSessionReliability =\n | 'reliable' // we hold the saved method (Stripe Elements / SolidGate) or the provider charges it (Paddle / Whop API)\n | 'conditional' // possible but may decline — Stripe **managed** checkout (vault charge, SCA not guaranteed) or an orchestrator's PSP-dependent routing (Primer)\n | 'none'\n\nexport interface SurfaceCapability {\n purchase: boolean\n /** Apple/Google Pay available on this surface. */\n wallets: boolean\n /** Reliability of an off-session upsell after a purchase on this surface. */\n offSession: OffSessionReliability\n}\n\nexport interface ProviderProfile {\n /** Merchant-of-Record (handles tax/compliance) vs. a PSP you settle through. */\n isMoR: boolean\n /** Upsell kinds this provider can charge off-session (one-click, no re-entry). */\n offSessionUpsells: UpsellKind[]\n /** Who charges the saved method off-session: you (PSP) or the provider (MoR/managed). */\n tokenModel: 'merchant' | 'provider'\n /** Routes across multiple processors (Primer; SolidGate also offers this) vs. a single acquirer. */\n orchestrator: boolean\n /**\n * Driver tier (Wave-4 decision, Simon 2026-07-02): `full` = a real driver ships\n * (Stripe, Paddle); `planned` = profile only — authoring/publish validate against\n * it, but no charge path exists yet (Whop, Primer, SolidGate). A new provider\n * becomes buildable by writing a driver; its profile already gates what authors\n * can express, so funnels written today stay valid when the driver lands.\n */\n status: 'full' | 'planned'\n /** Supported surfaces → per-surface capabilities. **Absent = not supported.** */\n surfaces: Partial<Record<CheckoutSurface, SurfaceCapability>>\n}\n\n/** Reliable off-session after this surface (we/the provider hold a chargeable method). */\nconst ON: SurfaceCapability = { purchase: true, wallets: true, offSession: 'reliable' }\n/** Stripe-managed checkout: a purchase works, but the off-session upsell may decline. */\nconst MANAGED: SurfaceCapability = { purchase: true, wallets: true, offSession: 'conditional' }\n/** Orchestrator-routed (Primer): off-session depends on which PSP vaulted the method. */\nconst ROUTED: SurfaceCapability = { purchase: true, wallets: true, offSession: 'conditional' }\nconst ALL_UPSELLS: UpsellKind[] = ['subscription', 'one-time', 'upgrade']\n\n/**\n * Provider capabilities (researched 2026-06-23 against provider docs + Funnelfox;\n * trial mechanics re-verified 2026-07-02, doc 09 §4.4).\n *\n * Three real-world corrections to the naive model:\n * 1. **Off-session upsell support is per-provider by *kind*** (`offSessionUpsells`):\n * Paddle can't stack a 2nd concurrent subscription (upgrade + one-time only);\n * Stripe/SolidGate/Whop/Primer can do all kinds.\n * 2. **Off-session *reliability* varies by the paywall surface** (`SurfaceCapability.\n * offSession`): Stripe **managed** checkout (`embedded`/`redirect`) upsells as a\n * direct charge against Stripe's vault → `conditional` (may decline); Elements\n * surfaces are `reliable`. Primer is `conditional` everywhere (PSP-dependent).\n * 3. **Surface availability is a hard constraint.** MoR/managed providers can't\n * expose a raw card field to your own UI: Paddle has no `express`/`element`/your\n * `sheet`; Whop has no raw `element`/`express`; Primer has no hosted `redirect`;\n * Stripe/SolidGate have no `popup`. A missing entry means \"not possible.\"\n */\nexport const PROVIDER_PROFILES: Record<CheckoutProvider, ProviderProfile> = {\n // PSP; you hold the PaymentMethod and fire your own off-session PaymentIntent on\n // the Elements surfaces (reliable). **Managed** Checkout (`embedded`/`redirect`)\n // upsells too, but as a direct charge against Stripe's vaulted card → conditional.\n // No provider \"popup\" surface.\n stripe: {\n isMoR: false, offSessionUpsells: ALL_UPSELLS, tokenModel: 'merchant', orchestrator: false, status: 'full',\n surfaces: { express: ON, element: ON, sheet: ON, embedded: MANAGED, redirect: MANAGED },\n },\n // Merchant-of-Record; card entry is always Paddle's frame → no own element/sheet/\n // express. Off-session via subscription one-time charge / collection_mode, but\n // **no 2nd concurrent subscription** (upgrade + one-time only), provider-initiated.\n paddle: {\n isMoR: true, offSessionUpsells: ['one-time', 'upgrade'], tokenModel: 'provider', orchestrator: false, status: 'full',\n surfaces: { embedded: ON, popup: ON, redirect: ON },\n },\n // Merchant-of-Record; iframe-only (no raw card field). Off-session works\n // (provider-initiated, async via webhooks). `sheet` = our chrome hosting their embed.\n whop: {\n isMoR: true, offSessionUpsells: ALL_UPSELLS, tokenModel: 'provider', orchestrator: false, status: 'planned',\n surfaces: { embedded: ON, redirect: ON, sheet: ON },\n },\n // Pure orchestrator (PSP-side); Headless renders express/element/sheet/embedded.\n // No hosted redirect page, no popup checkout. Off-session is PSP-conditional —\n // the vault lives with whichever processor Primer routed to (data matches this\n // comment as of 2026-07-02; it previously said conditional but coded reliable).\n primer: {\n isMoR: false, offSessionUpsells: ALL_UPSELLS, tokenModel: 'merchant', orchestrator: true, status: 'planned',\n surfaces: { express: ROUTED, element: ROUTED, sheet: ROUTED, embedded: ROUTED },\n },\n // PSP **and** orchestrator (own acquiring + connectors routing across Stripe/Adyen/\n // PayPal). One Payment Form (element/sheet/embedded) + hosted page + wallet button.\n // Strong native off-session (Recurring API). No popup.\n solidgate: {\n isMoR: false, offSessionUpsells: ALL_UPSELLS, tokenModel: 'merchant', orchestrator: true, status: 'planned',\n surfaces: { express: ON, element: ON, sheet: ON, embedded: ON, redirect: ON },\n },\n}\n\nexport interface ValidationResult {\n ok: boolean\n reason?: string\n /** Non-fatal caveat (e.g. Paddle upgrade-only). */\n note?: string\n}\n\n/** Surfaces a provider supports, for the editor/AI to steer authors. */\nexport function surfacesFor(provider: CheckoutProvider): CheckoutSurface[] {\n return Object.keys(PROVIDER_PROFILES[provider]?.surfaces ?? {}) as CheckoutSurface[]\n}\n\n/** Whether a provider is a Merchant of Record (it owns tax/compliance). */\nexport function isMerchantOfRecord(provider: CheckoutProvider): boolean {\n return PROVIDER_PROFILES[provider]?.isMoR ?? false\n}\n\n/** Whether a provider routes across multiple processors (Primer, SolidGate). */\nexport function isOrchestrator(provider: CheckoutProvider): boolean {\n return PROVIDER_PROFILES[provider]?.orchestrator ?? false\n}\n\n/**\n * Validate a (provider, surface) for a **purchase**: the surface must exist for\n * the provider and accept a payment. Surface availability is the real constraint\n * (e.g. Paddle has no `element`).\n */\nexport function validateCheckout(provider: CheckoutProvider, surface: CheckoutSurface): ValidationResult {\n const cap = PROVIDER_PROFILES[provider]?.surfaces[surface]\n if (!cap) return { ok: false, reason: `${provider} has no '${surface}' surface` }\n return cap.purchase ? { ok: true } : { ok: false, reason: `'${surface}' can't take a purchase on ${provider}` }\n}\n\n/**\n * Validate an **off-session upsell** of `kind` after a purchase made on\n * `paywallSurface`. Combines provider support for the kind (Paddle can't stack a\n * 2nd subscription) with the paywall surface's off-session reliability (Stripe\n * managed checkout is `conditional` — returned as a `note`, not a hard block).\n */\nexport function validateUpsell(\n provider: CheckoutProvider,\n paywallSurface: CheckoutSurface,\n kind: UpsellKind = 'subscription',\n): ValidationResult {\n const profile = PROVIDER_PROFILES[provider]\n if (!profile) return { ok: false, reason: `unknown provider '${provider}'` }\n if (!profile.offSessionUpsells.includes(kind)) {\n const can = profile.offSessionUpsells.length ? ` (it supports: ${profile.offSessionUpsells.join(', ')})` : ''\n return { ok: false, reason: `${provider} can't charge a '${kind}' upsell off-session${can}` }\n }\n const cap = profile.surfaces[paywallSurface]\n if (!cap) return { ok: false, reason: `${provider} has no '${paywallSurface}' surface to upsell after` }\n if (cap.offSession === 'none') {\n return { ok: false, reason: `a purchase on '${paywallSurface}' retains no chargeable method for an upsell` }\n }\n if (cap.offSession === 'conditional') {\n return { ok: true, note: `off-session upsell after ${provider} '${paywallSurface}' may decline — prefer a reliable surface or wire an on-session fallback` }\n }\n return { ok: true }\n}\n\n// ── Checkout error taxonomy (pure — drivers + server both normalize into it) ──\n\n/**\n * Normalized failure category — the driver/platform maps each provider's decline\n * codes into one of these so funnels can route/recover by reason. `authentication_\n * required` (3DS/SCA) and `requires_payment_method` are the cases an **off-session**\n * upsell can't satisfy → recover on-session (re-collect a card).\n */\nexport type CheckoutErrorCategory =\n | 'card_declined'\n | 'insufficient_funds'\n | 'expired_card'\n | 'prepaid_card' // card funding is prepaid — trials/subscriptions commonly decline; route to a real-card recapture page\n | 'authentication_required' // SCA/3DS needed — off-session can't challenge\n | 'requires_payment_method' // no usable saved method\n | 'processing_error'\n | 'canceled'\n | 'unknown'\n\nexport interface CheckoutError {\n category: CheckoutErrorCategory\n message: string\n /** Raw provider decline code, if any (e.g. Stripe `card_declined`/`insufficient_funds`). */\n declineCode?: string\n /** Whether re-attempting (e.g. an on-session re-collection) may succeed. */\n retryable: boolean\n}\n\n/** Build a {@link CheckoutError} (driver/test helper). */\nexport function checkoutError(\n category: CheckoutErrorCategory,\n message: string,\n extra: { declineCode?: string; retryable?: boolean } = {},\n): CheckoutError {\n const retryable = extra.retryable ?? (category === 'authentication_required' || category === 'requires_payment_method' || category === 'processing_error')\n return { category, message, declineCode: extra.declineCode, retryable }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commerce/capabilities.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBO,IAAM,eAAA,uBAAoD,GAAA,CAAqB;AAAA,EACpF,SAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF,CAAC;AAEM,SAAS,gBAAgB,OAAA,EAAmC;AACjE,EAAA,OAAO,eAAA,CAAgB,IAAI,OAAO,CAAA;AACpC;AAgDA,IAAM,KAAwB,EAAE,QAAA,EAAU,MAAM,OAAA,EAAS,IAAA,EAAM,YAAY,UAAA,EAAW;AAEtF,IAAM,UAA6B,EAAE,QAAA,EAAU,MAAM,OAAA,EAAS,IAAA,EAAM,YAAY,aAAA,EAAc;AAE9F,IAAM,SAA4B,EAAE,QAAA,EAAU,MAAM,OAAA,EAAS,IAAA,EAAM,YAAY,aAAA,EAAc;AAC7F,IAAM,WAAA,GAA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M,4BAA4B,QAAQ,CAAA,EAAA,EAAK,cAAc,CAAA,6EAAA,CAAA,EAA2E;AAAA,EAC7J;AACA,EAAA,OAAO,EAAE,IAAI,IAAA,EAAK;AACpB;AA+BO,SAAS,aAAA,CACd,QAAA,EACA,OAAA,EACA,KAAA,GAAuD,EAAC,EACzC;AACf,EAAA,MAAM,YAAY,KAAA,CAAM,SAAA,KAAc,aAAa,yBAAA,IAA6B,QAAA,KAAa,6BAA6B,QAAA,KAAa,kBAAA,CAAA;AACvI,EAAA,OAAO,EAAE,QAAA,EAAU,OAAA,EAAS,WAAA,EAAa,KAAA,CAAM,aAAa,SAAA,EAAU;AACxE","file":"chunk-YY375F2B.js","sourcesContent":["/**\n * The provider capability matrix + checkout error taxonomy — the PURE half of the\n * checkout seam, extracted from checkout.tsx so it ships through the **manifest\n * entry** (no React): the API's publish validation, the editor, AI authoring, and\n * local dev all run the SAME checks the runtime primitives use (phase-3 §3.1b —\n * \"the SDK ships this as data\"). The React half (driver seam, `useCheckout`,\n * `<Checkout>`/`<Upsell>`) stays in ./checkout, which re-exports everything here.\n */\n\nexport type CheckoutSurface =\n | 'express' // wallet quick-buttons (Apple/Google Pay) — inline\n | 'element' // inline card form — inline\n | 'embedded' // provider-managed inline checkout — inline\n | 'sheet' // bottom-sheet popup — opens on click\n | 'popup' // provider-hosted overlay — opens on click\n | 'redirect' // provider-hosted page — opens on click\n\nexport type CheckoutProvider = 'stripe' | 'paddle' | 'whop' | 'primer' | 'solidgate'\nexport type CheckoutIntent = 'purchase' | 'upsell'\n\n/** Surfaces that render inline (vs. those that open on click). */\nexport const INLINE_SURFACES: ReadonlySet<CheckoutSurface> = new Set<CheckoutSurface>([\n 'express',\n 'element',\n 'embedded',\n])\n\nexport function isInlineSurface(surface: CheckoutSurface): boolean {\n return INLINE_SURFACES.has(surface)\n}\n\n/**\n * The kind of off-session upsell (researched against Funnelfox's changelog, which\n * ships these as distinct features). The discriminating real-world constraint is\n * **stacking a 2nd concurrent subscription** — Paddle can't, SolidGate/Stripe can.\n */\nexport type UpsellKind =\n | 'subscription' // charge a NEW, 2nd concurrent subscription off-session (stacking)\n | 'one-time' // charge a one-time add-on off-session\n | 'upgrade' // change the existing subscription's plan\n\n/** Reliability of an off-session upsell charge AFTER a purchase on a surface. */\nexport type OffSessionReliability =\n | 'reliable' // we hold the saved method (Stripe Elements / SolidGate) or the provider charges it (Paddle / Whop API)\n | 'conditional' // possible but may decline — Stripe **managed** checkout (vault charge, SCA not guaranteed) or an orchestrator's PSP-dependent routing (Primer)\n | 'none'\n\nexport interface SurfaceCapability {\n purchase: boolean\n /** Apple/Google Pay available on this surface. */\n wallets: boolean\n /** Reliability of an off-session upsell after a purchase on this surface. */\n offSession: OffSessionReliability\n}\n\nexport interface ProviderProfile {\n /** Merchant-of-Record (handles tax/compliance) vs. a PSP you settle through. */\n isMoR: boolean\n /** Upsell kinds this provider can charge off-session (one-click, no re-entry). */\n offSessionUpsells: UpsellKind[]\n /** Who charges the saved method off-session: you (PSP) or the provider (MoR/managed). */\n tokenModel: 'merchant' | 'provider'\n /** Routes across multiple processors (Primer; SolidGate also offers this) vs. a single acquirer. */\n orchestrator: boolean\n /**\n * Driver tier (Wave-4 decision, Simon 2026-07-02): `full` = a real driver ships\n * (Stripe, Paddle); `planned` = profile only — authoring/publish validate against\n * it, but no charge path exists yet (Whop, Primer, SolidGate). A new provider\n * becomes buildable by writing a driver; its profile already gates what authors\n * can express, so funnels written today stay valid when the driver lands.\n */\n status: 'full' | 'planned'\n /** Supported surfaces → per-surface capabilities. **Absent = not supported.** */\n surfaces: Partial<Record<CheckoutSurface, SurfaceCapability>>\n}\n\n/** Reliable off-session after this surface (we/the provider hold a chargeable method). */\nconst ON: SurfaceCapability = { purchase: true, wallets: true, offSession: 'reliable' }\n/** Stripe-managed checkout: a purchase works, but the off-session upsell may decline. */\nconst MANAGED: SurfaceCapability = { purchase: true, wallets: true, offSession: 'conditional' }\n/** Orchestrator-routed (Primer): off-session depends on which PSP vaulted the method. */\nconst ROUTED: SurfaceCapability = { purchase: true, wallets: true, offSession: 'conditional' }\nconst ALL_UPSELLS: UpsellKind[] = ['subscription', 'one-time', 'upgrade']\n\n/**\n * Provider capabilities (researched 2026-06-23 against provider docs + Funnelfox;\n * trial mechanics re-verified 2026-07-02, doc 09 §4.4).\n *\n * Three real-world corrections to the naive model:\n * 1. **Off-session upsell support is per-provider by *kind*** (`offSessionUpsells`):\n * Paddle can't stack a 2nd concurrent subscription (upgrade + one-time only);\n * Stripe/SolidGate/Whop/Primer can do all kinds.\n * 2. **Off-session *reliability* varies by the paywall surface** (`SurfaceCapability.\n * offSession`): Stripe **managed** checkout (`embedded`/`redirect`) upsells as a\n * direct charge against Stripe's vault → `conditional` (may decline); Elements\n * surfaces are `reliable`. Primer is `conditional` everywhere (PSP-dependent).\n * 3. **Surface availability is a hard constraint.** MoR/managed providers can't\n * expose a raw card field to your own UI: Paddle has no `express`/`element`/your\n * `sheet`; Whop has no raw `element`/`express`; Primer has no hosted `redirect`;\n * Stripe/SolidGate have no `popup`. A missing entry means \"not possible.\"\n */\nexport const PROVIDER_PROFILES: Record<CheckoutProvider, ProviderProfile> = {\n // PSP; you hold the PaymentMethod and fire your own off-session PaymentIntent on\n // the Elements surfaces (reliable). **Managed** Checkout (`embedded`/`redirect`)\n // upsells too, but as a direct charge against Stripe's vaulted card → conditional.\n // No provider \"popup\" surface.\n stripe: {\n isMoR: false, offSessionUpsells: ALL_UPSELLS, tokenModel: 'merchant', orchestrator: false, status: 'full',\n surfaces: { express: ON, element: ON, sheet: ON, embedded: MANAGED, redirect: MANAGED },\n },\n // Merchant-of-Record; card entry is always Paddle's frame → no own element/sheet/\n // express. Off-session via subscription one-time charge / collection_mode, but\n // **no 2nd concurrent subscription** (upgrade + one-time only), provider-initiated.\n paddle: {\n isMoR: true, offSessionUpsells: ['one-time', 'upgrade'], tokenModel: 'provider', orchestrator: false, status: 'full',\n surfaces: { embedded: ON, popup: ON, redirect: ON },\n },\n // Merchant-of-Record; iframe-only (no raw card field). Off-session works\n // (provider-initiated, async via webhooks). `sheet` = our chrome hosting their embed.\n whop: {\n isMoR: true, offSessionUpsells: ALL_UPSELLS, tokenModel: 'provider', orchestrator: false, status: 'planned',\n surfaces: { embedded: ON, redirect: ON, sheet: ON },\n },\n // Pure orchestrator (PSP-side); Headless renders express/element/sheet/embedded.\n // No hosted redirect page, no popup checkout. Off-session is PSP-conditional —\n // the vault lives with whichever processor Primer routed to (data matches this\n // comment as of 2026-07-02; it previously said conditional but coded reliable).\n primer: {\n isMoR: false, offSessionUpsells: ALL_UPSELLS, tokenModel: 'merchant', orchestrator: true, status: 'planned',\n surfaces: { express: ROUTED, element: ROUTED, sheet: ROUTED, embedded: ROUTED },\n },\n // PSP **and** orchestrator (own acquiring + connectors routing across Stripe/Adyen/\n // PayPal). One Payment Form (element/sheet/embedded) + hosted page + wallet button.\n // Strong native off-session (Recurring API). No popup.\n solidgate: {\n isMoR: false, offSessionUpsells: ALL_UPSELLS, tokenModel: 'merchant', orchestrator: true, status: 'planned',\n surfaces: { express: ON, element: ON, sheet: ON, embedded: ON, redirect: ON },\n },\n}\n\nexport interface ValidationResult {\n ok: boolean\n reason?: string\n /** Non-fatal caveat (e.g. Paddle upgrade-only). */\n note?: string\n}\n\n/** Surfaces a provider supports, for the editor/AI to steer authors. */\nexport function surfacesFor(provider: CheckoutProvider): CheckoutSurface[] {\n return Object.keys(PROVIDER_PROFILES[provider]?.surfaces ?? {}) as CheckoutSurface[]\n}\n\n/** Whether a provider is a Merchant of Record (it owns tax/compliance). */\nexport function isMerchantOfRecord(provider: CheckoutProvider): boolean {\n return PROVIDER_PROFILES[provider]?.isMoR ?? false\n}\n\n/** Whether a provider routes across multiple processors (Primer, SolidGate). */\nexport function isOrchestrator(provider: CheckoutProvider): boolean {\n return PROVIDER_PROFILES[provider]?.orchestrator ?? false\n}\n\n/**\n * Validate a (provider, surface) for a **purchase**: the surface must exist for\n * the provider and accept a payment. Surface availability is the real constraint\n * (e.g. Paddle has no `element`).\n */\nexport function validateCheckout(provider: CheckoutProvider, surface: CheckoutSurface): ValidationResult {\n const cap = PROVIDER_PROFILES[provider]?.surfaces[surface]\n if (!cap) return { ok: false, reason: `${provider} has no '${surface}' surface` }\n return cap.purchase ? { ok: true } : { ok: false, reason: `'${surface}' can't take a purchase on ${provider}` }\n}\n\n/**\n * Validate an **off-session upsell** of `kind` after a purchase made on\n * `paywallSurface`. Combines provider support for the kind (Paddle can't stack a\n * 2nd subscription) with the paywall surface's off-session reliability (Stripe\n * managed checkout is `conditional` — returned as a `note`, not a hard block).\n */\nexport function validateUpsell(\n provider: CheckoutProvider,\n paywallSurface: CheckoutSurface,\n kind: UpsellKind = 'subscription',\n): ValidationResult {\n const profile = PROVIDER_PROFILES[provider]\n if (!profile) return { ok: false, reason: `unknown provider '${provider}'` }\n if (!profile.offSessionUpsells.includes(kind)) {\n const can = profile.offSessionUpsells.length ? ` (it supports: ${profile.offSessionUpsells.join(', ')})` : ''\n return { ok: false, reason: `${provider} can't charge a '${kind}' upsell off-session${can}` }\n }\n const cap = profile.surfaces[paywallSurface]\n if (!cap) return { ok: false, reason: `${provider} has no '${paywallSurface}' surface to upsell after` }\n if (cap.offSession === 'none') {\n return { ok: false, reason: `a purchase on '${paywallSurface}' retains no chargeable method for an upsell` }\n }\n if (cap.offSession === 'conditional') {\n return { ok: true, note: `off-session upsell after ${provider} '${paywallSurface}' may decline — prefer a reliable surface or wire an on-session fallback` }\n }\n return { ok: true }\n}\n\n// ── Checkout error taxonomy (pure — drivers + server both normalize into it) ──\n\n/**\n * Normalized failure category — the driver/platform maps each provider's decline\n * codes into one of these so funnels can route/recover by reason. `authentication_\n * required` (3DS/SCA) and `requires_payment_method` are the cases an **off-session**\n * upsell can't satisfy → recover on-session (re-collect a card).\n */\nexport type CheckoutErrorCategory =\n | 'card_declined'\n | 'insufficient_funds'\n | 'expired_card'\n | 'prepaid_card' // card funding is prepaid — trials/subscriptions commonly decline; route to a real-card recapture page\n | 'authentication_required' // SCA/3DS needed — off-session can't challenge\n | 'requires_payment_method' // no usable saved method\n | 'processing_error'\n | 'canceled'\n | 'unknown'\n\nexport interface CheckoutError {\n category: CheckoutErrorCategory\n message: string\n /** Raw provider decline code, if any (e.g. Stripe `card_declined`/`insufficient_funds`). */\n declineCode?: string\n /** Whether re-attempting (e.g. an on-session re-collection) may succeed. */\n retryable: boolean\n}\n\n/** Build a {@link CheckoutError} (driver/test helper). */\nexport function checkoutError(\n category: CheckoutErrorCategory,\n message: string,\n extra: { declineCode?: string; retryable?: boolean } = {},\n): CheckoutError {\n const retryable = extra.retryable ?? (category === 'authentication_required' || category === 'requires_payment_method' || category === 'processing_error')\n return { category, message, declineCode: extra.declineCode, retryable }\n}\n"]}