@mrrocket/sdk 0.24.0 → 0.26.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.
- package/CHANGELOG.md +16 -1
- package/README.md +22 -1
- package/dist/browser/mrrocket-flows.js +3 -3
- package/dist/browser/mrrocket-preview.js +1 -0
- package/dist/browser/mrrocket-replay.js +3 -3
- package/dist/browser/mrrocket.js +2 -2
- package/dist/client.js +52 -3
- package/dist/client.js.map +1 -1
- package/dist/context.d.ts +2 -0
- package/dist/context.js.map +1 -1
- package/dist/core.d.ts +67 -1
- package/dist/core.js +28 -2
- package/dist/core.js.map +1 -1
- package/dist/preview.d.ts +101 -0
- package/dist/preview.js +308 -0
- package/dist/preview.js.map +1 -0
- package/dist/react-native/index.d.cts +1 -1
- package/dist/react-native/index.d.ts +1 -1
- package/dist/react-native/index.js +1 -1
- package/dist/react-native/index.js.map +1 -1
- package/dist/server.d.ts +18 -0
- package/dist/server.js +31 -0
- package/dist/server.js.map +1 -1
- package/package.json +1 -1
package/dist/core.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core.ts"],"sourcesContent":["/**\n * The part of the SDK that runs anywhere: experiment config, variant assignment, preview links and event shapes.\n * No React, no browser APIs, so the server helper, the proxy helper and the client share it.\n */\nimport type { CancelFlowConfig, OnboardingFlow } from \"./flows\";\nimport type { PaywallConfig } from \"./paywall\";\n\nexport type VariantId = string;\n\n/** This build of the SDK. Sent with the config request so MRRocket knows what the site runs (error tracking, flags). */\nexport const SDK_VERSION = \"0.24.0\";\n\n/** One variant of an experiment. `changes` replaces texts that the page marks with `<Text id>`. */\nexport interface VariantConfig {\n id: VariantId;\n /** Share of traffic, 0 to 1. The weights of an experiment add up to 1. */\n weight: number;\n changes?: Record<string, string>;\n /**\n * A redirect test: where this variant sends the visitor instead of the test's page (a path like \"/pricing-b\" or a\n * full address). Control has none and stays. SDK 0.7.0+.\n */\n url?: string;\n}\n\nexport interface ExperimentConfig {\n /** The experiment's key, the same as in Cockpit. */\n key: string;\n status: \"running\" | \"draft\" | \"stopped\";\n /** Control first. */\n variants: VariantConfig[];\n /** A winner that shipped: everyone gets it, and nobody is assigned anymore. */\n winner?: VariantId;\n /** A redirect test: the path of the page it runs on (\"/pricing\"). Visitors there are sent to their variant's `url`. */\n path?: string;\n}\n\n/** A page redirect set in MRRocket (Conversion › Landing pages › Redirect): everyone on `from` goes to `to`. SDK 0.7.0+. */\nexport interface RedirectConfig {\n /** A path of the site, like \"/old-pricing\". */\n from: string;\n /** A path or a full address. */\n to: string;\n}\n\nexport interface CockpitConfig {\n /** The product the public key belongs to. */\n project: string;\n /** The language the server chose for the words below, like \"de\" (`lang` on the request). SDK 0.21.0+. */\n lang?: string;\n /** The SDK's own words: English source word to translation (see words.ts). Absent for English. SDK 0.21.0+. */\n words?: Record<string, string>;\n experiments: ExperimentConfig[];\n /** The product's affiliate program: how many days a partner's referral is kept. Missing without a program. */\n referral?: { cookieDays: number };\n /** Session recordings: present only while the product records (Cockpit › Sessions). See `ReplayConfig`. */\n replay?: ReplayConfig;\n /** Feature flags of the product in Production (MRRocket › Build › Feature flags), evaluated by `useFlag` and `getFlag`. */\n flags?: FlagConfig[];\n /**\n * Published copy for texts the site marks (`<Text id>`, `data-ck-text`): a landing page's headline, subheadline and\n * button (`pricing.headline` …) and a paywall's (`paywall.<placement>.headline` …) as published in MRRocket. A\n * running test's variant changes them on top. Missing when nothing is published. SDK 0.5.0+.\n */\n texts?: Record<string, string>;\n /** The product's live cancel flow (MRRocket › Churn › Cancel flow), for `cancelFlow.open()`. SDK 0.7.0+. */\n cancelFlow?: CancelFlowConfig;\n /** The in-app steps of live onboarding flows (tours, checklists, modals). SDK 0.7.0+. */\n onboarding?: OnboardingFlow[];\n /** The product's brand color (\"#rrggbb\") for the onboarding dialogs when the app passes no accent. SDK 0.18.0+. */\n onboardingAccent?: string;\n /** A live Lifecycle journey has in-app messages: signed-in people ask `/api/sdk/inapp` for theirs. SDK 0.7.0+. */\n messages?: boolean;\n /** Page redirects set in MRRocket; the SDK sends visitors on before the page shows (`redirectFor`). SDK 0.7.0+. */\n redirects?: RedirectConfig[];\n /** Published paywalls with their pages, per placement (MRRocket › Conversion › Paywalls), for `paywall.open()`. SDK 0.14.0+. */\n paywalls?: PaywallConfig[];\n /**\n * The visitor's unit for A/B tests (0.24.0): the same daily visitor hash MRRocket counts a cookieless visitor by\n * (`v_…`, from the key, the day, the address and the browser, with a server secret). Without a signed-in id or the\n * `ck_id` cookie, tests and flags assign by it, so a visitor keeps their version all day across reloads and between\n * server render and browser, and their events carry it as `distinctId`. Held in memory only, never stored on the\n * device (a React Native app leaves it out of its cached config). Missing from an older MRRocket.\n */\n unit?: string;\n}\n\n/** One condition of a flag's audience, on a property of the person (`identify(id, props)`), the id or the page. */\nexport interface FlagCondition {\n /** \"Email\", \"Plan\", \"Country\", \"id\", \"path\" … Matched against the person's properties without regard to case. */\n property: string;\n op: \"is\" | \"is not\" | \"in\" | \"not in\" | \"≥\" | \"in cohort\";\n values: string[];\n}\n\n/** Users who match every condition, of whom `rollout` percent get the flag. No conditions: everyone. */\nexport interface FlagConditionSet {\n conditions: FlagCondition[];\n /** 0 to 100. */\n rollout: number;\n}\n\nexport interface FlagConfig {\n key: string;\n /** Off: everyone gets the off side. */\n on: boolean;\n /** The first set a person matches decides; none matched: off. */\n sets: FlagConditionSet[];\n /** Multivariate flags: the variants and their split in percent (control included). Missing for an on/off flag. */\n variants?: { key: string; split: number; payload?: string }[];\n /**\n * The key of the A/B test the flag measures, while it runs (0.24.0). Reading the flag then records one `$exposure`\n * per page view; `flagExposure` says which version.\n */\n experiment?: string;\n}\n\n/** What a person is for flag conditions: their properties from identify(), their id and the page they are on. */\nexport type FlagPerson = Record<string, unknown>;\n\nconst propOf = (person: FlagPerson, name: string) => {\n const want = name.trim().toLowerCase();\n for (const [k, v] of Object.entries(person)) if (k.toLowerCase() === want) return v;\n return undefined;\n};\n\n/** `\"@acme.com\"` matches every address at that domain; anything else matches the whole value, without regard to case. */\nconst same = (actual: string, value: string) => {\n const a = actual.trim().toLowerCase();\n const v = value.trim().toLowerCase();\n return v.startsWith(\"@\") ? a.endsWith(v) : a === v;\n};\n\nconst matchesCondition = (c: FlagCondition, person: FlagPerson) => {\n // Cohorts live in MRRocket; a browser cannot know them, so a cohort condition never matches here.\n if (c.op === \"in cohort\") return false;\n const raw = propOf(person, c.property);\n const actual = raw === undefined || raw === null ? \"\" : String(raw);\n if (c.op === \"≥\") {\n const a = Number(actual);\n const b = Number(c.values[0]);\n return actual !== \"\" && Number.isFinite(a) && Number.isFinite(b) && a >= b;\n }\n const hit = actual !== \"\" && c.values.some((v) => same(actual, v));\n return c.op === \"is\" || c.op === \"in\" ? hit : !hit;\n};\n\n/**\n * The flag for one person: `false` (off), `true` (on, an on/off flag) or the variant's key (a multivariate flag). The\n * bucket is a stable hash of flag and person, so a person keeps their side as the rollout grows.\n */\nexport const evaluateFlag = (flag: FlagConfig, distinctId: string, person: FlagPerson = {}): boolean | string => {\n if (!flag.on) return false;\n const subject = { id: distinctId, ...person };\n const set = flag.sets.length ? flag.sets.find((s) => s.conditions.every((c) => matchesCondition(c, subject))) : { conditions: [], rollout: 100 };\n if (!set) return false;\n if (flagUnit(`${flag.key}:rollout:${distinctId}`) * 100 >= set.rollout) return false;\n if (!flag.variants?.length) return true;\n const u = flagUnit(`${flag.key}:variant:${distinctId}`) * 100;\n let acc = 0;\n for (const v of flag.variants) {\n acc += v.split;\n if (u < acc) return v.key;\n }\n return flag.variants[flag.variants.length - 1].key;\n};\n\n/** A flag of the config for this person; an unknown flag (or no config) is off. */\nexport const flagFor = (key: string, config: CockpitConfig | null, distinctId: string, person: FlagPerson = {}) => {\n const flag = config?.flags?.find((f) => f.key === key);\n return flag ? evaluateFlag(flag, distinctId, person) : false;\n};\n\n/** The version id MRRocket counts at a position: \"control\" first, then \"a\", \"b\" … (`variantIndex` on the server). */\nexport const versionAt = (i: number): VariantId => (i <= 0 ? \"control\" : String.fromCharCode(96 + Math.min(i, 26)));\n\n/**\n * What reading a flag that measures a running test exposes (0.24.0): `{ experiment, variant }` for `$exposure`, or null\n * when the flag measures none or the person is not in the test (the flag is off, the person outside its audience, or a\n * multivariate flag's rollout leaves them out). A multivariate flag's variants count by position (the first is\n * control, then \"a\", \"b\" …); an on/off flag counts its rollout: on is \"a\", off is control.\n */\nexport const flagExposure = (key: string, config: CockpitConfig | null, distinctId: string, person: FlagPerson = {}): { experiment: string; variant: VariantId } | null => {\n const flag = config?.flags?.find((f) => f.key === key);\n if (!flag?.experiment || !flag.on) return null;\n const subject = { id: distinctId, ...person };\n if (flag.sets.length && !flag.sets.some((s) => s.conditions.every((c) => matchesCondition(c, subject)))) return null;\n const value = evaluateFlag(flag, distinctId, person);\n if (flag.variants?.length) {\n const i = typeof value === \"string\" ? flag.variants.findIndex((v) => v.key === value) : -1;\n return i < 0 ? null : { experiment: flag.experiment, variant: versionAt(i) };\n }\n return { experiment: flag.experiment, variant: value === true ? \"a\" : \"control\" };\n};\n\n/** One JavaScript error as it goes over the wire to `POST /api/sdk/errors`. */\nexport interface ErrorReport {\n /** \"TypeError\", \"Error\" … */\n type: string;\n message: string;\n /** The raw stack, at most 8 KB. MRRocket parses it into frames. */\n stack?: string;\n /** \"onerror\" (uncaught), \"onunhandledrejection\" (a rejected promise nobody caught) or \"manual\" (captureError). */\n mechanism: \"onerror\" | \"onunhandledrejection\" | \"manual\";\n handled: boolean;\n url: string;\n ts: number;\n /** What happened just before: pages and clicks, newest last, at most 20. */\n crumbs?: { ts: number; type: \"navigation\" | \"click\" | \"lifecycle\"; message: string }[];\n /** Your release (a version or commit), from the provider's `release` prop. */\n release?: string;\n distinctId?: string;\n sessionId?: string;\n}\n\n/**\n * Session recordings of a product, from the config. Recording also needs the visitor's own replay consent\n * (`<CockpitProvider replay>` or `setConsent({ replay: true })`); without it nothing is recorded or buffered.\n */\nexport interface ReplayConfig {\n /**\n * Share of sessions uploaded from their start, 0 to 1 (default 0.1). The others keep only the last minute in\n * memory and upload it when something goes wrong: a JS error, a rage click, a `purchase…` or `checkout…` event.\n */\n sampleRate: number;\n}\n\n/**\n * What the SDK may send and store.\n * - \"cookieless\" (default): no cookie, no localStorage. The server counts visitors with a hash of key, date, IP and\n * user agent that changes every day; since 0.24.0 the config hands that hash over as `unit`, kept in memory only, so\n * tests assign by it and events carry it.\n * - \"cookies\": a persistent `ck_id` cookie identifies the visitor across visits, `ck_sid` holds the session.\n * - \"off\": nothing is sent and nothing is stored.\n */\nexport type ConsentMode = \"cookieless\" | \"cookies\" | \"off\";\n\n/** Sent once when a signed-in person withdraws analytics consent, and stored as nothing but that fact on their record. */\nexport const CONSENT_OFF_EVENT = \"$consent_off\";\n\n/**\n * What `setConsent` takes: a mode as before, or the parts to change. `replay` is the separate consent for session\n * recordings (default false); it applies only while analytics is not \"off\".\n *\n * setConsent(\"cookies\");\n * setConsent({ replay: true });\n * setConsent({ analytics: \"cookieless\", replay: false });\n */\nexport type ConsentChoice = ConsentMode | { analytics?: ConsentMode; replay?: boolean };\n\n/** The campaign parameters the SDK reads from the landing URL. */\nexport const UTM_KEYS = [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_term\", \"utm_content\"] as const;\nexport type UtmKey = (typeof UTM_KEYS)[number];\n\n/** One event as it goes over the wire to `POST /api/sdk/events`. */\nexport interface CockpitEvent {\n event: string;\n /**\n * The visitor. In \"cookieless\" mode until identify() it is the config's `unit` (0.24.0, MRRocket's own daily visitor\n * hash, held in memory), or missing before the config has one: the server then makes that hash itself.\n */\n distinctId?: string;\n /** Ends after 30 minutes without an event. */\n sessionId?: string;\n props?: Record<string, unknown>;\n /** Milliseconds since the epoch. */\n ts: number;\n url?: string;\n /** `document.referrer` on the first page of a page load, the previous in-app URL after client-side navigation. */\n referrer?: string;\n utm_source?: string;\n utm_medium?: string;\n utm_campaign?: string;\n utm_term?: string;\n utm_content?: string;\n /** The screen size in CSS pixels (points on a phone). */\n screen?: { w: number; h: number };\n /** The app that sent it (React Native only): MRRocket stores it with the event and fills OS and device from it. */\n app?: AppContext;\n}\n\n/** Where a React Native event comes from. Every field is optional except the platform; nothing identifies the person. */\nexport interface AppContext {\n /** \"ios\" or \"android\" (React Native's `Platform.OS`). */\n platform: string;\n /** The app's version, like \"1.4.0\" (`expo-application`'s `nativeApplicationVersion`). */\n appVersion?: string;\n /** The build number, like \"42\". */\n build?: string;\n /** The OS version, like \"17.4\". */\n osVersion?: string;\n /** The device model, like \"iPhone 15 Pro\" (`expo-device`). */\n deviceModel?: string;\n /** \"phone\", \"tablet\", \"desktop\" or \"tv\" when `expo-device` knows it. */\n deviceType?: string;\n /** The first preferred locale, like \"de-DE\". */\n locale?: string;\n}\n\n/** The query parameter that forces variants, for previews in Cockpit: `?ck_preview=pricing-annual:a,home-hero:control`. */\nexport const PREVIEW_PARAM = \"ck_preview\";\n/** Set when Cockpit embeds the page: nothing is tracked, so previews never count as visits. */\nexport const EMBED_PARAM = \"ck_embed\";\n/** The cookie that keeps a visitor in the same variant across visits. Only written in \"cookies\" mode. */\nexport const ID_COOKIE = \"ck_id\";\n/**\n * The headers a customer's server sends with `GET /api/sdk/config` (and the server key) so MRRocket makes the unit of\n * the visitor it renders for, not of the server itself (0.24.0, `getCockpitConfig({ headers })`).\n */\nexport const VISITOR_IP_HEADER = \"x-mrrocket-visitor-ip\";\nexport const VISITOR_UA_HEADER = \"x-mrrocket-visitor-ua\";\n/** The cookie that holds the session id in \"cookies\" mode. */\nexport const SESSION_COOKIE = \"ck_sid\";\n/** A session ends after this long without an event. */\nexport const SESSION_TIMEOUT_MS = 30 * 60 * 1000;\n\n/** The UTM parameters from a parameter lookup (`URLSearchParams.get` in a browser). Empty values are left out. */\nexport const utmFrom = (get: (name: string) => string | null | undefined): Partial<Record<UtmKey, string>> => {\n const out: Partial<Record<UtmKey, string>> = {};\n for (const key of UTM_KEYS) {\n const value = get(key)?.trim();\n if (value) out[key] = value.slice(0, 150);\n }\n return out;\n};\n\n/** The UTM parameters of a query string, like `\"?utm_source=x\"`. Empty values are left out. */\nexport const readUtm = (search: string): Partial<Record<UtmKey, string>> => {\n const params = new URLSearchParams(search);\n return utmFrom((k) => params.get(k));\n};\n\n/**\n * The query parameters of a URL or query string, without `URLSearchParams` (React Native's is incomplete): `+` is a\n * space, values are percent-decoded, the first of a repeated name wins.\n */\nexport const parseQuery = (url: string): Record<string, string> => {\n const out: Record<string, string> = {};\n const q = url.split(\"#\")[0];\n const at = q.indexOf(\"?\");\n if (at < 0) return out;\n const dec = (s: string) => {\n try {\n return decodeURIComponent(s.replace(/\\+/g, \" \"));\n } catch {\n return s;\n }\n };\n for (const pair of q.slice(at + 1).split(\"&\")) {\n if (!pair) continue;\n const eq = pair.indexOf(\"=\");\n const k = dec(eq < 0 ? pair : pair.slice(0, eq));\n if (k && !(k in out)) out[k] = eq < 0 ? \"\" : dec(pair.slice(eq + 1));\n }\n return out;\n};\n\n/** FNV-1a, 32 bit, mapped to [0, 1). Stable across server and browser. */\nexport const hashUnit = (input: string) => {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0) / 4294967296;\n};\n\n/**\n * FNV-1a with murmur3's finalizer, mapped to [0, 1): ids that differ only at the end (\"user-1\", \"user-2\") still spread\n * evenly, so a 30 % rollout reaches about 30 % of people. Flags only; experiments keep `hashUnit` so nobody switches.\n */\nexport const flagUnit = (input: string) => {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n h ^= h >>> 16;\n h = Math.imul(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = Math.imul(h, 0xc2b2ae35);\n h ^= h >>> 16;\n return (h >>> 0) / 4294967296;\n};\n\nconst weightOf = (v: VariantConfig) => (typeof v.weight === \"number\" && v.weight > 0 ? v.weight : 0);\n\n/**\n * The variant a visitor sees: a shipped winner, control while the experiment does not run, else a stable bucket by\n * visitor over the cumulative weights. A version with weight 0 (stopped while its test runs) is never picked, also not\n * as the remainder when the weights add up to a little less than 1; with no weight above 0 everyone gets control.\n */\nexport const assign = (experiment: ExperimentConfig, distinctId: string): VariantId => {\n const control = experiment.variants[0]?.id ?? \"control\";\n if (experiment.winner) return experiment.winner;\n if (experiment.status !== \"running\") return control;\n const u = hashUnit(`${experiment.key}:${distinctId}`);\n let acc = 0;\n let last: VariantId | undefined;\n for (const v of experiment.variants) {\n const w = weightOf(v);\n if (!w) continue;\n acc += w;\n last = v.id;\n if (u < acc) return v.id;\n }\n return last ?? control;\n};\n\n/**\n * The first version each running test gave an id in this page load or app session (0.24.0), in memory only. When the\n * config is read again mid-session (MRRocket moves traffic to the better version while a test runs) the visitor keeps\n * what they see until the next page load or app start. A shipped winner, a stopped test or a version that is gone\n * apply at once. Keyed by test and id, so `identify()` assigns the new id afresh.\n */\nexport type KeptVariants = Map<string, VariantId>;\n\n/** `assign`, kept for the session in `kept` when one is given. */\nexport const assignKept = (experiment: ExperimentConfig, distinctId: string, kept?: KeptVariants): VariantId => {\n if (!kept || experiment.winner || experiment.status !== \"running\") return assign(experiment, distinctId);\n const mark = `${experiment.key}\\n${distinctId}`;\n const was = kept.get(mark);\n if (was !== undefined && experiment.variants.some((v) => v.id === was)) return was;\n const id = assign(experiment, distinctId);\n kept.set(mark, id);\n return id;\n};\n\n/** `\"a:b,c:d\"` → `{ a: \"b\", c: \"d\" }`. Ignores anything malformed. */\nexport const parsePreview = (value: string | string[] | null | undefined): Record<string, VariantId> => {\n const raw = Array.isArray(value) ? value[0] : value;\n if (!raw) return {};\n const out: Record<string, VariantId> = {};\n for (const pair of raw.split(\",\")) {\n const [key, variant] = pair.split(\":\");\n if (key && variant) out[key.trim()] = variant.trim();\n }\n return out;\n};\n\n/** A link that shows one variant of a page, for example in Cockpit's preview frames. */\nexport const previewHref = (url: string, forced: Record<string, VariantId>, embed = true) => {\n const [path, query = \"\"] = url.split(\"?\");\n const params = new URLSearchParams(query);\n const value = Object.entries(forced)\n .map(([k, v]) => `${k}:${v}`)\n .join(\",\");\n if (value) params.set(PREVIEW_PARAM, value);\n if (embed) params.set(EMBED_PARAM, \"1\");\n return `${path}?${params.toString()}`;\n};\n\n/** Whether a test is running (not a shipped winner, not stopped). */\nconst runs = (e: ExperimentConfig) => e.status === \"running\" && !e.winner;\n\n/**\n * Running tests that change the same text (0.24.0): per text id the running tests in config order; the first wins\n * (`textChanges` applies only its words, and only it is exposed by that text). Empty when none overlap.\n */\nexport const overlaps = (config: CockpitConfig | null): { text: string; keys: string[] }[] => {\n const by = new Map<string, string[]>();\n for (const e of config?.experiments ?? []) {\n if (!runs(e)) continue;\n for (const id of new Set(e.variants.flatMap((v) => Object.keys(v.changes ?? {})))) {\n const keys = by.get(id) ?? [];\n if (!keys.includes(e.key)) keys.push(e.key);\n by.set(id, keys);\n }\n }\n return [...by.entries()].filter(([, keys]) => keys.length > 1).map(([text, keys]) => ({ text, keys }));\n};\n\nconst warnedOverlaps = new Set<string>();\n\n/**\n * Tells the developer once per overlap, in the console, which running tests change the same text and which one wins.\n * The React provider calls it in a development build; core stays free of `process` so it runs on Workers and Edge.\n */\nexport const warnOverlaps = (config: CockpitConfig | null) => {\n for (const { text, keys } of overlaps(config))\n for (const other of keys.slice(1)) {\n const id = `${text}|${keys[0]}|${other}`;\n if (warnedOverlaps.has(id)) continue;\n warnedOverlaps.add(id);\n console.warn(`[MRRocket] The running tests \"${keys[0]}\" and \"${other}\" both change the text \"${text}\". \"${keys[0]}\" comes first in the config and wins; \"${other}\" leaves that text alone.`);\n }\n};\n\n/** The running test that owns each text id: the first in config order that changes it. */\nconst textOwners = (config: CockpitConfig | null) => {\n const owner = new Map<string, string>();\n for (const e of config?.experiments ?? []) {\n if (!runs(e)) continue;\n for (const v of e.variants) for (const id of Object.keys(v.changes ?? {})) if (!owner.has(id)) owner.set(id, e.key);\n }\n return owner;\n};\n\n/**\n * The experiments whose variants change the text `id`: showing that text is an exposure to them. Of running tests that\n * overlap on it only the first in config order counts (`overlaps`).\n */\nexport const experimentsOfText = (config: CockpitConfig | null, id: string) => {\n const owner = textOwners(config).get(id);\n return (config?.experiments ?? []).filter((e) => e.variants.some((v) => v.changes && id in v.changes) && (!runs(e) || e.key === owner)).map((e) => e.key);\n};\n\n/**\n * The variant for one experiment, from a forced preview first, then the config. Unknown experiments get control.\n * `distinctId` null (0.24.0): the visitor's id is not known yet (a cookieless page waiting for its `unit`, a server\n * render without one): a running test shows control and should record nothing; shipped winners apply. `kept` keeps\n * versions for the session (`assignKept`).\n */\nexport const resolveVariant = (key: string, config: CockpitConfig | null, distinctId: string | null, preview: Record<string, VariantId>, kept?: KeptVariants): VariantId => {\n if (preview[key]) return preview[key];\n const experiment = config?.experiments.find((e) => e.key === key);\n if (!experiment) return \"control\";\n if (distinctId === null && runs(experiment)) return experiment.variants[0]?.id ?? \"control\";\n return assignKept(experiment, distinctId ?? \"\", kept);\n};\n\n/**\n * Every text change that applies to this visitor: the published texts first, then the shipped winners, then the\n * running tests, each in config order. Control keeps the published (or the page's own) words, so only a non-control\n * variant (assigned, forced in a preview, or a shipped winner) changes them further. Two running tests on one text\n * (0.24.0): the first in config order wins and the other leaves that text alone, so neither group sees the other's\n * words (a console warning in development names both). A variant forced in a preview always shows.\n */\nexport const textChanges = (config: CockpitConfig | null, distinctId: string | null, preview: Record<string, VariantId>, kept?: KeptVariants) => {\n const out: Record<string, string> = { ...(config?.texts ?? {}) };\n const experiments = config?.experiments ?? [];\n const owner = textOwners(config);\n const changesOf = (e: ExperimentConfig) => {\n const id = resolveVariant(e.key, config, distinctId, preview, kept);\n if (id === (e.variants[0]?.id ?? \"control\")) return {};\n return e.variants.find((v) => v.id === id)?.changes ?? {};\n };\n for (const e of experiments) if (!runs(e) && !preview[e.key]) Object.assign(out, changesOf(e));\n for (const e of experiments) {\n if (!runs(e) || preview[e.key]) continue;\n for (const [id, words] of Object.entries(changesOf(e))) if (owner.get(id) === e.key) out[id] = words;\n }\n for (const e of experiments) if (preview[e.key]) Object.assign(out, changesOf(e));\n return out;\n};\n\n/**\n * The query parameter a redirect test adds to the variant's address (`ck_x=<test>:<variant>`): the page there records\n * the exposure and takes it out of the address bar. It also keeps that page from redirecting again.\n */\nexport const EXPOSURE_PARAM = \"ck_x\";\n\n/** What `redirectFor` decided: go to `to`, and/or the redirect test this page belongs to and the visitor's variant. */\nexport interface RedirectDecision {\n /** Where to send the visitor now. Missing for control, which stays on the page. */\n to?: string;\n /** The redirect test, while it runs: record `$exposure` for it (on this page for control, on `to` otherwise). */\n experiment?: string;\n variant?: VariantId;\n}\n\nconst pathOf = (p: string) => p.replace(/\\/+$/, \"\") || \"/\";\n\n/**\n * Where a page sends the visitor, before it shows: a page redirect set in MRRocket first, else a redirect test that runs\n * on this path (the visitor's variant, by the same stable assignment as every test). Null when nothing applies.\n *\n * - The new address keeps the page's query (UTM parameters) and its hash; a running test adds `ck_x=<test>:<variant>`,\n * so the page it lands on records the exposure (and never redirects again).\n * - `distinctId` null (no stable id, as on a server without the `ck_id` cookie): running tests are left to the browser,\n * page redirects and shipped winners still apply.\n * - A redirect to the page itself is ignored.\n */\nexport const redirectFor = (\n config: CockpitConfig | null,\n href: string,\n distinctId: string | null,\n preview: Record<string, VariantId> = {},\n kept?: KeptVariants,\n): RedirectDecision | null => {\n if (!config) return null;\n let here: URL;\n try {\n here = new URL(href);\n } catch {\n return null;\n }\n if (here.searchParams.has(EXPOSURE_PARAM)) return null;\n const path = pathOf(here.pathname);\n const go = (to: string, mark?: string) => {\n let t: URL;\n try {\n t = new URL(to, here);\n } catch {\n return undefined;\n }\n if (!/^https?:$/.test(t.protocol) || (t.origin === here.origin && pathOf(t.pathname) === path)) return undefined;\n here.searchParams.forEach((v, k) => {\n if (!t.searchParams.has(k)) t.searchParams.set(k, v);\n });\n if (mark) t.searchParams.set(EXPOSURE_PARAM, mark);\n if (!t.hash) t.hash = here.hash;\n return t.href;\n };\n for (const r of config.redirects ?? []) {\n const to = r.from && pathOf(r.from) === path ? go(r.to) : undefined;\n if (to) return { to };\n }\n for (const e of config.experiments) {\n if (!e.path || pathOf(e.path) !== path) continue;\n const running = e.status === \"running\" && !e.winner;\n if (running && distinctId === null && !preview[e.key]) return null;\n const variant = resolveVariant(e.key, config, distinctId, preview, kept);\n const url = e.variants.find((v) => v.id === variant)?.url;\n const to = url ? go(url, running ? `${e.key}:${variant}` : undefined) : undefined;\n return running ? { to, experiment: e.key, variant } : to ? { to } : null;\n }\n return null;\n};\n\n/** The test and variant a redirect test's `ck_x` names, when the config has them; null otherwise. */\nexport const exposureFrom = (config: CockpitConfig | null, value: string | null | undefined) => {\n const [key, variant] = (value ?? \"\").split(\":\");\n const e = config?.experiments.find((x) => x.key === key);\n return e && e.variants.some((v) => v.id === variant) ? { experiment: key, variant } : null;\n};\n\n/**\n * The MRRocket API host from `NEXT_PUBLIC_MRROCKET_HOST`. Written as a literal property access on purpose: Next.js\n * inlines `process.env.NEXT_PUBLIC_*` at build time, in the browser bundle and in the server bundle (also on\n * Cloudflare Workers), and only replaces the literal form. Without a bundler (or a `process`) it is undefined.\n */\nexport const envHost = (): string | undefined => {\n try {\n return process.env.NEXT_PUBLIC_MRROCKET_HOST || undefined;\n } catch {\n return undefined;\n }\n};\n\n/** The public key from `NEXT_PUBLIC_MRROCKET_KEY`, the default for the `apiKey` prop. Same literal-access rule as `envHost`. */\nexport const envKey = (): string | undefined => {\n try {\n return process.env.NEXT_PUBLIC_MRROCKET_KEY || undefined;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Where the API lives: the `host` prop, else `NEXT_PUBLIC_MRROCKET_HOST`, else \"\" (the page's own origin, which is how\n * MRRocket's own demo pages call it). Without a trailing slash.\n */\nexport const resolveHost = (host?: string) => (host ?? envHost() ?? \"\").trim().replace(/\\/+$/, \"\");\n\n/** A random visitor id. */\nexport const newDistinctId = () =>\n typeof crypto !== \"undefined\" && \"randomUUID\" in crypto ? crypto.randomUUID() : `ck_${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AQ;AACJ,WAAO;AAAA,EACX;AACJ;AAGO,IAAM,SAAS,MAA0B;AAC5C,MAAI;AACA,WAAO,QAAQ,IAAI,4BAA4B;AAAA,EACnD,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAMO,IAAM,cAAc,CAAC,UAAmB,QAAQ,QAAQ,KAAK,IAAI,KAAK,EAAE,QAAQ,QAAQ,EAAE;AAG1F,IAAM,gBAAgB,MACzB,OAAO,WAAW,eAAe,gBAAgB,SAAS,OAAO,WAAW,IAAI,MAAM,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC,GAAG,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/core.ts"],"sourcesContent":["/**\n * The part of the SDK that runs anywhere: experiment config, variant assignment, preview links and event shapes.\n * No React, no browser APIs, so the server helper, the proxy helper and the client share it.\n */\nimport type { CancelFlowConfig, OnboardingFlow } from \"./flows\";\nimport type { PaywallConfig } from \"./paywall\";\n\nexport type VariantId = string;\n\n/** This build of the SDK. Sent with the config request so MRRocket knows what the site runs (error tracking, flags). */\nexport const SDK_VERSION = \"0.26.0\";\n\n/** One variant of an experiment. `changes` replaces texts that the page marks with `<Text id>`. */\nexport interface VariantConfig {\n id: VariantId;\n /** Share of traffic, 0 to 1. The weights of an experiment add up to 1. */\n weight: number;\n changes?: Record<string, string>;\n /**\n * A redirect test: where this variant sends the visitor instead of the test's page (a path like \"/pricing-b\" or a\n * full address). Control has none and stays. SDK 0.7.0+.\n */\n url?: string;\n}\n\nexport interface ExperimentConfig {\n /** The experiment's key, the same as in Cockpit. */\n key: string;\n status: \"running\" | \"draft\" | \"stopped\";\n /** Control first. */\n variants: VariantConfig[];\n /** A winner that shipped: everyone gets it, and nobody is assigned anymore. */\n winner?: VariantId;\n /** A redirect test: the path of the page it runs on (\"/pricing\"). Visitors there are sent to their variant's `url`. */\n path?: string;\n}\n\n/** A page redirect set in MRRocket (Conversion › Landing pages › Redirect): everyone on `from` goes to `to`. SDK 0.7.0+. */\nexport interface RedirectConfig {\n /** A path of the site, like \"/old-pricing\". */\n from: string;\n /** A path or a full address. */\n to: string;\n}\n\nexport interface CockpitConfig {\n /** The product the public key belongs to. */\n project: string;\n /** The language the server chose for the words below, like \"de\" (`lang` on the request). SDK 0.21.0+. */\n lang?: string;\n /** The SDK's own words: English source word to translation (see words.ts). Absent for English. SDK 0.21.0+. */\n words?: Record<string, string>;\n experiments: ExperimentConfig[];\n /** The product's affiliate program: how many days a partner's referral is kept. Missing without a program. */\n referral?: { cookieDays: number };\n /** Session recordings: present only while the product records (Cockpit › Sessions). See `ReplayConfig`. */\n replay?: ReplayConfig;\n /** Feature flags of the product in Production (MRRocket › Build › Feature flags), evaluated by `useFlag` and `getFlag`. */\n flags?: FlagConfig[];\n /**\n * Published copy for texts the site marks (`<Text id>`, `data-ck-text`): a landing page's headline, subheadline and\n * button (`pricing.headline` …) and a paywall's (`paywall.<placement>.headline` …) as published in MRRocket. A\n * running test's variant changes them on top. Missing when nothing is published. SDK 0.5.0+.\n */\n texts?: Record<string, string>;\n /** The product's live cancel flow (MRRocket › Churn › Cancel flow), for `cancelFlow.open()`. SDK 0.7.0+. */\n cancelFlow?: CancelFlowConfig;\n /** The in-app steps of live onboarding flows (tours, checklists, modals). SDK 0.7.0+. */\n onboarding?: OnboardingFlow[];\n /** The product's brand color (\"#rrggbb\") for the onboarding dialogs when the app passes no accent. SDK 0.18.0+. */\n onboardingAccent?: string;\n /** A live Lifecycle journey has in-app messages: signed-in people ask `/api/sdk/inapp` for theirs. SDK 0.7.0+. */\n messages?: boolean;\n /** Page redirects set in MRRocket; the SDK sends visitors on before the page shows (`redirectFor`). SDK 0.7.0+. */\n redirects?: RedirectConfig[];\n /** Published paywalls with their pages, per placement (MRRocket › Conversion › Paywalls), for `paywall.open()`. SDK 0.14.0+. */\n paywalls?: PaywallConfig[];\n /**\n * The visitor's unit for A/B tests (0.24.0): the same daily visitor hash MRRocket counts a cookieless visitor by\n * (`v_…`, from the key, the day, the address and the browser, with a server secret). Without a signed-in id or the\n * `ck_id` cookie, tests and flags assign by it, so a visitor keeps their version all day across reloads and between\n * server render and browser, and their events carry it as `distinctId`. Held in memory only, never stored on the\n * device (a React Native app leaves it out of its cached config). Missing from an older MRRocket.\n */\n unit?: string;\n}\n\n/** One condition of a flag's audience, on a property of the person (`identify(id, props)`), the id or the page. */\nexport interface FlagCondition {\n /** \"Email\", \"Plan\", \"Country\", \"id\", \"path\" … Matched against the person's properties without regard to case. */\n property: string;\n op: \"is\" | \"is not\" | \"in\" | \"not in\" | \"≥\" | \"in cohort\";\n values: string[];\n}\n\n/** Users who match every condition, of whom `rollout` percent get the flag. No conditions: everyone. */\nexport interface FlagConditionSet {\n conditions: FlagCondition[];\n /** 0 to 100. */\n rollout: number;\n}\n\nexport interface FlagConfig {\n key: string;\n /** Off: everyone gets the off side. */\n on: boolean;\n /** The first set a person matches decides; none matched: off. */\n sets: FlagConditionSet[];\n /** Multivariate flags: the variants and their split in percent (control included). Missing for an on/off flag. */\n variants?: { key: string; split: number; payload?: string }[];\n /**\n * The key of the A/B test the flag measures, while it runs (0.24.0). Reading the flag then records one `$exposure`\n * per page view; `flagExposure` says which version.\n */\n experiment?: string;\n}\n\n/** What a person is for flag conditions: their properties from identify(), their id and the page they are on. */\nexport type FlagPerson = Record<string, unknown>;\n\nconst propOf = (person: FlagPerson, name: string) => {\n const want = name.trim().toLowerCase();\n for (const [k, v] of Object.entries(person)) if (k.toLowerCase() === want) return v;\n return undefined;\n};\n\n/** `\"@acme.com\"` matches every address at that domain; anything else matches the whole value, without regard to case. */\nconst same = (actual: string, value: string) => {\n const a = actual.trim().toLowerCase();\n const v = value.trim().toLowerCase();\n return v.startsWith(\"@\") ? a.endsWith(v) : a === v;\n};\n\nconst matchesCondition = (c: FlagCondition, person: FlagPerson) => {\n // Cohorts live in MRRocket; a browser cannot know them, so a cohort condition never matches here.\n if (c.op === \"in cohort\") return false;\n const raw = propOf(person, c.property);\n const actual = raw === undefined || raw === null ? \"\" : String(raw);\n if (c.op === \"≥\") {\n const a = Number(actual);\n const b = Number(c.values[0]);\n return actual !== \"\" && Number.isFinite(a) && Number.isFinite(b) && a >= b;\n }\n const hit = actual !== \"\" && c.values.some((v) => same(actual, v));\n return c.op === \"is\" || c.op === \"in\" ? hit : !hit;\n};\n\n/**\n * The flag for one person: `false` (off), `true` (on, an on/off flag) or the variant's key (a multivariate flag). The\n * bucket is a stable hash of flag and person, so a person keeps their side as the rollout grows.\n */\nexport const evaluateFlag = (flag: FlagConfig, distinctId: string, person: FlagPerson = {}): boolean | string => {\n if (!flag.on) return false;\n const subject = { id: distinctId, ...person };\n const set = flag.sets.length ? flag.sets.find((s) => s.conditions.every((c) => matchesCondition(c, subject))) : { conditions: [], rollout: 100 };\n if (!set) return false;\n if (flagUnit(`${flag.key}:rollout:${distinctId}`) * 100 >= set.rollout) return false;\n if (!flag.variants?.length) return true;\n const u = flagUnit(`${flag.key}:variant:${distinctId}`) * 100;\n let acc = 0;\n for (const v of flag.variants) {\n acc += v.split;\n if (u < acc) return v.key;\n }\n return flag.variants[flag.variants.length - 1].key;\n};\n\n/** A flag of the config for this person; an unknown flag (or no config) is off. */\nexport const flagFor = (key: string, config: CockpitConfig | null, distinctId: string, person: FlagPerson = {}) => {\n const flag = config?.flags?.find((f) => f.key === key);\n return flag ? evaluateFlag(flag, distinctId, person) : false;\n};\n\n/** The version id MRRocket counts at a position: \"control\" first, then \"a\", \"b\" … (`variantIndex` on the server). */\nexport const versionAt = (i: number): VariantId => (i <= 0 ? \"control\" : String.fromCharCode(96 + Math.min(i, 26)));\n\n/**\n * What reading a flag that measures a running test exposes (0.24.0): `{ experiment, variant }` for `$exposure`, or null\n * when the flag measures none or the person is not in the test (the flag is off, the person outside its audience, or a\n * multivariate flag's rollout leaves them out). A multivariate flag's variants count by position (the first is\n * control, then \"a\", \"b\" …); an on/off flag counts its rollout: on is \"a\", off is control.\n */\nexport const flagExposure = (key: string, config: CockpitConfig | null, distinctId: string, person: FlagPerson = {}): { experiment: string; variant: VariantId } | null => {\n const flag = config?.flags?.find((f) => f.key === key);\n if (!flag?.experiment || !flag.on) return null;\n const subject = { id: distinctId, ...person };\n if (flag.sets.length && !flag.sets.some((s) => s.conditions.every((c) => matchesCondition(c, subject)))) return null;\n const value = evaluateFlag(flag, distinctId, person);\n if (flag.variants?.length) {\n const i = typeof value === \"string\" ? flag.variants.findIndex((v) => v.key === value) : -1;\n return i < 0 ? null : { experiment: flag.experiment, variant: versionAt(i) };\n }\n return { experiment: flag.experiment, variant: value === true ? \"a\" : \"control\" };\n};\n\n/** One JavaScript error as it goes over the wire to `POST /api/sdk/errors`. */\nexport interface ErrorReport {\n /** \"TypeError\", \"Error\" … */\n type: string;\n message: string;\n /** The raw stack, at most 8 KB. MRRocket parses it into frames. */\n stack?: string;\n /** \"onerror\" (uncaught), \"onunhandledrejection\" (a rejected promise nobody caught) or \"manual\" (captureError). */\n mechanism: \"onerror\" | \"onunhandledrejection\" | \"manual\";\n handled: boolean;\n url: string;\n ts: number;\n /** What happened just before: pages and clicks, newest last, at most 20. */\n crumbs?: { ts: number; type: \"navigation\" | \"click\" | \"lifecycle\"; message: string }[];\n /** Your release (a version or commit), from the provider's `release` prop. */\n release?: string;\n distinctId?: string;\n sessionId?: string;\n}\n\n/**\n * Session recordings of a product, from the config. Recording also needs the visitor's own replay consent\n * (`<CockpitProvider replay>` or `setConsent({ replay: true })`); without it nothing is recorded or buffered.\n */\nexport interface ReplayConfig {\n /**\n * Share of sessions uploaded from their start, 0 to 1 (default 0.1). The others keep only the last minute in\n * memory and upload it when something goes wrong: a JS error, a rage click, a `purchase…` or `checkout…` event.\n */\n sampleRate: number;\n}\n\n/**\n * What the SDK may send and store.\n * - \"cookieless\" (default): no cookie, no localStorage. The server counts visitors with a hash of key, date, IP and\n * user agent that changes every day; since 0.24.0 the config hands that hash over as `unit`, kept in memory only, so\n * tests assign by it and events carry it.\n * - \"cookies\": a persistent `ck_id` cookie identifies the visitor across visits, `ck_sid` holds the session.\n * - \"off\": nothing is sent and nothing is stored.\n */\nexport type ConsentMode = \"cookieless\" | \"cookies\" | \"off\";\n\n/** Sent once when a signed-in person withdraws analytics consent, and stored as nothing but that fact on their record. */\nexport const CONSENT_OFF_EVENT = \"$consent_off\";\n\n/**\n * What `setConsent` takes: a mode as before, or the parts to change. `replay` is the separate consent for session\n * recordings (default false); it applies only while analytics is not \"off\".\n *\n * setConsent(\"cookies\");\n * setConsent({ replay: true });\n * setConsent({ analytics: \"cookieless\", replay: false });\n */\nexport type ConsentChoice = ConsentMode | { analytics?: ConsentMode; replay?: boolean };\n\n/** The campaign parameters the SDK reads from the landing URL. */\nexport const UTM_KEYS = [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_term\", \"utm_content\"] as const;\nexport type UtmKey = (typeof UTM_KEYS)[number];\n\n/** One event as it goes over the wire to `POST /api/sdk/events`. */\nexport interface CockpitEvent {\n event: string;\n /**\n * The visitor. In \"cookieless\" mode until identify() it is the config's `unit` (0.24.0, MRRocket's own daily visitor\n * hash, held in memory), or missing before the config has one: the server then makes that hash itself.\n */\n distinctId?: string;\n /** Ends after 30 minutes without an event. */\n sessionId?: string;\n props?: Record<string, unknown>;\n /** Milliseconds since the epoch. */\n ts: number;\n url?: string;\n /** `document.referrer` on the first page of a page load, the previous in-app URL after client-side navigation. */\n referrer?: string;\n utm_source?: string;\n utm_medium?: string;\n utm_campaign?: string;\n utm_term?: string;\n utm_content?: string;\n /** The screen size in CSS pixels (points on a phone). */\n screen?: { w: number; h: number };\n /** The app that sent it (React Native only): MRRocket stores it with the event and fills OS and device from it. */\n app?: AppContext;\n}\n\n/** Where a React Native event comes from. Every field is optional except the platform; nothing identifies the person. */\nexport interface AppContext {\n /** \"ios\" or \"android\" (React Native's `Platform.OS`). */\n platform: string;\n /** The app's version, like \"1.4.0\" (`expo-application`'s `nativeApplicationVersion`). */\n appVersion?: string;\n /** The build number, like \"42\". */\n build?: string;\n /** The OS version, like \"17.4\". */\n osVersion?: string;\n /** The device model, like \"iPhone 15 Pro\" (`expo-device`). */\n deviceModel?: string;\n /** \"phone\", \"tablet\", \"desktop\" or \"tv\" when `expo-device` knows it. */\n deviceType?: string;\n /** The first preferred locale, like \"de-DE\". */\n locale?: string;\n}\n\n/** The query parameter that forces variants, for previews in Cockpit: `?ck_preview=pricing-annual:a,home-hero:control`. */\nexport const PREVIEW_PARAM = \"ck_preview\";\n/** Set when Cockpit embeds the page: nothing is tracked, so previews never count as visits. */\nexport const EMBED_PARAM = \"ck_embed\";\n/**\n * 0.26.0, preview mode: `?mrr_preview=<token>` shows a change that waits for the owner's approval in MRRocket (new copy,\n * a test's version, a rewritten page) on the real page, for the before/after pictures of a request. The SDK reads the\n * change for the token from `GET /api/sdk/preview`, applies it like a shipped winner, and marks the page\n * (`PREVIEW_ATTR`). Nothing is tracked, recorded or stored on the device while the parameter is there.\n */\nexport const PREVIEW_TOKEN_PARAM = \"mrr_preview\";\n/** With `mrr_preview`: the owner edits the page's words in place (`?mrr_preview=<edit token>&mrr_edit=1`). */\nexport const PREVIEW_EDIT_PARAM = \"mrr_edit\";\n/** On `<html>`: \"loading\" while the change is read, \"ready\" once it is on the page, \"failed\" when it could not be read. */\nexport const PREVIEW_ATTR = \"data-mrr-preview\";\n/** On `<html>` beside \"ready\": what of the change found no place on the page, as a JSON list (missing when all did). */\nexport const PREVIEW_MISSED_ATTR = \"data-mrr-preview-missed\";\n/**\n * The words of an unseen status line the SDK adds beside the attributes (`<div role=\"status\" data-mrr-preview-status>`,\n * one transparent pixel): \"mrr-preview-ready\", then what was missed. A browser that can only wait for text and read the\n * page's outline (MRRocket's screenshot browser) knows by it that the change is on the page.\n */\nexport const PREVIEW_READY_TEXT = \"mrr-preview-ready\";\n/** The cookie that keeps a visitor in the same variant across visits. Only written in \"cookies\" mode. */\nexport const ID_COOKIE = \"ck_id\";\n/**\n * The headers a customer's server sends with `GET /api/sdk/config` (and the server key) so MRRocket makes the unit of\n * the visitor it renders for, not of the server itself (0.24.0, `getCockpitConfig({ headers })`).\n */\nexport const VISITOR_IP_HEADER = \"x-mrrocket-visitor-ip\";\nexport const VISITOR_UA_HEADER = \"x-mrrocket-visitor-ua\";\n/** The cookie that holds the session id in \"cookies\" mode. */\nexport const SESSION_COOKIE = \"ck_sid\";\n/** A session ends after this long without an event. */\nexport const SESSION_TIMEOUT_MS = 30 * 60 * 1000;\n\n/** The UTM parameters from a parameter lookup (`URLSearchParams.get` in a browser). Empty values are left out. */\nexport const utmFrom = (get: (name: string) => string | null | undefined): Partial<Record<UtmKey, string>> => {\n const out: Partial<Record<UtmKey, string>> = {};\n for (const key of UTM_KEYS) {\n const value = get(key)?.trim();\n if (value) out[key] = value.slice(0, 150);\n }\n return out;\n};\n\n/** The UTM parameters of a query string, like `\"?utm_source=x\"`. Empty values are left out. */\nexport const readUtm = (search: string): Partial<Record<UtmKey, string>> => {\n const params = new URLSearchParams(search);\n return utmFrom((k) => params.get(k));\n};\n\n/**\n * The query parameters of a URL or query string, without `URLSearchParams` (React Native's is incomplete): `+` is a\n * space, values are percent-decoded, the first of a repeated name wins.\n */\nexport const parseQuery = (url: string): Record<string, string> => {\n const out: Record<string, string> = {};\n const q = url.split(\"#\")[0];\n const at = q.indexOf(\"?\");\n if (at < 0) return out;\n const dec = (s: string) => {\n try {\n return decodeURIComponent(s.replace(/\\+/g, \" \"));\n } catch {\n return s;\n }\n };\n for (const pair of q.slice(at + 1).split(\"&\")) {\n if (!pair) continue;\n const eq = pair.indexOf(\"=\");\n const k = dec(eq < 0 ? pair : pair.slice(0, eq));\n if (k && !(k in out)) out[k] = eq < 0 ? \"\" : dec(pair.slice(eq + 1));\n }\n return out;\n};\n\n/** FNV-1a, 32 bit, mapped to [0, 1). Stable across server and browser. */\nexport const hashUnit = (input: string) => {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0) / 4294967296;\n};\n\n/**\n * FNV-1a with murmur3's finalizer, mapped to [0, 1): ids that differ only at the end (\"user-1\", \"user-2\") still spread\n * evenly, so a 30 % rollout reaches about 30 % of people. Flags only; experiments keep `hashUnit` so nobody switches.\n */\nexport const flagUnit = (input: string) => {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n h ^= h >>> 16;\n h = Math.imul(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = Math.imul(h, 0xc2b2ae35);\n h ^= h >>> 16;\n return (h >>> 0) / 4294967296;\n};\n\nconst weightOf = (v: VariantConfig) => (typeof v.weight === \"number\" && v.weight > 0 ? v.weight : 0);\n\n/**\n * The variant a visitor sees: a shipped winner, control while the experiment does not run, else a stable bucket by\n * visitor over the cumulative weights. A version with weight 0 (stopped while its test runs) is never picked, also not\n * as the remainder when the weights add up to a little less than 1; with no weight above 0 everyone gets control.\n */\nexport const assign = (experiment: ExperimentConfig, distinctId: string): VariantId => {\n const control = experiment.variants[0]?.id ?? \"control\";\n if (experiment.winner) return experiment.winner;\n if (experiment.status !== \"running\") return control;\n const u = hashUnit(`${experiment.key}:${distinctId}`);\n let acc = 0;\n let last: VariantId | undefined;\n for (const v of experiment.variants) {\n const w = weightOf(v);\n if (!w) continue;\n acc += w;\n last = v.id;\n if (u < acc) return v.id;\n }\n return last ?? control;\n};\n\n/**\n * The first version each running test gave an id in this page load or app session (0.24.0), in memory only. When the\n * config is read again mid-session (MRRocket moves traffic to the better version while a test runs) the visitor keeps\n * what they see until the next page load or app start. A shipped winner, a stopped test or a version that is gone\n * apply at once. Keyed by test and id, so `identify()` assigns the new id afresh.\n */\nexport type KeptVariants = Map<string, VariantId>;\n\n/** `assign`, kept for the session in `kept` when one is given. */\nexport const assignKept = (experiment: ExperimentConfig, distinctId: string, kept?: KeptVariants): VariantId => {\n if (!kept || experiment.winner || experiment.status !== \"running\") return assign(experiment, distinctId);\n const mark = `${experiment.key}\\n${distinctId}`;\n const was = kept.get(mark);\n if (was !== undefined && experiment.variants.some((v) => v.id === was)) return was;\n const id = assign(experiment, distinctId);\n kept.set(mark, id);\n return id;\n};\n\n/** One change to a page that marks nothing for MRRocket (a rewritten text, a word the owner edited on the page). */\nexport type PreviewOp =\n /** The words of one element. With `from`, only when the element still reads that (or already the new words). */\n | { op: \"set\"; selector: string; text: string; from?: string }\n /** The page's own text (the element whose paragraphs carry the most words) replaced by this HTML. */\n | { op: \"body\"; html: string }\n /** The browser tab's title and the description search engines read. */\n | { op: \"meta\"; title?: string; description?: string };\n\n/** What `GET /api/sdk/preview?token=…` answers: the waiting change, in the shapes the SDK already applies. */\nexport interface PreviewPayload {\n /** The request's title and the version shown (\"Variant B\"), for the edit bar. */\n title?: string;\n version?: string;\n /** Published copy as it will read once approved, by text id (`pricing.headline`). */\n texts?: Record<string, string>;\n /** Tests that are not running yet (or are changed by the request), added to the config or replacing theirs by key. */\n experiments?: ExperimentConfig[];\n /** The version of each test this preview shows, as `ck_preview` would force it. */\n force?: Record<string, VariantId>;\n /** Other parts of the config as they will be (paywalls, onboarding). */\n config?: Partial<Pick<CockpitConfig, \"paywalls\" | \"onboarding\" | \"onboardingAccent\" | \"cancelFlow\">>;\n ops?: PreviewOp[];\n /** The text ids the request changes: checked on the page, highlighted in edit mode. */\n changed?: string[];\n /** The token may save edits (`PREVIEW_EDIT_PARAM`). */\n edit?: boolean;\n}\n\n/**\n * The config with a waiting change on top, and the versions it forces: texts over the published ones, a test by its\n * key replacing the config's or added to it. Redirects are left out: a preview stays on the page it opened.\n */\nexport const withPreview = (config: CockpitConfig | null, p: PreviewPayload): { config: CockpitConfig; force: Record<string, VariantId> } => {\n const base: CockpitConfig = config ?? { project: \"\", experiments: [] };\n const added = (p.experiments ?? []).filter((e) => e && typeof e.key === \"string\" && Array.isArray(e.variants));\n const keys = new Set(added.map((e) => e.key));\n const { redirects: _left, ...rest } = base;\n return {\n config: {\n ...rest,\n ...(p.config ?? {}),\n experiments: [...base.experiments.filter((e) => !keys.has(e.key)), ...added],\n ...(base.texts || p.texts ? { texts: { ...(base.texts ?? {}), ...(p.texts ?? {}) } } : {}),\n },\n force: { ...(p.force ?? {}) },\n };\n};\n\n/** `\"a:b,c:d\"` → `{ a: \"b\", c: \"d\" }`. Ignores anything malformed. */\nexport const parsePreview = (value: string | string[] | null | undefined): Record<string, VariantId> => {\n const raw = Array.isArray(value) ? value[0] : value;\n if (!raw) return {};\n const out: Record<string, VariantId> = {};\n for (const pair of raw.split(\",\")) {\n const [key, variant] = pair.split(\":\");\n if (key && variant) out[key.trim()] = variant.trim();\n }\n return out;\n};\n\n/** A link that shows one variant of a page, for example in Cockpit's preview frames. */\nexport const previewHref = (url: string, forced: Record<string, VariantId>, embed = true) => {\n const [path, query = \"\"] = url.split(\"?\");\n const params = new URLSearchParams(query);\n const value = Object.entries(forced)\n .map(([k, v]) => `${k}:${v}`)\n .join(\",\");\n if (value) params.set(PREVIEW_PARAM, value);\n if (embed) params.set(EMBED_PARAM, \"1\");\n return `${path}?${params.toString()}`;\n};\n\n/** Whether a test is running (not a shipped winner, not stopped). */\nconst runs = (e: ExperimentConfig) => e.status === \"running\" && !e.winner;\n\n/**\n * Running tests that change the same text (0.24.0): per text id the running tests in config order; the first wins\n * (`textChanges` applies only its words, and only it is exposed by that text). Empty when none overlap.\n */\nexport const overlaps = (config: CockpitConfig | null): { text: string; keys: string[] }[] => {\n const by = new Map<string, string[]>();\n for (const e of config?.experiments ?? []) {\n if (!runs(e)) continue;\n for (const id of new Set(e.variants.flatMap((v) => Object.keys(v.changes ?? {})))) {\n const keys = by.get(id) ?? [];\n if (!keys.includes(e.key)) keys.push(e.key);\n by.set(id, keys);\n }\n }\n return [...by.entries()].filter(([, keys]) => keys.length > 1).map(([text, keys]) => ({ text, keys }));\n};\n\nconst warnedOverlaps = new Set<string>();\n\n/**\n * Tells the developer once per overlap, in the console, which running tests change the same text and which one wins.\n * The React provider calls it in a development build; core stays free of `process` so it runs on Workers and Edge.\n */\nexport const warnOverlaps = (config: CockpitConfig | null) => {\n for (const { text, keys } of overlaps(config))\n for (const other of keys.slice(1)) {\n const id = `${text}|${keys[0]}|${other}`;\n if (warnedOverlaps.has(id)) continue;\n warnedOverlaps.add(id);\n console.warn(`[MRRocket] The running tests \"${keys[0]}\" and \"${other}\" both change the text \"${text}\". \"${keys[0]}\" comes first in the config and wins; \"${other}\" leaves that text alone.`);\n }\n};\n\n/** The running test that owns each text id: the first in config order that changes it. */\nconst textOwners = (config: CockpitConfig | null) => {\n const owner = new Map<string, string>();\n for (const e of config?.experiments ?? []) {\n if (!runs(e)) continue;\n for (const v of e.variants) for (const id of Object.keys(v.changes ?? {})) if (!owner.has(id)) owner.set(id, e.key);\n }\n return owner;\n};\n\n/**\n * The experiments whose variants change the text `id`: showing that text is an exposure to them. Of running tests that\n * overlap on it only the first in config order counts (`overlaps`).\n */\nexport const experimentsOfText = (config: CockpitConfig | null, id: string) => {\n const owner = textOwners(config).get(id);\n return (config?.experiments ?? []).filter((e) => e.variants.some((v) => v.changes && id in v.changes) && (!runs(e) || e.key === owner)).map((e) => e.key);\n};\n\n/**\n * The variant for one experiment, from a forced preview first, then the config. Unknown experiments get control.\n * `distinctId` null (0.24.0): the visitor's id is not known yet (a cookieless page waiting for its `unit`, a server\n * render without one): a running test shows control and should record nothing; shipped winners apply. `kept` keeps\n * versions for the session (`assignKept`).\n */\nexport const resolveVariant = (key: string, config: CockpitConfig | null, distinctId: string | null, preview: Record<string, VariantId>, kept?: KeptVariants): VariantId => {\n if (preview[key]) return preview[key];\n const experiment = config?.experiments.find((e) => e.key === key);\n if (!experiment) return \"control\";\n if (distinctId === null && runs(experiment)) return experiment.variants[0]?.id ?? \"control\";\n return assignKept(experiment, distinctId ?? \"\", kept);\n};\n\n/**\n * Every text change that applies to this visitor: the published texts first, then the shipped winners, then the\n * running tests, each in config order. Control keeps the published (or the page's own) words, so only a non-control\n * variant (assigned, forced in a preview, or a shipped winner) changes them further. Two running tests on one text\n * (0.24.0): the first in config order wins and the other leaves that text alone, so neither group sees the other's\n * words (a console warning in development names both). A variant forced in a preview always shows.\n */\nexport const textChanges = (config: CockpitConfig | null, distinctId: string | null, preview: Record<string, VariantId>, kept?: KeptVariants) => {\n const out: Record<string, string> = { ...(config?.texts ?? {}) };\n const experiments = config?.experiments ?? [];\n const owner = textOwners(config);\n const changesOf = (e: ExperimentConfig) => {\n const id = resolveVariant(e.key, config, distinctId, preview, kept);\n if (id === (e.variants[0]?.id ?? \"control\")) return {};\n return e.variants.find((v) => v.id === id)?.changes ?? {};\n };\n for (const e of experiments) if (!runs(e) && !preview[e.key]) Object.assign(out, changesOf(e));\n for (const e of experiments) {\n if (!runs(e) || preview[e.key]) continue;\n for (const [id, words] of Object.entries(changesOf(e))) if (owner.get(id) === e.key) out[id] = words;\n }\n for (const e of experiments) if (preview[e.key]) Object.assign(out, changesOf(e));\n return out;\n};\n\n/**\n * The query parameter a redirect test adds to the variant's address (`ck_x=<test>:<variant>`): the page there records\n * the exposure and takes it out of the address bar. It also keeps that page from redirecting again.\n */\nexport const EXPOSURE_PARAM = \"ck_x\";\n\n/** What `redirectFor` decided: go to `to`, and/or the redirect test this page belongs to and the visitor's variant. */\nexport interface RedirectDecision {\n /** Where to send the visitor now. Missing for control, which stays on the page. */\n to?: string;\n /** The redirect test, while it runs: record `$exposure` for it (on this page for control, on `to` otherwise). */\n experiment?: string;\n variant?: VariantId;\n}\n\nconst pathOf = (p: string) => p.replace(/\\/+$/, \"\") || \"/\";\n\n/**\n * Where a page sends the visitor, before it shows: a page redirect set in MRRocket first, else a redirect test that runs\n * on this path (the visitor's variant, by the same stable assignment as every test). Null when nothing applies.\n *\n * - The new address keeps the page's query (UTM parameters) and its hash; a running test adds `ck_x=<test>:<variant>`,\n * so the page it lands on records the exposure (and never redirects again).\n * - `distinctId` null (no stable id, as on a server without the `ck_id` cookie): running tests are left to the browser,\n * page redirects and shipped winners still apply.\n * - A redirect to the page itself is ignored.\n */\nexport const redirectFor = (\n config: CockpitConfig | null,\n href: string,\n distinctId: string | null,\n preview: Record<string, VariantId> = {},\n kept?: KeptVariants,\n): RedirectDecision | null => {\n if (!config) return null;\n let here: URL;\n try {\n here = new URL(href);\n } catch {\n return null;\n }\n if (here.searchParams.has(EXPOSURE_PARAM)) return null;\n const path = pathOf(here.pathname);\n const go = (to: string, mark?: string) => {\n let t: URL;\n try {\n t = new URL(to, here);\n } catch {\n return undefined;\n }\n if (!/^https?:$/.test(t.protocol) || (t.origin === here.origin && pathOf(t.pathname) === path)) return undefined;\n here.searchParams.forEach((v, k) => {\n if (!t.searchParams.has(k)) t.searchParams.set(k, v);\n });\n if (mark) t.searchParams.set(EXPOSURE_PARAM, mark);\n if (!t.hash) t.hash = here.hash;\n return t.href;\n };\n for (const r of config.redirects ?? []) {\n const to = r.from && pathOf(r.from) === path ? go(r.to) : undefined;\n if (to) return { to };\n }\n for (const e of config.experiments) {\n if (!e.path || pathOf(e.path) !== path) continue;\n const running = e.status === \"running\" && !e.winner;\n if (running && distinctId === null && !preview[e.key]) return null;\n const variant = resolveVariant(e.key, config, distinctId, preview, kept);\n const url = e.variants.find((v) => v.id === variant)?.url;\n const to = url ? go(url, running ? `${e.key}:${variant}` : undefined) : undefined;\n return running ? { to, experiment: e.key, variant } : to ? { to } : null;\n }\n return null;\n};\n\n/** The test and variant a redirect test's `ck_x` names, when the config has them; null otherwise. */\nexport const exposureFrom = (config: CockpitConfig | null, value: string | null | undefined) => {\n const [key, variant] = (value ?? \"\").split(\":\");\n const e = config?.experiments.find((x) => x.key === key);\n return e && e.variants.some((v) => v.id === variant) ? { experiment: key, variant } : null;\n};\n\n/**\n * The MRRocket API host from `NEXT_PUBLIC_MRROCKET_HOST`. Written as a literal property access on purpose: Next.js\n * inlines `process.env.NEXT_PUBLIC_*` at build time, in the browser bundle and in the server bundle (also on\n * Cloudflare Workers), and only replaces the literal form. Without a bundler (or a `process`) it is undefined.\n */\nexport const envHost = (): string | undefined => {\n try {\n return process.env.NEXT_PUBLIC_MRROCKET_HOST || undefined;\n } catch {\n return undefined;\n }\n};\n\n/** The public key from `NEXT_PUBLIC_MRROCKET_KEY`, the default for the `apiKey` prop. Same literal-access rule as `envHost`. */\nexport const envKey = (): string | undefined => {\n try {\n return process.env.NEXT_PUBLIC_MRROCKET_KEY || undefined;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Where the API lives: the `host` prop, else `NEXT_PUBLIC_MRROCKET_HOST`, else \"\" (the page's own origin, which is how\n * MRRocket's own demo pages call it). Without a trailing slash.\n */\nexport const resolveHost = (host?: string) => (host ?? envHost() ?? \"\").trim().replace(/\\/+$/, \"\");\n\n/** A random visitor id. */\nexport const newDistinctId = () =>\n typeof crypto !== \"undefined\" && \"randomUUID\" in crypto ? crypto.randomUUID() : `ck_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n"],"mappings":";AAUO,IAAM,cAAc;AA8G3B,IAAM,SAAS,CAAC,QAAoB,SAAiB;AACjD,QAAM,OAAO,KAAK,KAAK,EAAE,YAAY;AACrC,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,MAAM,EAAG,KAAI,EAAE,YAAY,MAAM,KAAM,QAAO;AAClF,SAAO;AACX;AAGA,IAAM,OAAO,CAAC,QAAgB,UAAkB;AAC5C,QAAM,IAAI,OAAO,KAAK,EAAE,YAAY;AACpC,QAAM,IAAI,MAAM,KAAK,EAAE,YAAY;AACnC,SAAO,EAAE,WAAW,GAAG,IAAI,EAAE,SAAS,CAAC,IAAI,MAAM;AACrD;AAEA,IAAM,mBAAmB,CAAC,GAAkB,WAAuB;AAE/D,MAAI,EAAE,OAAO,YAAa,QAAO;AACjC,QAAM,MAAM,OAAO,QAAQ,EAAE,QAAQ;AACrC,QAAM,SAAS,QAAQ,UAAa,QAAQ,OAAO,KAAK,OAAO,GAAG;AAClE,MAAI,EAAE,OAAO,UAAK;AACd,UAAM,IAAI,OAAO,MAAM;AACvB,UAAM,I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AAC,MAAM,EAAE,OAAO,OAAO,IAAI,EAAE,YAAY,KAAK,QAAQ,IAAI;AAC1F;AAOO,IAAM,UAAU,MAA0B;AAC7C,MAAI;AACA,WAAO,QAAQ,IAAI,6BAA6B;AAAA,EACpD,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAGO,IAAM,SAAS,MAA0B;AAC5C,MAAI;AACA,WAAO,QAAQ,IAAI,4BAA4B;AAAA,EACnD,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAMO,IAAM,cAAc,CAAC,UAAmB,QAAQ,QAAQ,KAAK,IAAI,KAAK,EAAE,QAAQ,QAAQ,EAAE;AAG1F,IAAM,gBAAgB,MACzB,OAAO,WAAW,eAAe,gBAAgB,SAAS,OAAO,WAAW,IAAI,MAAM,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC,GAAG,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC;","names":[]}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Preview mode on the page (0.26.0), loaded only when the address carries `mrr_preview=<token>`:
|
|
3
|
+
*
|
|
4
|
+
* finishPreview puts what the published texts and forced versions cannot carry onto the page (`ops`), checks that
|
|
5
|
+
* every changed text has its place, and marks `<html data-mrr-preview="ready">` for the screenshot;
|
|
6
|
+
* what found no place is listed in `data-mrr-preview-missed`, never dropped silently
|
|
7
|
+
* startEdit `mrr_edit=1` with a token that may save: a slim bar at the top, the page's words editable in
|
|
8
|
+
* place (text only), Save sends each changed element's selector, old and new words to MRRocket
|
|
9
|
+
*
|
|
10
|
+
* The owner reads the bar, never a visitor: its words are English and stay out of the translated words (words.ts).
|
|
11
|
+
* Nothing here sends an event; the SDK itself tracks nothing while the parameter is there.
|
|
12
|
+
*/
|
|
13
|
+
import { type CockpitConfig, type PreviewPayload, type VariantId } from "./core.js";
|
|
14
|
+
/** One edit the owner made on the page: where, what it read, what it reads now. */
|
|
15
|
+
export interface PreviewEdit {
|
|
16
|
+
selector: string;
|
|
17
|
+
/** The text id when the element is one the site marks (`data-ck-text`). */
|
|
18
|
+
textId?: string;
|
|
19
|
+
from: string;
|
|
20
|
+
to: string;
|
|
21
|
+
}
|
|
22
|
+
/** What `POST /api/sdk/preview/edit` answers. */
|
|
23
|
+
export interface PreviewSaveResult {
|
|
24
|
+
ok: boolean;
|
|
25
|
+
/** Edits written into the request. */
|
|
26
|
+
saved?: number;
|
|
27
|
+
/** Edits handed to the request's agent to put in (words the request did not carry). */
|
|
28
|
+
handed?: number;
|
|
29
|
+
/** Edits that could not be saved, each with why. */
|
|
30
|
+
missed?: {
|
|
31
|
+
selector: string;
|
|
32
|
+
reason: string;
|
|
33
|
+
}[];
|
|
34
|
+
error?: string;
|
|
35
|
+
}
|
|
36
|
+
export interface PreviewEnv {
|
|
37
|
+
host: string;
|
|
38
|
+
token: string;
|
|
39
|
+
edit: boolean;
|
|
40
|
+
/** The page's path, sent with the edits. */
|
|
41
|
+
path: string;
|
|
42
|
+
fetch?: typeof fetch;
|
|
43
|
+
/** Closes the tab or leaves edit mode (Cancel, and Done after a save). */
|
|
44
|
+
leave?: () => void;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The waiting change for the token, and the config with it on top. Null when MRRocket does not answer with one (an
|
|
48
|
+
* expired token, a request that no longer waits): the page then shows as it is and is marked "failed".
|
|
49
|
+
*/
|
|
50
|
+
export declare const readPreview: (host: string, token: string, config: CockpitConfig | null, fetchFn?: typeof fetch) => Promise<{
|
|
51
|
+
payload: PreviewPayload;
|
|
52
|
+
config: CockpitConfig;
|
|
53
|
+
force: Record<string, VariantId>;
|
|
54
|
+
} | null>;
|
|
55
|
+
/** Elements whose words can be edited when they hold text only. */
|
|
56
|
+
export declare const EDITABLE = "h1,h2,h3,h4,h5,h6,p,li,a,button,blockquote,figcaption,label,span,td,th,dt,dd,summary,strong,em,b,i,small,div";
|
|
57
|
+
/** On the span the React `<Text>` renders around its words in preview mode; the element that holds it is the text's element. */
|
|
58
|
+
export declare const WRAP_ATTR = "data-mrr-wrap";
|
|
59
|
+
/** Text only: every child is a text node or a line break (or the one `<Text>` wrapper), and there are words. */
|
|
60
|
+
export declare const holdsOnlyText: (el: Element) => boolean;
|
|
61
|
+
/** A CSS path to the element: from the nearest ancestor with an id, else from `body`, by tag and position. */
|
|
62
|
+
export declare const cssPath: (el: Element) => string;
|
|
63
|
+
/**
|
|
64
|
+
* Applies the ops and checks the changed texts. Returns what found no place: a text id the page does not mark, a
|
|
65
|
+
* selector that is not there, an element that reads something else by now.
|
|
66
|
+
*/
|
|
67
|
+
export declare const applyPreview: (doc: Document, p: PreviewPayload) => string[];
|
|
68
|
+
/**
|
|
69
|
+
* Marks the page for the screenshot: ready, with what was missed (at most 20 entries of 200 characters), on `<html>`
|
|
70
|
+
* and as one unseen status line (`PREVIEW_READY_TEXT`) for a browser that can only wait for text.
|
|
71
|
+
*/
|
|
72
|
+
export declare const markPreview: (doc: Document, state: "loading" | "ready" | "failed", missed?: string[]) => void;
|
|
73
|
+
/** The elements whose words the owner may edit: text only, never the bar, a form field or a `<Text>` wrapper itself. */
|
|
74
|
+
export declare const editableElements: (doc: Document) => Element[];
|
|
75
|
+
export interface PreviewEditor {
|
|
76
|
+
/** The edits made so far. */
|
|
77
|
+
edits: () => PreviewEdit[];
|
|
78
|
+
save: () => Promise<PreviewSaveResult>;
|
|
79
|
+
stop: () => void;
|
|
80
|
+
}
|
|
81
|
+
/** What the bar says after a save, in the owner's words. */
|
|
82
|
+
export declare const savedLine: (r: PreviewSaveResult) => string;
|
|
83
|
+
/**
|
|
84
|
+
* Edit mode: the bar, the editable words and Save. Links and buttons of the page do not act while it is on, so a click
|
|
85
|
+
* places the cursor instead of leaving the page.
|
|
86
|
+
*/
|
|
87
|
+
export declare const startEdit: (doc: Document, p: PreviewPayload, env: PreviewEnv) => PreviewEditor;
|
|
88
|
+
/** The change on the page, the mark for the screenshot, and edit mode when the token allows it. */
|
|
89
|
+
export declare const finishPreview: (doc: Document, p: PreviewPayload, env: PreviewEnv) => {
|
|
90
|
+
missed: string[];
|
|
91
|
+
editor: PreviewEditor | null;
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* The script tag's whole preview in one call: reads the change, answers the config with it on top and `show`, which the
|
|
95
|
+
* script calls once its texts are on the page. Null when there is no change to show.
|
|
96
|
+
*/
|
|
97
|
+
export declare const bootPreview: (host: string, token: string, config: CockpitConfig | null) => Promise<{
|
|
98
|
+
config: CockpitConfig;
|
|
99
|
+
force: Record<string, string>;
|
|
100
|
+
show: () => undefined;
|
|
101
|
+
} | null>;
|
package/dist/preview.js
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
// src/preview.ts
|
|
2
|
+
import { PREVIEW_ATTR, PREVIEW_EDIT_PARAM, PREVIEW_MISSED_ATTR, PREVIEW_READY_TEXT, withPreview } from "./core.js";
|
|
3
|
+
var readPreview = async (host, token, config, fetchFn = fetch) => {
|
|
4
|
+
const res = await fetchFn(`${host}/api/sdk/preview?token=${encodeURIComponent(token)}`);
|
|
5
|
+
const payload = res.ok ? await res.json().catch(() => null) : null;
|
|
6
|
+
return payload && typeof payload === "object" ? { payload, ...withPreview(config, payload) } : null;
|
|
7
|
+
};
|
|
8
|
+
var norm = (s) => (s ?? "").replace(/\s+/g, " ").trim();
|
|
9
|
+
var SKIP = "script,style,noscript,svg,template,iframe,textarea,input,select,option,[data-mrr-bar]";
|
|
10
|
+
var EDITABLE = "h1,h2,h3,h4,h5,h6,p,li,a,button,blockquote,figcaption,label,span,td,th,dt,dd,summary,strong,em,b,i,small,div";
|
|
11
|
+
var WRAP_ATTR = "data-mrr-wrap";
|
|
12
|
+
var onlyWrap = (el) => {
|
|
13
|
+
const only = el.children.length === 1 ? el.children[0] : null;
|
|
14
|
+
return only && only.getAttribute(WRAP_ATTR) !== null && norm(only.textContent) === norm(el.textContent) ? only : null;
|
|
15
|
+
};
|
|
16
|
+
var textIdOf = (el) => el.getAttribute("data-ck-text") || onlyWrap(el)?.getAttribute("data-ck-text") || void 0;
|
|
17
|
+
var holdsOnlyText = (el) => {
|
|
18
|
+
if (!norm(el.textContent)) return false;
|
|
19
|
+
if (onlyWrap(el)) return true;
|
|
20
|
+
for (const n of Array.from(el.childNodes)) {
|
|
21
|
+
if (n.nodeType === 3) continue;
|
|
22
|
+
if (n.nodeType === 1 && n.tagName.toLowerCase() === "br") continue;
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
return true;
|
|
26
|
+
};
|
|
27
|
+
var cssPath = (el) => {
|
|
28
|
+
const parts = [];
|
|
29
|
+
let e = el;
|
|
30
|
+
while (e) {
|
|
31
|
+
const tag = e.tagName.toLowerCase();
|
|
32
|
+
if (tag === "body" || tag === "html") {
|
|
33
|
+
parts.unshift("body");
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
if (e.id && /^[A-Za-z][\w-]*$/.test(e.id)) {
|
|
37
|
+
parts.unshift(`${tag}#${e.id}`);
|
|
38
|
+
break;
|
|
39
|
+
}
|
|
40
|
+
const parent = e.parentElement;
|
|
41
|
+
const same = parent ? Array.from(parent.children).filter((c) => c.tagName === e.tagName) : [e];
|
|
42
|
+
parts.unshift(same.length > 1 ? `${tag}:nth-of-type(${same.indexOf(e) + 1})` : tag);
|
|
43
|
+
e = parent;
|
|
44
|
+
}
|
|
45
|
+
return parts.join(" > ");
|
|
46
|
+
};
|
|
47
|
+
var textBox = (doc) => {
|
|
48
|
+
const marked = doc.querySelector("[data-mrr-body]");
|
|
49
|
+
if (marked) return marked;
|
|
50
|
+
const weight = /* @__PURE__ */ new Map();
|
|
51
|
+
for (const p of Array.from(doc.querySelectorAll("p"))) {
|
|
52
|
+
const n = norm(p.textContent).length;
|
|
53
|
+
if (n < 40 || !p.parentElement || p.closest("header, footer, nav, aside")) continue;
|
|
54
|
+
weight.set(p.parentElement, (weight.get(p.parentElement) ?? 0) + n);
|
|
55
|
+
}
|
|
56
|
+
let best = null;
|
|
57
|
+
for (const [el, n] of weight) if (!best || n > (weight.get(best) ?? 0)) best = el;
|
|
58
|
+
return best ?? doc.querySelector("article") ?? doc.querySelector("main");
|
|
59
|
+
};
|
|
60
|
+
var applyOp = (doc, op) => {
|
|
61
|
+
if (op.op === "set") {
|
|
62
|
+
let el = null;
|
|
63
|
+
try {
|
|
64
|
+
el = doc.querySelector(op.selector);
|
|
65
|
+
} catch {
|
|
66
|
+
return `${op.selector} (not a selector)`;
|
|
67
|
+
}
|
|
68
|
+
if (!el) return `${op.selector} (not on the page)`;
|
|
69
|
+
const now = norm(el.textContent);
|
|
70
|
+
if (op.from !== void 0 && now !== norm(op.from) && now !== norm(op.text)) return `${op.selector} (reads something else now)`;
|
|
71
|
+
el.textContent = op.text;
|
|
72
|
+
el.setAttribute("data-mrr-changed", "");
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
if (op.op === "body") {
|
|
76
|
+
const box = textBox(doc);
|
|
77
|
+
if (!box) return "the page's text (no text block found)";
|
|
78
|
+
box.innerHTML = op.html;
|
|
79
|
+
box.setAttribute("data-mrr-changed", "");
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
if (op.title) doc.title = op.title;
|
|
83
|
+
if (op.description !== void 0) {
|
|
84
|
+
let meta = doc.querySelector('meta[name="description"]');
|
|
85
|
+
if (!meta && doc.head) {
|
|
86
|
+
meta = doc.createElement("meta");
|
|
87
|
+
meta.setAttribute("name", "description");
|
|
88
|
+
doc.head.appendChild(meta);
|
|
89
|
+
}
|
|
90
|
+
meta?.setAttribute("content", op.description);
|
|
91
|
+
}
|
|
92
|
+
return null;
|
|
93
|
+
};
|
|
94
|
+
var applyPreview = (doc, p) => {
|
|
95
|
+
const missed = [];
|
|
96
|
+
for (const id of p.changed ?? []) {
|
|
97
|
+
const marks = Array.from(doc.querySelectorAll("[data-ck-text]")).filter((el) => el.getAttribute("data-ck-text") === id);
|
|
98
|
+
if (!marks.length) missed.push(`${id} (the page does not mark this text)`);
|
|
99
|
+
for (const el of marks) (el.getAttribute(WRAP_ATTR) !== null && el.parentElement ? el.parentElement : el).setAttribute("data-mrr-changed", "");
|
|
100
|
+
}
|
|
101
|
+
for (const op of p.ops ?? []) {
|
|
102
|
+
const miss = applyOp(doc, op);
|
|
103
|
+
if (miss) missed.push(miss);
|
|
104
|
+
}
|
|
105
|
+
return missed;
|
|
106
|
+
};
|
|
107
|
+
var markPreview = (doc, state, missed = []) => {
|
|
108
|
+
const root = doc.documentElement;
|
|
109
|
+
const list = missed.slice(0, 20).map((m) => m.slice(0, 200));
|
|
110
|
+
root.setAttribute(PREVIEW_ATTR, state);
|
|
111
|
+
if (list.length) root.setAttribute(PREVIEW_MISSED_ATTR, JSON.stringify(list));
|
|
112
|
+
else root.removeAttribute(PREVIEW_MISSED_ATTR);
|
|
113
|
+
if (state !== "ready" || !doc.body) return;
|
|
114
|
+
let line = doc.querySelector("[data-mrr-preview-status]");
|
|
115
|
+
if (!line) {
|
|
116
|
+
line = doc.createElement("div");
|
|
117
|
+
line.setAttribute("data-mrr-preview-status", "");
|
|
118
|
+
line.setAttribute("role", "status");
|
|
119
|
+
line.setAttribute("style", "position:fixed;left:0;top:0;width:1px;height:1px;overflow:hidden;opacity:0;pointer-events:none");
|
|
120
|
+
doc.body.appendChild(line);
|
|
121
|
+
}
|
|
122
|
+
line.textContent = list.length ? `${PREVIEW_READY_TEXT} missed: ${list.join(" | ")}` : PREVIEW_READY_TEXT;
|
|
123
|
+
};
|
|
124
|
+
var editableElements = (doc) => Array.from(doc.querySelectorAll(EDITABLE)).filter((el) => !el.closest(SKIP) && el.getAttribute(WRAP_ATTR) === null && holdsOnlyText(el));
|
|
125
|
+
var BAR_CSS = "[data-mrr-bar]{position:fixed;top:0;left:0;right:0;z-index:2147483647;display:flex;align-items:center;gap:12px;height:44px;padding:0 12px;background:#fff;color:#1d2939;border-bottom:1px solid #e4e7ec;font:500 13px/1 Inter,system-ui,-apple-system,sans-serif;box-sizing:border-box}[data-mrr-bar] b{font-weight:600}[data-mrr-bar] span[data-mrr-note]{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#667085}[data-mrr-bar] button{all:unset;box-sizing:border-box;cursor:pointer;height:28px;padding:0 10px;border-radius:6px;font:600 13px/28px Inter,system-ui,sans-serif;color:#344054;box-shadow:inset 0 0 0 1px #d0d5dd;background:#fff}[data-mrr-bar] button[data-mrr-save]{color:#fff;background:#3f76ff;box-shadow:none}[data-mrr-bar] button[disabled]{opacity:.5;cursor:default}[data-mrr-bar] button:focus-visible{outline:2px solid #3f76ff;outline-offset:2px}html[data-mrr-editing]{scroll-padding-top:52px}html[data-mrr-editing] body{margin-top:44px!important}[data-mrr-edit]{cursor:text;outline:1px dashed transparent;outline-offset:2px;border-radius:2px}[data-mrr-edit]:hover{outline-color:#98a2b3}[data-mrr-edit][data-mrr-changed]{outline:1px solid #3f76ff}[data-mrr-edit]:focus{outline:2px solid #3f76ff}[data-mrr-edit][data-mrr-edited]{background:rgba(63,118,255,.08)}";
|
|
126
|
+
var savedLine = (r) => {
|
|
127
|
+
if (!r.ok) return r.error || "Could not save. Open the page from MRRocket again.";
|
|
128
|
+
const parts = [];
|
|
129
|
+
if (r.saved) parts.push(`${r.saved} saved`);
|
|
130
|
+
if (r.handed) parts.push(`${r.handed} handed to the agent`);
|
|
131
|
+
if (r.missed?.length) parts.push(`${r.missed.length} not saved (${r.missed[0].reason})`);
|
|
132
|
+
return parts.length ? `${parts.join(" \xB7 ")}. The request in MRRocket shows the new version.` : "Nothing changed.";
|
|
133
|
+
};
|
|
134
|
+
var startEdit = (doc, p, env) => {
|
|
135
|
+
const root = doc.documentElement;
|
|
136
|
+
root.setAttribute("data-mrr-editing", "");
|
|
137
|
+
const style = doc.createElement("style");
|
|
138
|
+
style.setAttribute("data-mrr-bar-style", "");
|
|
139
|
+
style.textContent = BAR_CSS;
|
|
140
|
+
(doc.head ?? root).appendChild(style);
|
|
141
|
+
const bar = doc.createElement("div");
|
|
142
|
+
bar.setAttribute("data-mrr-bar", "");
|
|
143
|
+
bar.setAttribute("role", "toolbar");
|
|
144
|
+
bar.setAttribute("aria-label", "MRRocket page editor");
|
|
145
|
+
const name = doc.createElement("b");
|
|
146
|
+
name.textContent = "MRRocket";
|
|
147
|
+
const note = doc.createElement("span");
|
|
148
|
+
note.setAttribute("data-mrr-note", "");
|
|
149
|
+
note.setAttribute("aria-live", "polite");
|
|
150
|
+
const idle = `Editing ${[p.title, p.version].filter(Boolean).join(" \xB7 ") || "this page"}. Click any text to change it.`;
|
|
151
|
+
note.textContent = idle;
|
|
152
|
+
const cancel = doc.createElement("button");
|
|
153
|
+
cancel.setAttribute("type", "button");
|
|
154
|
+
cancel.textContent = "Cancel";
|
|
155
|
+
const save = doc.createElement("button");
|
|
156
|
+
save.setAttribute("type", "button");
|
|
157
|
+
save.setAttribute("data-mrr-save", "");
|
|
158
|
+
save.textContent = "Save";
|
|
159
|
+
bar.appendChild(name);
|
|
160
|
+
bar.appendChild(note);
|
|
161
|
+
bar.appendChild(cancel);
|
|
162
|
+
bar.appendChild(save);
|
|
163
|
+
(doc.body ?? root).appendChild(bar);
|
|
164
|
+
const original = /* @__PURE__ */ new Map();
|
|
165
|
+
const els = editableElements(doc);
|
|
166
|
+
for (const el of els) {
|
|
167
|
+
original.set(el, el.textContent ?? "");
|
|
168
|
+
el.setAttribute("data-mrr-edit", "");
|
|
169
|
+
el.setAttribute("contenteditable", "plaintext-only");
|
|
170
|
+
if (el.contentEditable !== void 0 && el.contentEditable !== "plaintext-only") el.setAttribute("contenteditable", "true");
|
|
171
|
+
el.setAttribute("spellcheck", "true");
|
|
172
|
+
}
|
|
173
|
+
const edits = () => els.filter((el) => norm(el.textContent) !== norm(original.get(el))).map((el) => ({ selector: cssPath(el), ...textIdOf(el) ? { textId: textIdOf(el) } : {}, from: norm(original.get(el)), to: norm(el.textContent) }));
|
|
174
|
+
const inBar = (t) => !!(t && t.closest?.("[data-mrr-bar]"));
|
|
175
|
+
const still = (e) => {
|
|
176
|
+
if (inBar(e.target)) return;
|
|
177
|
+
e.preventDefault();
|
|
178
|
+
e.stopPropagation();
|
|
179
|
+
};
|
|
180
|
+
const onKey = (e) => {
|
|
181
|
+
const k = e;
|
|
182
|
+
if (inBar(k.target)) return;
|
|
183
|
+
if (k.key === "Enter") {
|
|
184
|
+
k.preventDefault();
|
|
185
|
+
k.target?.blur?.();
|
|
186
|
+
}
|
|
187
|
+
if (k.key === "Escape") k.target?.blur?.();
|
|
188
|
+
k.stopPropagation();
|
|
189
|
+
};
|
|
190
|
+
const onPaste = (e) => {
|
|
191
|
+
const c = e;
|
|
192
|
+
if (inBar(c.target)) return;
|
|
193
|
+
c.preventDefault();
|
|
194
|
+
const text = c.clipboardData?.getData("text/plain") ?? "";
|
|
195
|
+
const sel = doc.getSelection?.();
|
|
196
|
+
if (!sel?.rangeCount) return;
|
|
197
|
+
sel.deleteFromDocument();
|
|
198
|
+
sel.getRangeAt(0).insertNode(doc.createTextNode(text.replace(/\s+/g, " ")));
|
|
199
|
+
sel.collapseToEnd();
|
|
200
|
+
};
|
|
201
|
+
const onInput = (e) => {
|
|
202
|
+
const el = e.target?.closest?.("[data-mrr-edit]");
|
|
203
|
+
if (!el) return;
|
|
204
|
+
if (norm(el.textContent) !== norm(original.get(el))) el.setAttribute("data-mrr-edited", "");
|
|
205
|
+
else el.removeAttribute("data-mrr-edited");
|
|
206
|
+
const n = edits().length;
|
|
207
|
+
note.textContent = n ? `${n} ${n === 1 ? "change" : "changes"} not saved yet.` : idle;
|
|
208
|
+
};
|
|
209
|
+
const onBlur = (e) => {
|
|
210
|
+
const el = e.target?.closest?.("[data-mrr-edit]");
|
|
211
|
+
if (el && el.children.length && !onlyWrap(el)) el.textContent = norm(el.textContent);
|
|
212
|
+
};
|
|
213
|
+
doc.addEventListener("click", still, true);
|
|
214
|
+
doc.addEventListener("submit", still, true);
|
|
215
|
+
doc.addEventListener("keydown", onKey, true);
|
|
216
|
+
doc.addEventListener("paste", onPaste, true);
|
|
217
|
+
doc.addEventListener("input", onInput, true);
|
|
218
|
+
doc.addEventListener("blur", onBlur, true);
|
|
219
|
+
const stop = () => {
|
|
220
|
+
doc.removeEventListener("click", still, true);
|
|
221
|
+
doc.removeEventListener("submit", still, true);
|
|
222
|
+
doc.removeEventListener("keydown", onKey, true);
|
|
223
|
+
doc.removeEventListener("paste", onPaste, true);
|
|
224
|
+
doc.removeEventListener("input", onInput, true);
|
|
225
|
+
doc.removeEventListener("blur", onBlur, true);
|
|
226
|
+
for (const el of els) {
|
|
227
|
+
el.removeAttribute("contenteditable");
|
|
228
|
+
el.removeAttribute("data-mrr-edit");
|
|
229
|
+
el.removeAttribute("data-mrr-edited");
|
|
230
|
+
el.removeAttribute("spellcheck");
|
|
231
|
+
}
|
|
232
|
+
bar.remove();
|
|
233
|
+
style.remove();
|
|
234
|
+
root.removeAttribute("data-mrr-editing");
|
|
235
|
+
};
|
|
236
|
+
let busy = false;
|
|
237
|
+
const send = async () => {
|
|
238
|
+
const list = edits();
|
|
239
|
+
if (!list.length) return { ok: true, saved: 0 };
|
|
240
|
+
try {
|
|
241
|
+
const res = await (env.fetch ?? fetch)(`${env.host}/api/sdk/preview/edit`, {
|
|
242
|
+
method: "POST",
|
|
243
|
+
headers: { "content-type": "application/json" },
|
|
244
|
+
body: JSON.stringify({ token: env.token, path: env.path, edits: list })
|
|
245
|
+
});
|
|
246
|
+
const body = await res.json().catch(() => null);
|
|
247
|
+
if (!res.ok) return { ok: false, error: body?.error || (res.status === 401 ? "This edit link has expired. Open the page from MRRocket again." : `MRRocket answered ${res.status}.`) };
|
|
248
|
+
return body ?? { ok: false, error: "MRRocket's answer could not be read." };
|
|
249
|
+
} catch {
|
|
250
|
+
return { ok: false, error: "MRRocket could not be reached. Nothing was saved." };
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
save.addEventListener("click", () => {
|
|
254
|
+
if (busy) return;
|
|
255
|
+
busy = true;
|
|
256
|
+
save.setAttribute("disabled", "");
|
|
257
|
+
note.textContent = "Saving\u2026";
|
|
258
|
+
void send().then((r) => {
|
|
259
|
+
busy = false;
|
|
260
|
+
save.removeAttribute("disabled");
|
|
261
|
+
note.textContent = savedLine(r);
|
|
262
|
+
if (!r.ok) return;
|
|
263
|
+
const lost = new Set((r.missed ?? []).map((m) => m.selector));
|
|
264
|
+
for (const el of els) {
|
|
265
|
+
if (lost.has(cssPath(el))) continue;
|
|
266
|
+
original.set(el, el.textContent ?? "");
|
|
267
|
+
el.removeAttribute("data-mrr-edited");
|
|
268
|
+
}
|
|
269
|
+
cancel.textContent = "Done";
|
|
270
|
+
});
|
|
271
|
+
});
|
|
272
|
+
cancel.addEventListener("click", () => {
|
|
273
|
+
for (const el of els) if (norm(el.textContent) !== norm(original.get(el))) el.textContent = original.get(el) ?? "";
|
|
274
|
+
stop();
|
|
275
|
+
env.leave?.();
|
|
276
|
+
});
|
|
277
|
+
return { edits, save: send, stop };
|
|
278
|
+
};
|
|
279
|
+
var finishPreview = (doc, p, env) => {
|
|
280
|
+
const missed = applyPreview(doc, p);
|
|
281
|
+
markPreview(doc, "ready", missed);
|
|
282
|
+
return { missed, editor: env.edit && p.edit && !doc.querySelector("[data-mrr-bar]") ? startEdit(doc, p, env) : null };
|
|
283
|
+
};
|
|
284
|
+
var bootPreview = async (host, token, config) => {
|
|
285
|
+
const r = await readPreview(host, token, config);
|
|
286
|
+
if (!r) return null;
|
|
287
|
+
const edit = new URLSearchParams(window.location.search).get(PREVIEW_EDIT_PARAM) === "1";
|
|
288
|
+
return {
|
|
289
|
+
config: r.config,
|
|
290
|
+
force: r.force,
|
|
291
|
+
show: () => void finishPreview(document, r.payload, { host, token, edit, path: window.location.pathname, leave: () => window.close() })
|
|
292
|
+
};
|
|
293
|
+
};
|
|
294
|
+
export {
|
|
295
|
+
EDITABLE,
|
|
296
|
+
WRAP_ATTR,
|
|
297
|
+
applyPreview,
|
|
298
|
+
bootPreview,
|
|
299
|
+
cssPath,
|
|
300
|
+
editableElements,
|
|
301
|
+
finishPreview,
|
|
302
|
+
holdsOnlyText,
|
|
303
|
+
markPreview,
|
|
304
|
+
readPreview,
|
|
305
|
+
savedLine,
|
|
306
|
+
startEdit
|
|
307
|
+
};
|
|
308
|
+
//# sourceMappingURL=preview.js.map
|