@appfunnel-dev/sdk 2.0.0-canary.0 → 2.0.0-canary.2

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 (43) hide show
  1. package/dist/capabilities-7_hy5f5G.d.cts +114 -0
  2. package/dist/capabilities-7_hy5f5G.d.ts +114 -0
  3. package/dist/checkout-CZmEvWfC.d.cts +317 -0
  4. package/dist/checkout-DiQvRT5q.d.ts +317 -0
  5. package/dist/chunk-7UC5VXOR.js +446 -0
  6. package/dist/chunk-7UC5VXOR.js.map +1 -0
  7. package/dist/chunk-LJYLGLFS.cjs +153 -0
  8. package/dist/chunk-LJYLGLFS.cjs.map +1 -0
  9. package/dist/chunk-UIR6TGEW.js +97 -0
  10. package/dist/chunk-UIR6TGEW.js.map +1 -0
  11. package/dist/chunk-VQOD2Z6Q.cjs +104 -0
  12. package/dist/chunk-VQOD2Z6Q.cjs.map +1 -0
  13. package/dist/chunk-YY375F2B.js +140 -0
  14. package/dist/chunk-YY375F2B.js.map +1 -0
  15. package/dist/chunk-Z3TWO2PW.cjs +475 -0
  16. package/dist/chunk-Z3TWO2PW.cjs.map +1 -0
  17. package/dist/driver-paddle.cjs +814 -0
  18. package/dist/driver-paddle.cjs.map +1 -0
  19. package/dist/driver-paddle.d.cts +10 -0
  20. package/dist/driver-paddle.d.ts +10 -0
  21. package/dist/driver-paddle.js +811 -0
  22. package/dist/driver-paddle.js.map +1 -0
  23. package/dist/driver-stripe.cjs +2253 -0
  24. package/dist/driver-stripe.cjs.map +1 -0
  25. package/dist/driver-stripe.d.cts +8 -0
  26. package/dist/driver-stripe.d.ts +8 -0
  27. package/dist/driver-stripe.js +2247 -0
  28. package/dist/driver-stripe.js.map +1 -0
  29. package/dist/index.cjs +1953 -813
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +183 -933
  32. package/dist/index.d.ts +183 -933
  33. package/dist/index.js +1674 -655
  34. package/dist/index.js.map +1 -1
  35. package/dist/manifest-DQThneiG.d.cts +777 -0
  36. package/dist/manifest-DQThneiG.d.ts +777 -0
  37. package/dist/manifest-entry.cjs +203 -0
  38. package/dist/manifest-entry.cjs.map +1 -0
  39. package/dist/manifest-entry.d.cts +184 -0
  40. package/dist/manifest-entry.d.ts +184 -0
  41. package/dist/manifest-entry.js +98 -0
  42. package/dist/manifest-entry.js.map +1 -0
  43. package/package.json +37 -4
@@ -0,0 +1,153 @@
1
+ 'use strict';
2
+
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJS = (cb, mod) => function __require() {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
+ ));
32
+
33
+ // src/commerce/capabilities.ts
34
+ var INLINE_SURFACES = /* @__PURE__ */ new Set([
35
+ "express",
36
+ "element",
37
+ "embedded"
38
+ ]);
39
+ function isInlineSurface(surface) {
40
+ return INLINE_SURFACES.has(surface);
41
+ }
42
+ var ON = { purchase: true, wallets: true, offSession: "reliable" };
43
+ var MANAGED = { purchase: true, wallets: true, offSession: "conditional" };
44
+ var ROUTED = { purchase: true, wallets: true, offSession: "conditional" };
45
+ var ALL_UPSELLS = ["subscription", "one-time", "upgrade"];
46
+ var PROVIDER_PROFILES = {
47
+ // PSP; you hold the PaymentMethod and fire your own off-session PaymentIntent on
48
+ // the Elements surfaces (reliable). **Managed** Checkout (`embedded`/`redirect`)
49
+ // upsells too, but as a direct charge against Stripe's vaulted card → conditional.
50
+ // No provider "popup" surface.
51
+ stripe: {
52
+ isMoR: false,
53
+ offSessionUpsells: ALL_UPSELLS,
54
+ tokenModel: "merchant",
55
+ orchestrator: false,
56
+ status: "full",
57
+ surfaces: { express: ON, element: ON, sheet: ON, embedded: MANAGED, redirect: MANAGED }
58
+ },
59
+ // Merchant-of-Record; card entry is always Paddle's frame → no own element/sheet/
60
+ // express. Off-session via subscription one-time charge / collection_mode, but
61
+ // **no 2nd concurrent subscription** (upgrade + one-time only), provider-initiated.
62
+ paddle: {
63
+ isMoR: true,
64
+ offSessionUpsells: ["one-time", "upgrade"],
65
+ tokenModel: "provider",
66
+ orchestrator: false,
67
+ status: "full",
68
+ surfaces: { embedded: ON, popup: ON, redirect: ON }
69
+ },
70
+ // Merchant-of-Record; iframe-only (no raw card field). Off-session works
71
+ // (provider-initiated, async via webhooks). `sheet` = our chrome hosting their embed.
72
+ whop: {
73
+ isMoR: true,
74
+ offSessionUpsells: ALL_UPSELLS,
75
+ tokenModel: "provider",
76
+ orchestrator: false,
77
+ status: "planned",
78
+ surfaces: { embedded: ON, redirect: ON, sheet: ON }
79
+ },
80
+ // Pure orchestrator (PSP-side); Headless renders express/element/sheet/embedded.
81
+ // No hosted redirect page, no popup checkout. Off-session is PSP-conditional —
82
+ // the vault lives with whichever processor Primer routed to (data matches this
83
+ // comment as of 2026-07-02; it previously said conditional but coded reliable).
84
+ primer: {
85
+ isMoR: false,
86
+ offSessionUpsells: ALL_UPSELLS,
87
+ tokenModel: "merchant",
88
+ orchestrator: true,
89
+ status: "planned",
90
+ surfaces: { express: ROUTED, element: ROUTED, sheet: ROUTED, embedded: ROUTED }
91
+ },
92
+ // PSP **and** orchestrator (own acquiring + connectors routing across Stripe/Adyen/
93
+ // PayPal). One Payment Form (element/sheet/embedded) + hosted page + wallet button.
94
+ // Strong native off-session (Recurring API). No popup.
95
+ solidgate: {
96
+ isMoR: false,
97
+ offSessionUpsells: ALL_UPSELLS,
98
+ tokenModel: "merchant",
99
+ orchestrator: true,
100
+ status: "planned",
101
+ surfaces: { express: ON, element: ON, sheet: ON, embedded: ON, redirect: ON }
102
+ }
103
+ };
104
+ function surfacesFor(provider) {
105
+ return Object.keys(PROVIDER_PROFILES[provider]?.surfaces ?? {});
106
+ }
107
+ function isMerchantOfRecord(provider) {
108
+ return PROVIDER_PROFILES[provider]?.isMoR ?? false;
109
+ }
110
+ function isOrchestrator(provider) {
111
+ return PROVIDER_PROFILES[provider]?.orchestrator ?? false;
112
+ }
113
+ function validateCheckout(provider, surface) {
114
+ const cap = PROVIDER_PROFILES[provider]?.surfaces[surface];
115
+ if (!cap) return { ok: false, reason: `${provider} has no '${surface}' surface` };
116
+ return cap.purchase ? { ok: true } : { ok: false, reason: `'${surface}' can't take a purchase on ${provider}` };
117
+ }
118
+ function validateUpsell(provider, paywallSurface, kind = "subscription") {
119
+ const profile = PROVIDER_PROFILES[provider];
120
+ if (!profile) return { ok: false, reason: `unknown provider '${provider}'` };
121
+ if (!profile.offSessionUpsells.includes(kind)) {
122
+ const can = profile.offSessionUpsells.length ? ` (it supports: ${profile.offSessionUpsells.join(", ")})` : "";
123
+ return { ok: false, reason: `${provider} can't charge a '${kind}' upsell off-session${can}` };
124
+ }
125
+ const cap = profile.surfaces[paywallSurface];
126
+ if (!cap) return { ok: false, reason: `${provider} has no '${paywallSurface}' surface to upsell after` };
127
+ if (cap.offSession === "none") {
128
+ return { ok: false, reason: `a purchase on '${paywallSurface}' retains no chargeable method for an upsell` };
129
+ }
130
+ if (cap.offSession === "conditional") {
131
+ return { ok: true, note: `off-session upsell after ${provider} '${paywallSurface}' may decline \u2014 prefer a reliable surface or wire an on-session fallback` };
132
+ }
133
+ return { ok: true };
134
+ }
135
+ function checkoutError(category, message, extra = {}) {
136
+ const retryable = extra.retryable ?? (category === "authentication_required" || category === "requires_payment_method" || category === "processing_error");
137
+ return { category, message, declineCode: extra.declineCode, retryable };
138
+ }
139
+
140
+ exports.INLINE_SURFACES = INLINE_SURFACES;
141
+ exports.PROVIDER_PROFILES = PROVIDER_PROFILES;
142
+ exports.__commonJS = __commonJS;
143
+ exports.__export = __export;
144
+ exports.__toESM = __toESM;
145
+ exports.checkoutError = checkoutError;
146
+ exports.isInlineSurface = isInlineSurface;
147
+ exports.isMerchantOfRecord = isMerchantOfRecord;
148
+ exports.isOrchestrator = isOrchestrator;
149
+ exports.surfacesFor = surfacesFor;
150
+ exports.validateCheckout = validateCheckout;
151
+ exports.validateUpsell = validateUpsell;
152
+ //# sourceMappingURL=chunk-LJYLGLFS.cjs.map
153
+ //# sourceMappingURL=chunk-LJYLGLFS.cjs.map
@@ -0,0 +1 @@
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,EAA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AAA,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"]}
@@ -0,0 +1,97 @@
1
+ import { checkoutError } from './chunk-YY375F2B.js';
2
+
3
+ // src/drivers/wire.ts
4
+ function endpoint(ctx, path = "") {
5
+ const base = ctx.apiBase.replace(/\/+$/, "");
6
+ return `${base}/campaign/${encodeURIComponent(ctx.campaignId)}/v2/checkout${path}`;
7
+ }
8
+ async function postJson(url, body) {
9
+ const res = await fetch(url, {
10
+ method: "POST",
11
+ headers: { "content-type": "application/json" },
12
+ body: JSON.stringify(body)
13
+ });
14
+ if (!res.ok) throw checkoutError("processing_error", `checkout request failed (HTTP ${res.status})`);
15
+ return await res.json();
16
+ }
17
+ function toCheckoutError(e) {
18
+ if (e && typeof e === "object" && "category" in e && "message" in e && "retryable" in e) {
19
+ return e;
20
+ }
21
+ return checkoutError("processing_error", e instanceof Error ? e.message : "Checkout request failed");
22
+ }
23
+ function postSession(ctx, req, correlationId) {
24
+ const body = {
25
+ funnelId: ctx.funnelId,
26
+ mode: ctx.mode,
27
+ productKey: req.product,
28
+ intent: req.intent,
29
+ kind: req.kind,
30
+ // null (not absent) = explicit off-session — the server validates surfaces
31
+ // against the capability matrix, so never let one default in transit.
32
+ surface: req.surface ?? null,
33
+ sessionId: ctx.sessionId ?? void 0,
34
+ visitorId: ctx.visitorId ?? void 0,
35
+ // Buyer email collected by the funnel (user.email) — Stripe Customer creation,
36
+ // receipts, Paddle prefill. Injected at attempt time by the FunnelProvider seam.
37
+ email: req.email,
38
+ correlationId
39
+ };
40
+ return postJson(endpoint(ctx), body);
41
+ }
42
+ function postComplete(ctx, correlationId, providerRef) {
43
+ const body = { providerRef };
44
+ return postJson(
45
+ endpoint(ctx, `/${encodeURIComponent(correlationId)}/complete`),
46
+ body
47
+ );
48
+ }
49
+ function settlementToResult(s) {
50
+ return { ok: true, amountMinor: s.amountMinor, currency: s.currency, eventId: s.eventId };
51
+ }
52
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
53
+ async function completeWithPoll(ctx, correlationId, opts = {}) {
54
+ const attempts = opts.attempts ?? 5;
55
+ const intervalMs = opts.intervalMs ?? 2e3;
56
+ try {
57
+ for (let i = 0; i < attempts; i++) {
58
+ const res = await postComplete(ctx, correlationId, opts.providerRef);
59
+ if (res.step === "settled") return settlementToResult(res.result);
60
+ if (res.step === "failed") return { ok: false, error: res.error };
61
+ if (i < attempts - 1) await sleep(intervalMs);
62
+ }
63
+ } catch (e) {
64
+ return { ok: false, error: toCheckoutError(e) };
65
+ }
66
+ return {
67
+ ok: false,
68
+ error: checkoutError(
69
+ "processing_error",
70
+ opts.timeoutMessage ?? "The payment has not been confirmed yet \u2014 please check back shortly.",
71
+ // `completion_timeout` marks "the poll ran out while the attempt was still
72
+ // pending" — drivers key double-charge guards on it (the attempt may still
73
+ // settle server-side; it was never refused).
74
+ { retryable: true, declineCode: "completion_timeout" }
75
+ )
76
+ };
77
+ }
78
+ function leaveForRedirect(url) {
79
+ return new Promise((resolve) => {
80
+ if (typeof window !== "undefined") {
81
+ const onPageshow = (event) => {
82
+ if (!event.persisted) return;
83
+ window.removeEventListener("pageshow", onPageshow);
84
+ resolve({
85
+ ok: false,
86
+ error: checkoutError("canceled", "Returned from the hosted checkout without completing")
87
+ });
88
+ };
89
+ window.addEventListener("pageshow", onPageshow);
90
+ }
91
+ window.location.assign(url);
92
+ });
93
+ }
94
+
95
+ export { completeWithPoll, leaveForRedirect, postComplete, postSession, settlementToResult, toCheckoutError };
96
+ //# sourceMappingURL=chunk-UIR6TGEW.js.map
97
+ //# sourceMappingURL=chunk-UIR6TGEW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/drivers/wire.ts"],"names":[],"mappings":";;;AAqBA,SAAS,QAAA,CAAS,GAAA,EAA4B,IAAA,GAAO,EAAA,EAAY;AAC/D,EAAA,MAAM,IAAA,GAAO,GAAA,CAAI,OAAA,CAAQ,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAC3C,EAAA,OAAO,CAAA,EAAG,IAAI,CAAA,UAAA,EAAa,kBAAA,CAAmB,IAAI,UAAU,CAAC,eAAe,IAAI,CAAA,CAAA;AAClF;AAEA,eAAe,QAAA,CAAY,KAAa,IAAA,EAA2B;AACjE,EAAA,MAAM,GAAA,GAAM,MAAM,KAAA,CAAM,GAAA,EAAK;AAAA,IAC3B,MAAA,EAAQ,MAAA;AAAA,IACR,OAAA,EAAS,EAAE,cAAA,EAAgB,kBAAA,EAAmB;AAAA,IAC9C,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,IAAI;AAAA,GAC1B,CAAA;AAGD,EAAA,IAAI,CAAC,IAAI,EAAA,EAAI,MAAM,cAAc,kBAAA,EAAoB,CAAA,8BAAA,EAAiC,GAAA,CAAI,MAAM,CAAA,CAAA,CAAG,CAAA;AACnG,EAAA,OAAQ,MAAM,IAAI,IAAA,EAAK;AACzB;AAGO,SAAS,gBAAgB,CAAA,EAA2B;AACzD,EAAA,IAAI,CAAA,IAAK,OAAO,CAAA,KAAM,QAAA,IAAY,cAAc,CAAA,IAAK,SAAA,IAAa,CAAA,IA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AAO,WAAW,WAAA,EAAa;AACjC,MAAA,MAAM,UAAA,GAAa,CAAC,KAAA,KAA+B;AACjD,QAAA,IAAI,CAAC,MAAM,SAAA,EAAW;AACtB,QAAA,MAAA,CAAO,mBAAA,CAAoB,YAAY,UAAU,CAAA;AACjD,QAAA,OAAA,CAAQ;AAAA,UACN,EAAA,EAAI,KAAA;AAAA,UACJ,KAAA,EAAO,aAAA,CAAc,UAAA,EAAY,sDAAsD;AAAA,SACxF,CAAA;AAAA,MACH,CAAA;AACA,MAAA,MAAA,CAAO,gBAAA,CAAiB,YAAY,UAAU,CAAA;AAAA,IAChD;AACA,IAAA,MAAA,CAAO,QAAA,CAAS,OAAO,GAAG,CAAA;AAAA,EAC5B,CAAC,CAAA;AACH","file":"chunk-UIR6TGEW.js","sourcesContent":["/**\n * Shared wire plumbing for the checkout drivers — the CLIENT half of the v2\n * checkout contract (commerce/checkout-api.ts). Lives under drivers/ (not\n * commerce/) on purpose: it ships only inside the `driver-*` subpath entries,\n * so the core funnel entry never bundles a checkout fetch — the core SDK talks\n * to a {@link CheckoutDriver}, never to the wire.\n *\n * Only `import type` from commerce/checkout(.tsx) here — a runtime import would\n * drag the React checkout primitives into every driver chunk. The one runtime\n * dependency is the pure error taxonomy (capabilities.ts).\n */\nimport type {\n CheckoutCompleteRequest,\n CheckoutCompleteResponse,\n CheckoutSessionRequest,\n CheckoutSessionResponse,\n CheckoutSettlement,\n} from '../commerce/checkout-api'\nimport type { CheckoutDriverContext, CheckoutRequest, CheckoutResult } from '../commerce/checkout'\nimport { checkoutError, type CheckoutError } from '../commerce/capabilities'\n\nfunction endpoint(ctx: CheckoutDriverContext, path = ''): string {\n const base = ctx.apiBase.replace(/\\/+$/, '')\n return `${base}/campaign/${encodeURIComponent(ctx.campaignId)}/v2/checkout${path}`\n}\n\nasync function postJson<T>(url: string, body: unknown): Promise<T> {\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n // The contract speaks in `step` responses, not HTTP errors — a non-2xx means the\n // request never reached the checkout service properly (proxy, deploy, outage).\n if (!res.ok) throw checkoutError('processing_error', `checkout request failed (HTTP ${res.status})`)\n return (await res.json()) as T\n}\n\n/** Normalize any thrown value into the taxonomy (network drops → `processing_error`). */\nexport function toCheckoutError(e: unknown): CheckoutError {\n if (e && typeof e === 'object' && 'category' in e && 'message' in e && 'retryable' in e) {\n return e as CheckoutError\n }\n return checkoutError('processing_error', e instanceof Error ? e.message : 'Checkout request failed')\n}\n\n/**\n * Open a checkout attempt: `POST {apiBase}/campaign/{campaignId}/v2/checkout`.\n * The correlationId is client-minted per ATTEMPT (idempotency key + the id the\n * server stamps into provider metadata) — mint it once, reuse it on retries.\n */\nexport function postSession(\n ctx: CheckoutDriverContext,\n req: CheckoutRequest,\n correlationId: string,\n): Promise<CheckoutSessionResponse> {\n const body: CheckoutSessionRequest = {\n funnelId: ctx.funnelId,\n mode: ctx.mode,\n productKey: req.product,\n intent: req.intent,\n kind: req.kind,\n // null (not absent) = explicit off-session — the server validates surfaces\n // against the capability matrix, so never let one default in transit.\n surface: req.surface ?? null,\n sessionId: ctx.sessionId ?? undefined,\n visitorId: ctx.visitorId ?? undefined,\n // Buyer email collected by the funnel (user.email) — Stripe Customer creation,\n // receipts, Paddle prefill. Injected at attempt time by the FunnelProvider seam.\n email: req.email,\n correlationId,\n }\n return postJson<CheckoutSessionResponse>(endpoint(ctx), body)\n}\n\n/** Ask the server to VERIFY with the provider and write the money facts (idempotent). */\nexport function postComplete(\n ctx: CheckoutDriverContext,\n correlationId: string,\n providerRef?: string,\n): Promise<CheckoutCompleteResponse> {\n const body: CheckoutCompleteRequest = { providerRef }\n return postJson<CheckoutCompleteResponse>(\n endpoint(ctx, `/${encodeURIComponent(correlationId)}/complete`),\n body,\n )\n}\n\n/** Server settlement → the SDK's CheckoutResult (eventId passes through for pixel dedup). */\nexport function settlementToResult(s: CheckoutSettlement): CheckoutResult {\n return { ok: true, amountMinor: s.amountMinor, currency: s.currency, eventId: s.eventId }\n}\n\nexport interface CompletePollOptions {\n providerRef?: string\n /** Total complete attempts before giving up (default 5). */\n attempts?: number\n /** Delay between attempts (default 2000ms). */\n intervalMs?: number\n /** Error message when the provider hasn't confirmed inside the window (MoR/async). */\n timeoutMessage?: string\n}\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\n\n/**\n * Complete with a bounded poll. Sync providers (Stripe) settle on the first\n * attempt — the server verifies against the provider inline. MoR/async providers\n * (Paddle) settle via webhook, so `pending` is normal: re-poll a few times, then\n * stop holding the UI hostage — the charge may still land server-side, which is\n * why the timeout error is `retryable` and the message should say the receipt\n * can still arrive (the server's money facts don't depend on this browser).\n */\nexport async function completeWithPoll(\n ctx: CheckoutDriverContext,\n correlationId: string,\n opts: CompletePollOptions = {},\n): Promise<CheckoutResult> {\n const attempts = opts.attempts ?? 5\n const intervalMs = opts.intervalMs ?? 2000\n try {\n for (let i = 0; i < attempts; i++) {\n const res = await postComplete(ctx, correlationId, opts.providerRef)\n if (res.step === 'settled') return settlementToResult(res.result)\n if (res.step === 'failed') return { ok: false, error: res.error }\n if (i < attempts - 1) await sleep(intervalMs)\n }\n } catch (e) {\n return { ok: false, error: toCheckoutError(e) }\n }\n return {\n ok: false,\n error: checkoutError(\n 'processing_error',\n opts.timeoutMessage ?? 'The payment has not been confirmed yet — please check back shortly.',\n // `completion_timeout` marks \"the poll ran out while the attempt was still\n // pending\" — drivers key double-charge guards on it (the attempt may still\n // settle server-side; it was never refused).\n { retryable: true, declineCode: 'completion_timeout' },\n ),\n }\n}\n\n/**\n * The `redirect` step hand-off: navigate to the provider-hosted page and return a\n * promise that settles ONLY if the buyer comes back to this very page. The page\n * is leaving — resolving early would fire `purchase.complete`/navigation for a\n * charge that hasn't happened, and rejecting would flash an error during the\n * (successful) hand-off — so while the navigation proceeds the promise stays\n * pending and `useCheckout` stays in `loading`, the truthful UI for a page\n * mid-navigation. The hosted page's SUCCESS return URL re-enters the funnel with\n * `af_checkout={correlationId}` (a fresh load — this promise is gone; the SDK's\n * resume leg settles the attempt).\n *\n * The one way THIS page comes back to life is a bfcache restore (browser Back\n * from the hosted page): `pageshow` with `persisted: true`. That is a buyer who\n * abandoned the hosted checkout — resolve `canceled` so the trigger re-enables\n * and inline redirect placeholders recover instead of spinning forever.\n */\nexport function leaveForRedirect(url: string): Promise<CheckoutResult> {\n return new Promise<CheckoutResult>((resolve) => {\n if (typeof window !== 'undefined') {\n const onPageshow = (event: PageTransitionEvent) => {\n if (!event.persisted) return\n window.removeEventListener('pageshow', onPageshow)\n resolve({\n ok: false,\n error: checkoutError('canceled', 'Returned from the hosted checkout without completing'),\n })\n }\n window.addEventListener('pageshow', onPageshow)\n }\n window.location.assign(url)\n })\n}\n"]}
@@ -0,0 +1,104 @@
1
+ 'use strict';
2
+
3
+ var chunkLJYLGLFS_cjs = require('./chunk-LJYLGLFS.cjs');
4
+
5
+ // src/drivers/wire.ts
6
+ function endpoint(ctx, path = "") {
7
+ const base = ctx.apiBase.replace(/\/+$/, "");
8
+ return `${base}/campaign/${encodeURIComponent(ctx.campaignId)}/v2/checkout${path}`;
9
+ }
10
+ async function postJson(url, body) {
11
+ const res = await fetch(url, {
12
+ method: "POST",
13
+ headers: { "content-type": "application/json" },
14
+ body: JSON.stringify(body)
15
+ });
16
+ if (!res.ok) throw chunkLJYLGLFS_cjs.checkoutError("processing_error", `checkout request failed (HTTP ${res.status})`);
17
+ return await res.json();
18
+ }
19
+ function toCheckoutError(e) {
20
+ if (e && typeof e === "object" && "category" in e && "message" in e && "retryable" in e) {
21
+ return e;
22
+ }
23
+ return chunkLJYLGLFS_cjs.checkoutError("processing_error", e instanceof Error ? e.message : "Checkout request failed");
24
+ }
25
+ function postSession(ctx, req, correlationId) {
26
+ const body = {
27
+ funnelId: ctx.funnelId,
28
+ mode: ctx.mode,
29
+ productKey: req.product,
30
+ intent: req.intent,
31
+ kind: req.kind,
32
+ // null (not absent) = explicit off-session — the server validates surfaces
33
+ // against the capability matrix, so never let one default in transit.
34
+ surface: req.surface ?? null,
35
+ sessionId: ctx.sessionId ?? void 0,
36
+ visitorId: ctx.visitorId ?? void 0,
37
+ // Buyer email collected by the funnel (user.email) — Stripe Customer creation,
38
+ // receipts, Paddle prefill. Injected at attempt time by the FunnelProvider seam.
39
+ email: req.email,
40
+ correlationId
41
+ };
42
+ return postJson(endpoint(ctx), body);
43
+ }
44
+ function postComplete(ctx, correlationId, providerRef) {
45
+ const body = { providerRef };
46
+ return postJson(
47
+ endpoint(ctx, `/${encodeURIComponent(correlationId)}/complete`),
48
+ body
49
+ );
50
+ }
51
+ function settlementToResult(s) {
52
+ return { ok: true, amountMinor: s.amountMinor, currency: s.currency, eventId: s.eventId };
53
+ }
54
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
55
+ async function completeWithPoll(ctx, correlationId, opts = {}) {
56
+ const attempts = opts.attempts ?? 5;
57
+ const intervalMs = opts.intervalMs ?? 2e3;
58
+ try {
59
+ for (let i = 0; i < attempts; i++) {
60
+ const res = await postComplete(ctx, correlationId, opts.providerRef);
61
+ if (res.step === "settled") return settlementToResult(res.result);
62
+ if (res.step === "failed") return { ok: false, error: res.error };
63
+ if (i < attempts - 1) await sleep(intervalMs);
64
+ }
65
+ } catch (e) {
66
+ return { ok: false, error: toCheckoutError(e) };
67
+ }
68
+ return {
69
+ ok: false,
70
+ error: chunkLJYLGLFS_cjs.checkoutError(
71
+ "processing_error",
72
+ opts.timeoutMessage ?? "The payment has not been confirmed yet \u2014 please check back shortly.",
73
+ // `completion_timeout` marks "the poll ran out while the attempt was still
74
+ // pending" — drivers key double-charge guards on it (the attempt may still
75
+ // settle server-side; it was never refused).
76
+ { retryable: true, declineCode: "completion_timeout" }
77
+ )
78
+ };
79
+ }
80
+ function leaveForRedirect(url) {
81
+ return new Promise((resolve) => {
82
+ if (typeof window !== "undefined") {
83
+ const onPageshow = (event) => {
84
+ if (!event.persisted) return;
85
+ window.removeEventListener("pageshow", onPageshow);
86
+ resolve({
87
+ ok: false,
88
+ error: chunkLJYLGLFS_cjs.checkoutError("canceled", "Returned from the hosted checkout without completing")
89
+ });
90
+ };
91
+ window.addEventListener("pageshow", onPageshow);
92
+ }
93
+ window.location.assign(url);
94
+ });
95
+ }
96
+
97
+ exports.completeWithPoll = completeWithPoll;
98
+ exports.leaveForRedirect = leaveForRedirect;
99
+ exports.postComplete = postComplete;
100
+ exports.postSession = postSession;
101
+ exports.settlementToResult = settlementToResult;
102
+ exports.toCheckoutError = toCheckoutError;
103
+ //# sourceMappingURL=chunk-VQOD2Z6Q.cjs.map
104
+ //# sourceMappingURL=chunk-VQOD2Z6Q.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/drivers/wire.ts"],"names":["checkoutError"],"mappings":";;;;;AAqBA,SAAS,QAAA,CAAS,GAAA,EAA4B,IAAA,GAAO,EAAA,EAAY;AAC/D,EAAA,MAAM,IAAA,GAAO,GAAA,CAAI,OAAA,CAAQ,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAC3C,EAAA,OAAO,CAAA,EAAG,IAAI,CAAA,UAAA,EAAa,kBAAA,CAAmB,IAAI,UAAU,CAAC,eAAe,IAAI,CAAA,CAAA;AAClF;AAEA,eAAe,QAAA,CAAY,KAAa,IAAA,EAA2B;AACjE,EAAA,MAAM,GAAA,GAAM,MAAM,KAAA,CAAM,GAAA,EAAK;AAAA,IAC3B,MAAA,EAAQ,MAAA;AAAA,IACR,OAAA,EAAS,EAAE,cAAA,EAAgB,kBAAA,EAAmB;AAAA,IAC9C,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,IAAI;AAAA,GAC1B,CAAA;AAGD,EAAA,IAAI,CAAC,IAAI,EAAA,EAAI,MAAMA,gCAAc,kBAAA,EAAoB,CAAA,8BAAA,EAAiC,GAAA,CAAI,MAAM,CAAA,CAAA,CAAG,CAAA;AACnG,EAAA,OAAQ,MAAM,IAAI,IAAA,EAAK;AACzB;AAGO,SAAS,gB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D,GACF;AACF;AAkBO,SAAS,iBAAiB,GAAA,EAAsC;AACrE,EAAA,OAAO,IAAI,OAAA,CAAwB,CAAC,OAAA,KAAY;AAC9C,IAAA,IAAI,OAAO,WAAW,WAAA,EAAa;AACjC,MAAA,MAAM,UAAA,GAAa,CAAC,KAAA,KAA+B;AACjD,QAAA,IAAI,CAAC,MAAM,SAAA,EAAW;AACtB,QAAA,MAAA,CAAO,mBAAA,CAAoB,YAAY,UAAU,CAAA;AACjD,QAAA,OAAA,CAAQ;AAAA,UACN,EAAA,EAAI,KAAA;AAAA,UACJ,KAAA,EAAOA,+BAAA,CAAc,UAAA,EAAY,sDAAsD;AAAA,SACxF,CAAA;AAAA,MACH,CAAA;AACA,MAAA,MAAA,CAAO,gBAAA,CAAiB,YAAY,UAAU,CAAA;AAAA,IAChD;AACA,IAAA,MAAA,CAAO,QAAA,CAAS,OAAO,GAAG,CAAA;AAAA,EAC5B,CAAC,CAAA;AACH","file":"chunk-VQOD2Z6Q.cjs","sourcesContent":["/**\n * Shared wire plumbing for the checkout drivers — the CLIENT half of the v2\n * checkout contract (commerce/checkout-api.ts). Lives under drivers/ (not\n * commerce/) on purpose: it ships only inside the `driver-*` subpath entries,\n * so the core funnel entry never bundles a checkout fetch — the core SDK talks\n * to a {@link CheckoutDriver}, never to the wire.\n *\n * Only `import type` from commerce/checkout(.tsx) here — a runtime import would\n * drag the React checkout primitives into every driver chunk. The one runtime\n * dependency is the pure error taxonomy (capabilities.ts).\n */\nimport type {\n CheckoutCompleteRequest,\n CheckoutCompleteResponse,\n CheckoutSessionRequest,\n CheckoutSessionResponse,\n CheckoutSettlement,\n} from '../commerce/checkout-api'\nimport type { CheckoutDriverContext, CheckoutRequest, CheckoutResult } from '../commerce/checkout'\nimport { checkoutError, type CheckoutError } from '../commerce/capabilities'\n\nfunction endpoint(ctx: CheckoutDriverContext, path = ''): string {\n const base = ctx.apiBase.replace(/\\/+$/, '')\n return `${base}/campaign/${encodeURIComponent(ctx.campaignId)}/v2/checkout${path}`\n}\n\nasync function postJson<T>(url: string, body: unknown): Promise<T> {\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n // The contract speaks in `step` responses, not HTTP errors — a non-2xx means the\n // request never reached the checkout service properly (proxy, deploy, outage).\n if (!res.ok) throw checkoutError('processing_error', `checkout request failed (HTTP ${res.status})`)\n return (await res.json()) as T\n}\n\n/** Normalize any thrown value into the taxonomy (network drops → `processing_error`). */\nexport function toCheckoutError(e: unknown): CheckoutError {\n if (e && typeof e === 'object' && 'category' in e && 'message' in e && 'retryable' in e) {\n return e as CheckoutError\n }\n return checkoutError('processing_error', e instanceof Error ? e.message : 'Checkout request failed')\n}\n\n/**\n * Open a checkout attempt: `POST {apiBase}/campaign/{campaignId}/v2/checkout`.\n * The correlationId is client-minted per ATTEMPT (idempotency key + the id the\n * server stamps into provider metadata) — mint it once, reuse it on retries.\n */\nexport function postSession(\n ctx: CheckoutDriverContext,\n req: CheckoutRequest,\n correlationId: string,\n): Promise<CheckoutSessionResponse> {\n const body: CheckoutSessionRequest = {\n funnelId: ctx.funnelId,\n mode: ctx.mode,\n productKey: req.product,\n intent: req.intent,\n kind: req.kind,\n // null (not absent) = explicit off-session — the server validates surfaces\n // against the capability matrix, so never let one default in transit.\n surface: req.surface ?? null,\n sessionId: ctx.sessionId ?? undefined,\n visitorId: ctx.visitorId ?? undefined,\n // Buyer email collected by the funnel (user.email) — Stripe Customer creation,\n // receipts, Paddle prefill. Injected at attempt time by the FunnelProvider seam.\n email: req.email,\n correlationId,\n }\n return postJson<CheckoutSessionResponse>(endpoint(ctx), body)\n}\n\n/** Ask the server to VERIFY with the provider and write the money facts (idempotent). */\nexport function postComplete(\n ctx: CheckoutDriverContext,\n correlationId: string,\n providerRef?: string,\n): Promise<CheckoutCompleteResponse> {\n const body: CheckoutCompleteRequest = { providerRef }\n return postJson<CheckoutCompleteResponse>(\n endpoint(ctx, `/${encodeURIComponent(correlationId)}/complete`),\n body,\n )\n}\n\n/** Server settlement → the SDK's CheckoutResult (eventId passes through for pixel dedup). */\nexport function settlementToResult(s: CheckoutSettlement): CheckoutResult {\n return { ok: true, amountMinor: s.amountMinor, currency: s.currency, eventId: s.eventId }\n}\n\nexport interface CompletePollOptions {\n providerRef?: string\n /** Total complete attempts before giving up (default 5). */\n attempts?: number\n /** Delay between attempts (default 2000ms). */\n intervalMs?: number\n /** Error message when the provider hasn't confirmed inside the window (MoR/async). */\n timeoutMessage?: string\n}\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\n\n/**\n * Complete with a bounded poll. Sync providers (Stripe) settle on the first\n * attempt — the server verifies against the provider inline. MoR/async providers\n * (Paddle) settle via webhook, so `pending` is normal: re-poll a few times, then\n * stop holding the UI hostage — the charge may still land server-side, which is\n * why the timeout error is `retryable` and the message should say the receipt\n * can still arrive (the server's money facts don't depend on this browser).\n */\nexport async function completeWithPoll(\n ctx: CheckoutDriverContext,\n correlationId: string,\n opts: CompletePollOptions = {},\n): Promise<CheckoutResult> {\n const attempts = opts.attempts ?? 5\n const intervalMs = opts.intervalMs ?? 2000\n try {\n for (let i = 0; i < attempts; i++) {\n const res = await postComplete(ctx, correlationId, opts.providerRef)\n if (res.step === 'settled') return settlementToResult(res.result)\n if (res.step === 'failed') return { ok: false, error: res.error }\n if (i < attempts - 1) await sleep(intervalMs)\n }\n } catch (e) {\n return { ok: false, error: toCheckoutError(e) }\n }\n return {\n ok: false,\n error: checkoutError(\n 'processing_error',\n opts.timeoutMessage ?? 'The payment has not been confirmed yet — please check back shortly.',\n // `completion_timeout` marks \"the poll ran out while the attempt was still\n // pending\" — drivers key double-charge guards on it (the attempt may still\n // settle server-side; it was never refused).\n { retryable: true, declineCode: 'completion_timeout' },\n ),\n }\n}\n\n/**\n * The `redirect` step hand-off: navigate to the provider-hosted page and return a\n * promise that settles ONLY if the buyer comes back to this very page. The page\n * is leaving — resolving early would fire `purchase.complete`/navigation for a\n * charge that hasn't happened, and rejecting would flash an error during the\n * (successful) hand-off — so while the navigation proceeds the promise stays\n * pending and `useCheckout` stays in `loading`, the truthful UI for a page\n * mid-navigation. The hosted page's SUCCESS return URL re-enters the funnel with\n * `af_checkout={correlationId}` (a fresh load — this promise is gone; the SDK's\n * resume leg settles the attempt).\n *\n * The one way THIS page comes back to life is a bfcache restore (browser Back\n * from the hosted page): `pageshow` with `persisted: true`. That is a buyer who\n * abandoned the hosted checkout — resolve `canceled` so the trigger re-enables\n * and inline redirect placeholders recover instead of spinning forever.\n */\nexport function leaveForRedirect(url: string): Promise<CheckoutResult> {\n return new Promise<CheckoutResult>((resolve) => {\n if (typeof window !== 'undefined') {\n const onPageshow = (event: PageTransitionEvent) => {\n if (!event.persisted) return\n window.removeEventListener('pageshow', onPageshow)\n resolve({\n ok: false,\n error: checkoutError('canceled', 'Returned from the hosted checkout without completing'),\n })\n }\n window.addEventListener('pageshow', onPageshow)\n }\n window.location.assign(url)\n })\n}\n"]}
@@ -0,0 +1,140 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ // If the importer is in node compatibility mode or this is not an ESM
24
+ // file that has been converted to a CommonJS file using a Babel-
25
+ // compatible transform (i.e. "__esModule" has not been set), then set
26
+ // "default" to the CommonJS "module.exports" for node compatibility.
27
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
+ mod
29
+ ));
30
+
31
+ // src/commerce/capabilities.ts
32
+ var INLINE_SURFACES = /* @__PURE__ */ new Set([
33
+ "express",
34
+ "element",
35
+ "embedded"
36
+ ]);
37
+ function isInlineSurface(surface) {
38
+ return INLINE_SURFACES.has(surface);
39
+ }
40
+ var ON = { purchase: true, wallets: true, offSession: "reliable" };
41
+ var MANAGED = { purchase: true, wallets: true, offSession: "conditional" };
42
+ var ROUTED = { purchase: true, wallets: true, offSession: "conditional" };
43
+ var ALL_UPSELLS = ["subscription", "one-time", "upgrade"];
44
+ var PROVIDER_PROFILES = {
45
+ // PSP; you hold the PaymentMethod and fire your own off-session PaymentIntent on
46
+ // the Elements surfaces (reliable). **Managed** Checkout (`embedded`/`redirect`)
47
+ // upsells too, but as a direct charge against Stripe's vaulted card → conditional.
48
+ // No provider "popup" surface.
49
+ stripe: {
50
+ isMoR: false,
51
+ offSessionUpsells: ALL_UPSELLS,
52
+ tokenModel: "merchant",
53
+ orchestrator: false,
54
+ status: "full",
55
+ surfaces: { express: ON, element: ON, sheet: ON, embedded: MANAGED, redirect: MANAGED }
56
+ },
57
+ // Merchant-of-Record; card entry is always Paddle's frame → no own element/sheet/
58
+ // express. Off-session via subscription one-time charge / collection_mode, but
59
+ // **no 2nd concurrent subscription** (upgrade + one-time only), provider-initiated.
60
+ paddle: {
61
+ isMoR: true,
62
+ offSessionUpsells: ["one-time", "upgrade"],
63
+ tokenModel: "provider",
64
+ orchestrator: false,
65
+ status: "full",
66
+ surfaces: { embedded: ON, popup: ON, redirect: ON }
67
+ },
68
+ // Merchant-of-Record; iframe-only (no raw card field). Off-session works
69
+ // (provider-initiated, async via webhooks). `sheet` = our chrome hosting their embed.
70
+ whop: {
71
+ isMoR: true,
72
+ offSessionUpsells: ALL_UPSELLS,
73
+ tokenModel: "provider",
74
+ orchestrator: false,
75
+ status: "planned",
76
+ surfaces: { embedded: ON, redirect: ON, sheet: ON }
77
+ },
78
+ // Pure orchestrator (PSP-side); Headless renders express/element/sheet/embedded.
79
+ // No hosted redirect page, no popup checkout. Off-session is PSP-conditional —
80
+ // the vault lives with whichever processor Primer routed to (data matches this
81
+ // comment as of 2026-07-02; it previously said conditional but coded reliable).
82
+ primer: {
83
+ isMoR: false,
84
+ offSessionUpsells: ALL_UPSELLS,
85
+ tokenModel: "merchant",
86
+ orchestrator: true,
87
+ status: "planned",
88
+ surfaces: { express: ROUTED, element: ROUTED, sheet: ROUTED, embedded: ROUTED }
89
+ },
90
+ // PSP **and** orchestrator (own acquiring + connectors routing across Stripe/Adyen/
91
+ // PayPal). One Payment Form (element/sheet/embedded) + hosted page + wallet button.
92
+ // Strong native off-session (Recurring API). No popup.
93
+ solidgate: {
94
+ isMoR: false,
95
+ offSessionUpsells: ALL_UPSELLS,
96
+ tokenModel: "merchant",
97
+ orchestrator: true,
98
+ status: "planned",
99
+ surfaces: { express: ON, element: ON, sheet: ON, embedded: ON, redirect: ON }
100
+ }
101
+ };
102
+ function surfacesFor(provider) {
103
+ return Object.keys(PROVIDER_PROFILES[provider]?.surfaces ?? {});
104
+ }
105
+ function isMerchantOfRecord(provider) {
106
+ return PROVIDER_PROFILES[provider]?.isMoR ?? false;
107
+ }
108
+ function isOrchestrator(provider) {
109
+ return PROVIDER_PROFILES[provider]?.orchestrator ?? false;
110
+ }
111
+ function validateCheckout(provider, surface) {
112
+ const cap = PROVIDER_PROFILES[provider]?.surfaces[surface];
113
+ if (!cap) return { ok: false, reason: `${provider} has no '${surface}' surface` };
114
+ return cap.purchase ? { ok: true } : { ok: false, reason: `'${surface}' can't take a purchase on ${provider}` };
115
+ }
116
+ function validateUpsell(provider, paywallSurface, kind = "subscription") {
117
+ const profile = PROVIDER_PROFILES[provider];
118
+ if (!profile) return { ok: false, reason: `unknown provider '${provider}'` };
119
+ if (!profile.offSessionUpsells.includes(kind)) {
120
+ const can = profile.offSessionUpsells.length ? ` (it supports: ${profile.offSessionUpsells.join(", ")})` : "";
121
+ return { ok: false, reason: `${provider} can't charge a '${kind}' upsell off-session${can}` };
122
+ }
123
+ const cap = profile.surfaces[paywallSurface];
124
+ if (!cap) return { ok: false, reason: `${provider} has no '${paywallSurface}' surface to upsell after` };
125
+ if (cap.offSession === "none") {
126
+ return { ok: false, reason: `a purchase on '${paywallSurface}' retains no chargeable method for an upsell` };
127
+ }
128
+ if (cap.offSession === "conditional") {
129
+ return { ok: true, note: `off-session upsell after ${provider} '${paywallSurface}' may decline \u2014 prefer a reliable surface or wire an on-session fallback` };
130
+ }
131
+ return { ok: true };
132
+ }
133
+ function checkoutError(category, message, extra = {}) {
134
+ const retryable = extra.retryable ?? (category === "authentication_required" || category === "requires_payment_method" || category === "processing_error");
135
+ return { category, message, declineCode: extra.declineCode, retryable };
136
+ }
137
+
138
+ export { INLINE_SURFACES, PROVIDER_PROFILES, __commonJS, __export, __toESM, checkoutError, isInlineSurface, isMerchantOfRecord, isOrchestrator, surfacesFor, validateCheckout, validateUpsell };
139
+ //# sourceMappingURL=chunk-YY375F2B.js.map
140
+ //# sourceMappingURL=chunk-YY375F2B.js.map
@@ -0,0 +1 @@
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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MAAA,EAAQ;AAC7B,IAAA,OAAO,EAAE,EAAA,EAAI,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-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"]}