@mrrocket/sdk 0.4.0 → 0.8.0

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/CHANGELOG.md +30 -0
  2. package/README.md +102 -7
  3. package/dist/api.d.ts +23 -3
  4. package/dist/api.js +7 -3
  5. package/dist/api.js.map +1 -1
  6. package/dist/browser/mrrocket-flows.js +64 -0
  7. package/dist/browser/mrrocket-push.js +1 -0
  8. package/dist/browser/mrrocket-replay.js +3 -3
  9. package/dist/browser/mrrocket-sw.js +1 -0
  10. package/dist/browser/mrrocket.js +2 -1
  11. package/dist/browser.d.ts +1 -1
  12. package/dist/browser.js +3 -1
  13. package/dist/browser.js.map +1 -1
  14. package/dist/client.d.ts +36 -1
  15. package/dist/client.js +161 -6
  16. package/dist/client.js.map +1 -1
  17. package/dist/context.d.ts +10 -0
  18. package/dist/context.js.map +1 -1
  19. package/dist/core.d.ts +64 -3
  20. package/dist/core.js +54 -2
  21. package/dist/core.js.map +1 -1
  22. package/dist/feedback.d.ts +19 -4
  23. package/dist/feedback.js +652 -190
  24. package/dist/feedback.js.map +1 -1
  25. package/dist/flows-ui.d.ts +23 -0
  26. package/dist/flows-ui.js +384 -0
  27. package/dist/flows-ui.js.map +1 -0
  28. package/dist/flows-web.d.ts +19 -0
  29. package/dist/flows-web.js +42 -0
  30. package/dist/flows-web.js.map +1 -0
  31. package/dist/flows.d.ts +222 -0
  32. package/dist/flows.js +409 -0
  33. package/dist/flows.js.map +1 -0
  34. package/dist/index.d.ts +5 -2
  35. package/dist/index.js +9 -1
  36. package/dist/index.js.map +1 -1
  37. package/dist/proxy.d.ts +34 -1
  38. package/dist/proxy.js +14 -1
  39. package/dist/proxy.js.map +1 -1
  40. package/dist/push-web.d.ts +43 -0
  41. package/dist/push-web.js +81 -0
  42. package/dist/push-web.js.map +1 -0
  43. package/dist/react-native/index.d.cts +305 -3
  44. package/dist/react-native/index.d.ts +305 -3
  45. package/dist/react-native/index.js +852 -31
  46. package/dist/react-native/index.js.map +1 -1
  47. package/dist/styles.d.ts +1 -1
  48. package/dist/styles.js +127 -24
  49. package/dist/styles.js.map +1 -1
  50. package/dist/ui.d.ts +3 -0
  51. package/dist/ui.js +12 -0
  52. package/dist/ui.js.map +1 -1
  53. package/package.json +10 -2
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/flows.ts"],"sourcesContent":["/**\n * The cancel flow, onboarding and in-app messages (SDK 0.7.0): what MRRocket's config and `GET /api/sdk/inapp` serve,\n * and one controller that decides what shows when and records what the person did. No DOM and no React: the web\n * renderer (flows-ui.ts, loaded only when something shows) and the React Native one (native/flows-view.ts) draw\n * `view()` and call the actions.\n *\n * What it records, as normal events under the SDK's analytics consent (nothing with consent \"off\"):\n * - `$cancel_flow` `{action: \"shown\" | \"answered\" | \"offer\" | \"finished\", run, version, …}`. MRRocket turns a\n * `finished` with `outcome: \"saved\"` into a save and with `outcome: \"cancelled\"` into a cancellation on the Churn page.\n * MRRocket never changes a subscription: an accepted offer goes to the app's `onSave`, a confirmed cancel to its\n * `onCancel`, and only after they succeed is the outcome recorded.\n * - `$onboarding` `{flow, step?, action: \"started\" | \"shown\" | \"completed\" | \"dismissed\"}`.\n * - `$inapp` `{message, journey, action: \"shown\" | \"clicked\" | \"dismissed\"}`; the journey moves the person on.\n */\nimport type { CockpitConfig } from \"./core\";\n\nexport const CANCEL_EVENT = \"$cancel_flow\";\nexport const ONBOARDING_EVENT = \"$onboarding\";\nexport const INAPP_EVENT = \"$inapp\";\n\nexport type CancelOfferKind = \"discount\" | \"pause\" | \"downgrade\" | \"contact\";\n\n/** What one answer of the survey offers before the confirmation. An answer without one goes straight to it. */\nexport interface CancelOffer {\n kind: CancelOfferKind;\n headline: string;\n /** Discount: percent off. */\n percent?: number;\n /** Discount: for how many months; pause: up to how many months. */\n months?: number;\n /** Downgrade: the plan to switch to, as MRRocket knows it from the payment provider. */\n plan?: string;\n planName?: string;\n}\n\n/** The product's live cancel flow (MRRocket › Churn › Cancel flow). */\nexport interface CancelFlowConfig {\n /** Grows with every publish. */\n version: number;\n question: string;\n /** The survey's answers, in order. */\n reasons: { id: string; label: string }[];\n /** The offer per answer id. */\n offers: Record<string, CancelOffer>;\n confirm: { title: string; body: string; button: string };\n /**\n * Who gets the survey and the offers: business customers only. Anyone else (a consumer, or a customer the app does\n * not say) gets the plain confirmation, with nothing in the way of cancelling (§ 312k BGB).\n */\n offersFor: \"business\";\n}\n\nexport type OnboardingStepKind = \"tour\" | \"checklist\" | \"modal\";\n\nexport interface OnboardingStep {\n id: string;\n kind: OnboardingStepKind;\n title: string;\n body?: string;\n button?: string;\n /** Tour steps: the element they point at, marked `data-ck-target=\"<target>\"` in the app. Without it: a card. */\n target?: string;\n /** Checklist items: the event that ticks them (`track(\"<event>\")`). Without it the person ticks it themselves. */\n event?: string;\n}\n\n/** A live onboarding flow's in-app steps (MRRocket › Conversion › Onboarding); its emails go out from MRRocket. */\nexport interface OnboardingFlow {\n id: string;\n name: string;\n /** When it starts: an event's words (\"Signed up\", \"First export\"), or \"First launch\" / \"First visit\". */\n trigger: string;\n steps: OnboardingStep[];\n}\n\n/** An in-app message a Lifecycle journey has for this person. */\nexport interface InAppMessage {\n id: string;\n journey?: string;\n title: string;\n body?: string;\n button?: string;\n /** Where the button goes (http(s) or a path of the app). */\n url?: string;\n style: \"banner\" | \"modal\";\n}\n\n/** What `GET /api/sdk/inapp` answers for one signed-in person. */\nexport interface InAppState {\n /** Progress per onboarding flow: the steps done and whether the person closed it. */\n onboarding: Record<string, { done: string[]; dismissed?: boolean }>;\n messages: InAppMessage[];\n}\n\nexport interface CancelFlowResult {\n /** \"cancelled\": confirmed; \"saved\": took the offer; \"kept\": closed the dialog without cancelling. */\n outcome: \"cancelled\" | \"saved\" | \"kept\";\n reason?: string;\n reasonLabel?: string;\n offer?: CancelOffer;\n /** What the customer wrote on the confirmation, if anything. */\n comment?: string;\n /** This run's id, the same as in the events. */\n run: string;\n}\n\nexport interface CancelFlowOptions {\n /**\n * \"business\" shows the survey and the offers; anything else (the default) only the plain confirmation, so a\n * consumer can always cancel in one step (§ 312k BGB).\n */\n customer?: \"business\" | \"consumer\";\n /** The customer's current price, to show what a discount costs (`{ amount: 29, currency: \"EUR\" }`). */\n price?: { amount: number; currency: string; interval?: \"month\" | \"year\" };\n /** The customer confirmed: cancel the subscription in your code. Throwing keeps the dialog open with an error. */\n onCancel?: (result: CancelFlowResult) => unknown;\n /** The customer took an offer: apply it in your code (coupon, pause, plan change). Throwing keeps the dialog open. */\n onSave?: (result: CancelFlowResult) => unknown;\n /** Closed without cancelling or taking an offer. */\n onClose?: (result: CancelFlowResult) => void;\n}\n\n/** What a renderer draws. */\nexport type FlowView =\n | {\n type: \"cancel\";\n screen: \"survey\" | \"offer\" | \"confirm\";\n flow: CancelFlowConfig;\n /** The answer picked on the survey. */\n reason?: string;\n offer?: CancelOffer;\n price?: CancelFlowOptions[\"price\"];\n busy: boolean;\n error?: string;\n /** The step for the dots, 1 to `steps`. */\n step: number;\n steps: number;\n }\n | { type: \"step\"; flow: OnboardingFlow; step: OnboardingStep; index: number; total: number; last: boolean }\n | { type: \"checklist\"; flow: OnboardingFlow; items: { step: OnboardingStep; done: boolean }[] }\n | { type: \"message\"; message: InAppMessage };\n\nexport interface FlowsEnv {\n /** Records an event under the SDK's consent (the normal queue). */\n track(event: string, props?: Record<string, unknown>): void;\n /** Whose messages and progress these are: the identify() id; undefined while nobody is signed in. */\n personId(): string | undefined;\n /** `GET /api/sdk/inapp` for that person; null when it fails. */\n fetchInApp(personId: string): Promise<InAppState | null>;\n /** Keeps onboarding progress on the device; only while the consent lets the SDK store something. */\n storage?: () => { get(key: string): string | null | Promise<string | null>; set(key: string, value: string): void } | null;\n /** Opens a message's link. */\n openUrl?: (url: string) => void;\n /** Start onboarding flows by their trigger on its own (default true). */\n auto?: boolean;\n}\n\nexport interface FlowsController {\n setConfig(config: CockpitConfig | null): void;\n /** The person changed (identify, reset, consent): loads their messages and onboarding progress. */\n refresh(): Promise<void>;\n /** An event the app recorded: starts flows whose trigger it is and ticks checklist items. */\n onEvent(name: string): void;\n openCancelFlow(options?: CancelFlowOptions): Promise<CancelFlowResult>;\n /** Starts an onboarding flow now (the first live one without an id). False when there is none to start. */\n startOnboarding(id?: string): boolean;\n view(): FlowView | null;\n subscribe(listener: () => void): () => void;\n /** `accept(comment)`: a \"Talk to us\" offer sends what the customer wrote with it. */\n cancel: { pick(reason: string): void; next(): void; accept(comment?: string): void; decline(): void; confirm(comment?: string): void; close(): void };\n onboarding: { next(): void; check(stepId: string): void; dismiss(): void };\n message: { click(): void; dismiss(): void };\n}\n\n/** The plain confirmation, when the product has no live cancel flow (or MRRocket was not reachable). */\nexport const PLAIN_CANCEL: CancelFlowConfig = {\n version: 0,\n question: \"\",\n reasons: [],\n offers: {},\n confirm: { title: \"Cancel your subscription?\", body: \"You keep access until the end of the billing period.\", button: \"Cancel subscription\" },\n offersFor: \"business\",\n};\n\nconst FAILED = \"Something went wrong. Please try again.\";\nconst PROGRESS_KEY = \"mrrocket:onboarding\";\n\n/** `\"Signed up\"` → `signed_up`, the way MRRocket names events from words. */\nexport const eventSlug = (s: string) =>\n s\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\nconst SIGNUP = new Set([\"signed_up\", \"signup\", \"sign_up\", \"registered\", \"account_created\", \"user_signed_up\"]);\n\n/** Whether recording `event` is the trigger's moment (\"Signed up\" is any of the usual signup event names). */\nexport const matchesTrigger = (trigger: string, event: string) => {\n const t = eventSlug(trigger);\n const e = eventSlug(event);\n if (!t || !e) return false;\n return t === e || (SIGNUP.has(t) && SIGNUP.has(e));\n};\n\n/** Triggers that mean \"the first time the person opens the app\": the flow starts on load until it is done. */\nexport const startsOnLoad = (trigger: string) =>\n /^(first (launch|visit|open|session|login|sign ?in|app open)|app (opened|launched)|on load|every visit|always)?$/i.test(trigger.trim());\n\n/** A random id for one cancel flow run. */\nexport const runId = () => `cf_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;\n\n/** The money a discount leaves: `29 EUR` at 30 % → `20.30`. */\nexport const discounted = (amount: number, percent: number) => Math.round(amount * (1 - percent / 100) * 100) / 100;\n\n/** \"€20.30\" in the customer's own currency, without a library. */\nexport const money = (amount: number, currency: string) => {\n try {\n return new Intl.NumberFormat(undefined, { style: \"currency\", currency }).format(amount);\n } catch {\n return `${amount.toFixed(2)} ${currency}`;\n }\n};\n\n/** The button of an offer. */\nexport const offerButton = (o: CancelOffer) =>\n o.kind === \"contact\" ? \"Send to the team\" : o.kind === \"pause\" ? \"Pause instead\" : o.kind === \"downgrade\" ? \"Switch plan\" : \"Accept offer\";\n\n/** A link a message may open: http(s), or a path of the app. Nothing else (no `javascript:`). */\nexport const safeUrl = (url: string | undefined) => {\n const u = (url ?? \"\").trim();\n return /^https?:\\/\\//i.test(u) || /^\\/(?!\\/)/.test(u) ? u : undefined;\n};\n\ninterface Progress {\n done: Set<string>;\n dismissed: boolean;\n}\n\ninterface CancelRun {\n flow: CancelFlowConfig;\n options: CancelFlowOptions;\n plain: boolean;\n screen: \"survey\" | \"offer\" | \"confirm\";\n reason?: string;\n run: string;\n busy: boolean;\n error?: string;\n resolve: (r: CancelFlowResult) => void;\n promise: Promise<CancelFlowResult>;\n}\n\nexport const createFlows = (env: FlowsEnv): FlowsController => {\n let config: CockpitConfig | null = null;\n let cancel: CancelRun | null = null;\n let active: string | null = null;\n let messages: InAppMessage[] = [];\n let known = false;\n let loading: Promise<void> | null = null;\n let loadedFor: string | undefined;\n let progressFor: string | undefined | null = null;\n const progress = new Map<string, Progress>();\n const handled = new Set<string>();\n const shown = new Set<string>();\n const listeners = new Set<() => void>();\n const auto = env.auto !== false;\n\n const flows = () => config?.onboarding ?? [];\n const flowById = (id: string | null) => (id ? flows().find((f) => f.id === id) : undefined);\n const prog = (id: string) => {\n let p = progress.get(id);\n if (!p) progress.set(id, (p = { done: new Set(), dismissed: false }));\n return p;\n };\n const finished = (f: OnboardingFlow) => {\n const p = progress.get(f.id);\n return !!p && (p.dismissed || f.steps.every((s) => p.done.has(s.id)));\n };\n\n const keyOf = (pid: string | undefined) => `${PROGRESS_KEY}:${pid ?? \"visitor\"}`;\n\n const save = () => {\n const store = env.storage?.();\n if (!store) return;\n const out: Record<string, { done: string[]; dismissed?: boolean }> = {};\n for (const [id, p] of progress) out[id] = { done: [...p.done], ...(p.dismissed ? { dismissed: true } : {}) };\n try {\n store.set(keyOf(env.personId()), JSON.stringify(out));\n } catch {\n // Storage full or gone: progress stays in memory.\n }\n };\n\n const merge = (state: InAppState[\"onboarding\"] | undefined) => {\n for (const [id, s] of Object.entries(state ?? {})) {\n const p = prog(id);\n for (const d of s.done ?? []) p.done.add(d);\n if (s.dismissed) p.dismissed = true;\n }\n };\n\n // ---------- What shows ----------\n\n const onboardingView = (): FlowView | null => {\n const flow = flowById(active);\n if (!flow) return null;\n const p = prog(flow.id);\n const at = flow.steps.findIndex((s) => !p.done.has(s.id));\n if (at < 0 || p.dismissed) return null;\n const step = flow.steps[at];\n if (step.kind === \"checklist\") {\n let from = at;\n while (from > 0 && flow.steps[from - 1].kind === \"checklist\") from--;\n let to = at;\n while (to + 1 < flow.steps.length && flow.steps[to + 1].kind === \"checklist\") to++;\n return { type: \"checklist\", flow, items: flow.steps.slice(from, to + 1).map((s) => ({ step: s, done: p.done.has(s.id) })) };\n }\n return { type: \"step\", flow, step, index: at, total: flow.steps.length, last: at === flow.steps.length - 1 };\n };\n\n const view = (): FlowView | null => {\n if (cancel) {\n const offer = cancel.reason ? cancel.flow.offers[cancel.reason] : undefined;\n return {\n type: \"cancel\",\n screen: cancel.screen,\n flow: cancel.flow,\n reason: cancel.reason,\n offer: cancel.screen === \"offer\" ? offer : undefined,\n price: cancel.options.price,\n busy: cancel.busy,\n error: cancel.error,\n step: cancel.plain ? 1 : cancel.screen === \"survey\" ? 1 : cancel.screen === \"offer\" ? 2 : 3,\n steps: cancel.plain ? 1 : 3,\n };\n }\n const ob = onboardingView();\n if (ob) return ob;\n // A flow that just ended lets the next thing show.\n if (active) active = null;\n const m = messages.find((x) => !handled.has(x.id));\n return m ? { type: \"message\", message: m } : null;\n };\n\n /** Tells the renderers, and records what became visible (once per step or message per page load). */\n const emit = () => {\n const v = view();\n if (v?.type === \"step\" && !shown.has(`s:${v.step.id}`)) {\n shown.add(`s:${v.step.id}`);\n env.track(ONBOARDING_EVENT, { flow: v.flow.id, step: v.step.id, kind: v.step.kind, action: \"shown\" });\n } else if (v?.type === \"checklist\") {\n for (const i of v.items)\n if (!i.done && !shown.has(`s:${i.step.id}`)) {\n shown.add(`s:${i.step.id}`);\n env.track(ONBOARDING_EVENT, { flow: v.flow.id, step: i.step.id, kind: \"checklist\", action: \"shown\" });\n }\n } else if (v?.type === \"message\" && !shown.has(`m:${v.message.id}`)) {\n shown.add(`m:${v.message.id}`);\n env.track(INAPP_EVENT, { message: v.message.id, journey: v.message.journey, action: \"shown\" });\n }\n for (const l of [...listeners]) {\n try {\n l();\n } catch {\n // One renderer must not stop another.\n }\n }\n };\n\n const start = (flow: OnboardingFlow) => {\n if (active === flow.id) return true;\n if (active && flowById(active) && !finished(flowById(active)!)) return false;\n active = flow.id;\n env.track(ONBOARDING_EVENT, { flow: flow.id, action: \"started\" });\n emit();\n return true;\n };\n\n /** Flows whose trigger is \"the first launch\" start once their progress is known (never twice for a done flow). */\n const autoStart = () => {\n if (!auto || active || !known) return;\n // Without an id or storage a \"first launch\" could not be told from any other: no automatic start then.\n if (!env.personId() && !env.storage?.()) return;\n const next = flows().find((f) => startsOnLoad(f.trigger) && f.steps.length && !finished(f));\n if (next) start(next);\n };\n\n const refresh = () => {\n const pid = env.personId();\n // Another person on this device: nothing of the one before carries over.\n if (progressFor !== null && progressFor !== pid) {\n progress.clear();\n handled.clear();\n active = null;\n loadedFor = undefined;\n }\n progressFor = pid;\n const run = (async () => {\n const store = env.storage?.();\n if (store) {\n try {\n const raw = await store.get(keyOf(pid));\n if (raw) merge(JSON.parse(raw) as InAppState[\"onboarding\"]);\n } catch {\n // A damaged entry is ignored.\n }\n }\n const wants = flows().length > 0 || !!config?.messages;\n if (pid && wants && loadedFor !== pid) {\n loadedFor = pid;\n const state = await env.fetchInApp(pid).catch(() => null);\n if (state && env.personId() === pid) {\n merge(state.onboarding);\n messages = (state.messages ?? []).filter((m) => m && m.id && m.title);\n }\n }\n if (!pid) messages = [];\n known = true;\n autoStart();\n emit();\n })();\n loading = run.finally(() => {\n if (loading === run) loading = null;\n });\n return loading;\n };\n\n // ---------- Cancel flow ----------\n\n const result = (c: CancelRun, outcome: CancelFlowResult[\"outcome\"], comment?: string): CancelFlowResult => {\n const offer = c.reason ? c.flow.offers[c.reason] : undefined;\n return {\n outcome,\n run: c.run,\n ...(c.reason ? { reason: c.reason, reasonLabel: c.flow.reasons.find((r) => r.id === c.reason)?.label } : {}),\n ...(outcome === \"saved\" && offer ? { offer } : {}),\n ...(comment?.trim() ? { comment: comment.trim().slice(0, 500) } : {}),\n };\n };\n\n const finish = (c: CancelRun, r: CancelFlowResult) => {\n env.track(CANCEL_EVENT, {\n action: \"finished\",\n run: c.run,\n version: c.flow.version,\n outcome: r.outcome,\n customer: c.options.customer ?? \"consumer\",\n ...(r.reason ? { reason: r.reason } : {}),\n ...(r.offer ? { offer: r.offer.kind } : {}),\n ...(r.comment ? { comment: r.comment } : {}),\n });\n if (cancel === c) cancel = null;\n c.resolve(r);\n emit();\n };\n\n /** Runs the app's callback; the outcome is recorded only once it went through. */\n const settle = (c: CancelRun, outcome: \"saved\" | \"cancelled\", comment?: string) => {\n if (c.busy) return;\n const r = result(c, outcome, comment);\n const fn = outcome === \"saved\" ? c.options.onSave : c.options.onCancel;\n c.busy = true;\n c.error = undefined;\n emit();\n Promise.resolve()\n .then(() => fn?.(r))\n .then(\n () => finish(c, r),\n () => {\n c.busy = false;\n c.error = FAILED;\n emit();\n },\n );\n };\n\n const openCancelFlow = (options: CancelFlowOptions = {}) => {\n if (cancel) return cancel.promise;\n const flow = config?.cancelFlow ?? PLAIN_CANCEL;\n const plain = options.customer !== \"business\" || flow.reasons.length < 2;\n let resolve: (r: CancelFlowResult) => void = () => {};\n const promise = new Promise<CancelFlowResult>((r) => (resolve = r));\n const c: CancelRun = { flow, options, plain, screen: plain ? \"confirm\" : \"survey\", run: runId(), busy: false, resolve, promise };\n cancel = c;\n env.track(CANCEL_EVENT, { action: \"shown\", run: c.run, version: flow.version, customer: options.customer ?? \"consumer\", plain });\n emit();\n return promise;\n };\n\n const controller: FlowsController = {\n setConfig: (c) => {\n config = c;\n if (active && !flowById(active)) active = null;\n emit();\n },\n refresh,\n onEvent: (name) => {\n if (!name || name.startsWith(\"$\")) return;\n const flow = flowById(active);\n let ticked = false;\n if (flow) {\n const p = prog(flow.id);\n for (const s of flow.steps)\n if (s.kind === \"checklist\" && s.event && !p.done.has(s.id) && matchesTrigger(s.event, name)) {\n p.done.add(s.id);\n ticked = true;\n env.track(ONBOARDING_EVENT, { flow: flow.id, step: s.id, kind: s.kind, action: \"completed\" });\n }\n }\n if (ticked) {\n save();\n emit();\n }\n // Like the first-launch start: only for someone whose progress is kept, so nobody gets a flow twice.\n if (!auto || (!env.personId() && !env.storage?.())) return;\n const next = flows().find((f) => f.steps.length && matchesTrigger(f.trigger, name) && !finished(f));\n if (next) start(next);\n },\n openCancelFlow,\n startOnboarding: (id) => {\n const f = id ? flowById(id) : flows().find((x) => x.steps.length && !finished(x));\n if (!f || !f.steps.length) return false;\n const p = prog(f.id);\n // Started by hand: a flow the person closed before shows again.\n p.dismissed = false;\n return start(f);\n },\n view,\n subscribe: (l) => {\n listeners.add(l);\n return () => listeners.delete(l);\n },\n cancel: {\n pick: (reason) => {\n if (!cancel || cancel.busy || !cancel.flow.reasons.some((r) => r.id === reason)) return;\n cancel.reason = reason;\n cancel.error = undefined;\n emit();\n },\n next: () => {\n const c = cancel;\n if (!c || c.screen !== \"survey\" || !c.reason) return;\n env.track(CANCEL_EVENT, { action: \"answered\", run: c.run, version: c.flow.version, reason: c.reason });\n c.screen = c.flow.offers[c.reason] ? \"offer\" : \"confirm\";\n emit();\n },\n accept: (comment) => {\n const c = cancel;\n if (!c || c.screen !== \"offer\" || !c.reason) return;\n const offer = c.flow.offers[c.reason];\n if (!c.busy)\n env.track(CANCEL_EVENT, {\n action: \"offer\",\n run: c.run,\n version: c.flow.version,\n reason: c.reason,\n offer: offer?.kind,\n outcome: \"accepted\",\n });\n settle(c, \"saved\", comment);\n },\n decline: () => {\n const c = cancel;\n if (!c || c.screen !== \"offer\" || c.busy) return;\n env.track(CANCEL_EVENT, {\n action: \"offer\",\n run: c.run,\n version: c.flow.version,\n reason: c.reason,\n offer: c.reason ? c.flow.offers[c.reason]?.kind : undefined,\n outcome: \"declined\",\n });\n c.screen = \"confirm\";\n c.error = undefined;\n emit();\n },\n confirm: (comment) => {\n const c = cancel;\n if (!c || c.screen !== \"confirm\") return;\n settle(c, \"cancelled\", comment);\n },\n close: () => {\n const c = cancel;\n if (!c || c.busy) return;\n const r = result(c, \"kept\");\n c.options.onClose?.(r);\n finish(c, r);\n },\n },\n onboarding: {\n next: () => {\n const v = onboardingView();\n if (v?.type !== \"step\") return;\n prog(v.flow.id).done.add(v.step.id);\n env.track(ONBOARDING_EVENT, { flow: v.flow.id, step: v.step.id, kind: v.step.kind, action: \"completed\" });\n save();\n emit();\n },\n check: (stepId) => {\n const v = onboardingView();\n if (v?.type !== \"checklist\") return;\n const item = v.items.find((i) => i.step.id === stepId);\n if (!item || item.done) return;\n prog(v.flow.id).done.add(stepId);\n env.track(ONBOARDING_EVENT, { flow: v.flow.id, step: stepId, kind: \"checklist\", action: \"completed\" });\n save();\n emit();\n },\n dismiss: () => {\n const v = onboardingView();\n if (!v || (v.type !== \"step\" && v.type !== \"checklist\")) return;\n prog(v.flow.id).dismissed = true;\n env.track(ONBOARDING_EVENT, { flow: v.flow.id, ...(v.type === \"step\" ? { step: v.step.id } : {}), action: \"dismissed\" });\n active = null;\n save();\n emit();\n },\n },\n message: {\n click: () => {\n const v = view();\n if (v?.type !== \"message\") return;\n handled.add(v.message.id);\n env.track(INAPP_EVENT, { message: v.message.id, journey: v.message.journey, action: \"clicked\" });\n const url = safeUrl(v.message.url);\n emit();\n if (url) env.openUrl?.(url);\n },\n dismiss: () => {\n const v = view();\n if (v?.type !== \"message\") return;\n handled.add(v.message.id);\n env.track(INAPP_EVENT, { message: v.message.id, journey: v.message.journey, action: \"dismissed\" });\n emit();\n },\n },\n };\n return controller;\n};\n"],"mappings":";AAgBO,IAAM,eAAe;AACrB,IAAM,mBAAmB;AACzB,IAAM,cAAc;AA6JpB,IAAM,eAAiC;AAAA,EAC1C,SAAS;AAAA,EACT,UAAU;AAAA,EACV,SAAS,CAAC;AAAA,EACV,QAAQ,CAAC;AAAA,EACT,SAAS,EAAE,OAAO,6BAA6B,MAAM,wDAAwD,QAAQ,sBAAsB;AAAA,EAC3I,WAAW;AACf;AAEA,IAAM,SAAS;AACf,IAAM,eAAe;AAGd,IAAM,YAAY,CAAC,MACtB,EACK,KAAK,EACL,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,YAAY,EAAE;AAE/B,IAAM,SAAS,oBAAI,IAAI,CAAC,aAAa,UAAU,WAAW,cAAc,mBAAmB,gBAAgB,CAAC;AAGrG,IAAM,iBAAiB,CAAC,SAAiB,UAAkB;AAC9D,QAAM,IAAI,UAAU,OAAO;AAC3B,QAAM,IAAI,UAAU,KAAK;AACzB,MAAI,CAAC,KAAK,CAAC,EAAG,QAAO;AACrB,SAAO,MAAM,KAAM,OAAO,IAAI,CAAC,KAAK,OAAO,IAAI,CAAC;AACpD;AAGO,IAAM,eAAe,CAAC,YACzB,mHAAmH,KAAK,QAAQ,KAAK,CAAC;AAGnI,IAAM,QAAQ,MAAM,MAAM,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC;AAG3F,I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,EAAE,QAAQ,SAAS,QAAQ,UAAU,CAAC;AAC/F,cAAM,MAAM,QAAQ,EAAE,QAAQ,GAAG;AACjC,aAAK;AACL,YAAI,IAAK,KAAI,UAAU,GAAG;AAAA,MAC9B;AAAA,MACA,SAAS,MAAM;AACX,cAAM,IAAI,KAAK;AACf,YAAI,GAAG,SAAS,UAAW;AAC3B,gBAAQ,IAAI,EAAE,QAAQ,EAAE;AACxB,YAAI,MAAM,aAAa,EAAE,SAAS,EAAE,QAAQ,IAAI,SAAS,EAAE,QAAQ,SAAS,QAAQ,YAAY,CAAC;AACjG,aAAK;AAAA,MACT;AAAA,IACJ;AAAA,EACJ;AACA,SAAO;AACX;","names":[]}
package/dist/index.d.ts CHANGED
@@ -1,3 +1,6 @@
1
- export { type ChangelogEntry, type CockpitProviderProps, type CockpitUser, type FeedbackBoardInfo, type FeedbackBoardProps, type FeedbackComment, type FeedbackList, type FeedbackPost, type FeedbackRoadmap, type FeedbackWidgetProps, type PostStatus, type SurveyAnswer, type SurveyDefinition, type SurveyQuestion, type SurveyQuestionKind, CockpitProvider, Experiment, FeedbackBoard, FeedbackWidget, Survey, Text, WIDGET_CSS, createApi, useCockpit, useFeedback, useFlag, useFlagVariant, useStyles, useVariant, } from "./browser.js";
2
- export { type CockpitConfig, type CockpitEvent, type ConsentChoice, type ConsentMode, type ReplayConfig, type ErrorReport, type ExperimentConfig, type FlagCondition, type FlagConditionSet, type FlagConfig, type FlagPerson, type VariantConfig, type VariantId, EMBED_PARAM, SDK_VERSION, ID_COOKIE, PREVIEW_PARAM, SESSION_COOKIE, assign, evaluateFlag, parsePreview, previewHref, } from "./core.js";
1
+ export { type ChangelogEntry, type CockpitProviderProps, type CockpitUser, type FeedbackBoardInfo, type FeedbackBoardProps, type FeedbackComment, type FeedbackList, type FeedbackPost, type FeedbackRoadmap, type FeedbackWidgetProps, type PostStatus, type SurveyAnswer, type SurveyDefinition, type SurveyQuestion, type SurveyQuestionKind, CockpitProvider, Experiment, FeedbackBoard, FeedbackWidget, Survey, Text, WIDGET_CSS, createApi, useCancelFlow, useCockpit, useFeedback, useFlag, useFlagVariant, usePush, useStyles, useVariant, } from "./browser.js";
2
+ export type { PushResult, PushStatus, WebPushOptions } from "./push-web.js";
3
+ export { type CockpitConfig, type CockpitEvent, type ConsentChoice, type ConsentMode, type ReplayConfig, type ErrorReport, type ExperimentConfig, type FlagCondition, type FlagConditionSet, type FlagConfig, type FlagPerson, type RedirectConfig, type RedirectDecision, type VariantConfig, type VariantId, EMBED_PARAM, EXPOSURE_PARAM, SDK_VERSION, ID_COOKIE, PREVIEW_PARAM, SESSION_COOKIE, assign, evaluateFlag, parsePreview, previewHref, redirectFor, } from "./core.js";
4
+ export { type CancelFlowConfig, type CancelFlowOptions, type CancelFlowResult, type CancelOffer, type InAppMessage, type OnboardingFlow, type OnboardingStep, } from "./flows.js";
5
+ export type { FlowsTheme } from "./flows-ui.js";
3
6
  export { type AttributionMode, type CheckoutReferral, type Referral, REFERRAL_COOKIE, getReferral, readReferralCookie, referralForCheckout, referralLink, } from "./referral.js";
package/dist/index.js CHANGED
@@ -8,15 +8,18 @@ import {
8
8
  Text,
9
9
  WIDGET_CSS,
10
10
  createApi,
11
+ useCancelFlow,
11
12
  useCockpit,
12
13
  useFeedback,
13
14
  useFlag,
14
15
  useFlagVariant,
16
+ usePush,
15
17
  useStyles,
16
18
  useVariant
17
19
  } from "./browser.js";
18
20
  import {
19
21
  EMBED_PARAM,
22
+ EXPOSURE_PARAM,
20
23
  SDK_VERSION,
21
24
  ID_COOKIE,
22
25
  PREVIEW_PARAM,
@@ -24,7 +27,8 @@ import {
24
27
  assign,
25
28
  evaluateFlag,
26
29
  parsePreview,
27
- previewHref
30
+ previewHref,
31
+ redirectFor
28
32
  } from "./core.js";
29
33
  import {
30
34
  REFERRAL_COOKIE,
@@ -36,6 +40,7 @@ import {
36
40
  export {
37
41
  CockpitProvider,
38
42
  EMBED_PARAM,
43
+ EXPOSURE_PARAM,
39
44
  Experiment,
40
45
  FeedbackBoard,
41
46
  FeedbackWidget,
@@ -54,12 +59,15 @@ export {
54
59
  parsePreview,
55
60
  previewHref,
56
61
  readReferralCookie,
62
+ redirectFor,
57
63
  referralForCheckout,
58
64
  referralLink,
65
+ useCancelFlow,
59
66
  useCockpit,
60
67
  useFeedback,
61
68
  useFlag,
62
69
  useFlagVariant,
70
+ usePush,
63
71
  useStyles,
64
72
  useVariant
65
73
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export {\n type ChangelogEntry,\n type CockpitProviderProps,\n type CockpitUser,\n type FeedbackBoardInfo,\n type FeedbackBoardProps,\n type FeedbackComment,\n type FeedbackList,\n type FeedbackPost,\n type FeedbackRoadmap,\n type FeedbackWidgetProps,\n type PostStatus,\n type SurveyAnswer,\n type SurveyDefinition,\n type SurveyQuestion,\n type SurveyQuestionKind,\n CockpitProvider,\n Experiment,\n FeedbackBoard,\n FeedbackWidget,\n Survey,\n Text,\n WIDGET_CSS,\n createApi,\n useCockpit,\n useFeedback,\n useFlag,\n useFlagVariant,\n useStyles,\n useVariant,\n} from \"./browser\";\nexport {\n type CockpitConfig,\n type CockpitEvent,\n type ConsentChoice,\n type ConsentMode,\n type ReplayConfig,\n type ErrorReport,\n type ExperimentConfig,\n type FlagCondition,\n type FlagConditionSet,\n type FlagConfig,\n type FlagPerson,\n type VariantConfig,\n type VariantId,\n EMBED_PARAM,\n SDK_VERSION,\n ID_COOKIE,\n PREVIEW_PARAM,\n SESSION_COOKIE,\n assign,\n evaluateFlag,\n parsePreview,\n previewHref,\n} from \"./core\";\nexport {\n type AttributionMode,\n type CheckoutReferral,\n type Referral,\n REFERRAL_COOKIE,\n getReferral,\n readReferralCookie,\n referralForCheckout,\n referralLink,\n} from \"./referral\";\n"],"mappings":";AAAA;AAAA,EAgBI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP;AAAA,EAcI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP;AAAA,EAII;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export {\n type ChangelogEntry,\n type CockpitProviderProps,\n type CockpitUser,\n type FeedbackBoardInfo,\n type FeedbackBoardProps,\n type FeedbackComment,\n type FeedbackList,\n type FeedbackPost,\n type FeedbackRoadmap,\n type FeedbackWidgetProps,\n type PostStatus,\n type SurveyAnswer,\n type SurveyDefinition,\n type SurveyQuestion,\n type SurveyQuestionKind,\n CockpitProvider,\n Experiment,\n FeedbackBoard,\n FeedbackWidget,\n Survey,\n Text,\n WIDGET_CSS,\n createApi,\n useCancelFlow,\n useCockpit,\n useFeedback,\n useFlag,\n useFlagVariant,\n usePush,\n useStyles,\n useVariant,\n} from \"./browser\";\nexport type { PushResult, PushStatus, WebPushOptions } from \"./push-web\";\nexport {\n type CockpitConfig,\n type CockpitEvent,\n type ConsentChoice,\n type ConsentMode,\n type ReplayConfig,\n type ErrorReport,\n type ExperimentConfig,\n type FlagCondition,\n type FlagConditionSet,\n type FlagConfig,\n type FlagPerson,\n type RedirectConfig,\n type RedirectDecision,\n type VariantConfig,\n type VariantId,\n EMBED_PARAM,\n EXPOSURE_PARAM,\n SDK_VERSION,\n ID_COOKIE,\n PREVIEW_PARAM,\n SESSION_COOKIE,\n assign,\n evaluateFlag,\n parsePreview,\n previewHref,\n redirectFor,\n} from \"./core\";\nexport {\n type CancelFlowConfig,\n type CancelFlowOptions,\n type CancelFlowResult,\n type CancelOffer,\n type InAppMessage,\n type OnboardingFlow,\n type OnboardingStep,\n} from \"./flows\";\nexport type { FlowsTheme } from \"./flows-ui\";\nexport {\n type AttributionMode,\n type CheckoutReferral,\n type Referral,\n REFERRAL_COOKIE,\n getReferral,\n readReferralCookie,\n referralForCheckout,\n referralLink,\n} from \"./referral\";\n"],"mappings":";AAAA;AAAA,EAgBI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAEP;AAAA,EAgBI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAWP;AAAA,EAII;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;","names":[]}
package/dist/proxy.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { type CockpitConfig } from "./core.js";
2
+ export { getCockpitConfig } from "./server.js";
1
3
  /** What `request.cookies` (Next's `RequestCookies`) offers: read, and set so that the page of this request sees the id. */
2
4
  interface IncomingCookies {
3
5
  get(name: string): {
@@ -25,4 +27,35 @@ interface OutgoingCookies {
25
27
  * }
26
28
  */
27
29
  export declare const withCockpitId: (incoming: IncomingCookies, outgoing: OutgoingCookies) => void;
28
- export {};
30
+ /**
31
+ * For `proxy.ts`: where to send this request, or null to render it. Page redirects set in MRRocket (Landing pages ›
32
+ * Redirect) and redirect tests (Experiments) answer before the page renders, so nobody sees the old page flash. The
33
+ * page the visitor lands on records the test's exposure (`<CockpitProvider>` reads `ck_x` there); control renders as
34
+ * usual and the provider records it.
35
+ *
36
+ * A running test needs a stable visitor id to keep each person in one variant: the `ck_id` cookie (consent "cookies",
37
+ * with `withCockpitId` before this), or your signed-in user id as `distinctId`. Without either, the test is left to the
38
+ * browser (the provider redirects after the first paint); page redirects and shipped winners still answer here.
39
+ *
40
+ * import { NextResponse, type NextRequest } from "next/server";
41
+ * import { experimentRedirect, getCockpitConfig } from "@mrrocket/sdk/next/proxy";
42
+ *
43
+ * export async function proxy(request: NextRequest) {
44
+ * const to = experimentRedirect(request, await getCockpitConfig({ timeoutMs: 800 }));
45
+ * return to ? NextResponse.redirect(to, 307) : NextResponse.next();
46
+ * }
47
+ * export const config = { matcher: ["/pricing", "/old-pricing"] };
48
+ *
49
+ * Keep the matcher to the pages with a redirect or a test: each matched request waits for the config (at most
50
+ * `timeoutMs`; MRRocket unreachable means no redirect).
51
+ */
52
+ export declare const experimentRedirect: (request: {
53
+ url: string;
54
+ cookies?: {
55
+ get(name: string): {
56
+ value: string;
57
+ } | undefined;
58
+ };
59
+ }, config: CockpitConfig | null, options?: {
60
+ distinctId?: string;
61
+ }) => string | null;
package/dist/proxy.js CHANGED
@@ -1,12 +1,25 @@
1
1
  // src/proxy.ts
2
- import { ID_COOKIE, newDistinctId } from "./core.js";
2
+ import { ID_COOKIE, PREVIEW_PARAM, newDistinctId, parsePreview, redirectFor } from "./core.js";
3
+ import { getCockpitConfig } from "./server.js";
3
4
  var withCockpitId = (incoming, outgoing) => {
4
5
  if (incoming.get(ID_COOKIE)) return;
5
6
  const id = newDistinctId();
6
7
  incoming.set(ID_COOKIE, id);
7
8
  outgoing.set(ID_COOKIE, id, { path: "/", maxAge: 60 * 60 * 24 * 365, sameSite: "lax" });
8
9
  };
10
+ var experimentRedirect = (request, config, options = {}) => {
11
+ const id = options.distinctId ?? request.cookies?.get(ID_COOKIE)?.value ?? null;
12
+ let preview = {};
13
+ try {
14
+ preview = parsePreview(new URL(request.url).searchParams.get(PREVIEW_PARAM));
15
+ } catch {
16
+ return null;
17
+ }
18
+ return redirectFor(config, request.url, id, preview)?.to ?? null;
19
+ };
9
20
  export {
21
+ experimentRedirect,
22
+ getCockpitConfig,
10
23
  withCockpitId
11
24
  };
12
25
  //# sourceMappingURL=proxy.js.map
package/dist/proxy.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/proxy.ts"],"sourcesContent":["import { ID_COOKIE, newDistinctId } from \"./core\";\n\n/** What `request.cookies` (Next's `RequestCookies`) offers: read, and set so that the page of this request sees the id. */\ninterface IncomingCookies {\n get(name: string): { value: string } | undefined;\n set(name: string, value: string): unknown;\n}\n\n/** What `response.cookies` (Next's `ResponseCookies`) offers: set with options. */\ninterface OutgoingCookies {\n set(name: string, value: string, options?: { path?: string; maxAge?: number; sameSite?: \"lax\" | \"strict\" | \"none\" }): unknown;\n}\n\n/**\n * For `proxy.ts`: gives a first-time visitor their `ck_id` before the page renders, so the server already assigns\n * the variant they will keep. It writes a cookie, so only use it with `consent=\"cookies\"` and only once the visitor\n * agreed; in the default cookieless mode leave it out.\n *\n * export function proxy(request: NextRequest) {\n * const response = NextResponse.next();\n * withCockpitId(request.cookies, response.cookies);\n * return response;\n * }\n */\nexport const withCockpitId = (incoming: IncomingCookies, outgoing: OutgoingCookies) => {\n if (incoming.get(ID_COOKIE)) return;\n const id = newDistinctId();\n incoming.set(ID_COOKIE, id);\n outgoing.set(ID_COOKIE, id, { path: \"/\", maxAge: 60 * 60 * 24 * 365, sameSite: \"lax\" });\n};\n"],"mappings":";AAAA,SAAS,WAAW,qBAAqB;AAwBlC,IAAM,gBAAgB,CAAC,UAA2B,aAA8B;AACnF,MAAI,SAAS,IAAI,SAAS,EAAG;AAC7B,QAAM,KAAK,cAAc;AACzB,WAAS,IAAI,WAAW,EAAE;AAC1B,WAAS,IAAI,WAAW,IAAI,EAAE,MAAM,KAAK,QAAQ,KAAK,KAAK,KAAK,KAAK,UAAU,MAAM,CAAC;AAC1F;","names":[]}
1
+ {"version":3,"sources":["../src/proxy.ts"],"sourcesContent":["import { type CockpitConfig, ID_COOKIE, PREVIEW_PARAM, newDistinctId, parsePreview, redirectFor } from \"./core\";\n\nexport { getCockpitConfig } from \"./server\";\n\n/** What `request.cookies` (Next's `RequestCookies`) offers: read, and set so that the page of this request sees the id. */\ninterface IncomingCookies {\n get(name: string): { value: string } | undefined;\n set(name: string, value: string): unknown;\n}\n\n/** What `response.cookies` (Next's `ResponseCookies`) offers: set with options. */\ninterface OutgoingCookies {\n set(name: string, value: string, options?: { path?: string; maxAge?: number; sameSite?: \"lax\" | \"strict\" | \"none\" }): unknown;\n}\n\n/**\n * For `proxy.ts`: gives a first-time visitor their `ck_id` before the page renders, so the server already assigns\n * the variant they will keep. It writes a cookie, so only use it with `consent=\"cookies\"` and only once the visitor\n * agreed; in the default cookieless mode leave it out.\n *\n * export function proxy(request: NextRequest) {\n * const response = NextResponse.next();\n * withCockpitId(request.cookies, response.cookies);\n * return response;\n * }\n */\nexport const withCockpitId = (incoming: IncomingCookies, outgoing: OutgoingCookies) => {\n if (incoming.get(ID_COOKIE)) return;\n const id = newDistinctId();\n incoming.set(ID_COOKIE, id);\n outgoing.set(ID_COOKIE, id, { path: \"/\", maxAge: 60 * 60 * 24 * 365, sameSite: \"lax\" });\n};\n\n/**\n * For `proxy.ts`: where to send this request, or null to render it. Page redirects set in MRRocket (Landing pages ›\n * Redirect) and redirect tests (Experiments) answer before the page renders, so nobody sees the old page flash. The\n * page the visitor lands on records the test's exposure (`<CockpitProvider>` reads `ck_x` there); control renders as\n * usual and the provider records it.\n *\n * A running test needs a stable visitor id to keep each person in one variant: the `ck_id` cookie (consent \"cookies\",\n * with `withCockpitId` before this), or your signed-in user id as `distinctId`. Without either, the test is left to the\n * browser (the provider redirects after the first paint); page redirects and shipped winners still answer here.\n *\n * import { NextResponse, type NextRequest } from \"next/server\";\n * import { experimentRedirect, getCockpitConfig } from \"@mrrocket/sdk/next/proxy\";\n *\n * export async function proxy(request: NextRequest) {\n * const to = experimentRedirect(request, await getCockpitConfig({ timeoutMs: 800 }));\n * return to ? NextResponse.redirect(to, 307) : NextResponse.next();\n * }\n * export const config = { matcher: [\"/pricing\", \"/old-pricing\"] };\n *\n * Keep the matcher to the pages with a redirect or a test: each matched request waits for the config (at most\n * `timeoutMs`; MRRocket unreachable means no redirect).\n */\nexport const experimentRedirect = (\n request: { url: string; cookies?: { get(name: string): { value: string } | undefined } },\n config: CockpitConfig | null,\n options: { distinctId?: string } = {},\n): string | null => {\n const id = options.distinctId ?? request.cookies?.get(ID_COOKIE)?.value ?? null;\n let preview = {};\n try {\n preview = parsePreview(new URL(request.url).searchParams.get(PREVIEW_PARAM));\n } catch {\n return null;\n }\n return redirectFor(config, request.url, id, preview)?.to ?? null;\n};\n"],"mappings":";AAAA,SAA6B,WAAW,eAAe,eAAe,cAAc,mBAAmB;AAEvG,SAAS,wBAAwB;AAwB1B,IAAM,gBAAgB,CAAC,UAA2B,aAA8B;AACnF,MAAI,SAAS,IAAI,SAAS,EAAG;AAC7B,QAAM,KAAK,cAAc;AACzB,WAAS,IAAI,WAAW,EAAE;AAC1B,WAAS,IAAI,WAAW,IAAI,EAAE,MAAM,KAAK,QAAQ,KAAK,KAAK,KAAK,KAAK,UAAU,MAAM,CAAC;AAC1F;AAwBO,IAAM,qBAAqB,CAC9B,SACA,QACA,UAAmC,CAAC,MACpB;AAChB,QAAM,KAAK,QAAQ,cAAc,QAAQ,SAAS,IAAI,SAAS,GAAG,SAAS;AAC3E,MAAI,UAAU,CAAC;AACf,MAAI;AACA,cAAU,aAAa,IAAI,IAAI,QAAQ,GAAG,EAAE,aAAa,IAAI,aAAa,CAAC;AAAA,EAC/E,QAAQ;AACJ,WAAO;AAAA,EACX;AACA,SAAO,YAAY,QAAQ,QAAQ,KAAK,IAAI,OAAO,GAAG,MAAM;AAChE;","names":[]}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Web push in the browser (SDK 0.7.0): signs the signed-in person up for push notifications from the product's Lifecycle
3
+ * journeys. Loaded only when the site calls `push.subscribe()` (a dynamic import in Next.js, `sdk-push.js` for the script
4
+ * tag), so pages that never ask carry none of it.
5
+ *
6
+ * 1. The browser's permission (asked only from a click, and only when the site says so; `ask: false` only re-sends an
7
+ * existing subscription).
8
+ * 2. The service worker the site hosts (`/mrrocket-sw.js`, a copy of the file MRRocket serves), registered with the
9
+ * public key and MRRocket's address in its URL, so it can report opened notifications. A site with its own service
10
+ * worker imports ours there and passes `serviceWorker: false`.
11
+ * 3. The workspace's VAPID key from `GET /api/sdk/push`, the browser's subscription with it, and the subscription sent to
12
+ * `POST /api/sdk/push` for this person. A subscription made with another key is replaced.
13
+ */
14
+ export type PushStatus = "subscribed" | "denied" | "not-asked" | "unsupported" | "not-signed-in" | "error";
15
+ export interface PushResult {
16
+ status: PushStatus;
17
+ /** What went wrong, for "error" and "unsupported". */
18
+ reason?: string;
19
+ }
20
+ export interface WebPushOptions {
21
+ /**
22
+ * The service worker's path on your site (default "/mrrocket-sw.js"), or false when your site already has one that
23
+ * imports ours (`importScripts("/mrrocket-sw.js")`): the SDK then uses the one that is active.
24
+ */
25
+ serviceWorker?: string | false;
26
+ /** Ask for the permission when it was not given yet (default true). False: only re-send an existing subscription. */
27
+ ask?: boolean;
28
+ }
29
+ export interface WebPushContext {
30
+ host: string;
31
+ apiKey: string;
32
+ /** The identify() id; push needs a signed-in person. */
33
+ distinctId: string | undefined;
34
+ /** The permission, asked synchronously by the caller inside the click (Safari needs that), or the current one. */
35
+ permission?: Promise<NotificationPermission>;
36
+ }
37
+ /** True where the browser can receive web push (Safari 16.4+ only for sites added to the Home Screen on iOS). */
38
+ export declare const webPushSupported: () => boolean;
39
+ /** The permission, asked right away when `ask` and not given yet. Call it synchronously in the click handler. */
40
+ export declare const askPermission: (ask?: boolean) => Promise<NotificationPermission>;
41
+ export declare const subscribeWebPush: (ctx: WebPushContext, options?: WebPushOptions) => Promise<PushResult>;
42
+ /** Ends this browser's subscription and tells MRRocket (sign-out, or the person turned push off). */
43
+ export declare const unsubscribeWebPush: (ctx: WebPushContext) => Promise<boolean>;
@@ -0,0 +1,81 @@
1
+ // src/push-web.ts
2
+ var b64urlBytes = (s) => {
3
+ const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(s.length / 4) * 4, "="));
4
+ const out = new Uint8Array(bin.length);
5
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
6
+ return out;
7
+ };
8
+ var sameKey = (a, b) => {
9
+ if (!a) return false;
10
+ const x = new Uint8Array(a);
11
+ return x.length === b.length && x.every((v, i) => v === b[i]);
12
+ };
13
+ var webPushSupported = () => typeof window !== "undefined" && "serviceWorker" in navigator && "PushManager" in window && "Notification" in window;
14
+ var askPermission = (ask = true) => {
15
+ if (!webPushSupported()) return Promise.resolve("denied");
16
+ if (Notification.permission !== "default" || !ask) return Promise.resolve(Notification.permission);
17
+ try {
18
+ return Promise.resolve(Notification.requestPermission());
19
+ } catch {
20
+ return Promise.resolve("denied");
21
+ }
22
+ };
23
+ var registration = async (host, apiKey, sw) => {
24
+ if (sw !== false) {
25
+ const url = `${sw}?key=${encodeURIComponent(apiKey)}&host=${encodeURIComponent(host)}`;
26
+ await navigator.serviceWorker.register(url);
27
+ }
28
+ return navigator.serviceWorker.ready;
29
+ };
30
+ var subscribeWebPush = async (ctx, options = {}) => {
31
+ if (!webPushSupported()) return { status: "unsupported", reason: "This browser has no web push." };
32
+ if (!ctx.distinctId) return { status: "not-signed-in" };
33
+ const ask = options.ask !== false;
34
+ const permission = await (ctx.permission ?? askPermission(ask));
35
+ if (permission === "denied") return { status: "denied" };
36
+ if (permission !== "granted") return { status: ask ? "denied" : "not-asked" };
37
+ try {
38
+ const r = await fetch(`${ctx.host}/api/sdk/push?key=${encodeURIComponent(ctx.apiKey)}`);
39
+ const vapid = r.ok ? (await r.json()).web?.vapidKey : void 0;
40
+ if (!vapid) return { status: "error", reason: `MRRocket answered ${r.status} for the push key.` };
41
+ const key = b64urlBytes(vapid);
42
+ const reg = await registration(ctx.host, ctx.apiKey, options.serviceWorker ?? "/mrrocket-sw.js");
43
+ let sub = await reg.pushManager.getSubscription();
44
+ if (sub && !sameKey(sub.options?.applicationServerKey, key)) {
45
+ await sub.unsubscribe().catch(() => false);
46
+ sub = null;
47
+ }
48
+ sub ??= await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key });
49
+ const saved = await fetch(`${ctx.host}/api/sdk/push`, {
50
+ method: "POST",
51
+ headers: { "content-type": "application/json" },
52
+ body: JSON.stringify({ key: ctx.apiKey, distinctId: ctx.distinctId, platform: "web", subscription: sub.toJSON(), host: ctx.host })
53
+ });
54
+ return saved.ok ? { status: "subscribed" } : { status: "error", reason: `MRRocket answered ${saved.status}.` };
55
+ } catch (e) {
56
+ return { status: "error", reason: e instanceof Error ? e.message : String(e) };
57
+ }
58
+ };
59
+ var unsubscribeWebPush = async (ctx) => {
60
+ if (!webPushSupported()) return false;
61
+ try {
62
+ const reg = await navigator.serviceWorker.getRegistration();
63
+ const sub = await reg?.pushManager.getSubscription();
64
+ if (!sub) return false;
65
+ await fetch(`${ctx.host}/api/sdk/push`, {
66
+ method: "POST",
67
+ headers: { "content-type": "application/json" },
68
+ body: JSON.stringify({ key: ctx.apiKey, distinctId: ctx.distinctId, platform: "web", remove: true, endpoint: sub.endpoint })
69
+ }).catch(() => null);
70
+ return await sub.unsubscribe();
71
+ } catch {
72
+ return false;
73
+ }
74
+ };
75
+ export {
76
+ askPermission,
77
+ subscribeWebPush,
78
+ unsubscribeWebPush,
79
+ webPushSupported
80
+ };
81
+ //# sourceMappingURL=push-web.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/push-web.ts"],"sourcesContent":["/**\n * Web push in the browser (SDK 0.7.0): signs the signed-in person up for push notifications from the product's Lifecycle\n * journeys. Loaded only when the site calls `push.subscribe()` (a dynamic import in Next.js, `sdk-push.js` for the script\n * tag), so pages that never ask carry none of it.\n *\n * 1. The browser's permission (asked only from a click, and only when the site says so; `ask: false` only re-sends an\n * existing subscription).\n * 2. The service worker the site hosts (`/mrrocket-sw.js`, a copy of the file MRRocket serves), registered with the\n * public key and MRRocket's address in its URL, so it can report opened notifications. A site with its own service\n * worker imports ours there and passes `serviceWorker: false`.\n * 3. The workspace's VAPID key from `GET /api/sdk/push`, the browser's subscription with it, and the subscription sent to\n * `POST /api/sdk/push` for this person. A subscription made with another key is replaced.\n */\nexport type PushStatus = \"subscribed\" | \"denied\" | \"not-asked\" | \"unsupported\" | \"not-signed-in\" | \"error\";\n\nexport interface PushResult {\n status: PushStatus;\n /** What went wrong, for \"error\" and \"unsupported\". */\n reason?: string;\n}\n\nexport interface WebPushOptions {\n /**\n * The service worker's path on your site (default \"/mrrocket-sw.js\"), or false when your site already has one that\n * imports ours (`importScripts(\"/mrrocket-sw.js\")`): the SDK then uses the one that is active.\n */\n serviceWorker?: string | false;\n /** Ask for the permission when it was not given yet (default true). False: only re-send an existing subscription. */\n ask?: boolean;\n}\n\nexport interface WebPushContext {\n host: string;\n apiKey: string;\n /** The identify() id; push needs a signed-in person. */\n distinctId: string | undefined;\n /** The permission, asked synchronously by the caller inside the click (Safari needs that), or the current one. */\n permission?: Promise<NotificationPermission>;\n}\n\nconst b64urlBytes = (s: string) => {\n const bin = atob(s.replace(/-/g, \"+\").replace(/_/g, \"/\").padEnd(Math.ceil(s.length / 4) * 4, \"=\"));\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n};\n\nconst sameKey = (a: ArrayBuffer | null | undefined, b: Uint8Array) => {\n if (!a) return false;\n const x = new Uint8Array(a);\n return x.length === b.length && x.every((v, i) => v === b[i]);\n};\n\n/** True where the browser can receive web push (Safari 16.4+ only for sites added to the Home Screen on iOS). */\nexport const webPushSupported = () =>\n typeof window !== \"undefined\" && \"serviceWorker\" in navigator && \"PushManager\" in window && \"Notification\" in window;\n\n/** The permission, asked right away when `ask` and not given yet. Call it synchronously in the click handler. */\nexport const askPermission = (ask = true): Promise<NotificationPermission> => {\n if (!webPushSupported()) return Promise.resolve(\"denied\");\n if (Notification.permission !== \"default\" || !ask) return Promise.resolve(Notification.permission);\n try {\n return Promise.resolve(Notification.requestPermission());\n } catch {\n return Promise.resolve(\"denied\");\n }\n};\n\nconst registration = async (host: string, apiKey: string, sw: string | false) => {\n if (sw !== false) {\n const url = `${sw}?key=${encodeURIComponent(apiKey)}&host=${encodeURIComponent(host)}`;\n await navigator.serviceWorker.register(url);\n }\n return navigator.serviceWorker.ready;\n};\n\nexport const subscribeWebPush = async (ctx: WebPushContext, options: WebPushOptions = {}): Promise<PushResult> => {\n if (!webPushSupported()) return { status: \"unsupported\", reason: \"This browser has no web push.\" };\n if (!ctx.distinctId) return { status: \"not-signed-in\" };\n const ask = options.ask !== false;\n const permission = await (ctx.permission ?? askPermission(ask));\n if (permission === \"denied\") return { status: \"denied\" };\n if (permission !== \"granted\") return { status: ask ? \"denied\" : \"not-asked\" };\n try {\n const r = await fetch(`${ctx.host}/api/sdk/push?key=${encodeURIComponent(ctx.apiKey)}`);\n const vapid = r.ok ? ((await r.json()) as { web?: { vapidKey?: string } }).web?.vapidKey : undefined;\n if (!vapid) return { status: \"error\", reason: `MRRocket answered ${r.status} for the push key.` };\n const key = b64urlBytes(vapid);\n const reg = await registration(ctx.host, ctx.apiKey, options.serviceWorker ?? \"/mrrocket-sw.js\");\n let sub = await reg.pushManager.getSubscription();\n if (sub && !sameKey(sub.options?.applicationServerKey, key)) {\n await sub.unsubscribe().catch(() => false);\n sub = null;\n }\n sub ??= await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key });\n const saved = await fetch(`${ctx.host}/api/sdk/push`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ key: ctx.apiKey, distinctId: ctx.distinctId, platform: \"web\", subscription: sub.toJSON(), host: ctx.host }),\n });\n return saved.ok ? { status: \"subscribed\" } : { status: \"error\", reason: `MRRocket answered ${saved.status}.` };\n } catch (e) {\n return { status: \"error\", reason: e instanceof Error ? e.message : String(e) };\n }\n};\n\n/** Ends this browser's subscription and tells MRRocket (sign-out, or the person turned push off). */\nexport const unsubscribeWebPush = async (ctx: WebPushContext): Promise<boolean> => {\n if (!webPushSupported()) return false;\n try {\n const reg = await navigator.serviceWorker.getRegistration();\n const sub = await reg?.pushManager.getSubscription();\n if (!sub) return false;\n await fetch(`${ctx.host}/api/sdk/push`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ key: ctx.apiKey, distinctId: ctx.distinctId, platform: \"web\", remove: true, endpoint: sub.endpoint }),\n }).catch(() => null);\n return await sub.unsubscribe();\n } catch {\n return false;\n }\n};\n"],"mappings":";AAwCA,IAAM,cAAc,CAAC,MAAc;AAC/B,QAAM,MAAM,KAAK,EAAE,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,GAAG,EAAE,OAAO,KAAK,KAAK,EAAE,SAAS,CAAC,IAAI,GAAG,GAAG,CAAC;AACjG,QAAM,MAAM,IAAI,WAAW,IAAI,MAAM;AACrC,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,IAAK,KAAI,CAAC,IAAI,IAAI,WAAW,CAAC;AAC9D,SAAO;AACX;AAEA,IAAM,UAAU,CAAC,GAAmC,MAAkB;AAClE,MAAI,CAAC,EAAG,QAAO;AACf,QAAM,IAAI,IAAI,WAAW,CAAC;AAC1B,SAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,CAAC,GAAG,MAAM,MAAM,EAAE,CAAC,CAAC;AAChE;AAGO,IAAM,mBAAmB,MAC5B,OAAO,WAAW,eAAe,mBAAmB,aAAa,iBAAiB,UAAU,kBAAkB;AAG3G,IAAM,gBAAgB,CAAC,MAAM,SAA0C;AAC1E,MAAI,CAAC,iBAAiB,EAAG,QAAO,QAAQ,QAAQ,QAAQ;AACxD,MAAI,aAAa,eAAe,aAAa,CAAC,IAAK,QAAO,QAAQ,QAAQ,aAAa,UAAU;AACjG,MAAI;AACA,WAAO,QAAQ,QAAQ,aAAa,kBAAkB,CAAC;AAAA,EAC3D,QAAQ;AACJ,WAAO,QAAQ,QAAQ,QAAQ;AAAA,EACnC;AACJ;AAEA,IAAM,eAAe,OAAO,MAAc,QAAgB,OAAuB;AAC7E,MAAI,OAAO,OAAO;AACd,UAAM,MAAM,GAAG,E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