@guidelytech/shared 0.16.0 → 0.17.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/runtime.ts","../src/utils.ts","../src/platform.ts","../src/widgets.ts","../src/targeting-eval.ts","../src/events-util.ts","../src/errors.ts","../src/network.ts","../src/media.ts","../src/resource-center.ts","../src/howto-limits.ts","../src/page.ts","../src/tagging.ts","../src/complaints-limits.ts","../src/agents-limits.ts","../src/localization.ts","../src/guide-experiments.ts","../src/custom-css.ts","../src/contrast.ts"],"sourcesContent":["/**\n * Zod-free entry for browser runtimes: `import { evaluateRules } from \"@guidelytech/shared/runtime\"`.\n * Keeps zod and the schema definitions out of the SDK bundle.\n */\nexport * from \"./utils\";\nexport * from \"./platform\";\nexport * from \"./widgets\";\nexport * from \"./targeting-eval\";\nexport * from \"./events-util\";\nexport * from \"./errors\";\nexport * from \"./network\";\nexport * from \"./media\";\nexport * from \"./resource-center\";\nexport * from \"./howto-limits\";\nexport * from \"./page\";\nexport * from \"./tagging\";\nexport * from \"./complaints-limits\";\nexport * from \"./agents-limits\";\nexport * from \"./localization\";\nexport * from \"./guide-experiments\";\nexport * from \"./custom-css\";\nexport * from \"./contrast\";\n","/** FNV-1a 32-bit hash; deterministic across SDK and server for rollout bucketing. */\nexport function fnv1a(input: string): number {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193) >>> 0;\n }\n return h >>> 0;\n}\n\n/** Deterministic 0-99 bucket for percentage rollouts. */\nexport function rolloutBucket(subject: string, salt: string): number {\n return fnv1a(`${salt}:${subject}`) % 100;\n}\n\nexport function slugify(input: string): string {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 64) || \"untitled\";\n}\n\nconst ALPHABET = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n/** URL-safe random id. Uses crypto when available, falls back to Math.random (ids are not secrets). */\nexport function randomId(size = 16): string {\n const g: any = typeof globalThis !== \"undefined\" ? globalThis : {};\n let bytes: Uint8Array;\n if (g.crypto && typeof g.crypto.getRandomValues === \"function\") {\n bytes = new Uint8Array(size);\n g.crypto.getRandomValues(bytes);\n } else {\n bytes = new Uint8Array(size);\n for (let i = 0; i < size; i++) bytes[i] = Math.floor(Math.random() * 256);\n }\n let out = \"\";\n for (let i = 0; i < size; i++) out += ALPHABET[(bytes[i] as number) % ALPHABET.length];\n return out;\n}\n\nexport function isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** Safe nested getter: get(obj, \"account.plan\") */\nexport function getPath(obj: unknown, path: string): unknown {\n if (!path) return obj;\n let cur: any = obj;\n for (const part of path.split(\".\")) {\n if (cur == null) return undefined;\n cur = cur[part];\n }\n return cur;\n}\n\nexport function clamp(n: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, n));\n}\n\n/** Glob-style URL pattern match: `*` matches any chars except `/`, `**` matches anything. */\nexport function matchUrlPattern(pattern: string, url: string): boolean {\n if (!pattern) return true;\n if (pattern === url) return true;\n const escaped = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*/g, \"__GLOBSTAR__\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/__GLOBSTAR__/g, \".*\");\n const re = new RegExp(`^${escaped}$`);\n return re.test(url) || re.test(stripOrigin(url));\n}\n\nexport function stripOrigin(url: string): string {\n try {\n const u = new URL(url);\n return u.pathname + u.search + u.hash;\n } catch {\n return url;\n }\n}\n\n/** Safe regexp construction with a length cap to limit ReDoS exposure. */\nexport function safeRegExp(source: string, flags = \"i\"): RegExp | null {\n if (!source || source.length > 200) return null;\n try {\n return new RegExp(source, flags);\n } catch {\n return null;\n }\n}\n","/**\n * Cross-platform helpers shared by the web SDK, the React Native SDK and (as a reference for) the\n * native iOS/Android SDKs. Zod-free so it can ship in runtime bundles.\n */\n\n/** Platforms a guide can be delivered to. */\nexport const PLATFORMS = [\"web\", \"ios\", \"android\"] as const;\nexport type Platform = (typeof PLATFORMS)[number];\n\n/** Guides published before platforms existed have no `platforms` field and are web-only. */\nexport const DEFAULT_PLATFORMS: Platform[] = [\"web\"];\n\n/** Platforms a guide config targets (missing field → web only). */\nexport function guidePlatforms(config: { platforms?: readonly string[] | null }): string[] {\n return Array.isArray(config.platforms) ? [...config.platforms] : [...DEFAULT_PLATFORMS];\n}\n\nexport function supportsPlatform(config: { platforms?: readonly string[] | null }, platform: string): boolean {\n return guidePlatforms(config).includes(platform);\n}\n\n/** Attribute web apps put on elements to share a target id with their mobile apps. */\nexport const GUIDELY_ID_ATTRIBUTE = \"data-guidely-id\";\n\n/**\n * Extracts a Guidely target id from a trigger / advance / checklist value so the same guide works on\n * web and mobile. Accepts a bare id (`new-deal`), `#new-deal`, or `[data-guidely-id=\"new-deal\"]`\n * (also `data-testid` / `data-tour`). Returns null for selectors that cannot name a single id.\n */\nexport function guidelyIdFromSelector(value: string | null | undefined): string | null {\n const v = (value ?? \"\").trim();\n if (!v) return null;\n if (/^[A-Za-z0-9_][A-Za-z0-9_\\-:.]*$/.test(v)) return v;\n const hash = v.match(/^#([A-Za-z0-9_][A-Za-z0-9_\\-:.]*)$/);\n if (hash) return hash[1] as string;\n const attr = v.match(/^(?:[a-z][a-z0-9]*)?\\[\\s*data-(?:guidely-id|testid|tour)\\s*=\\s*([\"']?)([^\"'\\]]+)\\1\\s*\\]$/i);\n if (attr) return (attr[2] as string).trim();\n return null;\n}\n\n/**\n * Mobile SDKs have screens instead of URLs. URL-based features (URL patterns, `url_match` triggers,\n * multi-page steps, `url_visited` checklist tasks) match against the screen path `/<ScreenName>`.\n */\nexport function screenPath(screen: string | null | undefined): string {\n const s = (screen ?? \"\").trim();\n if (!s) return \"/\";\n return s.startsWith(\"/\") ? s : `/${s}`;\n}\n\n/**\n * Compares dotted version strings numerically (`2.10.0` > `2.9.3`). Non-numeric parts compare as\n * strings; a missing part counts as 0 (`2.1` == `2.1.0`). Returns -1, 0 or 1, or null when either\n * side is empty.\n */\nexport function compareVersions(a: unknown, b: unknown): -1 | 0 | 1 | null {\n const sa = a == null ? \"\" : String(a).trim().replace(/^v/i, \"\");\n const sb = b == null ? \"\" : String(b).trim().replace(/^v/i, \"\");\n if (!sa || !sb) return null;\n const pa = sa.split(/[.+-]/);\n const pb = sb.split(/[.+-]/);\n const n = Math.max(pa.length, pb.length);\n for (let i = 0; i < n; i++) {\n const x = pa[i] ?? \"0\";\n const y = pb[i] ?? \"0\";\n const nx = /^\\d+$/.test(x) ? Number(x) : NaN;\n const ny = /^\\d+$/.test(y) ? Number(y) : NaN;\n if (!Number.isNaN(nx) && !Number.isNaN(ny)) {\n if (nx !== ny) return nx < ny ? -1 : 1;\n } else if (x !== y) {\n return x < y ? -1 : 1;\n }\n }\n return 0;\n}\n","/**\n * Pure checklist / survey logic shared by every renderer (web runtime, React Native, and the\n * reference for the native SDKs). Zod-free; uses structural types so it stays in the runtime entry.\n */\n\nexport type SurveyAnswer = string | number | boolean | string[];\nexport type SurveyAnswers = Record<string, SurveyAnswer>;\n\nexport interface ShowWhen {\n questionId: string;\n op: \"equals\" | \"lte\" | \"gte\" | \"in\";\n value: string | number | string[];\n}\n\n/** Evaluates a question's `showWhen` condition against current answers. */\nexport function isQuestionVisible(q: { showWhen?: ShowWhen }, answers: SurveyAnswers): boolean {\n if (!q.showWhen) return true;\n const actual = answers[q.showWhen.questionId];\n if (actual === undefined) return false;\n const expected = q.showWhen.value;\n switch (q.showWhen.op) {\n case \"equals\":\n return Array.isArray(actual) ? actual.includes(String(expected)) : String(actual) === String(expected);\n case \"lte\":\n return Number(actual) <= Number(expected);\n case \"gte\":\n return Number(actual) >= Number(expected);\n case \"in\": {\n const list = Array.isArray(expected) ? expected : [String(expected)];\n return Array.isArray(actual) ? actual.some((a) => list.includes(a)) : list.includes(String(actual));\n }\n default:\n return false;\n }\n}\n\n/** Are all required tasks done? */\nexport function isChecklistComplete(config: { tasks: Array<{ id: string; required: boolean }> }, progress: { completedTaskIds: string[] }): boolean {\n const done = new Set(progress.completedTaskIds);\n return config.tasks.filter((t) => t.required).every((t) => done.has(t.id));\n}\n","/**\n * Zod-free targeting evaluation. Imported by the browser SDK via `@guidelytech/shared/runtime`\n * so the runtime bundle does not pull in zod. Schemas live in ./targeting.ts.\n */\nimport { compareVersions } from \"./platform\";\nimport { getPath, matchUrlPattern, rolloutBucket, safeRegExp } from \"./utils\";\n\nexport const RULE_OPERATORS = [\n \"equals\",\n \"not_equals\",\n \"contains\",\n \"not_contains\",\n \"starts_with\",\n \"ends_with\",\n \"exists\",\n \"not_exists\",\n \"gt\",\n \"gte\",\n \"lt\",\n \"lte\",\n \"in\",\n \"not_in\",\n \"regex\",\n \"is_true\",\n \"is_false\",\n \"before\",\n \"after\",\n] as const;\nexport type RuleOperator = (typeof RULE_OPERATORS)[number];\n\nexport const RULE_FIELDS = [\n \"user.attribute\",\n \"account.attribute\",\n \"user.role\",\n \"user.plan\",\n \"user.identified\",\n \"url.path\",\n \"url.full\",\n \"url.query\",\n \"device.type\",\n \"device.browser\",\n \"device.os\",\n \"visitor.firstVisit\",\n \"visitor.returning\",\n \"event.seen\",\n \"guide.completed\",\n \"guide.dismissed\",\n \"guide.seen\",\n \"checklist.completed\",\n \"audience.member\",\n \"datetime.now\",\n \"datetime.dayOfWeek\",\n \"datetime.hour\",\n \"rollout.percentage\",\n /** Guide A/B tests: the visitor's 0-99 bucket for the salt in `key` (see guide-experiments.ts). */\n \"experiment.bucket\",\n \"environment\",\n \"locale\",\n \"app.platform\",\n \"app.screen\",\n \"app.version\",\n \"page.views\",\n \"feature.clicks\",\n] as const;\nexport type RuleField = (typeof RULE_FIELDS)[number];\n\nexport interface Rule {\n id: string;\n field: RuleField;\n /** For attribute/query/event fields: the attribute key, query param name, event name, guide id... */\n key?: string;\n op: RuleOperator;\n value?: string | number | boolean | string[];\n /** When true, the rule is negated (exclusion rule). */\n negate?: boolean;\n}\n\nexport type RuleGroup = {\n id: string;\n op: \"and\" | \"or\";\n rules: Array<Rule | RuleGroup>;\n negate?: boolean;\n};\n\nexport function isRuleGroup(r: Rule | RuleGroup): r is RuleGroup {\n return (r as RuleGroup).rules !== undefined;\n}\n\nexport function emptyRuleGroup(id = \"root\"): RuleGroup {\n return { id, op: \"and\", rules: [] };\n}\n\n/** Everything targeting evaluation can see. Built by the SDK (browser) or the server. */\nexport interface TargetingContext {\n userId?: string | null;\n anonymousId: string;\n userAttributes: Record<string, unknown>;\n accountAttributes: Record<string, unknown>;\n url: string;\n path: string;\n query: Record<string, string>;\n device: { type: \"desktop\" | \"tablet\" | \"mobile\"; browser?: string; os?: string };\n firstVisit: boolean;\n eventsSeen: Set<string> | string[];\n completedGuides: Set<string> | string[];\n dismissedGuides: Set<string> | string[];\n seenGuides: Set<string> | string[];\n completedChecklists: Set<string> | string[];\n audienceIds: Set<string> | string[];\n now: Date;\n environment: string;\n locale?: string;\n /** `web`, `ios` or `android`. Missing means web. */\n platform?: string;\n /** Current screen name (mobile SDKs; set via `screen()`). */\n screen?: string;\n /** Host app version (mobile SDKs), e.g. `2.4.1`. */\n appVersion?: string;\n /** Salt for rollout (guide id). Set per guide before evaluating. */\n rolloutSalt?: string;\n /**\n * Views of tagged pages / clicks on tagged features in the last 30 days, by tag id. Only the server\n * fills it (audience evaluation); in the browser `page.views` / `feature.clicks` read 0.\n */\n tagUsage?: Record<string, number>;\n}\n\nfunction has(set: Set<string> | string[] | undefined, v: string): boolean {\n if (!set) return false;\n return set instanceof Set ? set.has(v) : set.includes(v);\n}\n\nfunction resolveField(rule: Rule, ctx: TargetingContext): unknown {\n switch (rule.field) {\n case \"user.attribute\":\n return rule.key ? getPath(ctx.userAttributes, rule.key) : undefined;\n case \"account.attribute\":\n return rule.key ? getPath(ctx.accountAttributes, rule.key) : undefined;\n case \"user.role\":\n return ctx.userAttributes.role;\n case \"user.plan\":\n return ctx.userAttributes.plan ?? ctx.accountAttributes.plan;\n case \"user.identified\":\n return !!ctx.userId;\n case \"url.path\":\n return ctx.path;\n case \"url.full\":\n return ctx.url;\n case \"url.query\":\n return rule.key ? ctx.query[rule.key] : undefined;\n case \"device.type\":\n return ctx.device.type;\n case \"device.browser\":\n return ctx.device.browser;\n case \"device.os\":\n return ctx.device.os;\n case \"visitor.firstVisit\":\n return ctx.firstVisit;\n case \"visitor.returning\":\n return !ctx.firstVisit;\n case \"event.seen\":\n return rule.key ? has(ctx.eventsSeen, rule.key) : false;\n case \"guide.completed\":\n return rule.key ? has(ctx.completedGuides, rule.key) : false;\n case \"guide.dismissed\":\n return rule.key ? has(ctx.dismissedGuides, rule.key) : false;\n case \"guide.seen\":\n return rule.key ? has(ctx.seenGuides, rule.key) : false;\n case \"checklist.completed\":\n return rule.key ? has(ctx.completedChecklists, rule.key) : false;\n case \"audience.member\":\n return rule.key ? has(ctx.audienceIds, rule.key) : false;\n case \"datetime.now\":\n return ctx.now.toISOString();\n case \"datetime.dayOfWeek\":\n return ctx.now.getDay();\n case \"datetime.hour\":\n return ctx.now.getHours();\n case \"rollout.percentage\":\n return rolloutBucket(ctx.userId || ctx.anonymousId, ctx.rolloutSalt || \"guidely\");\n case \"experiment.bucket\":\n return rule.key ? rolloutBucket(ctx.userId || ctx.anonymousId, rule.key) : undefined;\n case \"environment\":\n return ctx.environment;\n case \"locale\":\n return ctx.locale;\n case \"app.platform\":\n return ctx.platform ?? \"web\";\n case \"app.screen\":\n return ctx.screen;\n case \"app.version\":\n return ctx.appVersion;\n case \"page.views\":\n case \"feature.clicks\":\n return rule.key ? (ctx.tagUsage?.[rule.key] ?? 0) : 0;\n default:\n return undefined;\n }\n}\n\nfunction toNumber(v: unknown): number | null {\n if (typeof v === \"number\") return v;\n if (typeof v === \"string\" && v.trim() !== \"\" && !Number.isNaN(Number(v))) return Number(v);\n if (v instanceof Date) return v.getTime();\n return null;\n}\n\nfunction toDateMs(v: unknown): number | null {\n if (v instanceof Date) return v.getTime();\n if (typeof v === \"string\") {\n const t = Date.parse(v);\n return Number.isNaN(t) ? null : t;\n }\n if (typeof v === \"number\") return v;\n return null;\n}\n\nexport function compare(op: RuleOperator, actual: unknown, expected: Rule[\"value\"]): boolean {\n switch (op) {\n case \"exists\":\n return actual !== undefined && actual !== null && actual !== \"\";\n case \"not_exists\":\n return actual === undefined || actual === null || actual === \"\";\n case \"is_true\":\n return actual === true || actual === \"true\";\n case \"is_false\":\n return actual === false || actual === \"false\";\n case \"equals\":\n if (typeof actual === \"boolean\") return String(actual) === String(expected);\n return String(actual ?? \"\") === String(expected ?? \"\");\n case \"not_equals\":\n return String(actual ?? \"\") !== String(expected ?? \"\");\n case \"contains\":\n return typeof actual === \"string\" && actual.toLowerCase().includes(String(expected ?? \"\").toLowerCase());\n case \"not_contains\":\n return !(typeof actual === \"string\" && actual.toLowerCase().includes(String(expected ?? \"\").toLowerCase()));\n case \"starts_with\":\n return typeof actual === \"string\" && actual.startsWith(String(expected ?? \"\"));\n case \"ends_with\":\n return typeof actual === \"string\" && actual.endsWith(String(expected ?? \"\"));\n case \"gt\":\n case \"gte\":\n case \"lt\":\n case \"lte\": {\n const a = toNumber(actual);\n const b = toNumber(expected);\n if (a === null || b === null) return false;\n return op === \"gt\" ? a > b : op === \"gte\" ? a >= b : op === \"lt\" ? a < b : a <= b;\n }\n case \"in\": {\n const list = Array.isArray(expected) ? expected : String(expected ?? \"\").split(\",\").map((s) => s.trim());\n return list.includes(String(actual ?? \"\"));\n }\n case \"not_in\": {\n const list = Array.isArray(expected) ? expected : String(expected ?? \"\").split(\",\").map((s) => s.trim());\n return !list.includes(String(actual ?? \"\"));\n }\n case \"regex\": {\n const re = safeRegExp(String(expected ?? \"\"));\n return !!re && typeof actual === \"string\" && re.test(actual);\n }\n case \"before\": {\n const a = toDateMs(actual);\n const b = toDateMs(expected);\n return a !== null && b !== null && a < b;\n }\n case \"after\": {\n const a = toDateMs(actual);\n const b = toDateMs(expected);\n return a !== null && b !== null && a > b;\n }\n default:\n return false;\n }\n}\n\nexport function evaluateRule(rule: Rule, ctx: TargetingContext): boolean {\n let result: boolean;\n if (rule.field === \"url.path\" || rule.field === \"url.full\" || rule.field === \"app.screen\") {\n const actual = String(resolveField(rule, ctx) ?? \"\");\n if (rule.op === \"equals\") result = matchUrlPattern(String(rule.value ?? \"\"), actual);\n else if (rule.op === \"not_equals\") result = !matchUrlPattern(String(rule.value ?? \"\"), actual);\n else result = compare(rule.op, actual, rule.value);\n } else if (rule.field === \"app.version\" && [\"equals\", \"not_equals\", \"gt\", \"gte\", \"lt\", \"lte\"].includes(rule.op)) {\n const c = compareVersions(resolveField(rule, ctx), rule.value);\n if (c === null) result = rule.op === \"not_equals\";\n else result = rule.op === \"equals\" ? c === 0 : rule.op === \"not_equals\" ? c !== 0 : rule.op === \"gt\" ? c > 0 : rule.op === \"gte\" ? c >= 0 : rule.op === \"lt\" ? c < 0 : c <= 0;\n } else {\n result = compare(rule.op, resolveField(rule, ctx), rule.value);\n }\n return rule.negate ? !result : result;\n}\n\n/** Evaluate a rule tree. An empty group matches everyone. */\nexport function evaluateRules(group: RuleGroup | null | undefined, ctx: TargetingContext): boolean {\n if (!group || group.rules.length === 0) return group?.negate ? false : true;\n const results = group.rules.map((r) => (isRuleGroup(r) ? evaluateRules(r, ctx) : evaluateRule(r, ctx)));\n const value = group.op === \"and\" ? results.every(Boolean) : results.some(Boolean);\n return group.negate ? !value : value;\n}\n\n/** Fields whose evaluation requires server-held data. Used by docs/UI to annotate rules. */\nexport const SERVER_ASSISTED_FIELDS: RuleField[] = [\"audience.member\", \"guide.completed\", \"guide.dismissed\", \"guide.seen\", \"checklist.completed\", \"page.views\", \"feature.clicks\"];\n\n/** Who a guide is shown to, before its targeting rules: everyone, only signed-in (identified) users, or only anonymous visitors. */\nexport const GUIDE_VISIBILITIES = [\"everyone\", \"identified\", \"anonymous\"] as const;\nexport type GuideVisibility = (typeof GUIDE_VISIBILITIES)[number];\n\n/**\n * Targeting with the visibility folded in as a `user.identified` rule. The server sends guides to SDKs\n * this way, so every SDK applies it through the rules it already evaluates (SDKs that predate the field\n * resolve it as undefined and show the guide to nobody rather than to everyone).\n */\nexport function withVisibility(targeting: RuleGroup, visibility: GuideVisibility | undefined): RuleGroup {\n if (!visibility || visibility === \"everyone\") return targeting;\n return { id: \"visibility\", op: \"and\", rules: [{ id: \"visibility-rule\", field: \"user.identified\", op: visibility === \"identified\" ? \"is_true\" : \"is_false\" }, targeting] };\n}\n\nexport function describeRule(rule: Rule): string {\n const subject = rule.key ? `${rule.field}[${rule.key}]` : rule.field;\n const v = Array.isArray(rule.value) ? rule.value.join(\", \") : rule.value === undefined ? \"\" : String(rule.value);\n return `${rule.negate ? \"NOT \" : \"\"}${subject} ${rule.op.replace(/_/g, \" \")}${v ? ` \"${v}\"` : \"\"}`;\n}\n","/** Reserved property names that are stripped from `properties` to avoid collecting sensitive data. */\nexport const SENSITIVE_PROPERTY_PATTERN = /(password|passwd|secret|token|credit|card|cvv|ssn|iban)/i;\n\nexport const MAX_PROPERTY_BYTES = 8 * 1024;\n\nexport function sanitizeProperties(props: Record<string, unknown> | undefined): Record<string, unknown> {\n if (!props) return {};\n const out: Record<string, unknown> = {};\n let size = 0;\n for (const [k, v] of Object.entries(props)) {\n if (SENSITIVE_PROPERTY_PATTERN.test(k)) continue;\n if (typeof v === \"function\" || typeof v === \"symbol\") continue;\n const str = typeof v === \"string\" ? v : JSON.stringify(v ?? null);\n size += k.length + (str?.length ?? 0);\n if (size > MAX_PROPERTY_BYTES) break;\n out[k.slice(0, 100)] = typeof v === \"string\" ? v.slice(0, 1000) : v;\n }\n return out;\n}\n","import { fnv1a } from \"./utils\";\n\n/** One parsed stack frame. `file` is the script URL (or path) as the browser reported it. */\nexport interface StackFrame {\n fn?: string;\n file?: string;\n line?: number;\n col?: number;\n}\n\n/** Properties carried by an `exception` event (see `docs/product-analytics.md`). */\nexport interface ExceptionProperties {\n type: string;\n message: string;\n frames: StackFrame[];\n /** `onerror` | `unhandledrejection` | `manual` (captureException) | `console`. */\n source?: string;\n handled?: boolean;\n /** App version or commit (SDK option `release`); selects the matching uploaded source maps. */\n release?: string;\n /** Set by the server at ingestion; groups occurrences into an issue. */\n fingerprint?: string;\n}\n\nexport const MAX_STACK_FRAMES = 30;\n\n// Chrome / Edge / Node: \" at fn (https://x/app.js:1:2)\" or \" at https://x/app.js:1:2\"\nconst V8 = /^\\s*at (?:(.+?) \\()?((?:[a-z][\\w+.-]*:)?[^\\s()]+?):(\\d+):(\\d+)\\)?\\s*$/i;\n// Firefox / Safari: \"fn@https://x/app.js:1:2\" or \"@https://x/app.js:1:2\"\nconst GECKO = /^\\s*(.*?)@(.+?):(\\d+):(\\d+)\\s*$/;\n\n/** Parses `Error.stack` from V8, SpiderMonkey and JavaScriptCore into frames (innermost first). */\nexport function parseStack(stack: string | undefined | null, max = MAX_STACK_FRAMES): StackFrame[] {\n if (!stack || typeof stack !== \"string\") return [];\n const frames: StackFrame[] = [];\n for (const raw of stack.split(\"\\n\")) {\n if (frames.length >= max) break;\n const line = raw.slice(0, 1000);\n const m = V8.exec(line) ?? GECKO.exec(line);\n if (!m) continue;\n const fn = (m[1] || \"\").trim();\n frames.push({ fn: fn ? fn.slice(0, 200) : undefined, file: m[2]?.slice(0, 500), line: Number(m[3]), col: Number(m[4]) });\n }\n return frames;\n}\n\n/** Replaces volatile parts of a message (numbers, ids, quoted values) so repeats group together. */\nexport function normalizeErrorMessage(message: string): string {\n return (message || \"\")\n .slice(0, 500)\n .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, \"<uuid>\")\n .replace(/([\"'`]).*?\\1/g, \"<str>\")\n .replace(/\\b0x[0-9a-f]+\\b/gi, \"<hex>\")\n .replace(/\\d+(\\.\\d+)?/g, \"<n>\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\n/** Strips origin, query, hash and build hashes (`main.3f2a1b9c.js` → `main.js`) from a script URL. */\nexport function normalizeFrameFile(file: string | undefined): string {\n if (!file) return \"\";\n let path = file;\n try {\n path = new URL(file).pathname;\n } catch {\n path = file.replace(/[?#].*$/, \"\");\n }\n return path.replace(/[.-][0-9a-f]{6,}(?=\\.\\w+$)/i, \"\").replace(/\\/\\d+\\//g, \"/<n>/\");\n}\n\n/** Source map upload limits (`POST /api/v1/sourcemaps/upload`). */\n/** Per map, uncompressed (the CLI uploads maps gzipped). */\nexport const SOURCEMAP_MAX_FILE_BYTES = 100 * 1024 * 1024;\nexport const SOURCEMAP_MAX_FILES_PER_UPLOAD = 200;\n\n/**\n * Stable issue key for an exception: error type + normalised message + the innermost frame that\n * has a file (path without build hash + function name, or its original source + name when a source\n * map resolved it). Line/column numbers are left out because they change with every deploy of a\n * minified bundle.\n */\nexport function fingerprintError(input: { type?: string; message?: string; frames?: StackFrame[]; original?: { source: string; name?: string | null } | null }): string {\n const top = (input.frames ?? []).find((f) => f.file);\n // With a source map the original file and function name identify the frame across deploys, even\n // when a minifier renames functions between builds.\n const frameKey = input.original ? `src:${input.original.source}:${input.original.name || \"?\"}` : top ? `${normalizeFrameFile(top.file)}:${top.fn || \"?\"}` : \"\";\n const key = [input.type || \"Error\", normalizeErrorMessage(input.message || \"\"), frameKey].join(\"|\");\n const a = fnv1a(key).toString(16).padStart(8, \"0\");\n const b = fnv1a(`guidely:${key}`).toString(16).padStart(8, \"0\");\n return a + b;\n}\n","/* Network requests recorded into session replays (zod-free: imported by the SDK recorder). */\n\n/** rrweb plugin name for network events in recordings (event type 6, `data.plugin`). */\nexport const NETWORK_PLUGIN = \"guidely/network@1\";\n\n/** Request kinds, from `fetch`/`XMLHttpRequest` patching or `PerformanceResourceTiming.initiatorType`. */\nexport type NetworkRequestType = \"fetch\" | \"xhr\" | \"websocket\" | \"document\" | \"script\" | \"stylesheet\" | \"image\" | \"font\" | \"media\" | \"beacon\" | \"other\";\n\n/**\n * One network request in a recording: the payload of an rrweb plugin event\n * `{ type: 6, data: { plugin: NETWORK_PLUGIN, payload: NetworkPluginPayload } }`, batched.\n * Times are epoch milliseconds (same clock as rrweb event timestamps).\n *\n * A WebSocket is a request with `type: \"websocket\"` and `method: \"GET\"`, emitted when it opens\n * (`startTime`) and again, with the same `id`, when it closes (`endTime`, `closeCode`, `closeReason`,\n * totals in `messages`). Its frames are `WebSocketMessage`s referencing that `id`.\n */\nexport interface NetworkRequest {\n /** Stable id within the recording. */\n id: string;\n type: NetworkRequestType;\n method: string;\n /** Absolute URL; values of sensitive-looking query parameters replaced with `[redacted]`. */\n url: string;\n startTime: number;\n endTime?: number;\n durationMs?: number;\n /** HTTP status; 0 for network errors / blocked / aborted. Absent when the browser doesn't expose it. */\n status?: number;\n /** Set for failed requests: network error, abort or timeout message. */\n error?: string;\n /** Encoded bytes transferred / decoded response size, when known. */\n transferSize?: number;\n responseSize?: number;\n /** Only when `recordNetworkPayloads` is on; sensitive headers are `[redacted]`. */\n requestHeaders?: Record<string, string>;\n responseHeaders?: Record<string, string>;\n /** Text/JSON bodies, ≤10KB, sensitive JSON fields masked; `[binary]` / `[truncated]` markers otherwise. */\n requestBody?: string;\n responseBody?: string;\n /** WebSocket only: negotiated subprotocol, close details, and frame totals (all frames, including ones not recorded). */\n protocol?: string;\n closeCode?: number;\n closeReason?: string;\n messages?: { sent: number; received: number; sentBytes: number; receivedBytes: number; recorded: number };\n}\n\n/** One WebSocket frame. At most `WS_MAX_MESSAGES_PER_SOCKET` are recorded per connection per page load. */\nexport interface WebSocketMessage {\n /** The `NetworkRequest.id` of the connection. */\n socketId: string;\n dir: \"send\" | \"recv\";\n time: number;\n /** Bytes (UTF-8 length for text frames). */\n size: number;\n binary?: boolean;\n /** Only with `recordNetworkPayloads`: text ≤ 2KB (JSON with sensitive keys masked), else `[truncated]`; binary frames are `[binary <n> B]`. */\n data?: string;\n}\n\nexport interface NetworkPluginPayload {\n requests?: NetworkRequest[];\n messages?: WebSocketMessage[];\n /** Requests/frames dropped since the previous payload because a cap was reached. */\n dropped?: { requests?: number; messages?: number };\n}\n\nexport const WS_MAX_MESSAGES_PER_SOCKET = 200;\nexport const WS_MAX_MESSAGE_BYTES = 2048;\n\n/** Header names always replaced with `[redacted]` when payload capture is on. */\nexport const SENSITIVE_HEADER_PATTERN = /^(authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token|x-csrf-token|x-xsrf-token|x-guidely-key|x-guidely-conversation)$/i;\n\n/** Query parameter and JSON field names whose values are redacted. */\nexport const SENSITIVE_PARAM_PATTERN = /(token|key|secret|password|passwd|pwd|auth|session|code|sig|signature|credential|ssn|card|cvv|iban)/i;\n","/**\n * Media in article bodies: uploaded images, videos and PDFs, and video embeds from a fixed set of hosts.\n * Sanitizers (server, browser runtime) only keep an `<iframe>` whose `src` is the canonical embed URL\n * that `toEmbedUrl` produces, so authors can never point a frame anywhere else.\n *\n * An uploaded PDF reads inline, as its pages: the dashboard renders each page to an image when the\n * PDF is uploaded, and the body holds plain HTML every renderer already understands:\n *\n * <div class=\"gd-pdf\">\n * <a class=\"gd-file\" href=\"…/{id}.pdf\" target=\"_blank\">{file name}</a>\n * <div class=\"gd-pdf-pages\"><img src=\"…/{page}.webp\" alt=\"{file name}, page 1 of 12\"> …</div>\n * </div>\n *\n * Renderers that know the classes draw a swipeable page viewer with the PDF one tap away; older ones\n * show a link and the pages as images. A PDF whose pages couldn't be rendered (password-protected,\n * damaged) is just the `gd-file` link, drawn as a file card.\n */\n\nexport type EmbedProvider = \"youtube\" | \"vimeo\" | \"loom\" | \"wistia\";\n\nexport interface VideoEmbed {\n provider: EmbedProvider;\n /** Canonical player URL, safe to use as an iframe `src`. */\n src: string;\n /** Page a viewer can open instead (native SDKs show a link rather than a player). */\n watchUrl: string;\n /** Accessible iframe title. */\n title: string;\n}\n\nexport const MEDIA_IMAGE_TYPES = [\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"] as const;\nexport const MEDIA_VIDEO_TYPES = [\"video/mp4\", \"video/webm\"] as const;\nexport const MEDIA_FILE_TYPES = [\"application/pdf\"] as const;\nexport type MediaContentType = (typeof MEDIA_IMAGE_TYPES)[number] | (typeof MEDIA_VIDEO_TYPES)[number] | (typeof MEDIA_FILE_TYPES)[number];\nexport type MediaKind = \"image\" | \"video\" | \"file\";\nexport const MEDIA_IMAGE_MAX_BYTES = 10 * 1024 * 1024;\nexport const MEDIA_VIDEO_MAX_BYTES = 200 * 1024 * 1024;\nexport const MEDIA_FILE_MAX_BYTES = 50 * 1024 * 1024;\n/** The largest upload of any type. */\nexport const MEDIA_MAX_BYTES = Math.max(MEDIA_IMAGE_MAX_BYTES, MEDIA_VIDEO_MAX_BYTES, MEDIA_FILE_MAX_BYTES);\n\nexport function isMediaContentType(type: string): type is MediaContentType {\n return mediaKind(type) !== null;\n}\nexport function isVideoContentType(type: string): boolean {\n return (MEDIA_VIDEO_TYPES as readonly string[]).includes(type);\n}\nexport function mediaKind(type: string): MediaKind | null {\n if ((MEDIA_IMAGE_TYPES as readonly string[]).includes(type)) return \"image\";\n if ((MEDIA_VIDEO_TYPES as readonly string[]).includes(type)) return \"video\";\n if ((MEDIA_FILE_TYPES as readonly string[]).includes(type)) return \"file\";\n return null;\n}\nexport function mediaMaxBytes(type: string): number {\n const kind = mediaKind(type);\n return kind === \"video\" ? MEDIA_VIDEO_MAX_BYTES : kind === \"file\" ? MEDIA_FILE_MAX_BYTES : MEDIA_IMAGE_MAX_BYTES;\n}\n\n/** Class marking a link as an attached file (an uploaded PDF), drawn as a file card. */\nexport const FILE_LINK_CLASS = \"gd-file\";\n/** Class of the block holding a PDF's link and its rendered pages. */\nexport const PDF_BLOCK_CLASS = \"gd-pdf\";\n/** Class of the element wrapping a PDF's page images. */\nexport const PDF_PAGES_CLASS = \"gd-pdf-pages\";\n/** Pages rendered inline per PDF; readers open the PDF itself for the rest. */\nexport const PDF_MAX_PAGES = 40;\n\n/** True for an `<a>` with the file class and an absolute http(s) `href`: render it as a file card. */\nexport function isFileLink(className: string | null | undefined, href: string | null | undefined): boolean {\n return !!className && className.split(/\\s+/).includes(FILE_LINK_CLASS) && isSafeMediaUrl(href);\n}\n\nconst YOUTUBE_ID = /^[A-Za-z0-9_-]{11}$/;\nconst VIMEO_ID = /^\\d{1,12}$/;\nconst VIMEO_HASH = /^[0-9a-f]{6,20}$/i;\nconst LOOM_ID = /^[0-9a-f]{32}$/i;\nconst WISTIA_ID = /^[a-z0-9]{10}$/i;\n\nfunction parseUrl(input: string): URL | null {\n const s = input.trim();\n if (!s) return null;\n try {\n const u = new URL(/^[a-z][a-z0-9+.-]*:/i.test(s) ? s : `https://${s}`);\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n if (u.username || u.password || (u.port && u.port !== \"443\" && u.port !== \"80\")) return null;\n return u;\n } catch {\n return null;\n }\n}\n\n/** \"1h2m3s\", \"90s\", \"90\" → seconds. */\nfunction parseStart(v: string | null): number {\n if (!v) return 0;\n if (/^\\d+$/.test(v)) return Math.min(Number(v), 86400);\n const m = /^(?:(\\d+)h)?(?:(\\d+)m)?(?:(\\d+)s)?$/.exec(v);\n if (!m || !m[0]) return 0;\n return Math.min(Number(m[1] ?? 0) * 3600 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0), 86400);\n}\n\nfunction youtube(id: string, start: number): VideoEmbed | null {\n if (!YOUTUBE_ID.test(id)) return null;\n return {\n provider: \"youtube\",\n src: `https://www.youtube-nocookie.com/embed/${id}${start ? `?start=${start}` : \"\"}`,\n watchUrl: `https://www.youtube.com/watch?v=${id}${start ? `&t=${start}s` : \"\"}`,\n title: \"YouTube video\",\n };\n}\n\nfunction vimeo(id: string, hash: string | null): VideoEmbed | null {\n if (!VIMEO_ID.test(id) || (hash !== null && !VIMEO_HASH.test(hash))) return null;\n const h = hash ? hash.toLowerCase() : null;\n return { provider: \"vimeo\", src: `https://player.vimeo.com/video/${id}${h ? `?h=${h}` : \"\"}`, watchUrl: `https://vimeo.com/${id}${h ? `/${h}` : \"\"}`, title: \"Vimeo video\" };\n}\n\n/**\n * Turns a pasted video page or player URL from YouTube, Vimeo, Loom or Wistia into its canonical\n * embed. Returns null for anything else, including lookalike hosts.\n */\nexport function toEmbedUrl(input: string): VideoEmbed | null {\n const u = parseUrl(input);\n if (!u) return null;\n const host = u.hostname.toLowerCase().replace(/^www\\./, \"\");\n const parts = u.pathname.split(\"/\").filter(Boolean);\n switch (host) {\n case \"youtube.com\":\n case \"m.youtube.com\":\n case \"youtube-nocookie.com\": {\n const start = parseStart(u.searchParams.get(\"start\") ?? u.searchParams.get(\"t\"));\n if (parts[0] === \"watch\" && parts.length === 1) return youtube(u.searchParams.get(\"v\") ?? \"\", start);\n if ((parts[0] === \"embed\" || parts[0] === \"shorts\" || parts[0] === \"live\") && parts.length === 2) return youtube(parts[1]!, start);\n return null;\n }\n case \"youtu.be\":\n return parts.length === 1 ? youtube(parts[0]!, parseStart(u.searchParams.get(\"t\") ?? u.searchParams.get(\"start\"))) : null;\n case \"vimeo.com\":\n if (parts.length === 1) return vimeo(parts[0]!, null);\n if (parts.length === 2 && VIMEO_ID.test(parts[0]!)) return vimeo(parts[0]!, parts[1]!);\n return null;\n case \"player.vimeo.com\":\n return parts[0] === \"video\" && parts.length === 2 ? vimeo(parts[1]!, u.searchParams.get(\"h\")) : null;\n case \"loom.com\":\n if ((parts[0] === \"share\" || parts[0] === \"embed\") && parts.length === 2 && LOOM_ID.test(parts[1]!)) {\n const id = parts[1]!.toLowerCase();\n return { provider: \"loom\", src: `https://www.loom.com/embed/${id}`, watchUrl: `https://www.loom.com/share/${id}`, title: \"Loom video\" };\n }\n return null;\n default: {\n let id: string | undefined;\n if (host === \"fast.wistia.net\" || host === \"fast.wistia.com\") id = parts[0] === \"embed\" && parts[1] === \"iframe\" && parts.length === 3 ? parts[2] : undefined;\n else if (host === \"wi.st\" || host === \"wistia.com\" || /^[a-z0-9-]+\\.wistia\\.com$/.test(host)) id = parts[0] === \"medias\" && parts.length === 2 ? parts[1] : undefined;\n if (!id || !WISTIA_ID.test(id)) return null;\n return { provider: \"wistia\", src: `https://fast.wistia.net/embed/iframe/${id}`, watchUrl: `https://fast.wistia.net/embed/iframe/${id}`, title: \"Wistia video\" };\n }\n }\n}\n\n/** True only for a canonical embed URL (exactly what `toEmbedUrl` returns), so an iframe can't be pointed elsewhere. */\nexport function isAllowedEmbedSrc(src: string | null | undefined): boolean {\n if (!src) return false;\n return toEmbedUrl(src)?.src === src;\n}\n\n/** Fixed iframe attributes for an embed; sanitizers overwrite whatever the author's HTML carried. */\nexport const EMBED_IFRAME_ATTRS: Readonly<Record<string, string>> = {\n allow: \"fullscreen; picture-in-picture; encrypted-media\",\n allowfullscreen: \"\",\n loading: \"lazy\",\n referrerpolicy: \"strict-origin-when-cross-origin\",\n sandbox: \"allow-scripts allow-same-origin allow-presentation allow-popups allow-popups-to-escape-sandbox\",\n};\n\n/** Fixed `<video>` attributes: player controls, no autoplay or loop. */\nexport const VIDEO_ATTRS: Readonly<Record<string, string>> = { controls: \"\", preload: \"metadata\", playsinline: \"\" };\n\n/** `<video src>` / `poster` must be plain http(s): no data:, blob: or relative URLs (bodies render on customer sites). */\nexport function isSafeMediaUrl(url: string | null | undefined): boolean {\n if (!url) return false;\n try {\n const u = new URL(url);\n return (u.protocol === \"https:\" || u.protocol === \"http:\") && !u.username && !u.password;\n } catch {\n return false;\n }\n}\n\n/**\n * Still image for a guide step's video (`videoUrl`): YouTube serves one per video; other hosts don't\n * without an API call, so those steps use their own image (`imageUrl`) as the poster, or a plain tile.\n */\nexport function videoThumbnailUrl(url: string | null | undefined): string | null {\n const embed = url ? toEmbedUrl(url) : null;\n if (embed?.provider !== \"youtube\") return null;\n const id = embed.src.split(\"/embed/\")[1]?.split(\"?\")[0];\n return id ? `https://i.ytimg.com/vi/${id}/hqdefault.jpg` : null;\n}\n\n/** A video file a `<video>` can load directly (shows its first frame when there's no poster). */\nexport function isVideoFileUrl(url: string | null | undefined): boolean {\n return isSafeMediaUrl(url) && /\\.(mp4|webm|m4v|mov|ogv)$/i.test(new URL(url!).pathname);\n}\n\n/**\n * The video shown on a guide step: a poster with a play button that opens `url` in a new tab.\n * `poster` is the step's image, else the provider's thumbnail; null means draw a plain tile.\n */\nexport function stepVideo(step: { videoUrl?: string | null; imageUrl?: string | null }): { url: string; poster: string | null } | null {\n if (!step.videoUrl || !isSafeMediaUrl(step.videoUrl)) return null;\n return { url: step.videoUrl, poster: (step.imageUrl && isSafeMediaUrl(step.imageUrl) ? step.imageUrl : null) ?? videoThumbnailUrl(step.videoUrl) };\n}\n","/**\n * Resource center structure shared by every SDK: nested collections and audience targeting.\n *\n * Audience targeting decides what the help widget lists; it is not access control. The published\n * config (and every article body) is the same for all visitors of an environment, and end-user\n * identities are self-asserted, so never rely on it to keep an article private.\n */\n\n/** Collections nest at most this deep (a collection, its sections, and their sub-sections). */\nexport const MAX_COLLECTION_DEPTH = 3;\n\nexport interface RcCollectionLike {\n id: string;\n name: string;\n order: number;\n /** Parent collection; null/absent for a top-level collection. */\n parentId?: string | null;\n /** Shown only to members of any of these audiences; empty/absent means everyone. */\n audienceIds?: string[];\n}\n\nexport interface RcArticleLike {\n id: string;\n collectionId?: string | null;\n audienceIds?: string[];\n}\n\nexport interface RcSection<C extends RcCollectionLike, A extends RcArticleLike> {\n /** null for articles outside any (known) collection. */\n collection: C | null;\n /** Collection names from the top level down, e.g. [\"Billing\", \"Invoices\"]. */\n path: string[];\n /** 0 for a top-level collection. */\n depth: number;\n articles: A[];\n}\n\ntype Membership = ReadonlySet<string> | readonly string[] | undefined | null;\n\n/** True when an item targeted at `required` audiences is shown to someone in `member`. */\nexport function matchesAudiences(required: readonly string[] | undefined | null, member: Membership): boolean {\n if (!required || required.length === 0) return true;\n if (!member) return false;\n const has = member instanceof Set ? (id: string) => member.has(id) : (id: string) => (member as readonly string[]).includes(id);\n return required.some(has);\n}\n\n/**\n * Article sections in display order: each collection (depth first, siblings by `order`) with the\n * visible articles filed directly in it, then the uncategorized articles. A collection the viewer\n * isn't targeted by hides its whole subtree, and sections without visible articles are left out\n * (their sub-collections still appear). Unknown parents count as top level, so an old config or a\n * dangling reference never hides content.\n */\nexport function resourceCenterSections<C extends RcCollectionLike, A extends RcArticleLike>(collections: readonly C[], articles: readonly A[], member?: Membership): Array<RcSection<C, A>> {\n const byId = new Map(collections.map((c) => [c.id, c]));\n const children = new Map<string | null, C[]>();\n for (const c of collections) {\n const parent = c.parentId && c.parentId !== c.id && byId.has(c.parentId) ? c.parentId : null;\n const list = children.get(parent) ?? [];\n list.push(c);\n children.set(parent, list);\n }\n for (const list of children.values()) list.sort((a, b) => a.order - b.order || a.name.localeCompare(b.name));\n const direct = new Map<string, A[]>();\n const uncategorized: A[] = [];\n for (const a of articles) {\n if (!matchesAudiences(a.audienceIds, member)) continue;\n if (a.collectionId && byId.has(a.collectionId)) {\n const list = direct.get(a.collectionId) ?? [];\n list.push(a);\n direct.set(a.collectionId, list);\n } else uncategorized.push(a);\n }\n\n const sections: Array<RcSection<C, A>> = [];\n const seen = new Set<string>();\n const visit = (c: C, path: string[]) => {\n // A parent cycle in bad data would otherwise recurse forever; cycle members simply don't show.\n if (seen.has(c.id)) return;\n seen.add(c.id);\n if (!matchesAudiences(c.audienceIds, member)) return;\n const here = [...path, c.name];\n const list = direct.get(c.id);\n if (list?.length) sections.push({ collection: c, path: here, depth: here.length - 1, articles: list });\n for (const child of children.get(c.id) ?? []) visit(child, here);\n };\n for (const root of children.get(null) ?? []) visit(root, []);\n if (uncategorized.length) sections.push({ collection: null, path: [], depth: 0, articles: uncategorized });\n return sections;\n}\n\n/**\n * Whether one article is listed for a viewer: its own audiences and those of every collection above\n * it must match. For articles outside a loaded list (e.g. server search results).\n */\nexport function isArticleListed(collections: readonly RcCollectionLike[], article: RcArticleLike, member?: Membership): boolean {\n if (!matchesAudiences(article.audienceIds, member)) return false;\n const byId = new Map(collections.map((c) => [c.id, c]));\n let cur = article.collectionId ? byId.get(article.collectionId) : undefined;\n for (let guard = 0; cur && guard <= MAX_COLLECTION_DEPTH * 4; guard++) {\n if (!matchesAudiences(cur.audienceIds, member)) return false;\n cur = cur.parentId ? byId.get(cur.parentId) : undefined;\n }\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// Logged-in only articles\n// ---------------------------------------------------------------------------\n\n/** Who an article is listed for, besides its audiences: everyone, or logged-in (identified) visitors only. */\nexport const ARTICLE_VISIBILITIES = [\"everyone\", \"identified\"] as const;\nexport type ArticleVisibility = (typeof ARTICLE_VISIBILITIES)[number];\n\n/**\n * Reserved audience every logged-in visitor belongs to. The server folds an article's visibility into\n * the audiences it serves and adds this one to identified visitors' memberships, so every SDK (old ones\n * too) applies \"logged-in only\" through the audience matching it already does. Anonymous visitors never\n * identify, so their membership is empty and these articles stay hidden.\n */\nexport const LOGGED_IN_AUDIENCE = \"$identified\";\n\n/**\n * The audiences an article is served with. Logged-in only with no audiences becomes the reserved\n * audience; with audiences it is already implied, since audience membership only comes from identify.\n */\nexport function servedArticleAudiences(audienceIds: readonly string[], visibility: ArticleVisibility | string | null | undefined): string[] {\n return visibility === \"identified\" && audienceIds.length === 0 ? [LOGGED_IN_AUDIENCE] : [...audienceIds];\n}\n\n/** A visitor's memberships as matched against served articles: logged-in visitors are also in `LOGGED_IN_AUDIENCE`. */\nexport function visitorAudiences(audienceIds: readonly string[], identified: boolean): string[] {\n const ids = audienceIds.filter((id) => id !== LOGGED_IN_AUDIENCE);\n return identified ? [...ids, LOGGED_IN_AUDIENCE] : ids;\n}\n\n/** Ids of the articles a viewer sees (for filtering server search results the same way). */\nexport function visibleArticleIds(collections: readonly RcCollectionLike[], articles: readonly RcArticleLike[], member?: Membership): Set<string> {\n return new Set(resourceCenterSections(collections, articles, member).flatMap((s) => s.articles.map((a) => a.id)));\n}\n\n// ---------------------------------------------------------------------------\n// \"Show me\" prompts in help articles\n// ---------------------------------------------------------------------------\n\n/**\n * A \"Show me\" prompt in an article body is a plain link, `<p class=\"gd-show-me\"><a href=\"#guidely-show-me:<guide key>\">Show me how</a></p>`,\n * so it survives every sanitizer and reads as a harmless link anywhere else. The widgets turn it into a\n * button that starts the walkthrough (a live flow guide), or hide it when that guide isn't available.\n */\nexport const SHOW_ME_CLASS = \"gd-show-me\";\nexport const SHOW_ME_HREF_PREFIX = \"#guidely-show-me:\";\nconst SHOW_ME_KEY = /^[A-Za-z0-9_-]{1,64}$/;\n\nexport function showMeHref(guideKey: string): string {\n return `${SHOW_ME_HREF_PREFIX}${guideKey}`;\n}\n\n/** The guide key of a Show me link's `href`, or null. */\nexport function showMeKeyFromHref(href: string | null | undefined): string | null {\n if (!href || !href.startsWith(SHOW_ME_HREF_PREFIX)) return null;\n const key = href.slice(SHOW_ME_HREF_PREFIX.length);\n return SHOW_ME_KEY.test(key) ? key : null;\n}\n\n/** Guide keys of the Show me prompts in an article body, in order, without repeats (at most 10). */\nexport function showMeKeys(html: string | null | undefined): string[] {\n const out: string[] = [];\n for (const m of (html ?? \"\").matchAll(/href=\"#guidely-show-me:([A-Za-z0-9_-]{1,64})\"/g)) if (!out.includes(m[1]!)) out.push(m[1]!);\n return out.slice(0, 10);\n}\n\n/** The article body plays a video (uploaded, or embedded from YouTube, Vimeo, Loom or Wistia). */\nexport function hasVideoMedia(html: string | null | undefined): boolean {\n return /<(video|iframe)\\b/i.test(html ?? \"\");\n}\n\nconst words = (s: string) => s.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? [];\n\n/**\n * Help search on the device: every word of the query starts a word of the text, in any order, or the\n * query appears as typed. \"add user\" finds \"Add a new user\" and \"Users › Add\".\n */\nexport function matchesHelpQuery(text: string, query: string): boolean {\n const q = query.trim().toLowerCase();\n if (!q) return true;\n const hay = text.toLowerCase();\n if (hay.includes(q)) return true;\n const terms = words(q);\n if (!terms.length) return false;\n const have = words(hay);\n return terms.every((t) => have.some((w) => w.startsWith(t) || (t.length > 3 && t.endsWith(\"s\") && w.startsWith(t.slice(0, -1)))));\n}\n\n// ---------------------------------------------------------------------------\n// Modules (section order + targeting) and \"What's new\"\n// ---------------------------------------------------------------------------\n\nexport const RC_MODULE_IDS = [\"announcements\", \"search\", \"checklists\", \"guides\", \"articles\", \"links\", \"faqs\"] as const;\nexport type ResourceCenterModuleId = (typeof RC_MODULE_IDS)[number];\n\nexport const RC_MODULE_LABELS: Record<ResourceCenterModuleId, string> = {\n announcements: \"What's new\",\n search: \"Search\",\n checklists: \"Checklists\",\n guides: \"Guides & tours\",\n articles: \"Articles\",\n links: \"Links\",\n faqs: \"FAQs\",\n};\n\n/**\n * The resource center's sections in display order: the configured modules (unknown ids dropped,\n * missing ones appended enabled, in the default order), so an old config shows every section.\n */\nexport function orderedModules<M extends { id: string; enabled: boolean }>(modules: readonly M[] | null | undefined): Array<M | { id: ResourceCenterModuleId; enabled: true }> {\n const known = (modules ?? []).filter((m, i, all) => (RC_MODULE_IDS as readonly string[]).includes(m.id) && all.findIndex((x) => x.id === m.id) === i);\n const missing = RC_MODULE_IDS.filter((id) => !known.some((m) => m.id === id)).map((id) => ({ id, enabled: true as const }));\n return [...known, ...missing];\n}\n\n/** Announcements a visitor sees: published (not in the future), audience-matched, newest first. */\nexport function visibleAnnouncements<A extends { publishedAt: string; audienceIds?: string[] }>(items: readonly A[] | null | undefined, member?: Membership, now: number = Date.now()): A[] {\n return (items ?? [])\n .filter((a) => {\n const t = Date.parse(a.publishedAt);\n return !Number.isNaN(t) && t <= now && matchesAudiences(a.audienceIds, member);\n })\n .sort((a, b) => Date.parse(b.publishedAt) - Date.parse(a.publishedAt));\n}\n\n/** Unread count for the launcher badge: announcements published after the visitor last opened \"What's new\". */\nexport function unreadAnnouncements(items: readonly { publishedAt: string }[], lastSeenAt: string | null | undefined): number {\n const seen = lastSeenAt ? Date.parse(lastSeenAt) : NaN;\n if (Number.isNaN(seen)) return items.length;\n return items.filter((a) => Date.parse(a.publishedAt) > seen).length;\n}\n\n/**\n * A link to a help article from guide or article HTML: `<a href=\"#guidely-article:ID\">`. A fragment\n * survives every sanitizer (editor, server, SDK), and the SDKs open the article in the resource\n * center (or Scout's Help tab) instead of following the link.\n */\nexport const ARTICLE_HREF_PREFIX = \"#guidely-article:\";\nconst ARTICLE_ID = /^[A-Za-z0-9_-]{1,64}$/;\n\nexport function articleHref(articleId: string): string {\n return `${ARTICLE_HREF_PREFIX}${articleId}`;\n}\n\n/** The article id of an article link's `href`, or null. */\nexport function articleIdFromHref(href: string | null | undefined): string | null {\n if (!href || !href.startsWith(ARTICLE_HREF_PREFIX)) return null;\n const id = href.slice(ARTICLE_HREF_PREFIX.length);\n return ARTICLE_ID.test(id) ? id : null;\n}\n","/** How-to capture constants the browser SDK needs without zod (also exported from `@guidelytech/shared/runtime`). */\n\n/** Query parameter that starts capture mode in the SDK (separate from `guidely_authoring`, so SDKs without capture ignore it). */\nexport const CAPTURE_PARAM = \"guidely_capture\";\n/** Largest screenshot the capture endpoint accepts. */\nexport const CAPTURE_SCREENSHOT_MAX_BYTES = 8 * 1024 * 1024;\n","/**\n * Page helpers shared by the SDK (page-aware messenger) and the server (page matching, analytics).\n * Pure and zod-free.\n */\n\n/**\n * One path segment that looks like an identifier: digits, a UUID, or a long hex string (hashes,\n * Mongo ids). Written so the same source works as a JS RegExp and a Postgres ARE (`regexp_replace`\n * with flags `gi`), which keeps id folding identical in SQL and in code. A segment may be followed\n * by the page query parameters a project keeps in its paths (`/contacts/42?tab=notes`).\n */\nexport const PATH_ID_PATTERN = \"/([0-9]+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{12,})(?=[/?]|$)\";\n\n/** `/contacts/42/notes/9f8e…` → `/contacts/:id/notes/:id`; `/contacts/42?tab=notes` → `/contacts/:id?tab=notes`. */\nexport function foldPathIds(path: string): string {\n return path.replace(new RegExp(PATH_ID_PATTERN, \"gi\"), \"/:id\");\n}\n\n/** Path segments that say nothing about what a page is for. */\nconst GENERIC_SEGMENTS = new Set([\"\", \":id\", \"app\", \"apps\", \"dashboard\", \"home\", \"index\", \"main\", \"new\", \"edit\", \"view\", \"show\", \"details\", \"detail\", \"overview\", \"list\", \"all\", \"page\", \"pages\", \"en\", \"v1\", \"v2\"]);\n\nfunction segmentsOf(path: string): string[] {\n const clean = foldPathIds((path.split(/[?#]/)[0] || \"/\").toLowerCase());\n return clean\n .split(\"/\")\n .map((s) => s.replace(/\\.(html?|php|aspx?)$/, \"\"))\n .filter((s) => !GENERIC_SEGMENTS.has(s) && /[a-z]/.test(s) && s.length <= 40);\n}\n\n/** Words describing a page, from its path (`/settings/billing-plans/42` → `settings billing plans`). */\nexport function pageTerms(path: string): string[] {\n const words = segmentsOf(path).flatMap((s) => s.split(/[-_.+\\s]+/).filter((w) => w.length > 1 && /[a-z]/.test(w)));\n return [...new Set(words)].slice(0, 8);\n}\n\n/** A short human name for a page (`/app/invoices/42` → `Invoices`), or null for the root and unnamed pages. */\nexport function pageLabel(path: string): string | null {\n const last = segmentsOf(path).at(-1);\n if (!last) return null;\n const words = last.split(/[-_.+\\s]+/).filter(Boolean);\n if (!words.length) return null;\n const label = words.join(\" \");\n return label.charAt(0).toUpperCase() + label.slice(1);\n}\n\n/** The first name in a user's traits (`firstName`, `first_name`, or the first word of `name`), or null. */\nexport function firstNameFromTraits(traits: Record<string, unknown> | null | undefined): string | null {\n if (!traits) return null;\n const pick = (v: unknown) => (typeof v === \"string\" ? v.trim() : \"\");\n const first = pick(traits.firstName) || pick(traits.first_name) || pick(traits.firstname) || pick(traits.name).split(/\\s+/)[0] || \"\";\n // Never greet someone by an email address or an id.\n if (!first || first.length > 40 || first.includes(\"@\") || !/\\p{L}/u.test(first)) return null;\n return first;\n}\n","/**\n * Tagged pages and features (named rules over the URLs and clicks the SDK captures), shared by the server (retroactive\n * matching, SQL generation), the dashboard (previews) and the SDK (event properties). Pure and zod-free.\n *\n * - An `ElementSnapshot` is the compact description of a clicked element the SDK attaches to `click`\n * events (`properties.el`): tag, id, classes, a few safe attributes, nth-of-type, ~5 ancestors and\n * the shadow hosts above it. CSS selector rules are evaluated against it with {@link matchCssSelector},\n * so a rule written today also matches clicks stored before it existed.\n * - Older clicks carry only a selector string; {@link snapshotFromSelector} turns that string into a\n * partial snapshot so CSS rules still match them where the string says enough.\n */\n\n// ---------------------------------------------------------------------------\n// Element snapshots\n// ---------------------------------------------------------------------------\n\n/** One element in a snapshot: tag, id, classes, safe attributes and its 1-based nth-of-type. */\nexport interface ElementNode {\n t: string;\n id?: string;\n c?: string[];\n a?: Record<string, string>;\n n?: number;\n}\n\n/** A clicked element (`click.properties.el`): the element, its ancestors (`p`, parent first) and shadow hosts (`h`, nearest first). */\nexport interface ElementSnapshot extends ElementNode {\n p?: ElementNode[];\n h?: ElementNode[];\n}\n\nexport const SNAPSHOT_LIMITS = { classes: 8, className: 60, attrs: 6, attrValue: 100, ancestors: 5, hosts: 3, tag: 40, id: 80 } as const;\n\n/** Attributes a snapshot may carry besides `data-*` ones. Never `value`, never event handlers. */\nexport const SNAPSHOT_ATTRS = [\"role\", \"name\", \"type\", \"aria-label\", \"title\", \"alt\", \"for\", \"href\"] as const;\n\n/** Framework and state `data-*` attributes that say nothing stable about an element. */\nexport const NOISY_DATA_ATTR = /^data-(state|v-|react|radix|headlessui|svelte|orientation|highlighted|focus|key|index|side|align|disabled|selected|active|open|rbd|dnd|sveltekit|guidely-(mask|ignore|block))/i;\n\n/** The custom attribute that names a feature by default (`<button data-guidely-feature=\"Export CSV\">`). */\nexport const DEFAULT_FEATURE_ATTRIBUTE = \"data-guidely-feature\";\nexport const FEATURE_ATTRIBUTE_PATTERN = /^data-[a-z0-9][a-z0-9_.-]{0,60}$/;\n\nfunction str(v: unknown, max: number): string | undefined {\n return typeof v === \"string\" && v ? v.slice(0, max) : undefined;\n}\n\nfunction cleanNode(raw: unknown): ElementNode | null {\n if (!raw || typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n const t = str(r.t, SNAPSHOT_LIMITS.tag)?.toLowerCase();\n if (!t || !/^[a-z][a-z0-9-]*$/.test(t)) return null;\n const node: ElementNode = { t };\n const id = str(r.id, SNAPSHOT_LIMITS.id);\n if (id) node.id = id;\n if (Array.isArray(r.c)) {\n const c = r.c.filter((x): x is string => typeof x === \"string\" && !!x && x.length <= SNAPSHOT_LIMITS.className && !/\\s/.test(x)).slice(0, SNAPSHOT_LIMITS.classes);\n if (c.length) node.c = c;\n }\n if (r.a && typeof r.a === \"object\" && !Array.isArray(r.a)) {\n const a: Record<string, string> = {};\n for (const [k, v] of Object.entries(r.a as Record<string, unknown>)) {\n if (Object.keys(a).length >= SNAPSHOT_LIMITS.attrs) break;\n const key = k.toLowerCase();\n if (typeof v !== \"string\" || !(key.startsWith(\"data-\") || (SNAPSHOT_ATTRS as readonly string[]).includes(key)) || key === \"value\" || key.length > 60) continue;\n a[key] = v.slice(0, SNAPSHOT_LIMITS.attrValue);\n }\n if (Object.keys(a).length) node.a = a;\n }\n if (typeof r.n === \"number\" && Number.isInteger(r.n) && r.n >= 1 && r.n <= 10_000) node.n = r.n;\n return node;\n}\n\n/** Validates and trims a snapshot sent by an SDK (server side); null when it is not one. */\nexport function normalizeSnapshot(raw: unknown): ElementSnapshot | null {\n const el = cleanNode(raw);\n if (!el) return null;\n const r = raw as Record<string, unknown>;\n const out: ElementSnapshot = el;\n if (Array.isArray(r.p)) {\n const p = r.p.slice(0, SNAPSHOT_LIMITS.ancestors).map(cleanNode);\n // Ancestors are consecutive; stop at the first unusable one rather than skipping it.\n const cut = p.indexOf(null);\n const list = (cut === -1 ? p : p.slice(0, cut)) as ElementNode[];\n if (list.length) out.p = list;\n }\n if (Array.isArray(r.h)) {\n const h = r.h.slice(0, SNAPSHOT_LIMITS.hosts).map(cleanNode).filter((x): x is ElementNode => !!x);\n if (h.length) out.h = h;\n }\n return out;\n}\n\n/** JSON with sorted keys, so equal snapshots hash the same whatever order the SDK wrote them in. */\nexport function stableStringify(v: unknown): string {\n if (Array.isArray(v)) return `[${v.map(stableStringify).join(\",\")}]`;\n if (v && typeof v === \"object\") {\n const o = v as Record<string, unknown>;\n return `{${Object.keys(o)\n .filter((k) => o[k] !== undefined)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${stableStringify(o[k])}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(v ?? null);\n}\n\n// ---------------------------------------------------------------------------\n// CSS selector subset: parse + match against a snapshot\n// ---------------------------------------------------------------------------\n\nexport type AttrOp = \"exists\" | \"=\" | \"^=\" | \"$=\" | \"*=\" | \"~=\" | \"|=\";\n\nexport interface AttrTest {\n name: string;\n op: AttrOp;\n value?: string;\n /** `[attr=\"x\" i]` */\n insensitive?: boolean;\n}\n\nexport interface Compound {\n tag?: string;\n id?: string;\n classes: string[];\n attrs: AttrTest[];\n /** `:nth-of-type(n)`; `odd`/`even` as `{ a: 2, b: 1|0 }`; `:first-of-type` is `{ a: 0, b: 1 }`. */\n nth?: { a: number; b: number };\n}\n\n/** A complex selector: compounds left to right and the combinator before each (index 0 has none). */\nexport interface ComplexSelector {\n compounds: Compound[];\n combinators: Array<\" \" | \">\" | \">>>\">;\n}\n\nexport class SelectorSyntaxError extends Error {}\n\nconst IDENT_START = /[A-Za-z_\\u00a0-\\uffff-]/;\nconst IDENT_CHAR = /[A-Za-z0-9_\\u00a0-\\uffff-]/;\n\n/**\n * Parses the supported subset: type and universal selectors, `#id`, `.class`, `[attr]`,\n * `[attr=v]`, `^=`, `$=`, `*=`, `~=`, `|=` (optionally `i`), `:nth-of-type(n|odd|even)`,\n * `:first-of-type`, descendant and child combinators, `>>>` (shadow host) and selector lists.\n * Throws {@link SelectorSyntaxError} on anything else.\n */\nexport function parseCssSelector(input: string): ComplexSelector[] {\n const s = input.trim();\n if (!s) throw new SelectorSyntaxError(\"Empty selector\");\n if (s.length > 1000) throw new SelectorSyntaxError(\"Selector is too long\");\n let i = 0;\n const peek = () => s[i];\n const eof = () => i >= s.length;\n const fail = (msg: string): never => {\n throw new SelectorSyntaxError(`${msg} at position ${i + 1}`);\n };\n const ws = () => {\n let any = false;\n while (!eof() && /\\s/.test(s[i]!)) {\n i++;\n any = true;\n }\n return any;\n };\n const escape = (): string => {\n // after the backslash\n i++;\n const hex = /^[0-9a-fA-F]{1,6}/.exec(s.slice(i));\n if (hex) {\n i += hex[0].length;\n if (s[i] === \" \") i++;\n return String.fromCodePoint(parseInt(hex[0], 16));\n }\n if (eof()) fail(\"Unfinished escape\");\n return s[i++]!;\n };\n const ident = (): string => {\n let out = \"\";\n if (s[i] === \"\\\\\") out += escape();\n else if (!eof() && IDENT_START.test(s[i]!)) out += s[i++];\n else fail(\"Expected a name\");\n while (!eof()) {\n if (s[i] === \"\\\\\") out += escape();\n else if (IDENT_CHAR.test(s[i]!)) out += s[i++];\n else break;\n }\n return out;\n };\n const quoted = (): string => {\n const q = s[i++];\n let out = \"\";\n while (!eof() && s[i] !== q) {\n if (s[i] === \"\\\\\") out += escape();\n else out += s[i++];\n }\n if (eof()) fail(\"Unterminated string\");\n i++;\n return out;\n };\n const compound = (): Compound | null => {\n const c: Compound = { classes: [], attrs: [] };\n let any = false;\n if (peek() === \"*\") {\n i++;\n any = true;\n } else if (!eof() && (IDENT_START.test(peek()!) || peek() === \"\\\\\")) {\n c.tag = ident().toLowerCase();\n any = true;\n }\n for (;;) {\n const ch = peek();\n if (ch === \"#\") {\n i++;\n c.id = ident();\n } else if (ch === \".\") {\n i++;\n c.classes.push(ident());\n } else if (ch === \"[\") {\n i++;\n ws();\n const name = ident().toLowerCase();\n ws();\n let op: AttrOp = \"exists\";\n let value: string | undefined;\n let insensitive = false;\n if (peek() !== \"]\") {\n const m = /^(=|\\^=|\\$=|\\*=|~=|\\|=)/.exec(s.slice(i));\n if (!m) fail(\"Unsupported attribute operator\");\n op = m![1] as AttrOp;\n i += m![1]!.length;\n ws();\n value = peek() === '\"' || peek() === \"'\" ? quoted() : ident();\n ws();\n if (peek() === \"i\" || peek() === \"I\") {\n i++;\n insensitive = true;\n ws();\n } else if (peek() === \"s\" || peek() === \"S\") {\n i++;\n ws();\n }\n }\n if (peek() !== \"]\") fail(\"Expected ]\");\n i++;\n c.attrs.push({ name, op, ...(value !== undefined ? { value } : {}), ...(insensitive ? { insensitive } : {}) });\n } else if (ch === \":\") {\n i++;\n if (peek() === \":\") fail(\"Pseudo-elements are not supported\");\n const name = ident().toLowerCase();\n if (name === \"first-of-type\") c.nth = { a: 0, b: 1 };\n else if (name === \"nth-of-type\") {\n if (peek() !== \"(\") fail(\"Expected (\");\n i++;\n ws();\n const m = /^(odd|even|\\d+)/i.exec(s.slice(i));\n if (!m) fail(\"Only :nth-of-type(n), odd or even are supported\");\n i += m![0].length;\n ws();\n if (peek() !== \")\") fail(\"Expected )\");\n i++;\n const v = m![0].toLowerCase();\n c.nth = v === \"odd\" ? { a: 2, b: 1 } : v === \"even\" ? { a: 2, b: 0 } : { a: 0, b: Number(v) };\n } else fail(`Unsupported pseudo-class :${name}`);\n } else break;\n any = true;\n }\n return any ? c : null;\n };\n\n const list: ComplexSelector[] = [];\n for (;;) {\n ws();\n const sel: ComplexSelector = { compounds: [], combinators: [] };\n const first = compound();\n if (!first) fail(\"Expected a selector\");\n sel.compounds.push(first!);\n for (;;) {\n const hadWs = ws();\n if (eof() || peek() === \",\") break;\n let comb: \" \" | \">\" | \">>>\" = \" \";\n if (s.startsWith(\">>>\", i)) {\n comb = \">>>\";\n i += 3;\n ws();\n } else if (peek() === \">\") {\n comb = \">\";\n i++;\n ws();\n } else if (peek() === \"+\" || peek() === \"~\") fail(\"Sibling combinators are not supported\");\n else if (!hadWs) fail(\"Unexpected character\");\n const next = compound();\n if (!next) fail(\"Expected a selector after the combinator\");\n sel.compounds.push(next!);\n sel.combinators.push(comb);\n }\n list.push(sel);\n if (eof()) break;\n i++; // \",\"\n }\n return list;\n}\n\n/** Is the selector inside the supported subset? Returns the error message, or null when it parses. */\nexport function cssSelectorError(selector: string): string | null {\n try {\n parseCssSelector(selector);\n return null;\n } catch (e) {\n return e instanceof Error ? e.message : \"Invalid selector\";\n }\n}\n\nfunction attrMatches(test: AttrTest, node: ElementNode): boolean {\n let actual: string | undefined;\n if (test.name === \"id\") actual = node.id;\n else if (test.name === \"class\") actual = node.c?.join(\" \");\n else actual = node.a?.[test.name];\n if (actual === undefined) return false;\n if (test.op === \"exists\") return true;\n let v = test.value ?? \"\";\n if (test.insensitive) {\n actual = actual.toLowerCase();\n v = v.toLowerCase();\n }\n switch (test.op) {\n case \"=\":\n return actual === v;\n case \"^=\":\n return !!v && actual.startsWith(v);\n case \"$=\":\n return !!v && actual.endsWith(v);\n case \"*=\":\n return !!v && actual.includes(v);\n case \"~=\":\n return !!v && actual.split(/\\s+/).includes(v);\n case \"|=\":\n return actual === v || actual.startsWith(`${v}-`);\n default:\n return false;\n }\n}\n\n/** Does one compound match one node? An unknown nth-of-type fails `:nth-of-type` tests. */\nexport function compoundMatches(c: Compound, node: ElementNode): boolean {\n if (c.tag && c.tag !== node.t) return false;\n if (c.id !== undefined && node.id !== c.id) return false;\n for (const cls of c.classes) if (!node.c?.includes(cls)) return false;\n for (const a of c.attrs) if (!attrMatches(a, node)) return false;\n if (c.nth) {\n if (!node.n) return false;\n const { a, b } = c.nth;\n if (a === 0 ? node.n !== b : (node.n - b) % a !== 0 || (node.n - b) / a < 0) return false;\n }\n return true;\n}\n\n/** Matches compounds (right to left) against a chain of nodes: index 0 is the element, then its ancestors. */\nfunction chainMatches(compounds: Compound[], combinators: Array<\" \" | \">\">, nodes: ElementNode[], ci = compounds.length - 1, ni = 0): boolean {\n if (!compoundMatches(compounds[ci]!, nodes[ni]!)) return false;\n if (ci === 0) return true;\n const comb = combinators[ci - 1]!;\n if (comb === \">\") return ni + 1 < nodes.length && chainMatches(compounds, combinators, nodes, ci - 1, ni + 1);\n for (let k = ni + 1; k < nodes.length; k++) if (chainMatches(compounds, combinators, nodes, ci - 1, k)) return true;\n return false;\n}\n\nfunction complexMatches(sel: ComplexSelector, snap: ElementSnapshot): boolean {\n // Split at `>>>`: the last segment is matched inside the element's own tree, each earlier\n // segment's last compound against a shadow host further out (any depth, like the runtime).\n const segments: Array<{ compounds: Compound[]; combinators: Array<\" \" | \">\"> }> = [{ compounds: [sel.compounds[0]!], combinators: [] }];\n sel.combinators.forEach((comb, k) => {\n const next = sel.compounds[k + 1]!;\n if (comb === \">>>\") segments.push({ compounds: [next], combinators: [] });\n else {\n const seg = segments[segments.length - 1]!;\n seg.compounds.push(next);\n seg.combinators.push(comb);\n }\n });\n const last = segments.pop()!;\n const nodes: ElementNode[] = [snap, ...(snap.p ?? [])];\n if (!chainMatches(last.compounds, last.combinators, nodes)) return false;\n const hosts = snap.h ?? [];\n let from = 0;\n for (let k = segments.length - 1; k >= 0; k--) {\n const target = segments[k]!.compounds[segments[k]!.compounds.length - 1]!;\n let found = -1;\n for (let j = from; j < hosts.length; j++) {\n if (compoundMatches(target, hosts[j]!)) {\n found = j;\n break;\n }\n }\n if (found === -1) return false;\n from = found + 1;\n }\n return true;\n}\n\nconst parsedCache = new Map<string, ComplexSelector[] | null>();\n\n/** Does a CSS selector (subset, see {@link parseCssSelector}) match the snapshot? Invalid selectors match nothing. */\nexport function matchCssSelector(selector: string | ComplexSelector[], snap: ElementSnapshot): boolean {\n let list: ComplexSelector[] | null;\n if (typeof selector === \"string\") {\n if (!parsedCache.has(selector)) {\n if (parsedCache.size > 500) parsedCache.clear();\n try {\n parsedCache.set(selector, parseCssSelector(selector));\n } catch {\n parsedCache.set(selector, null);\n }\n }\n list = parsedCache.get(selector)!;\n } else list = selector;\n return !!list && list.some((sel) => complexMatches(sel, snap));\n}\n\nfunction nodeOfCompound(c: Compound): ElementNode {\n const node: ElementNode = { t: c.tag ?? \"*\" };\n if (c.id) node.id = c.id;\n if (c.classes.length) node.c = c.classes.slice(0, SNAPSHOT_LIMITS.classes);\n const a: Record<string, string> = {};\n for (const t of c.attrs) if (t.op === \"=\" && t.value !== undefined) a[t.name] = t.value;\n if (Object.keys(a).length) node.a = a;\n if (c.nth && c.nth.a === 0) node.n = c.nth.b;\n return node;\n}\n\n/**\n * A partial snapshot read from a stored selector string (clicks captured before snapshots existed):\n * `#form > div:nth-of-type(2) > button[data-testid=\"save\"]` becomes a `button` with that attribute,\n * nth 1-unknown, and two ancestors. Shadow steps (`c-app >>> button`) become hosts. Null when the\n * string is not a selector in the supported subset.\n */\nexport function snapshotFromSelector(selector: string, tag?: string | null): ElementSnapshot | null {\n let list: ComplexSelector[];\n try {\n list = parseCssSelector(selector);\n } catch {\n return null;\n }\n if (list.length !== 1) return null;\n const sel = list[0]!;\n const segments: Compound[][] = [[sel.compounds[0]!]];\n sel.combinators.forEach((comb, k) => {\n if (comb === \">>>\") segments.push([sel.compounds[k + 1]!]);\n else segments[segments.length - 1]!.push(sel.compounds[k + 1]!);\n });\n const own = segments.pop()!;\n const el = nodeOfCompound(own[own.length - 1]!);\n if (el.t === \"*\" && tag && /^[a-z][a-z0-9-]*$/i.test(tag)) el.t = tag.toLowerCase();\n const snap: ElementSnapshot = el;\n const p = own.slice(0, -1).reverse().map(nodeOfCompound);\n if (p.length) snap.p = p.slice(0, SNAPSHOT_LIMITS.ancestors);\n const h = segments.reverse().map((seg) => nodeOfCompound(seg[seg.length - 1]!));\n if (h.length) snap.h = h.slice(0, SNAPSHOT_LIMITS.hosts);\n return snap;\n}\n\n// ---------------------------------------------------------------------------\n// Page rules\n// ---------------------------------------------------------------------------\n\nexport type QueryParamOp = \"exists\" | \"absent\" | \"equals\" | \"contains\";\nexport interface QueryParamCondition {\n name: string;\n op: QueryParamOp;\n value?: string;\n}\n\n/**\n * One way a URL belongs to a page. `url`: a pattern (`/accounts/:id/settings`, `/reports/*`,\n * `/docs/**`, `//*\\/billing`, `https://app.acme.com/x`) plus optional query conditions; `regex`: a\n * regular expression over the path; `title`: the document title (`equals` / `contains`). With\n * `exclude`, matching URLs are taken out of the page instead.\n */\nexport interface PageRule {\n id?: string;\n type: \"url\" | \"regex\" | \"title\";\n value: string;\n op?: \"equals\" | \"contains\";\n query?: QueryParamCondition[];\n exclude?: boolean;\n}\n\nexport const PAGE_RULE_LIMITS = { rules: 20, value: 500, query: 5 } as const;\n\nexport interface PagePattern {\n /** Anchored regex source, valid both as a JS RegExp (flag `i`) and a Postgres ARE (`~*`). */\n source: string;\n /** What it runs against: the path (query removed) or the full URL without query and hash. */\n target: \"path\" | \"url\";\n /** Query conditions written into the pattern (`/search?tab=people`). */\n query: QueryParamCondition[];\n}\n\nconst escapeRe = (s: string) => s.replace(/[.+?^${}()|[\\]\\\\*]/g, \"\\\\$&\");\n\nfunction globToRegex(pattern: string): string {\n let out = \"\";\n for (let k = 0; k < pattern.length; k++) {\n const ch = pattern[k]!;\n if (ch === \"*\") {\n if (pattern[k + 1] === \"*\") {\n out += \".*\";\n k++;\n } else out += \"[^/]*\";\n } else if (ch === \":\" && (k === 0 || pattern[k - 1] === \"/\") && /[A-Za-z_]/.test(pattern[k + 1] ?? \"\")) {\n // `:name` path parameter: one whole segment.\n let j = k + 1;\n while (j < pattern.length && /[\\w]/.test(pattern[j]!)) j++;\n out += \"[^/]+\";\n k = j - 1;\n } else out += escapeRe(ch);\n }\n return out;\n}\n\n/** Turns a URL rule pattern into a regex. Query parameters in the pattern become conditions. */\nexport function pagePattern(raw: string): PagePattern {\n let p = raw.trim();\n const query: QueryParamCondition[] = [];\n const hash = p.indexOf(\"#\");\n if (hash !== -1) p = p.slice(0, hash);\n const q = p.indexOf(\"?\");\n if (q !== -1) {\n for (const part of p.slice(q + 1).split(\"&\")) {\n if (!part) continue;\n const eq = part.indexOf(\"=\");\n const name = decodeSafe(eq === -1 ? part : part.slice(0, eq));\n const value = eq === -1 ? undefined : decodeSafe(part.slice(eq + 1));\n if (!name) continue;\n query.push(value === undefined || value === \"*\" ? { name, op: \"exists\" } : { name, op: \"equals\", value });\n }\n p = p.slice(0, q);\n }\n let target: \"path\" | \"url\" = \"path\";\n // `//*` means any domain: keep only the path.\n if (p.startsWith(\"//*\")) p = p.slice(3);\n let prefix = \"\";\n const abs = /^(https?:)?\\/\\/([^/]+)(.*)$/i.exec(p);\n if (abs) {\n target = \"url\";\n prefix = `https?://${globToRegex(abs[2]!.toLowerCase())}`;\n p = abs[3] || \"/\";\n }\n if (!p.startsWith(\"/\")) p = `/${p}`;\n // A trailing slash is optional, as on most sites.\n const body = p.length > 1 && p.endsWith(\"/\") ? p.slice(0, -1) : p;\n const src = body === \"/\" ? \"/?\" : `${globToRegex(body)}/?`;\n return { source: `^${prefix}${src}$`, target, query: query.slice(0, PAGE_RULE_LIMITS.query) };\n}\n\nfunction decodeSafe(s: string): string {\n try {\n return decodeURIComponent(s.replace(/\\+/g, \" \"));\n } catch {\n return s;\n }\n}\n\n/** Regex (JS + Postgres) for a query condition over a raw URL. */\nexport function queryConditionRegex(c: QueryParamCondition): string {\n const name = escapeRe(c.name);\n switch (c.op) {\n case \"equals\":\n return `[?&]${name}=${escapeRe(encodeLoose(c.value ?? \"\"))}(&|#|$)`;\n case \"contains\":\n return `[?&]${name}=[^&#]*${escapeRe(encodeLoose(c.value ?? \"\"))}`;\n default:\n return `[?&]${name}(=|&|#|$)`;\n }\n}\n\n/** URL-encodes what browsers encode in query values, leaving the common safe characters alone. */\nfunction encodeLoose(v: string): string {\n return encodeURIComponent(v).replace(/%2F/gi, \"/\").replace(/%3A/gi, \":\").replace(/%2C/gi, \",\").replace(/%40/gi, \"@\");\n}\n\nexport interface PageContext {\n /** Full URL (with query) when known. */\n url?: string | null;\n /** Path as stored (`/a/b`, or `/a/b?section=x` with kept page parameters). */\n path?: string | null;\n title?: string | null;\n}\n\nfunction pathOnly(ctx: PageContext): string | null {\n if (ctx.path) return ctx.path.split(\"?\")[0] || \"/\";\n if (!ctx.url) return null;\n try {\n return new URL(ctx.url, \"http://x.invalid\").pathname;\n } catch {\n return null;\n }\n}\n\nfunction regexOrNull(source: string): RegExp | null {\n try {\n return new RegExp(source, \"i\");\n } catch {\n return null;\n }\n}\n\n/** JS twin of the SQL a page rule compiles to (server `pageRuleSql`). */\nexport function pageRuleMatches(rule: PageRule, ctx: PageContext): boolean {\n const path = pathOnly(ctx);\n if (rule.type === \"title\") {\n const t = (ctx.title ?? \"\").toLowerCase();\n const v = rule.value.toLowerCase();\n return !!t && (rule.op === \"contains\" ? t.includes(v) : t === v);\n }\n if (rule.type === \"regex\") {\n const re = regexOrNull(rule.value);\n return !!re && path !== null && re.test(path);\n }\n const pat = pagePattern(rule.value);\n const re = regexOrNull(pat.source);\n if (!re) return false;\n let subject: string | null = path;\n if (pat.target === \"url\") {\n if (!ctx.url) return false;\n subject = ctx.url.split(/[?#]/)[0]!;\n }\n if (subject === null || !re.test(subject)) return false;\n const conds = [...pat.query, ...(rule.query ?? [])];\n for (const c of conds) {\n const hit = !!ctx.url && new RegExp(queryConditionRegex(c), \"i\").test(ctx.url);\n if (c.op === \"absent\" ? hit : !hit) return false;\n }\n return true;\n}\n\n/** Included by any include rule and excluded by no exclude rule. */\nexport function pageRulesMatch(rules: PageRule[], ctx: PageContext): boolean {\n const include = rules.filter((r) => !r.exclude);\n if (!include.length || !include.some((r) => pageRuleMatches(r, ctx))) return false;\n return !rules.some((r) => r.exclude && pageRuleMatches(r, ctx));\n}\n\n/** Validation message for a page rule, or null. */\nexport function pageRuleError(rule: PageRule): string | null {\n const v = rule.value?.trim();\n if (!v) return \"A rule needs a value\";\n if (v.length > PAGE_RULE_LIMITS.value) return \"The rule is too long\";\n if (rule.type === \"regex\") {\n if (!regexOrNull(v)) return `\"${v}\" is not a valid regular expression`;\n if (/\\(\\?[<=!]/.test(v) || /\\\\[1-9]/.test(v)) return \"Look-arounds and back-references are not supported\";\n }\n if (rule.type === \"url\" && !regexOrNull(pagePattern(v).source)) return `\"${v}\" is not a valid URL rule`;\n for (const q of rule.query ?? []) if (!/^[A-Za-z0-9_.\\-[\\]]{1,60}$/.test(q.name)) return `\"${q.name}\" is not a query parameter name`;\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Feature rules\n// ---------------------------------------------------------------------------\n\nexport type SelectorOp = \"exact\" | \"prefix\" | \"contains\" | \"glob\" | \"css\";\n\n/**\n * One way a click belongs to a feature. Every condition present must hold. `selector.op = \"css\"`\n * evaluates a CSS selector against the element snapshot (or, for old clicks, the snapshot read from\n * the stored selector string); the other selector operators compare the stored selector string —\n * mobile taps store the accessibility id / `data-guidely-id` there, so `exact` works for them too.\n */\nexport interface FeatureRule {\n id?: string;\n selector?: { op: SelectorOp; value: string };\n text?: { op: \"equals\" | \"contains\"; value: string };\n tag?: string;\n href?: { op: \"equals\" | \"prefix\" | \"contains\"; value: string };\n /** Only clicks on this tagged page / URL pattern. */\n page?: { pageId?: string; pattern?: string };\n /** `web`, `ios`, `android` (mobile autocapture sets `properties.platform`). */\n platform?: string;\n exclude?: boolean;\n}\n\nexport const FEATURE_RULE_LIMITS = { rules: 20, value: 1000 } as const;\n\nexport interface ClickFacts {\n selector?: string | null;\n text?: string | null;\n tag?: string | null;\n href?: string | null;\n platform?: string | null;\n}\n\nfunction globMatch(pattern: string, value: string): boolean {\n const re = new RegExp(`^${pattern.split(\"*\").map(escapeRe).join(\".*\")}$`, \"s\");\n return re.test(value);\n}\n\n/** Does a click (facts + a CSS test) satisfy one rule's element conditions? Page scope is checked by the caller. */\nexport function featureRuleMatchesClick(rule: FeatureRule, click: ClickFacts, css: (selector: string) => boolean): boolean {\n if (!rule.selector && !rule.text && !rule.tag && !rule.href) return false;\n if (rule.selector) {\n const sel = click.selector ?? \"\";\n const v = rule.selector.value;\n const ok =\n rule.selector.op === \"css\" ? css(v) : rule.selector.op === \"exact\" ? sel === v : rule.selector.op === \"prefix\" ? sel.startsWith(v) : rule.selector.op === \"contains\" ? sel.includes(v) : globMatch(v, sel);\n if (!ok) return false;\n }\n if (rule.text) {\n const t = (click.text ?? \"\").toLowerCase();\n const v = rule.text.value.toLowerCase();\n if (rule.text.op === \"contains\" ? !t.includes(v) : t !== v) return false;\n }\n if (rule.tag && (click.tag ?? \"\").toLowerCase() !== rule.tag.toLowerCase()) return false;\n if (rule.href) {\n const h = click.href ?? \"\";\n const v = rule.href.value;\n if (rule.href.op === \"equals\" ? h !== v : rule.href.op === \"prefix\" ? !h.startsWith(v) : !h.includes(v)) return false;\n }\n if (rule.platform && (click.platform ?? \"web\") !== rule.platform) return false;\n return true;\n}\n\n/** Validation message for a feature rule, or null. */\nexport function featureRuleError(rule: FeatureRule): string | null {\n if (!rule.selector && !rule.text && !rule.tag && !rule.href) return \"A feature rule needs a selector, text, tag or link condition\";\n if (rule.selector) {\n const v = rule.selector.value?.trim();\n if (!v) return \"The selector is empty\";\n if (v.length > FEATURE_RULE_LIMITS.value) return \"The selector is too long\";\n if (rule.selector.op === \"css\") {\n const err = cssSelectorError(v);\n if (err) return `Unsupported CSS selector: ${err}`;\n }\n }\n if (rule.text && !rule.text.value.trim()) return \"The text condition is empty\";\n if (rule.href && !rule.href.value.trim()) return \"The link condition is empty\";\n if (rule.tag && !/^[a-z][a-z0-9-]{0,40}$/i.test(rule.tag)) return \"The tag is not an element name\";\n if (rule.page?.pattern) return pageRuleError({ type: \"url\", value: rule.page.pattern });\n return null;\n}\n\n/** Selector to find a feature's elements on a page (dashboard overlays, SDK property capture), when the rules give one. */\nexport function featureCssSelectors(rules: FeatureRule[]): string[] {\n const out: string[] = [];\n for (const r of rules) {\n if (r.exclude || !r.selector) continue;\n if ((r.selector.op === \"css\" || r.selector.op === \"exact\") && !cssSelectorError(r.selector.value)) out.push(r.selector.value);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Event properties captured from the DOM (configured per page / feature, sent in the SDK config)\n// ---------------------------------------------------------------------------\n\nexport interface TagPropertyDefinition {\n id: string;\n name: string;\n /** Element to read: CSS selector (may use `>>>`); empty = the clicked element itself (features only). */\n selector?: string;\n source: \"text\" | \"attribute\";\n /** Attribute name for `source: \"attribute\"`; `value` is never read. */\n attribute?: string;\n}\n\n/** One tag's capture config in the SDK payload (`SdkConfigResponse.tagging.properties`). */\nexport interface TagPropertyConfig {\n kind: \"page\" | \"feature\";\n tagId: string;\n /** Page rules (pages) or feature rules (features), evaluated in the browser. */\n pageRules?: PageRule[];\n featureRules?: FeatureRule[];\n properties: TagPropertyDefinition[];\n}\n\nexport interface TaggingSdkConfig {\n /** Attribute that names features automatically (null = off). */\n featureAttribute: string | null;\n properties: TagPropertyConfig[];\n}\n\nexport const TAG_PROPERTY_LIMITS = { perTag: 10, total: 50, value: 100 } as const;\n\n/** Attribute names an event property may read. */\nexport function propertyAttributeAllowed(name: string): boolean {\n const n = name.toLowerCase();\n if (n === \"value\" || n.startsWith(\"on\") || n === \"style\" || n === \"srcdoc\") return false;\n return /^[a-z][a-z0-9_:.-]{0,60}$/.test(n);\n}\n","/** Complaint types and limits shared by the server and the messenger runtime (zod-free). */\n\n/** Where a complaint is in its handling; the messenger shows it as Received → In review → Resolved. */\nexport const COMPLAINT_STATUSES = [\"open\", \"in_review\", \"resolved\"] as const;\nexport type ComplaintStatus = (typeof COMPLAINT_STATUSES)[number];\n\n/** Events a complaint webhook can fire on. */\nexport const COMPLAINT_EVENTS = [\"complaint.filed\", \"complaint.status_changed\", \"complaint.replied\", \"complaint.resolved\"] as const;\nexport type ComplaintEvent = (typeof COMPLAINT_EVENTS)[number];\n\n/** Extra questions a category asks for. */\nexport const COMPLAINT_FIELD_TYPES = [\"text\", \"choice\"] as const;\nexport type ComplaintFieldType = (typeof COMPLAINT_FIELD_TYPES)[number];\n\nexport const MAX_COMPLAINT_FIELDS = 8;\nexport const MAX_COMPLAINT_CHOICES = 12;\nexport const MAX_COMPLAINT_LENGTH = 4000;\nexport const MAX_COMPLAINT_ANSWER_LENGTH = 500;\n/** Largest screenshot the messenger may attach (after it scales the image down). */\nexport const MAX_COMPLAINT_ATTACHMENT_BYTES = 2 * 1024 * 1024;\n\nexport interface ComplaintField {\n /** Stable id (`invoice_number`), used as the answer's key in webhook payloads. */\n id: string;\n label: string;\n type: ComplaintFieldType;\n /** Choices for `choice` questions. */\n options?: string[];\n required: boolean;\n}\n\n/** \"CMP-1042\" for complaint number 1042. */\nexport const complaintReference = (number: number) => `CMP-${number}`;\n\n/** A category as the messenger offers it. */\nexport interface MessengerComplaintCategory {\n id: string;\n name: string;\n description: string;\n color: string;\n fields: ComplaintField[];\n}\n\n/** Complaints block of `MessengerConfig`; absent when the project doesn't take complaints. */\nexport interface MessengerComplaintsConfig {\n categories: MessengerComplaintCategory[];\n /** Visitors the app hasn't identified may file one (with an email address). */\n anonymous: boolean;\n}\n\n/** A complaint as the person who filed it sees it (on its conversation). */\nexport interface MessengerComplaint {\n id: string;\n reference: string;\n status: ComplaintStatus;\n categoryName: string;\n createdAt: string;\n}\n\n/** Scout offered the complaint form in a reply, with this category picked. */\nexport interface MessengerComplaintOffer {\n categoryId: string;\n name: string;\n}\n","/**\n * Agent Analytics: the `agent.conversation` turn the customer's own AI agents send (zod-free, so the\n * browser SDK can use the types and limits without bundling the schema). The schema is in agents.ts.\n */\n\nexport const AGENT_TURN_ROLES = [\"user\", \"assistant\", \"tool\", \"system\"] as const;\nexport type AgentTurnRole = (typeof AGENT_TURN_ROLES)[number];\n\n/** How a conversation ended, as the agent reports it. */\nexport const AGENT_OUTCOMES = [\"success\", \"failure\", \"escalated\", \"abandoned\"] as const;\nexport type AgentOutcome = (typeof AGENT_OUTCOMES)[number];\n\nexport const AGENT_TOOL_STATUSES = [\"ok\", \"error\"] as const;\nexport type AgentToolStatus = (typeof AGENT_TOOL_STATUSES)[number];\n\n/** Longest turn text accepted (characters). */\nexport const AGENT_TURN_MAX_TEXT = 20_000;\n/** Most turns in one request. */\nexport const AGENT_TURNS_PER_BATCH = 100;\n/** Most tool calls on one turn. */\nexport const AGENT_TOOL_CALLS_PER_TURN = 50;\n/** Metadata: at most this many keys, string values up to 500 characters, 4 KB in all. */\nexport const AGENT_METADATA_MAX_KEYS = 30;\nexport const AGENT_METADATA_MAX_BYTES = 4096;\n/** The built-in Scout agent's id; customer agents can't use it. */\nexport const SCOUT_AGENT_ID = \"scout\";\n\n/** One tool the agent called in a turn. Arguments and results are never sent or stored. */\nexport interface AgentToolCallInput {\n name: string;\n status?: AgentToolStatus;\n latencyMs?: number;\n}\n\n/** One `agent.conversation` turn. */\nexport interface AgentTurnInput {\n type?: \"agent.conversation\";\n /** Your conversation (thread) id. */\n conversationId: string;\n /** Your agent's id, e.g. \"support-bot\". The agent is created on its first turn. */\n agentId: string;\n /** Display name for a new agent (defaults to agentId). */\n agentName?: string;\n /** Idempotency key: a turn sent twice with the same id is stored once. */\n turnId?: string;\n role: AgentTurnRole;\n text?: string;\n toolCalls?: AgentToolCallInput[];\n /** How long the agent took to produce this turn (assistant turns). */\n latencyMs?: number;\n /** How the conversation ended, when this turn ends it (the latest reported outcome wins). */\n outcome?: AgentOutcome;\n /** Whether the person got what they came for, when the agent knows. */\n taskSuccess?: boolean;\n /** ISO 8601 time of the turn (default: when Guidely receives it). */\n occurredAt?: string;\n userId?: string | null;\n anonymousId?: string | null;\n accountId?: string | null;\n sessionId?: string | null;\n /** Flat key/value pairs (strings, numbers, booleans), e.g. { model: \"gpt-4.1\" }. */\n metadata?: Record<string, string | number | boolean | null>;\n}\n\n/** Response of both ingestion endpoints. */\nexport interface AgentEventsResponse {\n accepted: number;\n duplicates: number;\n /** Turns refused (an agent past the per-project limit, or a conversation past its turn limit). */\n rejected?: number;\n /** Turns dropped because this month's product analytics allowance is used up. */\n overLimit?: number;\n}\n","/**\n * Guide and resource-center localization (zod-free, so the browser SDK can import it).\n *\n * Every translatable text field has a stable key derived from ids, never from positions, so\n * reordering steps keeps translations attached: `steps.<stepId>.title`,\n * `steps.<stepId>.buttons.<buttonId>.label`, `checklist.tasks.<taskId>.title`,\n * `survey.questions.<questionId>.options.<optionId>.label`, …\n *\n * A visitor's language comes from (in order) an explicit SDK locale, the `language` / `locale`\n * trait, then the browser / device language. `resolveLocale` matches it against the languages a\n * guide is translated into (exact tag first, then the base language) and falls back to the\n * project's default language, in which the guide is written.\n */\nimport type { GuideConfig } from \"./guide\";\nimport type { PublishedGuide, ResourceCenterAnnouncement, ResourceCenterArticle, ResourceCenterConfig } from \"./sdk-api\";\n\nexport type TextKind = \"text\" | \"html\";\n\nexport interface TextEntry {\n key: string;\n /** Default-language text. */\n source: string;\n kind: TextKind;\n /** Human-readable location for translators (\"Step 2 · Title\"). */\n label: string;\n}\n\n/** Project-level language settings (Project.settings.localization). */\nexport interface LocalizationSettings {\n /** Language the content is written in. */\n defaultLocale: string;\n /** Additional languages offered for translation. */\n locales: string[];\n /** Machine-translate new and changed text into every language automatically. */\n autoTranslate?: boolean;\n /** Machine translations need a teammate's approval before visitors see them. */\n requireReview?: boolean;\n}\n\n/**\n * Review state of one translated text. `machine` texts were written by AI translation; `human`\n * ones were typed or imported by a teammate (approved by doing so). `outdated` means the source\n * text changed after the translation was written or approved.\n */\nexport interface TranslationReviewState {\n origin: \"machine\" | \"human\";\n approved: boolean;\n outdated: boolean;\n reviewedBy?: string | null;\n reviewedAt?: string | null;\n}\n\n/** locale → key → review state. Texts without a state are human translations from before review existed. */\nexport type TranslationReviewMap = Record<string, Record<string, TranslationReviewState>>;\n\n/** Does this translation still need a teammate to look at it? */\nexport function needsReview(state: TranslationReviewState | undefined): boolean {\n return !!state && ((state.origin === \"machine\" && !state.approved) || state.outdated);\n}\n\nexport const DEFAULT_LOCALE = \"en\";\n\n/** Common languages offered in the dashboard's language picker (any BCP 47 tag is accepted). */\nexport const COMMON_LOCALES: Array<{ code: string; name: string }> = [\n { code: \"en\", name: \"English\" },\n { code: \"en-GB\", name: \"English (UK)\" },\n { code: \"fr\", name: \"French\" },\n { code: \"fr-CA\", name: \"French (Canada)\" },\n { code: \"de\", name: \"German\" },\n { code: \"es\", name: \"Spanish\" },\n { code: \"es-MX\", name: \"Spanish (Mexico)\" },\n { code: \"it\", name: \"Italian\" },\n { code: \"pt\", name: \"Portuguese\" },\n { code: \"pt-BR\", name: \"Portuguese (Brazil)\" },\n { code: \"nl\", name: \"Dutch\" },\n { code: \"sv\", name: \"Swedish\" },\n { code: \"da\", name: \"Danish\" },\n { code: \"nb\", name: \"Norwegian\" },\n { code: \"fi\", name: \"Finnish\" },\n { code: \"pl\", name: \"Polish\" },\n { code: \"cs\", name: \"Czech\" },\n { code: \"tr\", name: \"Turkish\" },\n { code: \"ru\", name: \"Russian\" },\n { code: \"uk\", name: \"Ukrainian\" },\n { code: \"ar\", name: \"Arabic\" },\n { code: \"he\", name: \"Hebrew\" },\n { code: \"hi\", name: \"Hindi\" },\n { code: \"ja\", name: \"Japanese\" },\n { code: \"ko\", name: \"Korean\" },\n { code: \"zh-Hans\", name: \"Chinese (Simplified)\" },\n { code: \"zh-Hant\", name: \"Chinese (Traditional)\" },\n { code: \"id\", name: \"Indonesian\" },\n { code: \"th\", name: \"Thai\" },\n { code: \"vi\", name: \"Vietnamese\" },\n];\n\nexport function localeName(code: string): string {\n const exact = COMMON_LOCALES.find((l) => l.code.toLowerCase() === code.toLowerCase());\n if (exact) return exact.name;\n const base = COMMON_LOCALES.find((l) => l.code.toLowerCase() === baseLanguage(code));\n return base ? `${base.name} (${code})` : code;\n}\n\n/** `fr_FR` / `FR-fr` → `fr-FR`; script subtags keep title case (`zh-hans` → `zh-Hans`). Invalid input → \"\". */\nexport function normalizeLocale(input: unknown): string {\n if (typeof input !== \"string\") return \"\";\n const parts = input.trim().replace(/_/g, \"-\").split(\"-\").filter(Boolean);\n if (!parts.length || !/^[a-zA-Z]{2,3}$/.test(parts[0]!)) return \"\";\n return parts\n .slice(0, 3)\n .map((p, i) => (i === 0 ? p.toLowerCase() : p.length === 4 ? p[0]!.toUpperCase() + p.slice(1).toLowerCase() : p.length === 2 ? p.toUpperCase() : p))\n .join(\"-\");\n}\n\nexport function baseLanguage(locale: string): string {\n return normalizeLocale(locale).split(\"-\")[0] ?? \"\";\n}\n\n/**\n * Picks the language to show: for each requested locale in order, an exact match among\n * `available`, else one sharing its base language (`fr-CA` → `fr`, `fr` → `fr-FR`). Falls back to\n * `defaultLocale`. Matching ignores case.\n */\nexport function resolveLocale(requested: ReadonlyArray<string | null | undefined>, available: readonly string[], defaultLocale: string = DEFAULT_LOCALE): string {\n const def = normalizeLocale(defaultLocale) || DEFAULT_LOCALE;\n const avail = available.map(normalizeLocale).filter(Boolean);\n const all = [def, ...avail.filter((a) => a.toLowerCase() !== def.toLowerCase())];\n for (const raw of requested) {\n const want = normalizeLocale(raw);\n if (!want) continue;\n const exact = all.find((a) => a.toLowerCase() === want.toLowerCase());\n if (exact) return exact;\n const base = baseLanguage(want);\n const sameBase = all.find((a) => a.toLowerCase() === base) ?? all.find((a) => baseLanguage(a) === base);\n if (sameBase) return sameBase;\n }\n return def;\n}\n\n/** Locale candidates for a visitor: explicit option, traits (`language`, `locale`), then the platform's languages. */\nexport function visitorLocales(explicit: string | null | undefined, traits: Record<string, unknown> | null | undefined, platform: ReadonlyArray<string | null | undefined> = []): string[] {\n const out: string[] = [];\n const push = (v: unknown) => {\n const n = normalizeLocale(v);\n if (n && !out.includes(n)) out.push(n);\n };\n push(explicit);\n push(traits?.language);\n push(traits?.locale);\n for (const p of platform) push(p);\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Guides\n// ---------------------------------------------------------------------------\n\n/** Every translatable text in a guide config, in display order. Empty texts are skipped. */\nexport function guideTextEntries(config: Pick<GuideConfig, \"steps\" | \"checklist\" | \"survey\">): TextEntry[] {\n const out: TextEntry[] = [];\n const add = (key: string, source: string | undefined | null, kind: TextKind, label: string) => {\n if (source && source.trim()) out.push({ key, source, kind, label });\n };\n config.steps.forEach((s, i) => {\n const at = `Step ${i + 1}`;\n add(`steps.${s.id}.title`, s.title, \"text\", `${at} · Title`);\n add(`steps.${s.id}.body`, s.body, \"html\", `${at} · Body`);\n add(`steps.${s.id}.customHtml`, s.customHtml, \"html\", `${at} · Custom HTML`);\n add(`steps.${s.id}.imageAlt`, s.imageAlt, \"text\", `${at} · Image description`);\n s.buttons.forEach((b) => add(`steps.${s.id}.buttons.${b.id}.label`, b.label, \"text\", `${at} · Button “${b.label}”`));\n });\n const c = config.checklist;\n if (c) {\n add(\"checklist.launcherLabel\", c.launcherLabel, \"text\", \"Checklist · Launcher label\");\n add(\"checklist.completionTitle\", c.completionTitle, \"text\", \"Checklist · Completion title\");\n add(\"checklist.completionBody\", c.completionBody, \"html\", \"Checklist · Completion message\");\n c.tasks.forEach((t, i) => {\n add(`checklist.tasks.${t.id}.title`, t.title, \"text\", `Task ${i + 1} · Title`);\n add(`checklist.tasks.${t.id}.description`, t.description, \"html\", `Task ${i + 1} · Description`);\n });\n }\n const sv = config.survey;\n if (sv) {\n sv.questions.forEach((q, i) => {\n const at = `Question ${i + 1}`;\n add(`survey.questions.${q.id}.title`, q.title, \"text\", `${at} · Question`);\n add(`survey.questions.${q.id}.description`, q.description, \"text\", `${at} · Description`);\n add(`survey.questions.${q.id}.placeholder`, q.placeholder, \"text\", `${at} · Placeholder`);\n add(`survey.questions.${q.id}.lowLabel`, q.lowLabel, \"text\", `${at} · Low label`);\n add(`survey.questions.${q.id}.highLabel`, q.highLabel, \"text\", `${at} · High label`);\n q.options.forEach((o) => add(`survey.questions.${q.id}.options.${o.id}.label`, o.label, \"text\", `${at} · Option “${o.label}”`));\n });\n add(\"survey.thankYouTitle\", sv.thankYouTitle, \"text\", \"Survey · Thank-you title\");\n add(\"survey.thankYouBody\", sv.thankYouBody, \"html\", \"Survey · Thank-you message\");\n }\n return out;\n}\n\n/** Locales a guide has any translation for. */\nexport function guideLocales(config: Pick<GuideConfig, \"localization\">): string[] {\n const t = config.localization?.translations ?? {};\n return Object.keys(t).filter((l) => Object.values(t[l] ?? {}).some((v) => typeof v === \"string\" && v.trim() !== \"\"));\n}\n\nfunction pick(map: Record<string, string> | undefined, key: string, fallback: string): string;\nfunction pick(map: Record<string, string> | undefined, key: string, fallback: string | undefined): string | undefined;\nfunction pick(map: Record<string, string> | undefined, key: string, fallback: string | undefined): string | undefined {\n const v = map?.[key];\n return typeof v === \"string\" && v.trim() !== \"\" ? v : fallback;\n}\n\n/** The config with one language's translations applied (untranslated texts keep the default language). */\nexport function applyGuideTranslations<C extends Pick<GuideConfig, \"steps\" | \"checklist\" | \"survey\">>(config: C, map: Record<string, string> | undefined): C {\n if (!map || !Object.keys(map).length) return config;\n return {\n ...config,\n steps: config.steps.map((s) => ({\n ...s,\n title: pick(map, `steps.${s.id}.title`, s.title),\n body: pick(map, `steps.${s.id}.body`, s.body),\n customHtml: pick(map, `steps.${s.id}.customHtml`, s.customHtml),\n imageAlt: pick(map, `steps.${s.id}.imageAlt`, s.imageAlt),\n buttons: s.buttons.map((b) => ({ ...b, label: pick(map, `steps.${s.id}.buttons.${b.id}.label`, b.label) })),\n })),\n checklist: config.checklist\n ? {\n ...config.checklist,\n launcherLabel: pick(map, \"checklist.launcherLabel\", config.checklist.launcherLabel),\n completionTitle: pick(map, \"checklist.completionTitle\", config.checklist.completionTitle),\n completionBody: pick(map, \"checklist.completionBody\", config.checklist.completionBody),\n tasks: config.checklist.tasks.map((t) => ({ ...t, title: pick(map, `checklist.tasks.${t.id}.title`, t.title), description: pick(map, `checklist.tasks.${t.id}.description`, t.description) })),\n }\n : config.checklist,\n survey: config.survey\n ? {\n ...config.survey,\n thankYouTitle: pick(map, \"survey.thankYouTitle\", config.survey.thankYouTitle),\n thankYouBody: pick(map, \"survey.thankYouBody\", config.survey.thankYouBody),\n questions: config.survey.questions.map((q) => ({\n ...q,\n title: pick(map, `survey.questions.${q.id}.title`, q.title),\n description: pick(map, `survey.questions.${q.id}.description`, q.description),\n placeholder: pick(map, `survey.questions.${q.id}.placeholder`, q.placeholder),\n lowLabel: pick(map, `survey.questions.${q.id}.lowLabel`, q.lowLabel),\n highLabel: pick(map, `survey.questions.${q.id}.highLabel`, q.highLabel),\n options: q.options.map((o) => ({ ...o, label: pick(map, `survey.questions.${q.id}.options.${o.id}.label`, o.label) })),\n })),\n }\n : config.survey,\n };\n}\n\n/**\n * The guide as a visitor speaking `requested` should see it, with `locale` set to the language\n * chosen (the default language when none of the guide's translations match).\n */\nexport function localizeGuide(guide: PublishedGuide, requested: readonly string[], defaultLocale: string = DEFAULT_LOCALE): PublishedGuide & { locale: string } {\n const translations = guide.config.localization?.translations ?? {};\n const locale = resolveLocale(requested, guideLocales(guide.config), defaultLocale);\n const key = Object.keys(translations).find((l) => normalizeLocale(l).toLowerCase() === locale.toLowerCase());\n if (!key) return { ...guide, locale };\n return { ...guide, locale, config: applyGuideTranslations(guide.config, translations[key]) };\n}\n\nexport interface TranslationCoverage {\n locale: string;\n total: number;\n translated: number;\n /** Keys with no translation. */\n missing: string[];\n /** Keys whose translation exists but whose key no longer matches any text (stale). */\n stale: string[];\n}\n\nexport function translationCoverage(entries: readonly TextEntry[], map: Record<string, string> | undefined, locale: string): TranslationCoverage {\n const keys = new Set(entries.map((e) => e.key));\n const missing = entries.filter((e) => !pick(map, e.key, undefined)).map((e) => e.key);\n const stale = Object.keys(map ?? {}).filter((k) => !keys.has(k) && (map?.[k] ?? \"\").trim() !== \"\");\n return { locale, total: entries.length, translated: entries.length - missing.length, missing, stale };\n}\n\n// ---------------------------------------------------------------------------\n// Resource center\n// ---------------------------------------------------------------------------\n\n/** Translations carried by the published resource center (texts other than articles and announcements). */\nexport type ResourceCenterTranslations = Record<string, Record<string, string>>;\n\n/** Translatable resource-center texts (title, launcher label, links, FAQs, collections). */\nexport function resourceCenterTextEntries(rc: Pick<ResourceCenterConfig, \"title\" | \"launcher\" | \"links\" | \"faqs\" | \"collections\">): TextEntry[] {\n const out: TextEntry[] = [];\n const add = (key: string, source: string | undefined | null, kind: TextKind, label: string) => {\n if (source && source.trim()) out.push({ key, source, kind, label });\n };\n add(\"title\", rc.title, \"text\", \"Title\");\n add(\"launcher.label\", rc.launcher?.label, \"text\", \"Launcher label\");\n rc.collections.forEach((c) => {\n add(`collections.${c.id}.name`, c.name, \"text\", `Collection “${c.name}”`);\n add(`collections.${c.id}.description`, c.description, \"text\", `Collection “${c.name}” · Description`);\n });\n rc.links.forEach((l) => add(`links.${l.id}.label`, l.label, \"text\", `Link “${l.label}”`));\n rc.faqs.forEach((f, i) => {\n add(`faqs.${f.id}.question`, f.question, \"text\", `FAQ ${i + 1} · Question`);\n add(`faqs.${f.id}.answer`, f.answer, \"html\", `FAQ ${i + 1} · Answer`);\n });\n return out;\n}\n\n/** Article texts, keyed `title` / `summary` / `body`. */\nexport function articleTextEntries(a: { title: string; summary?: string | null; body?: string | null }): TextEntry[] {\n const out: TextEntry[] = [];\n if (a.title.trim()) out.push({ key: \"title\", source: a.title, kind: \"text\", label: \"Title\" });\n if (a.summary?.trim()) out.push({ key: \"summary\", source: a.summary, kind: \"text\", label: \"Summary\" });\n if (a.body?.trim()) out.push({ key: \"body\", source: a.body, kind: \"html\", label: \"Body\" });\n return out;\n}\n\n/** Locales the resource center offers (its own strings, articles or announcements). */\nexport function resourceCenterLocales(rc: ResourceCenterConfig): string[] {\n const set = new Set<string>(Object.keys(rc.translations ?? {}));\n for (const a of rc.articles) for (const l of Object.keys(a.translations ?? {})) set.add(l);\n for (const a of rc.announcements ?? []) for (const l of Object.keys(a.translations ?? {})) set.add(l);\n return [...set];\n}\n\nfunction translationFor<T>(map: Record<string, T> | undefined, locale: string): T | undefined {\n if (!map) return undefined;\n const key = Object.keys(map).find((l) => normalizeLocale(l).toLowerCase() === locale.toLowerCase());\n return key ? map[key] : undefined;\n}\n\nexport function localizeArticle(a: ResourceCenterArticle, locale: string): ResourceCenterArticle {\n const t = translationFor(a.translations, locale);\n if (!t) return a;\n const body = t.body?.trim() ? t.body : a.body;\n // A translated body that was left out of the snapshot is fetched with `?locale=`.\n return { ...a, title: t.title?.trim() ? t.title : a.title, summary: t.summary?.trim() ? t.summary : a.summary, body, ...(t.bodyOmitted ? { bodyOmitted: true } : {}) };\n}\n\nexport function localizeAnnouncement(a: ResourceCenterAnnouncement, locale: string): ResourceCenterAnnouncement {\n const t = translationFor(a.translations, locale);\n if (!t) return a;\n return { ...a, title: t.title?.trim() ? t.title : a.title, body: t.body?.trim() ? t.body : a.body };\n}\n\n/** The resource center in the visitor's language (with `locale` = the language chosen). */\nexport function localizeResourceCenter(rc: ResourceCenterConfig, requested: readonly string[], defaultLocale: string = DEFAULT_LOCALE): ResourceCenterConfig & { locale: string } {\n const locale = resolveLocale(requested, resourceCenterLocales(rc), defaultLocale);\n if (locale.toLowerCase() === normalizeLocale(defaultLocale).toLowerCase()) return { ...rc, locale };\n const map = translationFor(rc.translations, locale);\n return {\n ...rc,\n locale,\n title: pick(map, \"title\", rc.title),\n launcher: { ...rc.launcher, label: pick(map, \"launcher.label\", rc.launcher.label) },\n collections: rc.collections.map((c) => ({ ...c, name: pick(map, `collections.${c.id}.name`, c.name), description: pick(map, `collections.${c.id}.description`, c.description) })),\n links: rc.links.map((l) => ({ ...l, label: pick(map, `links.${l.id}.label`, l.label) })),\n faqs: rc.faqs.map((f) => ({ ...f, question: pick(map, `faqs.${f.id}.question`, f.question), answer: pick(map, `faqs.${f.id}.answer`, f.answer) })),\n articles: rc.articles.map((a) => localizeArticle(a, locale)),\n announcements: rc.announcements?.map((a) => localizeAnnouncement(a, locale)),\n };\n}\n","/**\n * Guide A/B tests (zod-free; shared by the server, the web SDK and the mobile SDK ports).\n *\n * Each visitor falls into a bucket 0–99: `rolloutBucket(userId || anonymousId, salt)` (FNV-1a,\n * see utils.ts), with `salt = experimentSalt(experimentId)`. Variants own consecutive bucket ranges\n * in their listed order, sized by their integer weights (which sum to 100). The server folds each\n * variant's range into the targeting it serves as two `experiment.bucket` rules, so every SDK\n * applies the split with the rule engine it already has, and assignment is the same everywhere:\n * the server's `assignGuideVariant` and an SDK evaluating the served rules always agree.\n */\nimport { rolloutBucket } from \"./utils\";\nimport type { Rule, RuleGroup } from \"./targeting-eval\";\n\n/** The \"no guide\" variant: visitors in it see nothing, and are measured against the guide variants. */\nexport const CONTROL_VARIANT_ID = \"control\";\n\nexport const GUIDE_EXPERIMENT_STATUSES = [\"draft\", \"running\", \"completed\"] as const;\nexport type GuideExperimentStatus = (typeof GUIDE_EXPERIMENT_STATUSES)[number];\n\nexport const GUIDE_EXPERIMENT_GOALS = [\"guide_completed\", \"event\", \"page_visit\", \"click_text\"] as const;\nexport type GuideExperimentGoalKind = (typeof GUIDE_EXPERIMENT_GOALS)[number];\n\nexport const GUIDE_EXPERIMENT_GOAL_LABELS: Record<GuideExperimentGoalKind, string> = {\n guide_completed: \"Completes the guide\",\n event: \"Tracks an event\",\n page_visit: \"Visits a page\",\n click_text: \"Clicks an element with text\",\n};\n\nexport interface GuideExperimentGoal {\n kind: GuideExperimentGoalKind;\n /** Event name, page path pattern (`/billing/*`) or click text, depending on `kind`. */\n value?: string;\n}\n\nexport interface GuideExperimentVariant {\n id: string;\n name: string;\n /** The guide shown to this variant; null for the control group (no guide). */\n guideId: string | null;\n /** Share of visitors, a whole percentage; all weights sum to 100. */\n weight: number;\n}\n\nexport function experimentSalt(experimentId: string): string {\n return `gx:${experimentId}`;\n}\n\n/** Bucket ranges `[from, to)` per variant, in order. */\nexport function variantRanges(variants: ReadonlyArray<Pick<GuideExperimentVariant, \"id\" | \"weight\">>): Array<{ id: string; from: number; to: number }> {\n let at = 0;\n return variants.map((v) => {\n const from = at;\n at = Math.min(100, at + Math.max(0, Math.round(v.weight)));\n return { id: v.id, from, to: at };\n });\n}\n\n/** The variant a visitor is in, or null when weights leave their bucket unassigned. */\nexport function assignGuideVariant(variants: ReadonlyArray<Pick<GuideExperimentVariant, \"id\" | \"weight\">>, experimentId: string, subject: string): string | null {\n const bucket = rolloutBucket(subject, experimentSalt(experimentId));\n return variantRanges(variants).find((r) => bucket >= r.from && bucket < r.to)?.id ?? null;\n}\n\n/** Rules restricting targeting to bucket range `[from, to)` of `salt`. */\nexport function experimentBucketRules(salt: string, from: number, to: number): Rule[] {\n return [\n { id: \"experiment-from\", field: \"experiment.bucket\", key: salt, op: \"gte\", value: from },\n { id: \"experiment-to\", field: \"experiment.bucket\", key: salt, op: \"lt\", value: to },\n ];\n}\n\n/** Targeting with a variant's bucket range folded in (an SDK without `experiment.bucket` shows the guide to nobody). */\nexport function withExperimentBucket(targeting: RuleGroup, salt: string, from: number, to: number): RuleGroup {\n return { id: \"experiment\", op: \"and\", rules: [...experimentBucketRules(salt, from, to), targeting] };\n}\n\n/** Problems with a variant list; empty when it can run. */\nexport function variantProblems(variants: ReadonlyArray<GuideExperimentVariant>): string[] {\n const problems: string[] = [];\n if (variants.length < 2) problems.push(\"An A/B test needs at least two variants.\");\n if (variants.length > 5) problems.push(\"An A/B test can have at most five variants.\");\n const guides = variants.filter((v) => v.guideId);\n if (guides.length === 0) problems.push(\"At least one variant must show a guide.\");\n if (variants.filter((v) => !v.guideId).length > 1) problems.push(\"Only one variant can be the control group (no guide).\");\n if (new Set(guides.map((v) => v.guideId)).size !== guides.length) problems.push(\"Each variant needs its own guide.\");\n if (new Set(variants.map((v) => v.id)).size !== variants.length) problems.push(\"Variant ids must be unique.\");\n if (variants.some((v) => !Number.isInteger(v.weight) || v.weight < 1)) problems.push(\"Every variant needs a whole-number share of at least 1%.\");\n const total = variants.reduce((s, v) => s + v.weight, 0);\n if (total !== 100) problems.push(`Traffic shares must add up to 100% (now ${total}%).`);\n return problems;\n}\n\n/** Splits 100% as evenly as possible across `n` variants (first ones get the remainder). */\nexport function evenWeights(n: number): number[] {\n if (n <= 0) return [];\n const base = Math.floor(100 / n);\n return Array.from({ length: n }, (_, i) => base + (i < 100 - base * n ? 1 : 0));\n}\n","/**\n * Custom CSS for guides and themes (zod-free; the server sanitizes on save, the web runtime\n * sanitizes again and scopes before injecting).\n *\n * Guides render inside the SDK's Shadow DOM, so page styles and guide styles never mix. Within the\n * shadow root, every rule is additionally prefixed with the guide's own container selector, so one\n * guide's CSS can't restyle another guide, the resource center or the messenger. Sanitizing removes\n * what could reach outside the container or load anything: `@import`, `:host` / `::slotted` rules,\n * `url()`s other than https images and `data:image/…`, legacy script hooks (`expression()`,\n * `behavior`, `-moz-binding`, `javascript:`) and any markup.\n */\n\nexport const MAX_CUSTOM_CSS = 20000;\n\nconst BLOCKED_AT_RULES = /^@(import|charset|namespace|document|-moz-document)\\b/i;\nconst ALLOWED_AT_RULES = /^@(media|supports|container|layer|keyframes|-webkit-keyframes|font-face)\\b/i;\n\ninterface Block {\n /** Selector or at-rule prelude; \"\" for a bare declaration list. */\n prelude: string;\n /** Declarations (for rules) or nested CSS (for grouping at-rules). */\n body: string;\n}\n\n/** Splits CSS into top-level `prelude { body }` blocks, respecting strings and nesting. Statements without a block are dropped. */\nfunction splitBlocks(css: string): Block[] {\n const out: Block[] = [];\n let i = 0;\n const n = css.length;\n while (i < n) {\n let prelude = \"\";\n let quote: string | null = null;\n while (i < n) {\n const ch = css[i]!;\n if (quote) {\n prelude += ch;\n if (ch === \"\\\\\") prelude += css[++i] ?? \"\";\n else if (ch === quote) quote = null;\n } else if (ch === '\"' || ch === \"'\") {\n quote = ch;\n prelude += ch;\n } else if (ch === \"{\") break;\n else if (ch === \";\") {\n prelude = \"\"; // a statement (e.g. @import) – dropped\n } else if (ch === \"}\") {\n prelude = \"\"; // stray brace\n } else prelude += ch;\n i++;\n }\n if (i >= n) break;\n // css[i] === \"{\"\n i++;\n let depth = 1;\n let body = \"\";\n quote = null;\n while (i < n && depth > 0) {\n const ch = css[i]!;\n if (quote) {\n body += ch;\n if (ch === \"\\\\\") body += css[++i] ?? \"\";\n else if (ch === quote) quote = null;\n } else if (ch === '\"' || ch === \"'\") {\n quote = ch;\n body += ch;\n } else if (ch === \"{\") {\n depth++;\n body += ch;\n } else if (ch === \"}\") {\n depth--;\n if (depth > 0) body += ch;\n } else body += ch;\n i++;\n }\n out.push({ prelude: prelude.trim(), body });\n }\n return out;\n}\n\n/** Splits a selector list on top-level commas. */\nfunction splitSelectors(list: string): string[] {\n const out: string[] = [];\n let depth = 0;\n let cur = \"\";\n for (const ch of list) {\n if (ch === \"(\" || ch === \"[\") depth++;\n else if (ch === \")\" || ch === \"]\") depth = Math.max(0, depth - 1);\n if (ch === \",\" && depth === 0) {\n out.push(cur.trim());\n cur = \"\";\n } else cur += ch;\n }\n if (cur.trim()) out.push(cur.trim());\n return out;\n}\n\nfunction safeUrl(raw: string): boolean {\n const u = raw.trim().replace(/^['\"]|['\"]$/g, \"\").trim();\n return /^https:\\/\\//i.test(u) || /^data:image\\/(png|jpe?g|gif|webp|svg\\+xml)[;,]/i.test(u);\n}\n\n/** Cleans one declaration list. */\nfunction cleanDeclarations(body: string): string {\n return body\n .replace(/url\\(([^)]*)\\)/gi, (m, inner: string) => (safeUrl(inner) ? m : \"none\"))\n .replace(/expression\\s*\\(/gi, \"(\")\n .replace(/javascript\\s*:/gi, \"\")\n .replace(/(^|[;{\\s])(-moz-binding|behavior)\\s*:[^;]*;?/gi, \"$1\")\n .replace(/[{}]/g, \"\")\n .trim();\n}\n\n/** Removes everything unsafe; keeps the rule structure. */\nexport function sanitizeCustomCss(input: string | null | undefined): string {\n if (!input) return \"\";\n let css = String(input).slice(0, MAX_CUSTOM_CSS);\n css = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\").replace(/<(script|style)\\b[^>]*>[\\s\\S]*?<\\/\\1\\s*>/gi, \"\").replace(/<\\/?[a-z!][^>]*>/gi, \"\").replace(/</g, \"\");\n return render(splitBlocks(css), 0);\n}\n\nfunction render(blocks: Block[], depth: number): string {\n const parts: string[] = [];\n for (const b of blocks) {\n if (!b.prelude) continue;\n if (b.prelude.startsWith(\"@\")) {\n if (BLOCKED_AT_RULES.test(b.prelude) || !ALLOWED_AT_RULES.test(b.prelude)) continue;\n if (/^@(-webkit-)?keyframes|^@font-face/i.test(b.prelude)) {\n // Keyframe selectors (from/to/50%) and font-face descriptors are declarations-like.\n const inner = /^@font-face/i.test(b.prelude) ? cleanDeclarations(b.body) : splitBlocks(b.body).map((k) => `${k.prelude}{${cleanDeclarations(k.body)}}`).join(\"\");\n parts.push(`${b.prelude}{${inner}}`);\n } else if (depth < 3) parts.push(`${b.prelude}{${render(splitBlocks(b.body), depth + 1)}}`);\n continue;\n }\n const selectors = splitSelectors(b.prelude).filter((s) => !/:host|::slotted|::part/i.test(s));\n if (!selectors.length) continue;\n parts.push(`${selectors.join(\",\")}{${cleanDeclarations(b.body)}}`);\n }\n return parts.join(\"\\n\");\n}\n\n/**\n * Prefixes every selector with `scope` (e.g. `.g-scope[data-guide=\"abc\"]`). `:root`, `html`,\n * `body`, `:scope` and `&` at the start of a selector refer to the container itself.\n */\nexport function scopeCustomCss(css: string, scope: string): string {\n return scopeBlocks(splitBlocks(sanitizeCustomCss(css)), scope, 0);\n}\n\nfunction scopeBlocks(blocks: Block[], scope: string, depth: number): string {\n const parts: string[] = [];\n for (const b of blocks) {\n if (b.prelude.startsWith(\"@\")) {\n if (/^@(-webkit-)?keyframes|^@font-face/i.test(b.prelude)) parts.push(`${b.prelude}{${b.body}}`);\n else if (depth < 3) parts.push(`${b.prelude}{${scopeBlocks(splitBlocks(b.body), scope, depth + 1)}}`);\n continue;\n }\n const sels = splitSelectors(b.prelude).map((s) => {\n const self = s.match(/^(:root|html|body|:scope|&)(?![\\w-])(.*)$/i);\n if (self) return `${scope}${self[2] ?? \"\"}`;\n return `${scope} ${s}`;\n });\n parts.push(`${sels.join(\",\")}{${b.body}}`);\n }\n return parts.join(\"\\n\");\n}\n","/**\n * WCAG 2.1 colour contrast (zod-free). The editor warns when a guide's colours fall below AA:\n * 4.5:1 for body text, 3:1 for large text and UI components (button outlines, the close icon).\n */\n\nexport const WCAG_AA_TEXT = 4.5;\nexport const WCAG_AA_LARGE = 3;\n\nfunction channel(c: number): number {\n const s = c / 255;\n return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;\n}\n\n/** `#rgb` / `#rrggbb` → [r, g, b]; null when not a hex colour. */\nexport function parseHexColor(hex: string | null | undefined): [number, number, number] | null {\n if (!hex) return null;\n const m = hex.trim().match(/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i);\n if (!m) return null;\n const h = m[1]!.length === 3 ? m[1]!.split(\"\").map((c) => c + c).join(\"\") : m[1]!;\n return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];\n}\n\nexport function relativeLuminance(hex: string): number | null {\n const rgb = parseHexColor(hex);\n if (!rgb) return null;\n return 0.2126 * channel(rgb[0]) + 0.7152 * channel(rgb[1]) + 0.0722 * channel(rgb[2]);\n}\n\n/** Contrast ratio 1–21 between two hex colours, or null when either is not a hex colour. */\nexport function contrastRatio(a: string, b: string): number | null {\n const la = relativeLuminance(a);\n const lb = relativeLuminance(b);\n if (la === null || lb === null) return null;\n const [hi, lo] = la > lb ? [la, lb] : [lb, la];\n return Math.round(((hi + 0.05) / (lo + 0.05)) * 100) / 100;\n}\n\n/** Text colour (black or white) with the better contrast on `background`. */\nexport function readableTextOn(background: string): \"#ffffff\" | \"#111827\" {\n const white = contrastRatio(background, \"#ffffff\") ?? 0;\n const dark = contrastRatio(background, \"#111827\") ?? 0;\n return white >= dark ? \"#ffffff\" : \"#111827\";\n}\n\nexport interface ContrastIssue {\n /** What is hard to read. */\n pair: \"text\" | \"button\" | \"link\";\n ratio: number;\n required: number;\n message: string;\n}\n\n/**\n * Contrast problems of a guide's effective colours (guide appearance over the project theme).\n * Buttons use white or dark text, whichever reads better, so only a mid-tone primary colour fails.\n */\nexport function contrastIssues(colors: { primaryColor?: string; backgroundColor?: string; textColor?: string }): ContrastIssue[] {\n const issues: ContrastIssue[] = [];\n const { primaryColor, backgroundColor, textColor } = colors;\n if (textColor && backgroundColor) {\n const r = contrastRatio(textColor, backgroundColor);\n if (r !== null && r < WCAG_AA_TEXT) issues.push({ pair: \"text\", ratio: r, required: WCAG_AA_TEXT, message: `Text on the background has a contrast of ${r}:1; WCAG AA needs ${WCAG_AA_TEXT}:1.` });\n }\n if (primaryColor) {\n const label = contrastRatio(primaryColor, readableTextOn(primaryColor));\n if (label !== null && label < WCAG_AA_TEXT) issues.push({ pair: \"button\", ratio: label, required: WCAG_AA_TEXT, message: `Button labels on the primary colour have a contrast of ${label}:1; WCAG AA needs ${WCAG_AA_TEXT}:1.` });\n if (backgroundColor) {\n const link = contrastRatio(primaryColor, backgroundColor);\n if (link !== null && link < WCAG_AA_LARGE) issues.push({ pair: \"link\", ratio: link, required: WCAG_AA_LARGE, message: `The primary colour on the background (links, outlined buttons) has a contrast of ${link}:1; WCAG AA needs ${WCAG_AA_LARGE}:1.` });\n }\n }\n return issues;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AAC,qBAAqB,YAAY,MAAM,CAAC;AAAA,EAClM;AACA,MAAI,cAAc;AAChB,UAAM,QAAQ,cAAc,cAAc,eAAe,YAAY,CAAC;AACtE,QAAI,UAAU,QAAQ,QAAQ,aAAc,QAAO,KAAK,EAAE,MAAM,UAAU,OAAO,OAAO,UAAU,cAAc,SAAS,0DAA0D,KAAK,qBAAqB,YAAY,MAAM,CAAC;AAChO,QAAI,iBAAiB;AACnB,YAAM,OAAO,cAAc,cAAc,eAAe;AACxD,UAAI,SAAS,QAAQ,OAAO,cAAe,QAAO,KAAK,EAAE,MAAM,QAAQ,OAAO,MAAM,UAAU,eAAe,SAAS,oFAAoF,IAAI,qBAAqB,aAAa,MAAM,CAAC;AAAA,IACzP;AAAA,EACF;AACA,SAAO;AACT;","names":["str","has","words","pick","re"]}
1
+ {"version":3,"sources":["../src/runtime.ts","../src/utils.ts","../src/platform.ts","../src/widgets.ts","../src/targeting-eval.ts","../src/events-util.ts","../src/errors.ts","../src/network.ts","../src/media.ts","../src/resource-center.ts","../src/howto-limits.ts","../src/page.ts","../src/tagging.ts","../src/complaints-limits.ts","../src/bug-reports-limits.ts","../src/agents-limits.ts","../src/localization.ts","../src/guide-experiments.ts","../src/custom-css.ts","../src/contrast.ts","../src/error-detail.ts"],"sourcesContent":["/**\n * Zod-free entry for browser runtimes: `import { evaluateRules } from \"@guidelytech/shared/runtime\"`.\n * Keeps zod and the schema definitions out of the SDK bundle.\n */\nexport * from \"./utils\";\nexport * from \"./platform\";\nexport * from \"./widgets\";\nexport * from \"./targeting-eval\";\nexport * from \"./events-util\";\nexport * from \"./errors\";\nexport * from \"./network\";\nexport * from \"./media\";\nexport * from \"./resource-center\";\nexport * from \"./howto-limits\";\nexport * from \"./page\";\nexport * from \"./tagging\";\nexport * from \"./complaints-limits\";\nexport * from \"./bug-reports-limits\";\nexport * from \"./agents-limits\";\nexport * from \"./localization\";\nexport * from \"./guide-experiments\";\nexport * from \"./custom-css\";\nexport * from \"./contrast\";\nexport * from \"./error-detail\";\n","/** FNV-1a 32-bit hash; deterministic across SDK and server for rollout bucketing. */\nexport function fnv1a(input: string): number {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193) >>> 0;\n }\n return h >>> 0;\n}\n\n/** Deterministic 0-99 bucket for percentage rollouts. */\nexport function rolloutBucket(subject: string, salt: string): number {\n return fnv1a(`${salt}:${subject}`) % 100;\n}\n\nexport function slugify(input: string): string {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 64) || \"untitled\";\n}\n\nconst ALPHABET = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n/** URL-safe random id. Uses crypto when available, falls back to Math.random (ids are not secrets). */\nexport function randomId(size = 16): string {\n const g: any = typeof globalThis !== \"undefined\" ? globalThis : {};\n let bytes: Uint8Array;\n if (g.crypto && typeof g.crypto.getRandomValues === \"function\") {\n bytes = new Uint8Array(size);\n g.crypto.getRandomValues(bytes);\n } else {\n bytes = new Uint8Array(size);\n for (let i = 0; i < size; i++) bytes[i] = Math.floor(Math.random() * 256);\n }\n let out = \"\";\n for (let i = 0; i < size; i++) out += ALPHABET[(bytes[i] as number) % ALPHABET.length];\n return out;\n}\n\nexport function isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** Safe nested getter: get(obj, \"account.plan\") */\nexport function getPath(obj: unknown, path: string): unknown {\n if (!path) return obj;\n let cur: any = obj;\n for (const part of path.split(\".\")) {\n if (cur == null) return undefined;\n cur = cur[part];\n }\n return cur;\n}\n\nexport function clamp(n: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, n));\n}\n\n/** Glob-style URL pattern match: `*` matches any chars except `/`, `**` matches anything. */\nexport function matchUrlPattern(pattern: string, url: string): boolean {\n if (!pattern) return true;\n if (pattern === url) return true;\n const escaped = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*/g, \"__GLOBSTAR__\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/__GLOBSTAR__/g, \".*\");\n const re = new RegExp(`^${escaped}$`);\n return re.test(url) || re.test(stripOrigin(url));\n}\n\nexport function stripOrigin(url: string): string {\n try {\n const u = new URL(url);\n return u.pathname + u.search + u.hash;\n } catch {\n return url;\n }\n}\n\n/** Safe regexp construction with a length cap to limit ReDoS exposure. */\nexport function safeRegExp(source: string, flags = \"i\"): RegExp | null {\n if (!source || source.length > 200) return null;\n try {\n return new RegExp(source, flags);\n } catch {\n return null;\n }\n}\n","/**\n * Cross-platform helpers shared by the web SDK, the React Native SDK and (as a reference for) the\n * native iOS/Android SDKs. Zod-free so it can ship in runtime bundles.\n */\n\n/** Platforms a guide can be delivered to. */\nexport const PLATFORMS = [\"web\", \"ios\", \"android\"] as const;\nexport type Platform = (typeof PLATFORMS)[number];\n\n/** Guides published before platforms existed have no `platforms` field and are web-only. */\nexport const DEFAULT_PLATFORMS: Platform[] = [\"web\"];\n\n/** Platforms a guide config targets (missing field → web only). */\nexport function guidePlatforms(config: { platforms?: readonly string[] | null }): string[] {\n return Array.isArray(config.platforms) ? [...config.platforms] : [...DEFAULT_PLATFORMS];\n}\n\nexport function supportsPlatform(config: { platforms?: readonly string[] | null }, platform: string): boolean {\n return guidePlatforms(config).includes(platform);\n}\n\n/** Attribute web apps put on elements to share a target id with their mobile apps. */\nexport const GUIDELY_ID_ATTRIBUTE = \"data-guidely-id\";\n\n/**\n * Extracts a Guidely target id from a trigger / advance / checklist value so the same guide works on\n * web and mobile. Accepts a bare id (`new-deal`), `#new-deal`, or `[data-guidely-id=\"new-deal\"]`\n * (also `data-testid` / `data-tour`). Returns null for selectors that cannot name a single id.\n */\nexport function guidelyIdFromSelector(value: string | null | undefined): string | null {\n const v = (value ?? \"\").trim();\n if (!v) return null;\n if (/^[A-Za-z0-9_][A-Za-z0-9_\\-:.]*$/.test(v)) return v;\n const hash = v.match(/^#([A-Za-z0-9_][A-Za-z0-9_\\-:.]*)$/);\n if (hash) return hash[1] as string;\n const attr = v.match(/^(?:[a-z][a-z0-9]*)?\\[\\s*data-(?:guidely-id|testid|tour)\\s*=\\s*([\"']?)([^\"'\\]]+)\\1\\s*\\]$/i);\n if (attr) return (attr[2] as string).trim();\n return null;\n}\n\n/**\n * Mobile SDKs have screens instead of URLs. URL-based features (URL patterns, `url_match` triggers,\n * multi-page steps, `url_visited` checklist tasks) match against the screen path `/<ScreenName>`.\n */\nexport function screenPath(screen: string | null | undefined): string {\n const s = (screen ?? \"\").trim();\n if (!s) return \"/\";\n return s.startsWith(\"/\") ? s : `/${s}`;\n}\n\n/**\n * Compares dotted version strings numerically (`2.10.0` > `2.9.3`). Non-numeric parts compare as\n * strings; a missing part counts as 0 (`2.1` == `2.1.0`). Returns -1, 0 or 1, or null when either\n * side is empty.\n */\nexport function compareVersions(a: unknown, b: unknown): -1 | 0 | 1 | null {\n const sa = a == null ? \"\" : String(a).trim().replace(/^v/i, \"\");\n const sb = b == null ? \"\" : String(b).trim().replace(/^v/i, \"\");\n if (!sa || !sb) return null;\n const pa = sa.split(/[.+-]/);\n const pb = sb.split(/[.+-]/);\n const n = Math.max(pa.length, pb.length);\n for (let i = 0; i < n; i++) {\n const x = pa[i] ?? \"0\";\n const y = pb[i] ?? \"0\";\n const nx = /^\\d+$/.test(x) ? Number(x) : NaN;\n const ny = /^\\d+$/.test(y) ? Number(y) : NaN;\n if (!Number.isNaN(nx) && !Number.isNaN(ny)) {\n if (nx !== ny) return nx < ny ? -1 : 1;\n } else if (x !== y) {\n return x < y ? -1 : 1;\n }\n }\n return 0;\n}\n","/**\n * Pure checklist / survey logic shared by every renderer (web runtime, React Native, and the\n * reference for the native SDKs). Zod-free; uses structural types so it stays in the runtime entry.\n */\n\nexport type SurveyAnswer = string | number | boolean | string[];\nexport type SurveyAnswers = Record<string, SurveyAnswer>;\n\nexport interface ShowWhen {\n questionId: string;\n op: \"equals\" | \"lte\" | \"gte\" | \"in\";\n value: string | number | string[];\n}\n\n/** Evaluates a question's `showWhen` condition against current answers. */\nexport function isQuestionVisible(q: { showWhen?: ShowWhen }, answers: SurveyAnswers): boolean {\n if (!q.showWhen) return true;\n const actual = answers[q.showWhen.questionId];\n if (actual === undefined) return false;\n const expected = q.showWhen.value;\n switch (q.showWhen.op) {\n case \"equals\":\n return Array.isArray(actual) ? actual.includes(String(expected)) : String(actual) === String(expected);\n case \"lte\":\n return Number(actual) <= Number(expected);\n case \"gte\":\n return Number(actual) >= Number(expected);\n case \"in\": {\n const list = Array.isArray(expected) ? expected : [String(expected)];\n return Array.isArray(actual) ? actual.some((a) => list.includes(a)) : list.includes(String(actual));\n }\n default:\n return false;\n }\n}\n\n/** Are all required tasks done? */\nexport function isChecklistComplete(config: { tasks: Array<{ id: string; required: boolean }> }, progress: { completedTaskIds: string[] }): boolean {\n const done = new Set(progress.completedTaskIds);\n return config.tasks.filter((t) => t.required).every((t) => done.has(t.id));\n}\n","/**\n * Zod-free targeting evaluation. Imported by the browser SDK via `@guidelytech/shared/runtime`\n * so the runtime bundle does not pull in zod. Schemas live in ./targeting.ts.\n */\nimport { compareVersions } from \"./platform\";\nimport { getPath, matchUrlPattern, rolloutBucket, safeRegExp } from \"./utils\";\n\nexport const RULE_OPERATORS = [\n \"equals\",\n \"not_equals\",\n \"contains\",\n \"not_contains\",\n \"starts_with\",\n \"ends_with\",\n \"exists\",\n \"not_exists\",\n \"gt\",\n \"gte\",\n \"lt\",\n \"lte\",\n \"in\",\n \"not_in\",\n \"regex\",\n \"is_true\",\n \"is_false\",\n \"before\",\n \"after\",\n] as const;\nexport type RuleOperator = (typeof RULE_OPERATORS)[number];\n\nexport const RULE_FIELDS = [\n \"user.attribute\",\n \"account.attribute\",\n \"user.role\",\n \"user.plan\",\n \"user.identified\",\n \"url.path\",\n \"url.full\",\n \"url.query\",\n \"device.type\",\n \"device.browser\",\n \"device.os\",\n \"visitor.firstVisit\",\n \"visitor.returning\",\n \"event.seen\",\n \"guide.completed\",\n \"guide.dismissed\",\n \"guide.seen\",\n \"checklist.completed\",\n \"audience.member\",\n \"datetime.now\",\n \"datetime.dayOfWeek\",\n \"datetime.hour\",\n \"rollout.percentage\",\n /** Guide A/B tests: the visitor's 0-99 bucket for the salt in `key` (see guide-experiments.ts). */\n \"experiment.bucket\",\n \"environment\",\n \"locale\",\n \"app.platform\",\n \"app.screen\",\n \"app.version\",\n \"page.views\",\n \"feature.clicks\",\n] as const;\nexport type RuleField = (typeof RULE_FIELDS)[number];\n\nexport interface Rule {\n id: string;\n field: RuleField;\n /** For attribute/query/event fields: the attribute key, query param name, event name, guide id... */\n key?: string;\n op: RuleOperator;\n value?: string | number | boolean | string[];\n /** When true, the rule is negated (exclusion rule). */\n negate?: boolean;\n}\n\nexport type RuleGroup = {\n id: string;\n op: \"and\" | \"or\";\n rules: Array<Rule | RuleGroup>;\n negate?: boolean;\n};\n\nexport function isRuleGroup(r: Rule | RuleGroup): r is RuleGroup {\n return (r as RuleGroup).rules !== undefined;\n}\n\nexport function emptyRuleGroup(id = \"root\"): RuleGroup {\n return { id, op: \"and\", rules: [] };\n}\n\n/** Everything targeting evaluation can see. Built by the SDK (browser) or the server. */\nexport interface TargetingContext {\n userId?: string | null;\n anonymousId: string;\n userAttributes: Record<string, unknown>;\n accountAttributes: Record<string, unknown>;\n url: string;\n path: string;\n query: Record<string, string>;\n device: { type: \"desktop\" | \"tablet\" | \"mobile\"; browser?: string; os?: string };\n firstVisit: boolean;\n eventsSeen: Set<string> | string[];\n completedGuides: Set<string> | string[];\n dismissedGuides: Set<string> | string[];\n seenGuides: Set<string> | string[];\n completedChecklists: Set<string> | string[];\n audienceIds: Set<string> | string[];\n now: Date;\n environment: string;\n locale?: string;\n /** `web`, `ios` or `android`. Missing means web. */\n platform?: string;\n /** Current screen name (mobile SDKs; set via `screen()`). */\n screen?: string;\n /** Host app version (mobile SDKs), e.g. `2.4.1`. */\n appVersion?: string;\n /** Salt for rollout (guide id). Set per guide before evaluating. */\n rolloutSalt?: string;\n /**\n * Views of tagged pages / clicks on tagged features in the last 30 days, by tag id. Only the server\n * fills it (audience evaluation); in the browser `page.views` / `feature.clicks` read 0.\n */\n tagUsage?: Record<string, number>;\n}\n\nfunction has(set: Set<string> | string[] | undefined, v: string): boolean {\n if (!set) return false;\n return set instanceof Set ? set.has(v) : set.includes(v);\n}\n\nfunction resolveField(rule: Rule, ctx: TargetingContext): unknown {\n switch (rule.field) {\n case \"user.attribute\":\n return rule.key ? getPath(ctx.userAttributes, rule.key) : undefined;\n case \"account.attribute\":\n return rule.key ? getPath(ctx.accountAttributes, rule.key) : undefined;\n case \"user.role\":\n return ctx.userAttributes.role;\n case \"user.plan\":\n return ctx.userAttributes.plan ?? ctx.accountAttributes.plan;\n case \"user.identified\":\n return !!ctx.userId;\n case \"url.path\":\n return ctx.path;\n case \"url.full\":\n return ctx.url;\n case \"url.query\":\n return rule.key ? ctx.query[rule.key] : undefined;\n case \"device.type\":\n return ctx.device.type;\n case \"device.browser\":\n return ctx.device.browser;\n case \"device.os\":\n return ctx.device.os;\n case \"visitor.firstVisit\":\n return ctx.firstVisit;\n case \"visitor.returning\":\n return !ctx.firstVisit;\n case \"event.seen\":\n return rule.key ? has(ctx.eventsSeen, rule.key) : false;\n case \"guide.completed\":\n return rule.key ? has(ctx.completedGuides, rule.key) : false;\n case \"guide.dismissed\":\n return rule.key ? has(ctx.dismissedGuides, rule.key) : false;\n case \"guide.seen\":\n return rule.key ? has(ctx.seenGuides, rule.key) : false;\n case \"checklist.completed\":\n return rule.key ? has(ctx.completedChecklists, rule.key) : false;\n case \"audience.member\":\n return rule.key ? has(ctx.audienceIds, rule.key) : false;\n case \"datetime.now\":\n return ctx.now.toISOString();\n case \"datetime.dayOfWeek\":\n return ctx.now.getDay();\n case \"datetime.hour\":\n return ctx.now.getHours();\n case \"rollout.percentage\":\n return rolloutBucket(ctx.userId || ctx.anonymousId, ctx.rolloutSalt || \"guidely\");\n case \"experiment.bucket\":\n return rule.key ? rolloutBucket(ctx.userId || ctx.anonymousId, rule.key) : undefined;\n case \"environment\":\n return ctx.environment;\n case \"locale\":\n return ctx.locale;\n case \"app.platform\":\n return ctx.platform ?? \"web\";\n case \"app.screen\":\n return ctx.screen;\n case \"app.version\":\n return ctx.appVersion;\n case \"page.views\":\n case \"feature.clicks\":\n return rule.key ? (ctx.tagUsage?.[rule.key] ?? 0) : 0;\n default:\n return undefined;\n }\n}\n\nfunction toNumber(v: unknown): number | null {\n if (typeof v === \"number\") return v;\n if (typeof v === \"string\" && v.trim() !== \"\" && !Number.isNaN(Number(v))) return Number(v);\n if (v instanceof Date) return v.getTime();\n return null;\n}\n\nfunction toDateMs(v: unknown): number | null {\n if (v instanceof Date) return v.getTime();\n if (typeof v === \"string\") {\n const t = Date.parse(v);\n return Number.isNaN(t) ? null : t;\n }\n if (typeof v === \"number\") return v;\n return null;\n}\n\nexport function compare(op: RuleOperator, actual: unknown, expected: Rule[\"value\"]): boolean {\n switch (op) {\n case \"exists\":\n return actual !== undefined && actual !== null && actual !== \"\";\n case \"not_exists\":\n return actual === undefined || actual === null || actual === \"\";\n case \"is_true\":\n return actual === true || actual === \"true\";\n case \"is_false\":\n return actual === false || actual === \"false\";\n case \"equals\":\n if (typeof actual === \"boolean\") return String(actual) === String(expected);\n return String(actual ?? \"\") === String(expected ?? \"\");\n case \"not_equals\":\n return String(actual ?? \"\") !== String(expected ?? \"\");\n case \"contains\":\n return typeof actual === \"string\" && actual.toLowerCase().includes(String(expected ?? \"\").toLowerCase());\n case \"not_contains\":\n return !(typeof actual === \"string\" && actual.toLowerCase().includes(String(expected ?? \"\").toLowerCase()));\n case \"starts_with\":\n return typeof actual === \"string\" && actual.startsWith(String(expected ?? \"\"));\n case \"ends_with\":\n return typeof actual === \"string\" && actual.endsWith(String(expected ?? \"\"));\n case \"gt\":\n case \"gte\":\n case \"lt\":\n case \"lte\": {\n const a = toNumber(actual);\n const b = toNumber(expected);\n if (a === null || b === null) return false;\n return op === \"gt\" ? a > b : op === \"gte\" ? a >= b : op === \"lt\" ? a < b : a <= b;\n }\n case \"in\": {\n const list = Array.isArray(expected) ? expected : String(expected ?? \"\").split(\",\").map((s) => s.trim());\n return list.includes(String(actual ?? \"\"));\n }\n case \"not_in\": {\n const list = Array.isArray(expected) ? expected : String(expected ?? \"\").split(\",\").map((s) => s.trim());\n return !list.includes(String(actual ?? \"\"));\n }\n case \"regex\": {\n const re = safeRegExp(String(expected ?? \"\"));\n return !!re && typeof actual === \"string\" && re.test(actual);\n }\n case \"before\": {\n const a = toDateMs(actual);\n const b = toDateMs(expected);\n return a !== null && b !== null && a < b;\n }\n case \"after\": {\n const a = toDateMs(actual);\n const b = toDateMs(expected);\n return a !== null && b !== null && a > b;\n }\n default:\n return false;\n }\n}\n\nexport function evaluateRule(rule: Rule, ctx: TargetingContext): boolean {\n let result: boolean;\n if (rule.field === \"url.path\" || rule.field === \"url.full\" || rule.field === \"app.screen\") {\n const actual = String(resolveField(rule, ctx) ?? \"\");\n if (rule.op === \"equals\") result = matchUrlPattern(String(rule.value ?? \"\"), actual);\n else if (rule.op === \"not_equals\") result = !matchUrlPattern(String(rule.value ?? \"\"), actual);\n else result = compare(rule.op, actual, rule.value);\n } else if (rule.field === \"app.version\" && [\"equals\", \"not_equals\", \"gt\", \"gte\", \"lt\", \"lte\"].includes(rule.op)) {\n const c = compareVersions(resolveField(rule, ctx), rule.value);\n if (c === null) result = rule.op === \"not_equals\";\n else result = rule.op === \"equals\" ? c === 0 : rule.op === \"not_equals\" ? c !== 0 : rule.op === \"gt\" ? c > 0 : rule.op === \"gte\" ? c >= 0 : rule.op === \"lt\" ? c < 0 : c <= 0;\n } else {\n result = compare(rule.op, resolveField(rule, ctx), rule.value);\n }\n return rule.negate ? !result : result;\n}\n\n/** Evaluate a rule tree. An empty group matches everyone. */\nexport function evaluateRules(group: RuleGroup | null | undefined, ctx: TargetingContext): boolean {\n if (!group || group.rules.length === 0) return group?.negate ? false : true;\n const results = group.rules.map((r) => (isRuleGroup(r) ? evaluateRules(r, ctx) : evaluateRule(r, ctx)));\n const value = group.op === \"and\" ? results.every(Boolean) : results.some(Boolean);\n return group.negate ? !value : value;\n}\n\n/** Fields whose evaluation requires server-held data. Used by docs/UI to annotate rules. */\nexport const SERVER_ASSISTED_FIELDS: RuleField[] = [\"audience.member\", \"guide.completed\", \"guide.dismissed\", \"guide.seen\", \"checklist.completed\", \"page.views\", \"feature.clicks\"];\n\n/** Who a guide is shown to, before its targeting rules: everyone, only signed-in (identified) users, or only anonymous visitors. */\nexport const GUIDE_VISIBILITIES = [\"everyone\", \"identified\", \"anonymous\"] as const;\nexport type GuideVisibility = (typeof GUIDE_VISIBILITIES)[number];\n\n/**\n * Targeting with the visibility folded in as a `user.identified` rule. The server sends guides to SDKs\n * this way, so every SDK applies it through the rules it already evaluates (SDKs that predate the field\n * resolve it as undefined and show the guide to nobody rather than to everyone).\n */\nexport function withVisibility(targeting: RuleGroup, visibility: GuideVisibility | undefined): RuleGroup {\n if (!visibility || visibility === \"everyone\") return targeting;\n return { id: \"visibility\", op: \"and\", rules: [{ id: \"visibility-rule\", field: \"user.identified\", op: visibility === \"identified\" ? \"is_true\" : \"is_false\" }, targeting] };\n}\n\nexport function describeRule(rule: Rule): string {\n const subject = rule.key ? `${rule.field}[${rule.key}]` : rule.field;\n const v = Array.isArray(rule.value) ? rule.value.join(\", \") : rule.value === undefined ? \"\" : String(rule.value);\n return `${rule.negate ? \"NOT \" : \"\"}${subject} ${rule.op.replace(/_/g, \" \")}${v ? ` \"${v}\"` : \"\"}`;\n}\n","/** Reserved property names that are stripped from `properties` to avoid collecting sensitive data. */\nexport const SENSITIVE_PROPERTY_PATTERN = /(password|passwd|secret|token|credit|card|cvv|ssn|iban)/i;\n\nexport const MAX_PROPERTY_BYTES = 8 * 1024;\n\n/** Longest app version kept (longer values are cut). */\nexport const MAX_APP_VERSION_LENGTH = 64;\n\n/**\n * An app version as stored and reported: trimmed, control characters removed, at most 64 characters,\n * or null when empty. Kept verbatim otherwise (`2.4.1`, `v2.4.1`, `2026.10.26-beta+512`), so reports\n * show what the app sent; ordering uses `compareVersions`.\n */\nexport function normalizeAppVersion(input: unknown): string | null {\n if (typeof input !== \"string\" && typeof input !== \"number\") return null;\n const printable = Array.from(String(input)).filter((c) => c.charCodeAt(0) > 31 && c.charCodeAt(0) !== 127).join(\"\");\n const v = printable.trim().slice(0, MAX_APP_VERSION_LENGTH).trim();\n return v || null;\n}\n\nexport function sanitizeProperties(props: Record<string, unknown> | undefined): Record<string, unknown> {\n if (!props) return {};\n const out: Record<string, unknown> = {};\n let size = 0;\n for (const [k, v] of Object.entries(props)) {\n if (SENSITIVE_PROPERTY_PATTERN.test(k)) continue;\n if (typeof v === \"function\" || typeof v === \"symbol\") continue;\n const str = typeof v === \"string\" ? v : JSON.stringify(v ?? null);\n size += k.length + (str?.length ?? 0);\n if (size > MAX_PROPERTY_BYTES) break;\n out[k.slice(0, 100)] = typeof v === \"string\" ? v.slice(0, 1000) : v;\n }\n return out;\n}\n","import { fnv1a } from \"./utils\";\n\n/** One parsed stack frame. `file` is the script URL (or path) as the browser reported it. */\nexport interface StackFrame {\n fn?: string;\n file?: string;\n line?: number;\n col?: number;\n /** False for library / framework frames (Sentry `in_app`); grouping skips them when an app frame exists. Unset = unknown. */\n inApp?: boolean;\n /** Module or package (Sentry `module`: `myapp.views`, `com.acme.Foo`), for platforms without file paths. */\n module?: string;\n /** JavaScript debug id of the frame's file (Sentry `debug_meta.images`); selects its source map before release + path. */\n debugId?: string;\n}\n\n/** Properties carried by an `exception` event (see `docs/product-analytics.md`). */\nexport interface ExceptionProperties {\n type: string;\n message: string;\n frames: StackFrame[];\n /** `onerror` | `unhandledrejection` | `manual` (captureException) | `console`. */\n source?: string;\n handled?: boolean;\n /** App version or commit (SDK option `release`); selects the matching uploaded source maps. */\n release?: string;\n /** Set by the server at ingestion; groups occurrences into an issue. */\n fingerprint?: string;\n}\n\nexport const MAX_STACK_FRAMES = 30;\n\n// Chrome / Edge / Node: \" at fn (https://x/app.js:1:2)\" or \" at https://x/app.js:1:2\"\nconst V8 = /^\\s*at (?:(.+?) \\()?((?:[a-z][\\w+.-]*:)?[^\\s()]+?):(\\d+):(\\d+)\\)?\\s*$/i;\n// Firefox / Safari: \"fn@https://x/app.js:1:2\" or \"@https://x/app.js:1:2\"\nconst GECKO = /^\\s*(.*?)@(.+?):(\\d+):(\\d+)\\s*$/;\n// Hermes (React Native release builds): \" at fn (address at index.android.bundle:1:9876)\"; the column is a bytecode offset.\nconst HERMES = /^\\s*at (?:(.+?) \\()?address at ([^\\s()]+?):(\\d+):(\\d+)\\)?\\s*$/;\n\n/**\n * `app:///<bundle>` for a React Native bundle path (`/data/…/index.android.bundle`,\n * `main.jsbundle`), so source maps uploaded with `--url-prefix /` match on any device.\n */\nexport function reactNativeBundleUrl(file: string): string {\n const base = file.replace(/[?#].*$/, \"\").split(\"/\").pop() || file;\n return `app:///${base}`;\n}\n\n/** Parses `Error.stack` from V8, SpiderMonkey, JavaScriptCore and Hermes into frames (innermost first). */\nexport function parseStack(stack: string | undefined | null, max = MAX_STACK_FRAMES): StackFrame[] {\n if (!stack || typeof stack !== \"string\") return [];\n const frames: StackFrame[] = [];\n for (const raw of stack.split(\"\\n\")) {\n if (frames.length >= max) break;\n const line = raw.slice(0, 1000);\n const hermes = HERMES.exec(line);\n const m = hermes ?? V8.exec(line) ?? GECKO.exec(line);\n if (!m) continue;\n const fn = (m[1] || \"\").trim();\n const file = hermes ? reactNativeBundleUrl(m[2]!) : m[2];\n frames.push({ fn: fn ? fn.slice(0, 200) : undefined, file: file?.slice(0, 500), line: Number(m[3]), col: Number(m[4]) });\n }\n return frames;\n}\n\n/** Replaces volatile parts of a message (numbers, ids, quoted values) so repeats group together. */\nexport function normalizeErrorMessage(message: string): string {\n return (message || \"\")\n .slice(0, 500)\n .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, \"<uuid>\")\n .replace(/([\"'`]).*?\\1/g, \"<str>\")\n .replace(/\\b0x[0-9a-f]+\\b/gi, \"<hex>\")\n .replace(/\\d+(\\.\\d+)?/g, \"<n>\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\n/** Strips origin, query, hash and build hashes (`main.3f2a1b9c.js` → `main.js`) from a script URL. */\nexport function normalizeFrameFile(file: string | undefined): string {\n if (!file) return \"\";\n let path = file;\n try {\n path = new URL(file).pathname;\n } catch {\n path = file.replace(/[?#].*$/, \"\");\n }\n return path.replace(/[.-][0-9a-f]{6,}(?=\\.\\w+$)/i, \"\").replace(/\\/\\d+\\//g, \"/<n>/\");\n}\n\n/** Source map upload limits (`POST /api/v1/sourcemaps/upload`). */\n/** Per map, uncompressed (the CLI uploads maps gzipped). */\nexport const SOURCEMAP_MAX_FILE_BYTES = 100 * 1024 * 1024;\nexport const SOURCEMAP_MAX_FILES_PER_UPLOAD = 200;\n\n/**\n * Stable issue key for an exception: error type + normalised message + the innermost frame that\n * has a file (path without build hash + function name, or its original source + name when a source\n * map resolved it). Line/column numbers are left out because they change with every deploy of a\n * minified bundle.\n */\nexport function fingerprintError(input: { type?: string; message?: string; frames?: StackFrame[]; original?: { source: string; name?: string | null } | null }): string {\n // The innermost app frame when frames say which are app code (Sentry SDKs), else the innermost frame with a file.\n const withFile = (input.frames ?? []).filter((f) => f.file || f.module);\n const top = withFile.find((f) => f.inApp === true) ?? withFile.find((f) => f.inApp !== false) ?? withFile[0];\n // With a source map the original file and function name identify the frame across deploys, even\n // when a minifier renames functions between builds.\n const frameKey = input.original ? `src:${input.original.source}:${input.original.name || \"?\"}` : top ? `${top.file ? normalizeFrameFile(top.file) : `mod:${top.module}`}:${top.fn || \"?\"}` : \"\";\n const key = [input.type || \"Error\", normalizeErrorMessage(input.message || \"\"), frameKey].join(\"|\");\n const a = fnv1a(key).toString(16).padStart(8, \"0\");\n const b = fnv1a(`guidely:${key}`).toString(16).padStart(8, \"0\");\n return a + b;\n}\n\n/**\n * Applies an SDK-supplied fingerprint (Sentry `fingerprint`: `[\"{{ default }}\", \"checkout\"]`) to the\n * computed one. `{{ default }}` stands for the computed fingerprint; without it the parts replace it.\n */\nexport function customFingerprint(parts: unknown, computed: string): string {\n if (!Array.isArray(parts) || parts.length === 0) return computed;\n const items = parts.filter((p): p is string | number => typeof p === \"string\" || typeof p === \"number\").map((p) => String(p).slice(0, 200)).slice(0, 20);\n if (items.length === 0) return computed;\n const isDefault = (p: string) => /^\\{\\{\\s*default\\s*\\}\\}$/i.test(p);\n if (items.every(isDefault)) return computed;\n const key = items.map((p) => (isDefault(p) ? computed : p)).join(\"|\");\n return fnv1a(key).toString(16).padStart(8, \"0\") + fnv1a(`guidely:fp:${key}`).toString(16).padStart(8, \"0\");\n}\n","/* Network requests recorded into session replays (zod-free: imported by the SDK recorder). */\n\n/** rrweb plugin name for network events in recordings (event type 6, `data.plugin`). */\nexport const NETWORK_PLUGIN = \"guidely/network@1\";\n\n/** Request kinds, from `fetch`/`XMLHttpRequest` patching or `PerformanceResourceTiming.initiatorType`. */\nexport type NetworkRequestType = \"fetch\" | \"xhr\" | \"websocket\" | \"document\" | \"script\" | \"stylesheet\" | \"image\" | \"font\" | \"media\" | \"beacon\" | \"other\";\n\n/**\n * One network request in a recording: the payload of an rrweb plugin event\n * `{ type: 6, data: { plugin: NETWORK_PLUGIN, payload: NetworkPluginPayload } }`, batched.\n * Times are epoch milliseconds (same clock as rrweb event timestamps).\n *\n * A WebSocket is a request with `type: \"websocket\"` and `method: \"GET\"`, emitted when it opens\n * (`startTime`) and again, with the same `id`, when it closes (`endTime`, `closeCode`, `closeReason`,\n * totals in `messages`). Its frames are `WebSocketMessage`s referencing that `id`.\n */\nexport interface NetworkRequest {\n /** Stable id within the recording. */\n id: string;\n type: NetworkRequestType;\n method: string;\n /** Absolute URL; values of sensitive-looking query parameters replaced with `[redacted]`. */\n url: string;\n startTime: number;\n endTime?: number;\n durationMs?: number;\n /** HTTP status; 0 for network errors / blocked / aborted. Absent when the browser doesn't expose it. */\n status?: number;\n /** Set for failed requests: network error, abort or timeout message. */\n error?: string;\n /** Encoded bytes transferred / decoded response size, when known. */\n transferSize?: number;\n responseSize?: number;\n /** Only when `recordNetworkPayloads` is on; sensitive headers are `[redacted]`. */\n requestHeaders?: Record<string, string>;\n responseHeaders?: Record<string, string>;\n /** Text/JSON bodies, ≤10KB, sensitive JSON fields masked; `[binary]` / `[truncated]` markers otherwise. */\n requestBody?: string;\n responseBody?: string;\n /** WebSocket only: negotiated subprotocol, close details, and frame totals (all frames, including ones not recorded). */\n protocol?: string;\n closeCode?: number;\n closeReason?: string;\n messages?: { sent: number; received: number; sentBytes: number; receivedBytes: number; recorded: number };\n}\n\n/** One WebSocket frame. At most `WS_MAX_MESSAGES_PER_SOCKET` are recorded per connection per page load. */\nexport interface WebSocketMessage {\n /** The `NetworkRequest.id` of the connection. */\n socketId: string;\n dir: \"send\" | \"recv\";\n time: number;\n /** Bytes (UTF-8 length for text frames). */\n size: number;\n binary?: boolean;\n /** Only with `recordNetworkPayloads`: text ≤ 2KB (JSON with sensitive keys masked), else `[truncated]`; binary frames are `[binary <n> B]`. */\n data?: string;\n}\n\nexport interface NetworkPluginPayload {\n requests?: NetworkRequest[];\n messages?: WebSocketMessage[];\n /** Requests/frames dropped since the previous payload because a cap was reached. */\n dropped?: { requests?: number; messages?: number };\n}\n\nexport const WS_MAX_MESSAGES_PER_SOCKET = 200;\nexport const WS_MAX_MESSAGE_BYTES = 2048;\n\n/** Header names always replaced with `[redacted]` when payload capture is on. */\nexport const SENSITIVE_HEADER_PATTERN = /^(authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token|x-csrf-token|x-xsrf-token|x-guidely-key|x-guidely-conversation)$/i;\n\n/** Query parameter and JSON field names whose values are redacted. */\nexport const SENSITIVE_PARAM_PATTERN = /(token|key|secret|password|passwd|pwd|auth|session|code|sig|signature|credential|ssn|card|cvv|iban)/i;\n","/**\n * Media in article bodies: uploaded images, videos and PDFs, and video embeds from a fixed set of hosts.\n * Sanitizers (server, browser runtime) only keep an `<iframe>` whose `src` is the canonical embed URL\n * that `toEmbedUrl` produces, so authors can never point a frame anywhere else.\n *\n * An uploaded PDF reads inline, as its pages: the dashboard renders each page to an image when the\n * PDF is uploaded, and the body holds plain HTML every renderer already understands:\n *\n * <div class=\"gd-pdf\">\n * <a class=\"gd-file\" href=\"…/{id}.pdf\" target=\"_blank\">{file name}</a>\n * <div class=\"gd-pdf-pages\"><img src=\"…/{page}.webp\" alt=\"{file name}, page 1 of 12\"> …</div>\n * </div>\n *\n * Renderers that know the classes draw a swipeable page viewer with the PDF one tap away; older ones\n * show a link and the pages as images. A PDF whose pages couldn't be rendered (password-protected,\n * damaged) is just the `gd-file` link, drawn as a file card.\n */\n\nexport type EmbedProvider = \"youtube\" | \"vimeo\" | \"loom\" | \"wistia\";\n\nexport interface VideoEmbed {\n provider: EmbedProvider;\n /** Canonical player URL, safe to use as an iframe `src`. */\n src: string;\n /** Page a viewer can open instead (native SDKs show a link rather than a player). */\n watchUrl: string;\n /** Accessible iframe title. */\n title: string;\n}\n\nexport const MEDIA_IMAGE_TYPES = [\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"] as const;\nexport const MEDIA_VIDEO_TYPES = [\"video/mp4\", \"video/webm\"] as const;\nexport const MEDIA_FILE_TYPES = [\"application/pdf\"] as const;\nexport type MediaContentType = (typeof MEDIA_IMAGE_TYPES)[number] | (typeof MEDIA_VIDEO_TYPES)[number] | (typeof MEDIA_FILE_TYPES)[number];\nexport type MediaKind = \"image\" | \"video\" | \"file\";\nexport const MEDIA_IMAGE_MAX_BYTES = 10 * 1024 * 1024;\nexport const MEDIA_VIDEO_MAX_BYTES = 200 * 1024 * 1024;\nexport const MEDIA_FILE_MAX_BYTES = 50 * 1024 * 1024;\n/** The largest upload of any type. */\nexport const MEDIA_MAX_BYTES = Math.max(MEDIA_IMAGE_MAX_BYTES, MEDIA_VIDEO_MAX_BYTES, MEDIA_FILE_MAX_BYTES);\n\nexport function isMediaContentType(type: string): type is MediaContentType {\n return mediaKind(type) !== null;\n}\nexport function isVideoContentType(type: string): boolean {\n return (MEDIA_VIDEO_TYPES as readonly string[]).includes(type);\n}\nexport function mediaKind(type: string): MediaKind | null {\n if ((MEDIA_IMAGE_TYPES as readonly string[]).includes(type)) return \"image\";\n if ((MEDIA_VIDEO_TYPES as readonly string[]).includes(type)) return \"video\";\n if ((MEDIA_FILE_TYPES as readonly string[]).includes(type)) return \"file\";\n return null;\n}\nexport function mediaMaxBytes(type: string): number {\n const kind = mediaKind(type);\n return kind === \"video\" ? MEDIA_VIDEO_MAX_BYTES : kind === \"file\" ? MEDIA_FILE_MAX_BYTES : MEDIA_IMAGE_MAX_BYTES;\n}\n\n/** Class marking a link as an attached file (an uploaded PDF), drawn as a file card. */\nexport const FILE_LINK_CLASS = \"gd-file\";\n/** Class of the block holding a PDF's link and its rendered pages. */\nexport const PDF_BLOCK_CLASS = \"gd-pdf\";\n/** Class of the element wrapping a PDF's page images. */\nexport const PDF_PAGES_CLASS = \"gd-pdf-pages\";\n/** Pages rendered inline per PDF; readers open the PDF itself for the rest. */\nexport const PDF_MAX_PAGES = 40;\n\n/** True for an `<a>` with the file class and an absolute http(s) `href`: render it as a file card. */\nexport function isFileLink(className: string | null | undefined, href: string | null | undefined): boolean {\n return !!className && className.split(/\\s+/).includes(FILE_LINK_CLASS) && isSafeMediaUrl(href);\n}\n\nconst YOUTUBE_ID = /^[A-Za-z0-9_-]{11}$/;\nconst VIMEO_ID = /^\\d{1,12}$/;\nconst VIMEO_HASH = /^[0-9a-f]{6,20}$/i;\nconst LOOM_ID = /^[0-9a-f]{32}$/i;\nconst WISTIA_ID = /^[a-z0-9]{10}$/i;\n\nfunction parseUrl(input: string): URL | null {\n const s = input.trim();\n if (!s) return null;\n try {\n const u = new URL(/^[a-z][a-z0-9+.-]*:/i.test(s) ? s : `https://${s}`);\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n if (u.username || u.password || (u.port && u.port !== \"443\" && u.port !== \"80\")) return null;\n return u;\n } catch {\n return null;\n }\n}\n\n/** \"1h2m3s\", \"90s\", \"90\" → seconds. */\nfunction parseStart(v: string | null): number {\n if (!v) return 0;\n if (/^\\d+$/.test(v)) return Math.min(Number(v), 86400);\n const m = /^(?:(\\d+)h)?(?:(\\d+)m)?(?:(\\d+)s)?$/.exec(v);\n if (!m || !m[0]) return 0;\n return Math.min(Number(m[1] ?? 0) * 3600 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0), 86400);\n}\n\nfunction youtube(id: string, start: number): VideoEmbed | null {\n if (!YOUTUBE_ID.test(id)) return null;\n return {\n provider: \"youtube\",\n src: `https://www.youtube-nocookie.com/embed/${id}${start ? `?start=${start}` : \"\"}`,\n watchUrl: `https://www.youtube.com/watch?v=${id}${start ? `&t=${start}s` : \"\"}`,\n title: \"YouTube video\",\n };\n}\n\nfunction vimeo(id: string, hash: string | null): VideoEmbed | null {\n if (!VIMEO_ID.test(id) || (hash !== null && !VIMEO_HASH.test(hash))) return null;\n const h = hash ? hash.toLowerCase() : null;\n return { provider: \"vimeo\", src: `https://player.vimeo.com/video/${id}${h ? `?h=${h}` : \"\"}`, watchUrl: `https://vimeo.com/${id}${h ? `/${h}` : \"\"}`, title: \"Vimeo video\" };\n}\n\n/**\n * Turns a pasted video page or player URL from YouTube, Vimeo, Loom or Wistia into its canonical\n * embed. Returns null for anything else, including lookalike hosts.\n */\nexport function toEmbedUrl(input: string): VideoEmbed | null {\n const u = parseUrl(input);\n if (!u) return null;\n const host = u.hostname.toLowerCase().replace(/^www\\./, \"\");\n const parts = u.pathname.split(\"/\").filter(Boolean);\n switch (host) {\n case \"youtube.com\":\n case \"m.youtube.com\":\n case \"youtube-nocookie.com\": {\n const start = parseStart(u.searchParams.get(\"start\") ?? u.searchParams.get(\"t\"));\n if (parts[0] === \"watch\" && parts.length === 1) return youtube(u.searchParams.get(\"v\") ?? \"\", start);\n if ((parts[0] === \"embed\" || parts[0] === \"shorts\" || parts[0] === \"live\") && parts.length === 2) return youtube(parts[1]!, start);\n return null;\n }\n case \"youtu.be\":\n return parts.length === 1 ? youtube(parts[0]!, parseStart(u.searchParams.get(\"t\") ?? u.searchParams.get(\"start\"))) : null;\n case \"vimeo.com\":\n if (parts.length === 1) return vimeo(parts[0]!, null);\n if (parts.length === 2 && VIMEO_ID.test(parts[0]!)) return vimeo(parts[0]!, parts[1]!);\n return null;\n case \"player.vimeo.com\":\n return parts[0] === \"video\" && parts.length === 2 ? vimeo(parts[1]!, u.searchParams.get(\"h\")) : null;\n case \"loom.com\":\n if ((parts[0] === \"share\" || parts[0] === \"embed\") && parts.length === 2 && LOOM_ID.test(parts[1]!)) {\n const id = parts[1]!.toLowerCase();\n return { provider: \"loom\", src: `https://www.loom.com/embed/${id}`, watchUrl: `https://www.loom.com/share/${id}`, title: \"Loom video\" };\n }\n return null;\n default: {\n let id: string | undefined;\n if (host === \"fast.wistia.net\" || host === \"fast.wistia.com\") id = parts[0] === \"embed\" && parts[1] === \"iframe\" && parts.length === 3 ? parts[2] : undefined;\n else if (host === \"wi.st\" || host === \"wistia.com\" || /^[a-z0-9-]+\\.wistia\\.com$/.test(host)) id = parts[0] === \"medias\" && parts.length === 2 ? parts[1] : undefined;\n if (!id || !WISTIA_ID.test(id)) return null;\n return { provider: \"wistia\", src: `https://fast.wistia.net/embed/iframe/${id}`, watchUrl: `https://fast.wistia.net/embed/iframe/${id}`, title: \"Wistia video\" };\n }\n }\n}\n\n/** True only for a canonical embed URL (exactly what `toEmbedUrl` returns), so an iframe can't be pointed elsewhere. */\nexport function isAllowedEmbedSrc(src: string | null | undefined): boolean {\n if (!src) return false;\n return toEmbedUrl(src)?.src === src;\n}\n\n/** Fixed iframe attributes for an embed; sanitizers overwrite whatever the author's HTML carried. */\nexport const EMBED_IFRAME_ATTRS: Readonly<Record<string, string>> = {\n allow: \"fullscreen; picture-in-picture; encrypted-media\",\n allowfullscreen: \"\",\n loading: \"lazy\",\n referrerpolicy: \"strict-origin-when-cross-origin\",\n sandbox: \"allow-scripts allow-same-origin allow-presentation allow-popups allow-popups-to-escape-sandbox\",\n};\n\n/** Fixed `<video>` attributes: player controls, no autoplay or loop. */\nexport const VIDEO_ATTRS: Readonly<Record<string, string>> = { controls: \"\", preload: \"metadata\", playsinline: \"\" };\n\n/** `<video src>` / `poster` must be plain http(s): no data:, blob: or relative URLs (bodies render on customer sites). */\nexport function isSafeMediaUrl(url: string | null | undefined): boolean {\n if (!url) return false;\n try {\n const u = new URL(url);\n return (u.protocol === \"https:\" || u.protocol === \"http:\") && !u.username && !u.password;\n } catch {\n return false;\n }\n}\n\n/**\n * Still image for a guide step's video (`videoUrl`): YouTube serves one per video; other hosts don't\n * without an API call, so those steps use their own image (`imageUrl`) as the poster, or a plain tile.\n */\nexport function videoThumbnailUrl(url: string | null | undefined): string | null {\n const embed = url ? toEmbedUrl(url) : null;\n if (embed?.provider !== \"youtube\") return null;\n const id = embed.src.split(\"/embed/\")[1]?.split(\"?\")[0];\n return id ? `https://i.ytimg.com/vi/${id}/hqdefault.jpg` : null;\n}\n\n/** A video file a `<video>` can load directly (shows its first frame when there's no poster). */\nexport function isVideoFileUrl(url: string | null | undefined): boolean {\n return isSafeMediaUrl(url) && /\\.(mp4|webm|m4v|mov|ogv)$/i.test(new URL(url!).pathname);\n}\n\n/**\n * The video shown on a guide step: a poster with a play button that opens `url` in a new tab.\n * `poster` is the step's image, else the provider's thumbnail; null means draw a plain tile.\n */\nexport function stepVideo(step: { videoUrl?: string | null; imageUrl?: string | null }): { url: string; poster: string | null } | null {\n if (!step.videoUrl || !isSafeMediaUrl(step.videoUrl)) return null;\n return { url: step.videoUrl, poster: (step.imageUrl && isSafeMediaUrl(step.imageUrl) ? step.imageUrl : null) ?? videoThumbnailUrl(step.videoUrl) };\n}\n","/**\n * Resource center structure shared by every SDK: nested collections and audience targeting.\n *\n * Audience targeting decides what the help widget lists; it is not access control. The published\n * config (and every article body) is the same for all visitors of an environment, and end-user\n * identities are self-asserted, so never rely on it to keep an article private.\n */\n\n/** Collections nest at most this deep (a collection, its sections, and their sub-sections). */\nexport const MAX_COLLECTION_DEPTH = 3;\n\nexport interface RcCollectionLike {\n id: string;\n name: string;\n order: number;\n /** Parent collection; null/absent for a top-level collection. */\n parentId?: string | null;\n /** Shown only to members of any of these audiences; empty/absent means everyone. */\n audienceIds?: string[];\n}\n\nexport interface RcArticleLike {\n id: string;\n collectionId?: string | null;\n audienceIds?: string[];\n}\n\nexport interface RcSection<C extends RcCollectionLike, A extends RcArticleLike> {\n /** null for articles outside any (known) collection. */\n collection: C | null;\n /** Collection names from the top level down, e.g. [\"Billing\", \"Invoices\"]. */\n path: string[];\n /** 0 for a top-level collection. */\n depth: number;\n articles: A[];\n}\n\ntype Membership = ReadonlySet<string> | readonly string[] | undefined | null;\n\n/** True when an item targeted at `required` audiences is shown to someone in `member`. */\nexport function matchesAudiences(required: readonly string[] | undefined | null, member: Membership): boolean {\n if (!required || required.length === 0) return true;\n if (!member) return false;\n const has = member instanceof Set ? (id: string) => member.has(id) : (id: string) => (member as readonly string[]).includes(id);\n return required.some(has);\n}\n\n/**\n * Article sections in display order: each collection (depth first, siblings by `order`) with the\n * visible articles filed directly in it, then the uncategorized articles. A collection the viewer\n * isn't targeted by hides its whole subtree, and sections without visible articles are left out\n * (their sub-collections still appear). Unknown parents count as top level, so an old config or a\n * dangling reference never hides content.\n */\nexport function resourceCenterSections<C extends RcCollectionLike, A extends RcArticleLike>(collections: readonly C[], articles: readonly A[], member?: Membership): Array<RcSection<C, A>> {\n const byId = new Map(collections.map((c) => [c.id, c]));\n const children = new Map<string | null, C[]>();\n for (const c of collections) {\n const parent = c.parentId && c.parentId !== c.id && byId.has(c.parentId) ? c.parentId : null;\n const list = children.get(parent) ?? [];\n list.push(c);\n children.set(parent, list);\n }\n for (const list of children.values()) list.sort((a, b) => a.order - b.order || a.name.localeCompare(b.name));\n const direct = new Map<string, A[]>();\n const uncategorized: A[] = [];\n for (const a of articles) {\n if (!matchesAudiences(a.audienceIds, member)) continue;\n if (a.collectionId && byId.has(a.collectionId)) {\n const list = direct.get(a.collectionId) ?? [];\n list.push(a);\n direct.set(a.collectionId, list);\n } else uncategorized.push(a);\n }\n\n const sections: Array<RcSection<C, A>> = [];\n const seen = new Set<string>();\n const visit = (c: C, path: string[]) => {\n // A parent cycle in bad data would otherwise recurse forever; cycle members simply don't show.\n if (seen.has(c.id)) return;\n seen.add(c.id);\n if (!matchesAudiences(c.audienceIds, member)) return;\n const here = [...path, c.name];\n const list = direct.get(c.id);\n if (list?.length) sections.push({ collection: c, path: here, depth: here.length - 1, articles: list });\n for (const child of children.get(c.id) ?? []) visit(child, here);\n };\n for (const root of children.get(null) ?? []) visit(root, []);\n if (uncategorized.length) sections.push({ collection: null, path: [], depth: 0, articles: uncategorized });\n return sections;\n}\n\n/**\n * Whether one article is listed for a viewer: its own audiences and those of every collection above\n * it must match. For articles outside a loaded list (e.g. server search results).\n */\nexport function isArticleListed(collections: readonly RcCollectionLike[], article: RcArticleLike, member?: Membership): boolean {\n if (!matchesAudiences(article.audienceIds, member)) return false;\n const byId = new Map(collections.map((c) => [c.id, c]));\n let cur = article.collectionId ? byId.get(article.collectionId) : undefined;\n for (let guard = 0; cur && guard <= MAX_COLLECTION_DEPTH * 4; guard++) {\n if (!matchesAudiences(cur.audienceIds, member)) return false;\n cur = cur.parentId ? byId.get(cur.parentId) : undefined;\n }\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// Logged-in only articles\n// ---------------------------------------------------------------------------\n\n/** Who an article is listed for, besides its audiences: everyone, or logged-in (identified) visitors only. */\nexport const ARTICLE_VISIBILITIES = [\"everyone\", \"identified\"] as const;\nexport type ArticleVisibility = (typeof ARTICLE_VISIBILITIES)[number];\n\n/**\n * Reserved audience every logged-in visitor belongs to. The server folds an article's visibility into\n * the audiences it serves and adds this one to identified visitors' memberships, so every SDK (old ones\n * too) applies \"logged-in only\" through the audience matching it already does. Anonymous visitors never\n * identify, so their membership is empty and these articles stay hidden.\n */\nexport const LOGGED_IN_AUDIENCE = \"$identified\";\n\n/**\n * The audiences an article is served with. Logged-in only with no audiences becomes the reserved\n * audience; with audiences it is already implied, since audience membership only comes from identify.\n */\nexport function servedArticleAudiences(audienceIds: readonly string[], visibility: ArticleVisibility | string | null | undefined): string[] {\n return visibility === \"identified\" && audienceIds.length === 0 ? [LOGGED_IN_AUDIENCE] : [...audienceIds];\n}\n\n/** A visitor's memberships as matched against served articles: logged-in visitors are also in `LOGGED_IN_AUDIENCE`. */\nexport function visitorAudiences(audienceIds: readonly string[], identified: boolean): string[] {\n const ids = audienceIds.filter((id) => id !== LOGGED_IN_AUDIENCE);\n return identified ? [...ids, LOGGED_IN_AUDIENCE] : ids;\n}\n\n/** Ids of the articles a viewer sees (for filtering server search results the same way). */\nexport function visibleArticleIds(collections: readonly RcCollectionLike[], articles: readonly RcArticleLike[], member?: Membership): Set<string> {\n return new Set(resourceCenterSections(collections, articles, member).flatMap((s) => s.articles.map((a) => a.id)));\n}\n\n// ---------------------------------------------------------------------------\n// \"Show me\" prompts in help articles\n// ---------------------------------------------------------------------------\n\n/**\n * A \"Show me\" prompt in an article body is a plain link, `<p class=\"gd-show-me\"><a href=\"#guidely-show-me:<guide key>\">Show me how</a></p>`,\n * so it survives every sanitizer and reads as a harmless link anywhere else. The widgets turn it into a\n * button that starts the walkthrough (a live flow guide), or hide it when that guide isn't available.\n */\nexport const SHOW_ME_CLASS = \"gd-show-me\";\nexport const SHOW_ME_HREF_PREFIX = \"#guidely-show-me:\";\nconst SHOW_ME_KEY = /^[A-Za-z0-9_-]{1,64}$/;\n\nexport function showMeHref(guideKey: string): string {\n return `${SHOW_ME_HREF_PREFIX}${guideKey}`;\n}\n\n/** The guide key of a Show me link's `href`, or null. */\nexport function showMeKeyFromHref(href: string | null | undefined): string | null {\n if (!href || !href.startsWith(SHOW_ME_HREF_PREFIX)) return null;\n const key = href.slice(SHOW_ME_HREF_PREFIX.length);\n return SHOW_ME_KEY.test(key) ? key : null;\n}\n\n/** Guide keys of the Show me prompts in an article body, in order, without repeats (at most 10). */\nexport function showMeKeys(html: string | null | undefined): string[] {\n const out: string[] = [];\n for (const m of (html ?? \"\").matchAll(/href=\"#guidely-show-me:([A-Za-z0-9_-]{1,64})\"/g)) if (!out.includes(m[1]!)) out.push(m[1]!);\n return out.slice(0, 10);\n}\n\n/** The article body plays a video (uploaded, or embedded from YouTube, Vimeo, Loom or Wistia). */\nexport function hasVideoMedia(html: string | null | undefined): boolean {\n return /<(video|iframe)\\b/i.test(html ?? \"\");\n}\n\nconst words = (s: string) => s.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? [];\n\n/**\n * Help search on the device: every word of the query starts a word of the text, in any order, or the\n * query appears as typed. \"add user\" finds \"Add a new user\" and \"Users › Add\".\n */\nexport function matchesHelpQuery(text: string, query: string): boolean {\n const q = query.trim().toLowerCase();\n if (!q) return true;\n const hay = text.toLowerCase();\n if (hay.includes(q)) return true;\n const terms = words(q);\n if (!terms.length) return false;\n const have = words(hay);\n return terms.every((t) => have.some((w) => w.startsWith(t) || (t.length > 3 && t.endsWith(\"s\") && w.startsWith(t.slice(0, -1)))));\n}\n\n// ---------------------------------------------------------------------------\n// Modules (section order + targeting) and \"What's new\"\n// ---------------------------------------------------------------------------\n\nexport const RC_MODULE_IDS = [\"announcements\", \"search\", \"checklists\", \"guides\", \"articles\", \"links\", \"faqs\"] as const;\nexport type ResourceCenterModuleId = (typeof RC_MODULE_IDS)[number];\n\nexport const RC_MODULE_LABELS: Record<ResourceCenterModuleId, string> = {\n announcements: \"What's new\",\n search: \"Search\",\n checklists: \"Checklists\",\n guides: \"Guides & tours\",\n articles: \"Articles\",\n links: \"Links\",\n faqs: \"FAQs\",\n};\n\n/**\n * The resource center's sections in display order: the configured modules (unknown ids dropped,\n * missing ones appended enabled, in the default order), so an old config shows every section.\n */\nexport function orderedModules<M extends { id: string; enabled: boolean }>(modules: readonly M[] | null | undefined): Array<M | { id: ResourceCenterModuleId; enabled: true }> {\n const known = (modules ?? []).filter((m, i, all) => (RC_MODULE_IDS as readonly string[]).includes(m.id) && all.findIndex((x) => x.id === m.id) === i);\n const missing = RC_MODULE_IDS.filter((id) => !known.some((m) => m.id === id)).map((id) => ({ id, enabled: true as const }));\n return [...known, ...missing];\n}\n\n/** Announcements a visitor sees: published (not in the future), audience-matched, newest first. */\nexport function visibleAnnouncements<A extends { publishedAt: string; audienceIds?: string[] }>(items: readonly A[] | null | undefined, member?: Membership, now: number = Date.now()): A[] {\n return (items ?? [])\n .filter((a) => {\n const t = Date.parse(a.publishedAt);\n return !Number.isNaN(t) && t <= now && matchesAudiences(a.audienceIds, member);\n })\n .sort((a, b) => Date.parse(b.publishedAt) - Date.parse(a.publishedAt));\n}\n\n/** Unread count for the launcher badge: announcements published after the visitor last opened \"What's new\". */\nexport function unreadAnnouncements(items: readonly { publishedAt: string }[], lastSeenAt: string | null | undefined): number {\n const seen = lastSeenAt ? Date.parse(lastSeenAt) : NaN;\n if (Number.isNaN(seen)) return items.length;\n return items.filter((a) => Date.parse(a.publishedAt) > seen).length;\n}\n\n/**\n * A link to a help article from guide or article HTML: `<a href=\"#guidely-article:ID\">`. A fragment\n * survives every sanitizer (editor, server, SDK), and the SDKs open the article in the resource\n * center (or Scout's Help tab) instead of following the link.\n */\nexport const ARTICLE_HREF_PREFIX = \"#guidely-article:\";\nconst ARTICLE_ID = /^[A-Za-z0-9_-]{1,64}$/;\n\nexport function articleHref(articleId: string): string {\n return `${ARTICLE_HREF_PREFIX}${articleId}`;\n}\n\n/** The article id of an article link's `href`, or null. */\nexport function articleIdFromHref(href: string | null | undefined): string | null {\n if (!href || !href.startsWith(ARTICLE_HREF_PREFIX)) return null;\n const id = href.slice(ARTICLE_HREF_PREFIX.length);\n return ARTICLE_ID.test(id) ? id : null;\n}\n","/** How-to capture constants the browser SDK needs without zod (also exported from `@guidelytech/shared/runtime`). */\n\n/** Query parameter that starts capture mode in the SDK (separate from `guidely_authoring`, so SDKs without capture ignore it). */\nexport const CAPTURE_PARAM = \"guidely_capture\";\n/** Largest screenshot the capture endpoint accepts. */\nexport const CAPTURE_SCREENSHOT_MAX_BYTES = 8 * 1024 * 1024;\n","/**\n * Page helpers shared by the SDK (page-aware messenger) and the server (page matching, analytics).\n * Pure and zod-free.\n */\n\n/**\n * One path segment that looks like an identifier: digits, a UUID, or a long hex string (hashes,\n * Mongo ids). Written so the same source works as a JS RegExp and a Postgres ARE (`regexp_replace`\n * with flags `gi`), which keeps id folding identical in SQL and in code. A segment may be followed\n * by the page query parameters a project keeps in its paths (`/contacts/42?tab=notes`).\n */\nexport const PATH_ID_PATTERN = \"/([0-9]+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{12,})(?=[/?]|$)\";\n\n/** `/contacts/42/notes/9f8e…` → `/contacts/:id/notes/:id`; `/contacts/42?tab=notes` → `/contacts/:id?tab=notes`. */\nexport function foldPathIds(path: string): string {\n return path.replace(new RegExp(PATH_ID_PATTERN, \"gi\"), \"/:id\");\n}\n\n/** Path segments that say nothing about what a page is for. */\nconst GENERIC_SEGMENTS = new Set([\"\", \":id\", \"app\", \"apps\", \"dashboard\", \"home\", \"index\", \"main\", \"new\", \"edit\", \"view\", \"show\", \"details\", \"detail\", \"overview\", \"list\", \"all\", \"page\", \"pages\", \"en\", \"v1\", \"v2\"]);\n\nfunction segmentsOf(path: string): string[] {\n const clean = foldPathIds((path.split(/[?#]/)[0] || \"/\").toLowerCase());\n return clean\n .split(\"/\")\n .map((s) => s.replace(/\\.(html?|php|aspx?)$/, \"\"))\n .filter((s) => !GENERIC_SEGMENTS.has(s) && /[a-z]/.test(s) && s.length <= 40);\n}\n\n/** Words describing a page, from its path (`/settings/billing-plans/42` → `settings billing plans`). */\nexport function pageTerms(path: string): string[] {\n const words = segmentsOf(path).flatMap((s) => s.split(/[-_.+\\s]+/).filter((w) => w.length > 1 && /[a-z]/.test(w)));\n return [...new Set(words)].slice(0, 8);\n}\n\n/** A short human name for a page (`/app/invoices/42` → `Invoices`), or null for the root and unnamed pages. */\nexport function pageLabel(path: string): string | null {\n const last = segmentsOf(path).at(-1);\n if (!last) return null;\n const words = last.split(/[-_.+\\s]+/).filter(Boolean);\n if (!words.length) return null;\n const label = words.join(\" \");\n return label.charAt(0).toUpperCase() + label.slice(1);\n}\n\n/** The first name in a user's traits (`firstName`, `first_name`, or the first word of `name`), or null. */\nexport function firstNameFromTraits(traits: Record<string, unknown> | null | undefined): string | null {\n if (!traits) return null;\n const pick = (v: unknown) => (typeof v === \"string\" ? v.trim() : \"\");\n const first = pick(traits.firstName) || pick(traits.first_name) || pick(traits.firstname) || pick(traits.name).split(/\\s+/)[0] || \"\";\n // Never greet someone by an email address or an id.\n if (!first || first.length > 40 || first.includes(\"@\") || !/\\p{L}/u.test(first)) return null;\n return first;\n}\n","/**\n * Tagged pages and features (named rules over the URLs and clicks the SDK captures), shared by the server (retroactive\n * matching, SQL generation), the dashboard (previews) and the SDK (event properties). Pure and zod-free.\n *\n * - An `ElementSnapshot` is the compact description of a clicked element the SDK attaches to `click`\n * events (`properties.el`): tag, id, classes, a few safe attributes, nth-of-type, ~5 ancestors and\n * the shadow hosts above it. CSS selector rules are evaluated against it with {@link matchCssSelector},\n * so a rule written today also matches clicks stored before it existed.\n * - Older clicks carry only a selector string; {@link snapshotFromSelector} turns that string into a\n * partial snapshot so CSS rules still match them where the string says enough.\n */\n\n// ---------------------------------------------------------------------------\n// Element snapshots\n// ---------------------------------------------------------------------------\n\n/** One element in a snapshot: tag, id, classes, safe attributes and its 1-based nth-of-type. */\nexport interface ElementNode {\n t: string;\n id?: string;\n c?: string[];\n a?: Record<string, string>;\n n?: number;\n}\n\n/** A clicked element (`click.properties.el`): the element, its ancestors (`p`, parent first) and shadow hosts (`h`, nearest first). */\nexport interface ElementSnapshot extends ElementNode {\n p?: ElementNode[];\n h?: ElementNode[];\n}\n\nexport const SNAPSHOT_LIMITS = { classes: 8, className: 60, attrs: 6, attrValue: 100, ancestors: 5, hosts: 3, tag: 40, id: 80 } as const;\n\n/** Attributes a snapshot may carry besides `data-*` ones. Never `value`, never event handlers. */\nexport const SNAPSHOT_ATTRS = [\"role\", \"name\", \"type\", \"aria-label\", \"title\", \"alt\", \"for\", \"href\"] as const;\n\n/** Framework and state `data-*` attributes that say nothing stable about an element. */\nexport const NOISY_DATA_ATTR = /^data-(state|v-|react|radix|headlessui|svelte|orientation|highlighted|focus|key|index|side|align|disabled|selected|active|open|rbd|dnd|sveltekit|guidely-(mask|ignore|block))/i;\n\n/** The custom attribute that names a feature by default (`<button data-guidely-feature=\"Export CSV\">`). */\nexport const DEFAULT_FEATURE_ATTRIBUTE = \"data-guidely-feature\";\nexport const FEATURE_ATTRIBUTE_PATTERN = /^data-[a-z0-9][a-z0-9_.-]{0,60}$/;\n\nfunction str(v: unknown, max: number): string | undefined {\n return typeof v === \"string\" && v ? v.slice(0, max) : undefined;\n}\n\nfunction cleanNode(raw: unknown): ElementNode | null {\n if (!raw || typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n const t = str(r.t, SNAPSHOT_LIMITS.tag)?.toLowerCase();\n if (!t || !/^[a-z][a-z0-9-]*$/.test(t)) return null;\n const node: ElementNode = { t };\n const id = str(r.id, SNAPSHOT_LIMITS.id);\n if (id) node.id = id;\n if (Array.isArray(r.c)) {\n const c = r.c.filter((x): x is string => typeof x === \"string\" && !!x && x.length <= SNAPSHOT_LIMITS.className && !/\\s/.test(x)).slice(0, SNAPSHOT_LIMITS.classes);\n if (c.length) node.c = c;\n }\n if (r.a && typeof r.a === \"object\" && !Array.isArray(r.a)) {\n const a: Record<string, string> = {};\n for (const [k, v] of Object.entries(r.a as Record<string, unknown>)) {\n if (Object.keys(a).length >= SNAPSHOT_LIMITS.attrs) break;\n const key = k.toLowerCase();\n if (typeof v !== \"string\" || !(key.startsWith(\"data-\") || (SNAPSHOT_ATTRS as readonly string[]).includes(key)) || key === \"value\" || key.length > 60) continue;\n a[key] = v.slice(0, SNAPSHOT_LIMITS.attrValue);\n }\n if (Object.keys(a).length) node.a = a;\n }\n if (typeof r.n === \"number\" && Number.isInteger(r.n) && r.n >= 1 && r.n <= 10_000) node.n = r.n;\n return node;\n}\n\n/** Validates and trims a snapshot sent by an SDK (server side); null when it is not one. */\nexport function normalizeSnapshot(raw: unknown): ElementSnapshot | null {\n const el = cleanNode(raw);\n if (!el) return null;\n const r = raw as Record<string, unknown>;\n const out: ElementSnapshot = el;\n if (Array.isArray(r.p)) {\n const p = r.p.slice(0, SNAPSHOT_LIMITS.ancestors).map(cleanNode);\n // Ancestors are consecutive; stop at the first unusable one rather than skipping it.\n const cut = p.indexOf(null);\n const list = (cut === -1 ? p : p.slice(0, cut)) as ElementNode[];\n if (list.length) out.p = list;\n }\n if (Array.isArray(r.h)) {\n const h = r.h.slice(0, SNAPSHOT_LIMITS.hosts).map(cleanNode).filter((x): x is ElementNode => !!x);\n if (h.length) out.h = h;\n }\n return out;\n}\n\n/** JSON with sorted keys, so equal snapshots hash the same whatever order the SDK wrote them in. */\nexport function stableStringify(v: unknown): string {\n if (Array.isArray(v)) return `[${v.map(stableStringify).join(\",\")}]`;\n if (v && typeof v === \"object\") {\n const o = v as Record<string, unknown>;\n return `{${Object.keys(o)\n .filter((k) => o[k] !== undefined)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${stableStringify(o[k])}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(v ?? null);\n}\n\n// ---------------------------------------------------------------------------\n// CSS selector subset: parse + match against a snapshot\n// ---------------------------------------------------------------------------\n\nexport type AttrOp = \"exists\" | \"=\" | \"^=\" | \"$=\" | \"*=\" | \"~=\" | \"|=\";\n\nexport interface AttrTest {\n name: string;\n op: AttrOp;\n value?: string;\n /** `[attr=\"x\" i]` */\n insensitive?: boolean;\n}\n\nexport interface Compound {\n tag?: string;\n id?: string;\n classes: string[];\n attrs: AttrTest[];\n /** `:nth-of-type(n)`; `odd`/`even` as `{ a: 2, b: 1|0 }`; `:first-of-type` is `{ a: 0, b: 1 }`. */\n nth?: { a: number; b: number };\n}\n\n/** A complex selector: compounds left to right and the combinator before each (index 0 has none). */\nexport interface ComplexSelector {\n compounds: Compound[];\n combinators: Array<\" \" | \">\" | \">>>\">;\n}\n\nexport class SelectorSyntaxError extends Error {}\n\nconst IDENT_START = /[A-Za-z_\\u00a0-\\uffff-]/;\nconst IDENT_CHAR = /[A-Za-z0-9_\\u00a0-\\uffff-]/;\n\n/**\n * Parses the supported subset: type and universal selectors, `#id`, `.class`, `[attr]`,\n * `[attr=v]`, `^=`, `$=`, `*=`, `~=`, `|=` (optionally `i`), `:nth-of-type(n|odd|even)`,\n * `:first-of-type`, descendant and child combinators, `>>>` (shadow host) and selector lists.\n * Throws {@link SelectorSyntaxError} on anything else.\n */\nexport function parseCssSelector(input: string): ComplexSelector[] {\n const s = input.trim();\n if (!s) throw new SelectorSyntaxError(\"Empty selector\");\n if (s.length > 1000) throw new SelectorSyntaxError(\"Selector is too long\");\n let i = 0;\n const peek = () => s[i];\n const eof = () => i >= s.length;\n const fail = (msg: string): never => {\n throw new SelectorSyntaxError(`${msg} at position ${i + 1}`);\n };\n const ws = () => {\n let any = false;\n while (!eof() && /\\s/.test(s[i]!)) {\n i++;\n any = true;\n }\n return any;\n };\n const escape = (): string => {\n // after the backslash\n i++;\n const hex = /^[0-9a-fA-F]{1,6}/.exec(s.slice(i));\n if (hex) {\n i += hex[0].length;\n if (s[i] === \" \") i++;\n return String.fromCodePoint(parseInt(hex[0], 16));\n }\n if (eof()) fail(\"Unfinished escape\");\n return s[i++]!;\n };\n const ident = (): string => {\n let out = \"\";\n if (s[i] === \"\\\\\") out += escape();\n else if (!eof() && IDENT_START.test(s[i]!)) out += s[i++];\n else fail(\"Expected a name\");\n while (!eof()) {\n if (s[i] === \"\\\\\") out += escape();\n else if (IDENT_CHAR.test(s[i]!)) out += s[i++];\n else break;\n }\n return out;\n };\n const quoted = (): string => {\n const q = s[i++];\n let out = \"\";\n while (!eof() && s[i] !== q) {\n if (s[i] === \"\\\\\") out += escape();\n else out += s[i++];\n }\n if (eof()) fail(\"Unterminated string\");\n i++;\n return out;\n };\n const compound = (): Compound | null => {\n const c: Compound = { classes: [], attrs: [] };\n let any = false;\n if (peek() === \"*\") {\n i++;\n any = true;\n } else if (!eof() && (IDENT_START.test(peek()!) || peek() === \"\\\\\")) {\n c.tag = ident().toLowerCase();\n any = true;\n }\n for (;;) {\n const ch = peek();\n if (ch === \"#\") {\n i++;\n c.id = ident();\n } else if (ch === \".\") {\n i++;\n c.classes.push(ident());\n } else if (ch === \"[\") {\n i++;\n ws();\n const name = ident().toLowerCase();\n ws();\n let op: AttrOp = \"exists\";\n let value: string | undefined;\n let insensitive = false;\n if (peek() !== \"]\") {\n const m = /^(=|\\^=|\\$=|\\*=|~=|\\|=)/.exec(s.slice(i));\n if (!m) fail(\"Unsupported attribute operator\");\n op = m![1] as AttrOp;\n i += m![1]!.length;\n ws();\n value = peek() === '\"' || peek() === \"'\" ? quoted() : ident();\n ws();\n if (peek() === \"i\" || peek() === \"I\") {\n i++;\n insensitive = true;\n ws();\n } else if (peek() === \"s\" || peek() === \"S\") {\n i++;\n ws();\n }\n }\n if (peek() !== \"]\") fail(\"Expected ]\");\n i++;\n c.attrs.push({ name, op, ...(value !== undefined ? { value } : {}), ...(insensitive ? { insensitive } : {}) });\n } else if (ch === \":\") {\n i++;\n if (peek() === \":\") fail(\"Pseudo-elements are not supported\");\n const name = ident().toLowerCase();\n if (name === \"first-of-type\") c.nth = { a: 0, b: 1 };\n else if (name === \"nth-of-type\") {\n if (peek() !== \"(\") fail(\"Expected (\");\n i++;\n ws();\n const m = /^(odd|even|\\d+)/i.exec(s.slice(i));\n if (!m) fail(\"Only :nth-of-type(n), odd or even are supported\");\n i += m![0].length;\n ws();\n if (peek() !== \")\") fail(\"Expected )\");\n i++;\n const v = m![0].toLowerCase();\n c.nth = v === \"odd\" ? { a: 2, b: 1 } : v === \"even\" ? { a: 2, b: 0 } : { a: 0, b: Number(v) };\n } else fail(`Unsupported pseudo-class :${name}`);\n } else break;\n any = true;\n }\n return any ? c : null;\n };\n\n const list: ComplexSelector[] = [];\n for (;;) {\n ws();\n const sel: ComplexSelector = { compounds: [], combinators: [] };\n const first = compound();\n if (!first) fail(\"Expected a selector\");\n sel.compounds.push(first!);\n for (;;) {\n const hadWs = ws();\n if (eof() || peek() === \",\") break;\n let comb: \" \" | \">\" | \">>>\" = \" \";\n if (s.startsWith(\">>>\", i)) {\n comb = \">>>\";\n i += 3;\n ws();\n } else if (peek() === \">\") {\n comb = \">\";\n i++;\n ws();\n } else if (peek() === \"+\" || peek() === \"~\") fail(\"Sibling combinators are not supported\");\n else if (!hadWs) fail(\"Unexpected character\");\n const next = compound();\n if (!next) fail(\"Expected a selector after the combinator\");\n sel.compounds.push(next!);\n sel.combinators.push(comb);\n }\n list.push(sel);\n if (eof()) break;\n i++; // \",\"\n }\n return list;\n}\n\n/** Is the selector inside the supported subset? Returns the error message, or null when it parses. */\nexport function cssSelectorError(selector: string): string | null {\n try {\n parseCssSelector(selector);\n return null;\n } catch (e) {\n return e instanceof Error ? e.message : \"Invalid selector\";\n }\n}\n\nfunction attrMatches(test: AttrTest, node: ElementNode): boolean {\n let actual: string | undefined;\n if (test.name === \"id\") actual = node.id;\n else if (test.name === \"class\") actual = node.c?.join(\" \");\n else actual = node.a?.[test.name];\n if (actual === undefined) return false;\n if (test.op === \"exists\") return true;\n let v = test.value ?? \"\";\n if (test.insensitive) {\n actual = actual.toLowerCase();\n v = v.toLowerCase();\n }\n switch (test.op) {\n case \"=\":\n return actual === v;\n case \"^=\":\n return !!v && actual.startsWith(v);\n case \"$=\":\n return !!v && actual.endsWith(v);\n case \"*=\":\n return !!v && actual.includes(v);\n case \"~=\":\n return !!v && actual.split(/\\s+/).includes(v);\n case \"|=\":\n return actual === v || actual.startsWith(`${v}-`);\n default:\n return false;\n }\n}\n\n/** Does one compound match one node? An unknown nth-of-type fails `:nth-of-type` tests. */\nexport function compoundMatches(c: Compound, node: ElementNode): boolean {\n if (c.tag && c.tag !== node.t) return false;\n if (c.id !== undefined && node.id !== c.id) return false;\n for (const cls of c.classes) if (!node.c?.includes(cls)) return false;\n for (const a of c.attrs) if (!attrMatches(a, node)) return false;\n if (c.nth) {\n if (!node.n) return false;\n const { a, b } = c.nth;\n if (a === 0 ? node.n !== b : (node.n - b) % a !== 0 || (node.n - b) / a < 0) return false;\n }\n return true;\n}\n\n/** Matches compounds (right to left) against a chain of nodes: index 0 is the element, then its ancestors. */\nfunction chainMatches(compounds: Compound[], combinators: Array<\" \" | \">\">, nodes: ElementNode[], ci = compounds.length - 1, ni = 0): boolean {\n if (!compoundMatches(compounds[ci]!, nodes[ni]!)) return false;\n if (ci === 0) return true;\n const comb = combinators[ci - 1]!;\n if (comb === \">\") return ni + 1 < nodes.length && chainMatches(compounds, combinators, nodes, ci - 1, ni + 1);\n for (let k = ni + 1; k < nodes.length; k++) if (chainMatches(compounds, combinators, nodes, ci - 1, k)) return true;\n return false;\n}\n\nfunction complexMatches(sel: ComplexSelector, snap: ElementSnapshot): boolean {\n // Split at `>>>`: the last segment is matched inside the element's own tree, each earlier\n // segment's last compound against a shadow host further out (any depth, like the runtime).\n const segments: Array<{ compounds: Compound[]; combinators: Array<\" \" | \">\"> }> = [{ compounds: [sel.compounds[0]!], combinators: [] }];\n sel.combinators.forEach((comb, k) => {\n const next = sel.compounds[k + 1]!;\n if (comb === \">>>\") segments.push({ compounds: [next], combinators: [] });\n else {\n const seg = segments[segments.length - 1]!;\n seg.compounds.push(next);\n seg.combinators.push(comb);\n }\n });\n const last = segments.pop()!;\n const nodes: ElementNode[] = [snap, ...(snap.p ?? [])];\n if (!chainMatches(last.compounds, last.combinators, nodes)) return false;\n const hosts = snap.h ?? [];\n let from = 0;\n for (let k = segments.length - 1; k >= 0; k--) {\n const target = segments[k]!.compounds[segments[k]!.compounds.length - 1]!;\n let found = -1;\n for (let j = from; j < hosts.length; j++) {\n if (compoundMatches(target, hosts[j]!)) {\n found = j;\n break;\n }\n }\n if (found === -1) return false;\n from = found + 1;\n }\n return true;\n}\n\nconst parsedCache = new Map<string, ComplexSelector[] | null>();\n\n/** Does a CSS selector (subset, see {@link parseCssSelector}) match the snapshot? Invalid selectors match nothing. */\nexport function matchCssSelector(selector: string | ComplexSelector[], snap: ElementSnapshot): boolean {\n let list: ComplexSelector[] | null;\n if (typeof selector === \"string\") {\n if (!parsedCache.has(selector)) {\n if (parsedCache.size > 500) parsedCache.clear();\n try {\n parsedCache.set(selector, parseCssSelector(selector));\n } catch {\n parsedCache.set(selector, null);\n }\n }\n list = parsedCache.get(selector)!;\n } else list = selector;\n return !!list && list.some((sel) => complexMatches(sel, snap));\n}\n\nfunction nodeOfCompound(c: Compound): ElementNode {\n const node: ElementNode = { t: c.tag ?? \"*\" };\n if (c.id) node.id = c.id;\n if (c.classes.length) node.c = c.classes.slice(0, SNAPSHOT_LIMITS.classes);\n const a: Record<string, string> = {};\n for (const t of c.attrs) if (t.op === \"=\" && t.value !== undefined) a[t.name] = t.value;\n if (Object.keys(a).length) node.a = a;\n if (c.nth && c.nth.a === 0) node.n = c.nth.b;\n return node;\n}\n\n/**\n * A partial snapshot read from a stored selector string (clicks captured before snapshots existed):\n * `#form > div:nth-of-type(2) > button[data-testid=\"save\"]` becomes a `button` with that attribute,\n * nth 1-unknown, and two ancestors. Shadow steps (`c-app >>> button`) become hosts. Null when the\n * string is not a selector in the supported subset.\n */\nexport function snapshotFromSelector(selector: string, tag?: string | null): ElementSnapshot | null {\n let list: ComplexSelector[];\n try {\n list = parseCssSelector(selector);\n } catch {\n return null;\n }\n if (list.length !== 1) return null;\n const sel = list[0]!;\n const segments: Compound[][] = [[sel.compounds[0]!]];\n sel.combinators.forEach((comb, k) => {\n if (comb === \">>>\") segments.push([sel.compounds[k + 1]!]);\n else segments[segments.length - 1]!.push(sel.compounds[k + 1]!);\n });\n const own = segments.pop()!;\n const el = nodeOfCompound(own[own.length - 1]!);\n if (el.t === \"*\" && tag && /^[a-z][a-z0-9-]*$/i.test(tag)) el.t = tag.toLowerCase();\n const snap: ElementSnapshot = el;\n const p = own.slice(0, -1).reverse().map(nodeOfCompound);\n if (p.length) snap.p = p.slice(0, SNAPSHOT_LIMITS.ancestors);\n const h = segments.reverse().map((seg) => nodeOfCompound(seg[seg.length - 1]!));\n if (h.length) snap.h = h.slice(0, SNAPSHOT_LIMITS.hosts);\n return snap;\n}\n\n// ---------------------------------------------------------------------------\n// Page rules\n// ---------------------------------------------------------------------------\n\nexport type QueryParamOp = \"exists\" | \"absent\" | \"equals\" | \"contains\";\nexport interface QueryParamCondition {\n name: string;\n op: QueryParamOp;\n value?: string;\n}\n\n/**\n * One way a URL belongs to a page. `url`: a pattern (`/accounts/:id/settings`, `/reports/*`,\n * `/docs/**`, `//*\\/billing`, `https://app.acme.com/x`) plus optional query conditions; `regex`: a\n * regular expression over the path; `title`: the document title (`equals` / `contains`). With\n * `exclude`, matching URLs are taken out of the page instead.\n */\nexport interface PageRule {\n id?: string;\n type: \"url\" | \"regex\" | \"title\";\n value: string;\n op?: \"equals\" | \"contains\";\n query?: QueryParamCondition[];\n exclude?: boolean;\n}\n\nexport const PAGE_RULE_LIMITS = { rules: 20, value: 500, query: 5 } as const;\n\nexport interface PagePattern {\n /** Anchored regex source, valid both as a JS RegExp (flag `i`) and a Postgres ARE (`~*`). */\n source: string;\n /** What it runs against: the path (query removed) or the full URL without query and hash. */\n target: \"path\" | \"url\";\n /** Query conditions written into the pattern (`/search?tab=people`). */\n query: QueryParamCondition[];\n}\n\nconst escapeRe = (s: string) => s.replace(/[.+?^${}()|[\\]\\\\*]/g, \"\\\\$&\");\n\nfunction globToRegex(pattern: string): string {\n let out = \"\";\n for (let k = 0; k < pattern.length; k++) {\n const ch = pattern[k]!;\n if (ch === \"*\") {\n if (pattern[k + 1] === \"*\") {\n out += \".*\";\n k++;\n } else out += \"[^/]*\";\n } else if (ch === \":\" && (k === 0 || pattern[k - 1] === \"/\") && /[A-Za-z_]/.test(pattern[k + 1] ?? \"\")) {\n // `:name` path parameter: one whole segment.\n let j = k + 1;\n while (j < pattern.length && /[\\w]/.test(pattern[j]!)) j++;\n out += \"[^/]+\";\n k = j - 1;\n } else out += escapeRe(ch);\n }\n return out;\n}\n\n/** Turns a URL rule pattern into a regex. Query parameters in the pattern become conditions. */\nexport function pagePattern(raw: string): PagePattern {\n let p = raw.trim();\n const query: QueryParamCondition[] = [];\n const hash = p.indexOf(\"#\");\n if (hash !== -1) p = p.slice(0, hash);\n const q = p.indexOf(\"?\");\n if (q !== -1) {\n for (const part of p.slice(q + 1).split(\"&\")) {\n if (!part) continue;\n const eq = part.indexOf(\"=\");\n const name = decodeSafe(eq === -1 ? part : part.slice(0, eq));\n const value = eq === -1 ? undefined : decodeSafe(part.slice(eq + 1));\n if (!name) continue;\n query.push(value === undefined || value === \"*\" ? { name, op: \"exists\" } : { name, op: \"equals\", value });\n }\n p = p.slice(0, q);\n }\n let target: \"path\" | \"url\" = \"path\";\n // `//*` means any domain: keep only the path.\n if (p.startsWith(\"//*\")) p = p.slice(3);\n let prefix = \"\";\n const abs = /^(https?:)?\\/\\/([^/]+)(.*)$/i.exec(p);\n if (abs) {\n target = \"url\";\n prefix = `https?://${globToRegex(abs[2]!.toLowerCase())}`;\n p = abs[3] || \"/\";\n }\n if (!p.startsWith(\"/\")) p = `/${p}`;\n // A trailing slash is optional, as on most sites.\n const body = p.length > 1 && p.endsWith(\"/\") ? p.slice(0, -1) : p;\n const src = body === \"/\" ? \"/?\" : `${globToRegex(body)}/?`;\n return { source: `^${prefix}${src}$`, target, query: query.slice(0, PAGE_RULE_LIMITS.query) };\n}\n\nfunction decodeSafe(s: string): string {\n try {\n return decodeURIComponent(s.replace(/\\+/g, \" \"));\n } catch {\n return s;\n }\n}\n\n/** Regex (JS + Postgres) for a query condition over a raw URL. */\nexport function queryConditionRegex(c: QueryParamCondition): string {\n const name = escapeRe(c.name);\n switch (c.op) {\n case \"equals\":\n return `[?&]${name}=${escapeRe(encodeLoose(c.value ?? \"\"))}(&|#|$)`;\n case \"contains\":\n return `[?&]${name}=[^&#]*${escapeRe(encodeLoose(c.value ?? \"\"))}`;\n default:\n return `[?&]${name}(=|&|#|$)`;\n }\n}\n\n/** URL-encodes what browsers encode in query values, leaving the common safe characters alone. */\nfunction encodeLoose(v: string): string {\n return encodeURIComponent(v).replace(/%2F/gi, \"/\").replace(/%3A/gi, \":\").replace(/%2C/gi, \",\").replace(/%40/gi, \"@\");\n}\n\nexport interface PageContext {\n /** Full URL (with query) when known. */\n url?: string | null;\n /** Path as stored (`/a/b`, or `/a/b?section=x` with kept page parameters). */\n path?: string | null;\n title?: string | null;\n}\n\nfunction pathOnly(ctx: PageContext): string | null {\n if (ctx.path) return ctx.path.split(\"?\")[0] || \"/\";\n if (!ctx.url) return null;\n try {\n return new URL(ctx.url, \"http://x.invalid\").pathname;\n } catch {\n return null;\n }\n}\n\nfunction regexOrNull(source: string): RegExp | null {\n try {\n return new RegExp(source, \"i\");\n } catch {\n return null;\n }\n}\n\n/** JS twin of the SQL a page rule compiles to (server `pageRuleSql`). */\nexport function pageRuleMatches(rule: PageRule, ctx: PageContext): boolean {\n const path = pathOnly(ctx);\n if (rule.type === \"title\") {\n const t = (ctx.title ?? \"\").toLowerCase();\n const v = rule.value.toLowerCase();\n return !!t && (rule.op === \"contains\" ? t.includes(v) : t === v);\n }\n if (rule.type === \"regex\") {\n const re = regexOrNull(rule.value);\n return !!re && path !== null && re.test(path);\n }\n const pat = pagePattern(rule.value);\n const re = regexOrNull(pat.source);\n if (!re) return false;\n let subject: string | null = path;\n if (pat.target === \"url\") {\n if (!ctx.url) return false;\n subject = ctx.url.split(/[?#]/)[0]!;\n }\n if (subject === null || !re.test(subject)) return false;\n const conds = [...pat.query, ...(rule.query ?? [])];\n for (const c of conds) {\n const hit = !!ctx.url && new RegExp(queryConditionRegex(c), \"i\").test(ctx.url);\n if (c.op === \"absent\" ? hit : !hit) return false;\n }\n return true;\n}\n\n/** Included by any include rule and excluded by no exclude rule. */\nexport function pageRulesMatch(rules: PageRule[], ctx: PageContext): boolean {\n const include = rules.filter((r) => !r.exclude);\n if (!include.length || !include.some((r) => pageRuleMatches(r, ctx))) return false;\n return !rules.some((r) => r.exclude && pageRuleMatches(r, ctx));\n}\n\n/** Validation message for a page rule, or null. */\nexport function pageRuleError(rule: PageRule): string | null {\n const v = rule.value?.trim();\n if (!v) return \"A rule needs a value\";\n if (v.length > PAGE_RULE_LIMITS.value) return \"The rule is too long\";\n if (rule.type === \"regex\") {\n if (!regexOrNull(v)) return `\"${v}\" is not a valid regular expression`;\n if (/\\(\\?[<=!]/.test(v) || /\\\\[1-9]/.test(v)) return \"Look-arounds and back-references are not supported\";\n }\n if (rule.type === \"url\" && !regexOrNull(pagePattern(v).source)) return `\"${v}\" is not a valid URL rule`;\n for (const q of rule.query ?? []) if (!/^[A-Za-z0-9_.\\-[\\]]{1,60}$/.test(q.name)) return `\"${q.name}\" is not a query parameter name`;\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Feature rules\n// ---------------------------------------------------------------------------\n\nexport type SelectorOp = \"exact\" | \"prefix\" | \"contains\" | \"glob\" | \"css\";\n\n/**\n * One way a click belongs to a feature. Every condition present must hold. `selector.op = \"css\"`\n * evaluates a CSS selector against the element snapshot (or, for old clicks, the snapshot read from\n * the stored selector string); the other selector operators compare the stored selector string —\n * mobile taps store the accessibility id / `data-guidely-id` there, so `exact` works for them too.\n */\nexport interface FeatureRule {\n id?: string;\n selector?: { op: SelectorOp; value: string };\n text?: { op: \"equals\" | \"contains\"; value: string };\n tag?: string;\n href?: { op: \"equals\" | \"prefix\" | \"contains\"; value: string };\n /** Only clicks on this tagged page / URL pattern. */\n page?: { pageId?: string; pattern?: string };\n /** `web`, `ios`, `android` (mobile autocapture sets `properties.platform`). */\n platform?: string;\n exclude?: boolean;\n}\n\nexport const FEATURE_RULE_LIMITS = { rules: 20, value: 1000 } as const;\n\nexport interface ClickFacts {\n selector?: string | null;\n text?: string | null;\n tag?: string | null;\n href?: string | null;\n platform?: string | null;\n}\n\nfunction globMatch(pattern: string, value: string): boolean {\n const re = new RegExp(`^${pattern.split(\"*\").map(escapeRe).join(\".*\")}$`, \"s\");\n return re.test(value);\n}\n\n/** Does a click (facts + a CSS test) satisfy one rule's element conditions? Page scope is checked by the caller. */\nexport function featureRuleMatchesClick(rule: FeatureRule, click: ClickFacts, css: (selector: string) => boolean): boolean {\n if (!rule.selector && !rule.text && !rule.tag && !rule.href) return false;\n if (rule.selector) {\n const sel = click.selector ?? \"\";\n const v = rule.selector.value;\n const ok =\n rule.selector.op === \"css\" ? css(v) : rule.selector.op === \"exact\" ? sel === v : rule.selector.op === \"prefix\" ? sel.startsWith(v) : rule.selector.op === \"contains\" ? sel.includes(v) : globMatch(v, sel);\n if (!ok) return false;\n }\n if (rule.text) {\n const t = (click.text ?? \"\").toLowerCase();\n const v = rule.text.value.toLowerCase();\n if (rule.text.op === \"contains\" ? !t.includes(v) : t !== v) return false;\n }\n if (rule.tag && (click.tag ?? \"\").toLowerCase() !== rule.tag.toLowerCase()) return false;\n if (rule.href) {\n const h = click.href ?? \"\";\n const v = rule.href.value;\n if (rule.href.op === \"equals\" ? h !== v : rule.href.op === \"prefix\" ? !h.startsWith(v) : !h.includes(v)) return false;\n }\n if (rule.platform && (click.platform ?? \"web\") !== rule.platform) return false;\n return true;\n}\n\n/** Validation message for a feature rule, or null. */\nexport function featureRuleError(rule: FeatureRule): string | null {\n if (!rule.selector && !rule.text && !rule.tag && !rule.href) return \"A feature rule needs a selector, text, tag or link condition\";\n if (rule.selector) {\n const v = rule.selector.value?.trim();\n if (!v) return \"The selector is empty\";\n if (v.length > FEATURE_RULE_LIMITS.value) return \"The selector is too long\";\n if (rule.selector.op === \"css\") {\n const err = cssSelectorError(v);\n if (err) return `Unsupported CSS selector: ${err}`;\n }\n }\n if (rule.text && !rule.text.value.trim()) return \"The text condition is empty\";\n if (rule.href && !rule.href.value.trim()) return \"The link condition is empty\";\n if (rule.tag && !/^[a-z][a-z0-9-]{0,40}$/i.test(rule.tag)) return \"The tag is not an element name\";\n if (rule.page?.pattern) return pageRuleError({ type: \"url\", value: rule.page.pattern });\n return null;\n}\n\n/** Selector to find a feature's elements on a page (dashboard overlays, SDK property capture), when the rules give one. */\nexport function featureCssSelectors(rules: FeatureRule[]): string[] {\n const out: string[] = [];\n for (const r of rules) {\n if (r.exclude || !r.selector) continue;\n if ((r.selector.op === \"css\" || r.selector.op === \"exact\") && !cssSelectorError(r.selector.value)) out.push(r.selector.value);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Event properties captured from the DOM (configured per page / feature, sent in the SDK config)\n// ---------------------------------------------------------------------------\n\nexport interface TagPropertyDefinition {\n id: string;\n name: string;\n /** Element to read: CSS selector (may use `>>>`); empty = the clicked element itself (features only). */\n selector?: string;\n source: \"text\" | \"attribute\";\n /** Attribute name for `source: \"attribute\"`; `value` is never read. */\n attribute?: string;\n}\n\n/** One tag's capture config in the SDK payload (`SdkConfigResponse.tagging.properties`). */\nexport interface TagPropertyConfig {\n kind: \"page\" | \"feature\";\n tagId: string;\n /** Page rules (pages) or feature rules (features), evaluated in the browser. */\n pageRules?: PageRule[];\n featureRules?: FeatureRule[];\n properties: TagPropertyDefinition[];\n}\n\nexport interface TaggingSdkConfig {\n /** Attribute that names features automatically (null = off). */\n featureAttribute: string | null;\n properties: TagPropertyConfig[];\n}\n\nexport const TAG_PROPERTY_LIMITS = { perTag: 10, total: 50, value: 100 } as const;\n\n/** Attribute names an event property may read. */\nexport function propertyAttributeAllowed(name: string): boolean {\n const n = name.toLowerCase();\n if (n === \"value\" || n.startsWith(\"on\") || n === \"style\" || n === \"srcdoc\") return false;\n return /^[a-z][a-z0-9_:.-]{0,60}$/.test(n);\n}\n","/** Complaint types and limits shared by the server and the messenger runtime (zod-free). */\n\n/** Where a complaint is in its handling; the messenger shows it as Received → In review → Resolved. */\nexport const COMPLAINT_STATUSES = [\"open\", \"in_review\", \"resolved\"] as const;\nexport type ComplaintStatus = (typeof COMPLAINT_STATUSES)[number];\n\n/** Events a complaint webhook can fire on. */\nexport const COMPLAINT_EVENTS = [\"complaint.filed\", \"complaint.status_changed\", \"complaint.replied\", \"complaint.resolved\"] as const;\nexport type ComplaintEvent = (typeof COMPLAINT_EVENTS)[number];\n\n/** Extra questions a category asks for. */\nexport const COMPLAINT_FIELD_TYPES = [\"text\", \"choice\"] as const;\nexport type ComplaintFieldType = (typeof COMPLAINT_FIELD_TYPES)[number];\n\nexport const MAX_COMPLAINT_FIELDS = 8;\nexport const MAX_COMPLAINT_CHOICES = 12;\nexport const MAX_COMPLAINT_LENGTH = 4000;\nexport const MAX_COMPLAINT_ANSWER_LENGTH = 500;\n/** Largest screenshot the messenger may attach (after it scales the image down). */\nexport const MAX_COMPLAINT_ATTACHMENT_BYTES = 2 * 1024 * 1024;\n\nexport interface ComplaintField {\n /** Stable id (`invoice_number`), used as the answer's key in webhook payloads. */\n id: string;\n label: string;\n type: ComplaintFieldType;\n /** Choices for `choice` questions. */\n options?: string[];\n required: boolean;\n}\n\n/** \"CMP-1042\" for complaint number 1042. */\nexport const complaintReference = (number: number) => `CMP-${number}`;\n\n/** A category as the messenger offers it. */\nexport interface MessengerComplaintCategory {\n id: string;\n name: string;\n description: string;\n color: string;\n fields: ComplaintField[];\n}\n\n/** Complaints block of `MessengerConfig`; absent when the project doesn't take complaints. */\nexport interface MessengerComplaintsConfig {\n categories: MessengerComplaintCategory[];\n /** Visitors the app hasn't identified may file one (with an email address). */\n anonymous: boolean;\n}\n\n/** A complaint as the person who filed it sees it (on its conversation). */\nexport interface MessengerComplaint {\n id: string;\n reference: string;\n status: ComplaintStatus;\n categoryName: string;\n createdAt: string;\n}\n\n/** Scout offered the complaint form in a reply, with this category picked. */\nexport interface MessengerComplaintOffer {\n categoryId: string;\n name: string;\n}\n","/** Bug report (user feedback) types and limits shared by the server and the SDK (zod-free). */\n\nexport const MAX_BUG_REPORT_LENGTH = 4000;\n/** Largest screenshot a bug report may carry (Sentry's feedback widget allows about the same). */\nexport const MAX_BUG_REPORT_SCREENSHOT_BYTES = 4 * 1024 * 1024;\n\n/** `guidely.captureFeedback(...)`. Only `message` is required. */\nexport interface BugReportInput {\n message: string;\n email?: string | null;\n name?: string | null;\n /** The error the report is about: an exception event id (defaults to the last error this page reported). */\n associatedEventId?: string | null;\n /** Free-form tags shown with the report (strings, at most 20). */\n tags?: Record<string, string>;\n /** One image (png, jpeg, webp or gif) as a File/Blob, or already base64-encoded. */\n screenshot?: Blob | { fileName: string; data: string } | null;\n}\n\n/** What `POST /v1/sdk/bug-reports` answers. */\nexport interface BugReportResponse {\n id: string;\n /** Linked to an error issue already (the associated error arrived first). */\n linked: boolean;\n}\n","/**\n * Agent Analytics: the `agent.conversation` turn the customer's own AI agents send (zod-free, so the\n * browser SDK can use the types and limits without bundling the schema). The schema is in agents.ts.\n */\n\nexport const AGENT_TURN_ROLES = [\"user\", \"assistant\", \"tool\", \"system\"] as const;\nexport type AgentTurnRole = (typeof AGENT_TURN_ROLES)[number];\n\n/** How a conversation ended, as the agent reports it. */\nexport const AGENT_OUTCOMES = [\"success\", \"failure\", \"escalated\", \"abandoned\"] as const;\nexport type AgentOutcome = (typeof AGENT_OUTCOMES)[number];\n\nexport const AGENT_TOOL_STATUSES = [\"ok\", \"error\"] as const;\nexport type AgentToolStatus = (typeof AGENT_TOOL_STATUSES)[number];\n\n/** Longest turn text accepted (characters). */\nexport const AGENT_TURN_MAX_TEXT = 20_000;\n/** Most turns in one request. */\nexport const AGENT_TURNS_PER_BATCH = 100;\n/** Most tool calls on one turn. */\nexport const AGENT_TOOL_CALLS_PER_TURN = 50;\n/** Metadata: at most this many keys, string values up to 500 characters, 4 KB in all. */\nexport const AGENT_METADATA_MAX_KEYS = 30;\nexport const AGENT_METADATA_MAX_BYTES = 4096;\n/** The built-in Scout agent's id; customer agents can't use it. */\nexport const SCOUT_AGENT_ID = \"scout\";\n\n/** One tool the agent called in a turn. Arguments and results are never sent or stored. */\nexport interface AgentToolCallInput {\n name: string;\n status?: AgentToolStatus;\n latencyMs?: number;\n}\n\n/** One `agent.conversation` turn. */\nexport interface AgentTurnInput {\n type?: \"agent.conversation\";\n /** Your conversation (thread) id. */\n conversationId: string;\n /** Your agent's id, e.g. \"support-bot\". The agent is created on its first turn. */\n agentId: string;\n /** Display name for a new agent (defaults to agentId). */\n agentName?: string;\n /** Idempotency key: a turn sent twice with the same id is stored once. */\n turnId?: string;\n role: AgentTurnRole;\n text?: string;\n toolCalls?: AgentToolCallInput[];\n /** How long the agent took to produce this turn (assistant turns). */\n latencyMs?: number;\n /** How the conversation ended, when this turn ends it (the latest reported outcome wins). */\n outcome?: AgentOutcome;\n /** Whether the person got what they came for, when the agent knows. */\n taskSuccess?: boolean;\n /** ISO 8601 time of the turn (default: when Guidely receives it). */\n occurredAt?: string;\n userId?: string | null;\n anonymousId?: string | null;\n accountId?: string | null;\n sessionId?: string | null;\n /** Flat key/value pairs (strings, numbers, booleans), e.g. { model: \"gpt-4.1\" }. */\n metadata?: Record<string, string | number | boolean | null>;\n}\n\n/** Response of both ingestion endpoints. */\nexport interface AgentEventsResponse {\n accepted: number;\n duplicates: number;\n /** Turns refused (an agent past the per-project limit, or a conversation past its turn limit). */\n rejected?: number;\n /** Turns dropped because this month's product analytics allowance is used up. */\n overLimit?: number;\n}\n","/**\n * Guide and resource-center localization (zod-free, so the browser SDK can import it).\n *\n * Every translatable text field has a stable key derived from ids, never from positions, so\n * reordering steps keeps translations attached: `steps.<stepId>.title`,\n * `steps.<stepId>.buttons.<buttonId>.label`, `checklist.tasks.<taskId>.title`,\n * `survey.questions.<questionId>.options.<optionId>.label`, …\n *\n * A visitor's language comes from (in order) an explicit SDK locale, the `language` / `locale`\n * trait, then the browser / device language. `resolveLocale` matches it against the languages a\n * guide is translated into (exact tag first, then the base language) and falls back to the\n * project's default language, in which the guide is written.\n */\nimport type { GuideConfig } from \"./guide\";\nimport type { PublishedGuide, ResourceCenterAnnouncement, ResourceCenterArticle, ResourceCenterConfig } from \"./sdk-api\";\n\nexport type TextKind = \"text\" | \"html\";\n\nexport interface TextEntry {\n key: string;\n /** Default-language text. */\n source: string;\n kind: TextKind;\n /** Human-readable location for translators (\"Step 2 · Title\"). */\n label: string;\n}\n\n/** Project-level language settings (Project.settings.localization). */\nexport interface LocalizationSettings {\n /** Language the content is written in. */\n defaultLocale: string;\n /** Additional languages offered for translation. */\n locales: string[];\n /** Machine-translate new and changed text into every language automatically. */\n autoTranslate?: boolean;\n /** Machine translations need a teammate's approval before visitors see them. */\n requireReview?: boolean;\n}\n\n/**\n * Review state of one translated text. `machine` texts were written by AI translation; `human`\n * ones were typed or imported by a teammate (approved by doing so). `outdated` means the source\n * text changed after the translation was written or approved.\n */\nexport interface TranslationReviewState {\n origin: \"machine\" | \"human\";\n approved: boolean;\n outdated: boolean;\n reviewedBy?: string | null;\n reviewedAt?: string | null;\n}\n\n/** locale → key → review state. Texts without a state are human translations from before review existed. */\nexport type TranslationReviewMap = Record<string, Record<string, TranslationReviewState>>;\n\n/** Does this translation still need a teammate to look at it? */\nexport function needsReview(state: TranslationReviewState | undefined): boolean {\n return !!state && ((state.origin === \"machine\" && !state.approved) || state.outdated);\n}\n\nexport const DEFAULT_LOCALE = \"en\";\n\n/** Common languages offered in the dashboard's language picker (any BCP 47 tag is accepted). */\nexport const COMMON_LOCALES: Array<{ code: string; name: string }> = [\n { code: \"en\", name: \"English\" },\n { code: \"en-GB\", name: \"English (UK)\" },\n { code: \"fr\", name: \"French\" },\n { code: \"fr-CA\", name: \"French (Canada)\" },\n { code: \"de\", name: \"German\" },\n { code: \"es\", name: \"Spanish\" },\n { code: \"es-MX\", name: \"Spanish (Mexico)\" },\n { code: \"it\", name: \"Italian\" },\n { code: \"pt\", name: \"Portuguese\" },\n { code: \"pt-BR\", name: \"Portuguese (Brazil)\" },\n { code: \"nl\", name: \"Dutch\" },\n { code: \"sv\", name: \"Swedish\" },\n { code: \"da\", name: \"Danish\" },\n { code: \"nb\", name: \"Norwegian\" },\n { code: \"fi\", name: \"Finnish\" },\n { code: \"pl\", name: \"Polish\" },\n { code: \"cs\", name: \"Czech\" },\n { code: \"tr\", name: \"Turkish\" },\n { code: \"ru\", name: \"Russian\" },\n { code: \"uk\", name: \"Ukrainian\" },\n { code: \"ar\", name: \"Arabic\" },\n { code: \"he\", name: \"Hebrew\" },\n { code: \"hi\", name: \"Hindi\" },\n { code: \"ja\", name: \"Japanese\" },\n { code: \"ko\", name: \"Korean\" },\n { code: \"zh-Hans\", name: \"Chinese (Simplified)\" },\n { code: \"zh-Hant\", name: \"Chinese (Traditional)\" },\n { code: \"id\", name: \"Indonesian\" },\n { code: \"th\", name: \"Thai\" },\n { code: \"vi\", name: \"Vietnamese\" },\n];\n\nexport function localeName(code: string): string {\n const exact = COMMON_LOCALES.find((l) => l.code.toLowerCase() === code.toLowerCase());\n if (exact) return exact.name;\n const base = COMMON_LOCALES.find((l) => l.code.toLowerCase() === baseLanguage(code));\n return base ? `${base.name} (${code})` : code;\n}\n\n/** `fr_FR` / `FR-fr` → `fr-FR`; script subtags keep title case (`zh-hans` → `zh-Hans`). Invalid input → \"\". */\nexport function normalizeLocale(input: unknown): string {\n if (typeof input !== \"string\") return \"\";\n const parts = input.trim().replace(/_/g, \"-\").split(\"-\").filter(Boolean);\n if (!parts.length || !/^[a-zA-Z]{2,3}$/.test(parts[0]!)) return \"\";\n return parts\n .slice(0, 3)\n .map((p, i) => (i === 0 ? p.toLowerCase() : p.length === 4 ? p[0]!.toUpperCase() + p.slice(1).toLowerCase() : p.length === 2 ? p.toUpperCase() : p))\n .join(\"-\");\n}\n\nexport function baseLanguage(locale: string): string {\n return normalizeLocale(locale).split(\"-\")[0] ?? \"\";\n}\n\n/**\n * Picks the language to show: for each requested locale in order, an exact match among\n * `available`, else one sharing its base language (`fr-CA` → `fr`, `fr` → `fr-FR`). Falls back to\n * `defaultLocale`. Matching ignores case.\n */\nexport function resolveLocale(requested: ReadonlyArray<string | null | undefined>, available: readonly string[], defaultLocale: string = DEFAULT_LOCALE): string {\n const def = normalizeLocale(defaultLocale) || DEFAULT_LOCALE;\n const avail = available.map(normalizeLocale).filter(Boolean);\n const all = [def, ...avail.filter((a) => a.toLowerCase() !== def.toLowerCase())];\n for (const raw of requested) {\n const want = normalizeLocale(raw);\n if (!want) continue;\n const exact = all.find((a) => a.toLowerCase() === want.toLowerCase());\n if (exact) return exact;\n const base = baseLanguage(want);\n const sameBase = all.find((a) => a.toLowerCase() === base) ?? all.find((a) => baseLanguage(a) === base);\n if (sameBase) return sameBase;\n }\n return def;\n}\n\n/** Locale candidates for a visitor: explicit option, traits (`language`, `locale`), then the platform's languages. */\nexport function visitorLocales(explicit: string | null | undefined, traits: Record<string, unknown> | null | undefined, platform: ReadonlyArray<string | null | undefined> = []): string[] {\n const out: string[] = [];\n const push = (v: unknown) => {\n const n = normalizeLocale(v);\n if (n && !out.includes(n)) out.push(n);\n };\n push(explicit);\n push(traits?.language);\n push(traits?.locale);\n for (const p of platform) push(p);\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Guides\n// ---------------------------------------------------------------------------\n\n/** Every translatable text in a guide config, in display order. Empty texts are skipped. */\nexport function guideTextEntries(config: Pick<GuideConfig, \"steps\" | \"checklist\" | \"survey\">): TextEntry[] {\n const out: TextEntry[] = [];\n const add = (key: string, source: string | undefined | null, kind: TextKind, label: string) => {\n if (source && source.trim()) out.push({ key, source, kind, label });\n };\n config.steps.forEach((s, i) => {\n const at = `Step ${i + 1}`;\n add(`steps.${s.id}.title`, s.title, \"text\", `${at} · Title`);\n add(`steps.${s.id}.body`, s.body, \"html\", `${at} · Body`);\n add(`steps.${s.id}.customHtml`, s.customHtml, \"html\", `${at} · Custom HTML`);\n add(`steps.${s.id}.imageAlt`, s.imageAlt, \"text\", `${at} · Image description`);\n s.buttons.forEach((b) => add(`steps.${s.id}.buttons.${b.id}.label`, b.label, \"text\", `${at} · Button “${b.label}”`));\n });\n const c = config.checklist;\n if (c) {\n add(\"checklist.launcherLabel\", c.launcherLabel, \"text\", \"Checklist · Launcher label\");\n add(\"checklist.completionTitle\", c.completionTitle, \"text\", \"Checklist · Completion title\");\n add(\"checklist.completionBody\", c.completionBody, \"html\", \"Checklist · Completion message\");\n c.tasks.forEach((t, i) => {\n add(`checklist.tasks.${t.id}.title`, t.title, \"text\", `Task ${i + 1} · Title`);\n add(`checklist.tasks.${t.id}.description`, t.description, \"html\", `Task ${i + 1} · Description`);\n });\n }\n const sv = config.survey;\n if (sv) {\n sv.questions.forEach((q, i) => {\n const at = `Question ${i + 1}`;\n add(`survey.questions.${q.id}.title`, q.title, \"text\", `${at} · Question`);\n add(`survey.questions.${q.id}.description`, q.description, \"text\", `${at} · Description`);\n add(`survey.questions.${q.id}.placeholder`, q.placeholder, \"text\", `${at} · Placeholder`);\n add(`survey.questions.${q.id}.lowLabel`, q.lowLabel, \"text\", `${at} · Low label`);\n add(`survey.questions.${q.id}.highLabel`, q.highLabel, \"text\", `${at} · High label`);\n q.options.forEach((o) => add(`survey.questions.${q.id}.options.${o.id}.label`, o.label, \"text\", `${at} · Option “${o.label}”`));\n });\n add(\"survey.thankYouTitle\", sv.thankYouTitle, \"text\", \"Survey · Thank-you title\");\n add(\"survey.thankYouBody\", sv.thankYouBody, \"html\", \"Survey · Thank-you message\");\n }\n return out;\n}\n\n/** Locales a guide has any translation for. */\nexport function guideLocales(config: Pick<GuideConfig, \"localization\">): string[] {\n const t = config.localization?.translations ?? {};\n return Object.keys(t).filter((l) => Object.values(t[l] ?? {}).some((v) => typeof v === \"string\" && v.trim() !== \"\"));\n}\n\nfunction pick(map: Record<string, string> | undefined, key: string, fallback: string): string;\nfunction pick(map: Record<string, string> | undefined, key: string, fallback: string | undefined): string | undefined;\nfunction pick(map: Record<string, string> | undefined, key: string, fallback: string | undefined): string | undefined {\n const v = map?.[key];\n return typeof v === \"string\" && v.trim() !== \"\" ? v : fallback;\n}\n\n/** The config with one language's translations applied (untranslated texts keep the default language). */\nexport function applyGuideTranslations<C extends Pick<GuideConfig, \"steps\" | \"checklist\" | \"survey\">>(config: C, map: Record<string, string> | undefined): C {\n if (!map || !Object.keys(map).length) return config;\n return {\n ...config,\n steps: config.steps.map((s) => ({\n ...s,\n title: pick(map, `steps.${s.id}.title`, s.title),\n body: pick(map, `steps.${s.id}.body`, s.body),\n customHtml: pick(map, `steps.${s.id}.customHtml`, s.customHtml),\n imageAlt: pick(map, `steps.${s.id}.imageAlt`, s.imageAlt),\n buttons: s.buttons.map((b) => ({ ...b, label: pick(map, `steps.${s.id}.buttons.${b.id}.label`, b.label) })),\n })),\n checklist: config.checklist\n ? {\n ...config.checklist,\n launcherLabel: pick(map, \"checklist.launcherLabel\", config.checklist.launcherLabel),\n completionTitle: pick(map, \"checklist.completionTitle\", config.checklist.completionTitle),\n completionBody: pick(map, \"checklist.completionBody\", config.checklist.completionBody),\n tasks: config.checklist.tasks.map((t) => ({ ...t, title: pick(map, `checklist.tasks.${t.id}.title`, t.title), description: pick(map, `checklist.tasks.${t.id}.description`, t.description) })),\n }\n : config.checklist,\n survey: config.survey\n ? {\n ...config.survey,\n thankYouTitle: pick(map, \"survey.thankYouTitle\", config.survey.thankYouTitle),\n thankYouBody: pick(map, \"survey.thankYouBody\", config.survey.thankYouBody),\n questions: config.survey.questions.map((q) => ({\n ...q,\n title: pick(map, `survey.questions.${q.id}.title`, q.title),\n description: pick(map, `survey.questions.${q.id}.description`, q.description),\n placeholder: pick(map, `survey.questions.${q.id}.placeholder`, q.placeholder),\n lowLabel: pick(map, `survey.questions.${q.id}.lowLabel`, q.lowLabel),\n highLabel: pick(map, `survey.questions.${q.id}.highLabel`, q.highLabel),\n options: q.options.map((o) => ({ ...o, label: pick(map, `survey.questions.${q.id}.options.${o.id}.label`, o.label) })),\n })),\n }\n : config.survey,\n };\n}\n\n/**\n * The guide as a visitor speaking `requested` should see it, with `locale` set to the language\n * chosen (the default language when none of the guide's translations match).\n */\nexport function localizeGuide(guide: PublishedGuide, requested: readonly string[], defaultLocale: string = DEFAULT_LOCALE): PublishedGuide & { locale: string } {\n const translations = guide.config.localization?.translations ?? {};\n const locale = resolveLocale(requested, guideLocales(guide.config), defaultLocale);\n const key = Object.keys(translations).find((l) => normalizeLocale(l).toLowerCase() === locale.toLowerCase());\n if (!key) return { ...guide, locale };\n return { ...guide, locale, config: applyGuideTranslations(guide.config, translations[key]) };\n}\n\nexport interface TranslationCoverage {\n locale: string;\n total: number;\n translated: number;\n /** Keys with no translation. */\n missing: string[];\n /** Keys whose translation exists but whose key no longer matches any text (stale). */\n stale: string[];\n}\n\nexport function translationCoverage(entries: readonly TextEntry[], map: Record<string, string> | undefined, locale: string): TranslationCoverage {\n const keys = new Set(entries.map((e) => e.key));\n const missing = entries.filter((e) => !pick(map, e.key, undefined)).map((e) => e.key);\n const stale = Object.keys(map ?? {}).filter((k) => !keys.has(k) && (map?.[k] ?? \"\").trim() !== \"\");\n return { locale, total: entries.length, translated: entries.length - missing.length, missing, stale };\n}\n\n// ---------------------------------------------------------------------------\n// Resource center\n// ---------------------------------------------------------------------------\n\n/** Translations carried by the published resource center (texts other than articles and announcements). */\nexport type ResourceCenterTranslations = Record<string, Record<string, string>>;\n\n/** Translatable resource-center texts (title, launcher label, links, FAQs, collections). */\nexport function resourceCenterTextEntries(rc: Pick<ResourceCenterConfig, \"title\" | \"launcher\" | \"links\" | \"faqs\" | \"collections\">): TextEntry[] {\n const out: TextEntry[] = [];\n const add = (key: string, source: string | undefined | null, kind: TextKind, label: string) => {\n if (source && source.trim()) out.push({ key, source, kind, label });\n };\n add(\"title\", rc.title, \"text\", \"Title\");\n add(\"launcher.label\", rc.launcher?.label, \"text\", \"Launcher label\");\n rc.collections.forEach((c) => {\n add(`collections.${c.id}.name`, c.name, \"text\", `Collection “${c.name}”`);\n add(`collections.${c.id}.description`, c.description, \"text\", `Collection “${c.name}” · Description`);\n });\n rc.links.forEach((l) => add(`links.${l.id}.label`, l.label, \"text\", `Link “${l.label}”`));\n rc.faqs.forEach((f, i) => {\n add(`faqs.${f.id}.question`, f.question, \"text\", `FAQ ${i + 1} · Question`);\n add(`faqs.${f.id}.answer`, f.answer, \"html\", `FAQ ${i + 1} · Answer`);\n });\n return out;\n}\n\n/** Article texts, keyed `title` / `summary` / `body`. */\nexport function articleTextEntries(a: { title: string; summary?: string | null; body?: string | null }): TextEntry[] {\n const out: TextEntry[] = [];\n if (a.title.trim()) out.push({ key: \"title\", source: a.title, kind: \"text\", label: \"Title\" });\n if (a.summary?.trim()) out.push({ key: \"summary\", source: a.summary, kind: \"text\", label: \"Summary\" });\n if (a.body?.trim()) out.push({ key: \"body\", source: a.body, kind: \"html\", label: \"Body\" });\n return out;\n}\n\n/** Locales the resource center offers (its own strings, articles or announcements). */\nexport function resourceCenterLocales(rc: ResourceCenterConfig): string[] {\n const set = new Set<string>(Object.keys(rc.translations ?? {}));\n for (const a of rc.articles) for (const l of Object.keys(a.translations ?? {})) set.add(l);\n for (const a of rc.announcements ?? []) for (const l of Object.keys(a.translations ?? {})) set.add(l);\n return [...set];\n}\n\nfunction translationFor<T>(map: Record<string, T> | undefined, locale: string): T | undefined {\n if (!map) return undefined;\n const key = Object.keys(map).find((l) => normalizeLocale(l).toLowerCase() === locale.toLowerCase());\n return key ? map[key] : undefined;\n}\n\nexport function localizeArticle(a: ResourceCenterArticle, locale: string): ResourceCenterArticle {\n const t = translationFor(a.translations, locale);\n if (!t) return a;\n const body = t.body?.trim() ? t.body : a.body;\n // A translated body that was left out of the snapshot is fetched with `?locale=`.\n return { ...a, title: t.title?.trim() ? t.title : a.title, summary: t.summary?.trim() ? t.summary : a.summary, body, ...(t.bodyOmitted ? { bodyOmitted: true } : {}) };\n}\n\nexport function localizeAnnouncement(a: ResourceCenterAnnouncement, locale: string): ResourceCenterAnnouncement {\n const t = translationFor(a.translations, locale);\n if (!t) return a;\n return { ...a, title: t.title?.trim() ? t.title : a.title, body: t.body?.trim() ? t.body : a.body };\n}\n\n/** The resource center in the visitor's language (with `locale` = the language chosen). */\nexport function localizeResourceCenter(rc: ResourceCenterConfig, requested: readonly string[], defaultLocale: string = DEFAULT_LOCALE): ResourceCenterConfig & { locale: string } {\n const locale = resolveLocale(requested, resourceCenterLocales(rc), defaultLocale);\n if (locale.toLowerCase() === normalizeLocale(defaultLocale).toLowerCase()) return { ...rc, locale };\n const map = translationFor(rc.translations, locale);\n return {\n ...rc,\n locale,\n title: pick(map, \"title\", rc.title),\n launcher: { ...rc.launcher, label: pick(map, \"launcher.label\", rc.launcher.label) },\n collections: rc.collections.map((c) => ({ ...c, name: pick(map, `collections.${c.id}.name`, c.name), description: pick(map, `collections.${c.id}.description`, c.description) })),\n links: rc.links.map((l) => ({ ...l, label: pick(map, `links.${l.id}.label`, l.label) })),\n faqs: rc.faqs.map((f) => ({ ...f, question: pick(map, `faqs.${f.id}.question`, f.question), answer: pick(map, `faqs.${f.id}.answer`, f.answer) })),\n articles: rc.articles.map((a) => localizeArticle(a, locale)),\n announcements: rc.announcements?.map((a) => localizeAnnouncement(a, locale)),\n };\n}\n","/**\n * Guide A/B tests (zod-free; shared by the server, the web SDK and the mobile SDK ports).\n *\n * Each visitor falls into a bucket 0–99: `rolloutBucket(userId || anonymousId, salt)` (FNV-1a,\n * see utils.ts), with `salt = experimentSalt(experimentId)`. Variants own consecutive bucket ranges\n * in their listed order, sized by their integer weights (which sum to 100). The server folds each\n * variant's range into the targeting it serves as two `experiment.bucket` rules, so every SDK\n * applies the split with the rule engine it already has, and assignment is the same everywhere:\n * the server's `assignGuideVariant` and an SDK evaluating the served rules always agree.\n */\nimport { rolloutBucket } from \"./utils\";\nimport type { Rule, RuleGroup } from \"./targeting-eval\";\n\n/** The \"no guide\" variant: visitors in it see nothing, and are measured against the guide variants. */\nexport const CONTROL_VARIANT_ID = \"control\";\n\nexport const GUIDE_EXPERIMENT_STATUSES = [\"draft\", \"running\", \"completed\"] as const;\nexport type GuideExperimentStatus = (typeof GUIDE_EXPERIMENT_STATUSES)[number];\n\nexport const GUIDE_EXPERIMENT_GOALS = [\"guide_completed\", \"event\", \"page_visit\", \"click_text\"] as const;\nexport type GuideExperimentGoalKind = (typeof GUIDE_EXPERIMENT_GOALS)[number];\n\nexport const GUIDE_EXPERIMENT_GOAL_LABELS: Record<GuideExperimentGoalKind, string> = {\n guide_completed: \"Completes the guide\",\n event: \"Tracks an event\",\n page_visit: \"Visits a page\",\n click_text: \"Clicks an element with text\",\n};\n\nexport interface GuideExperimentGoal {\n kind: GuideExperimentGoalKind;\n /** Event name, page path pattern (`/billing/*`) or click text, depending on `kind`. */\n value?: string;\n}\n\nexport interface GuideExperimentVariant {\n id: string;\n name: string;\n /** The guide shown to this variant; null for the control group (no guide). */\n guideId: string | null;\n /** Share of visitors, a whole percentage; all weights sum to 100. */\n weight: number;\n}\n\nexport function experimentSalt(experimentId: string): string {\n return `gx:${experimentId}`;\n}\n\n/** Bucket ranges `[from, to)` per variant, in order. */\nexport function variantRanges(variants: ReadonlyArray<Pick<GuideExperimentVariant, \"id\" | \"weight\">>): Array<{ id: string; from: number; to: number }> {\n let at = 0;\n return variants.map((v) => {\n const from = at;\n at = Math.min(100, at + Math.max(0, Math.round(v.weight)));\n return { id: v.id, from, to: at };\n });\n}\n\n/** The variant a visitor is in, or null when weights leave their bucket unassigned. */\nexport function assignGuideVariant(variants: ReadonlyArray<Pick<GuideExperimentVariant, \"id\" | \"weight\">>, experimentId: string, subject: string): string | null {\n const bucket = rolloutBucket(subject, experimentSalt(experimentId));\n return variantRanges(variants).find((r) => bucket >= r.from && bucket < r.to)?.id ?? null;\n}\n\n/** Rules restricting targeting to bucket range `[from, to)` of `salt`. */\nexport function experimentBucketRules(salt: string, from: number, to: number): Rule[] {\n return [\n { id: \"experiment-from\", field: \"experiment.bucket\", key: salt, op: \"gte\", value: from },\n { id: \"experiment-to\", field: \"experiment.bucket\", key: salt, op: \"lt\", value: to },\n ];\n}\n\n/** Targeting with a variant's bucket range folded in (an SDK without `experiment.bucket` shows the guide to nobody). */\nexport function withExperimentBucket(targeting: RuleGroup, salt: string, from: number, to: number): RuleGroup {\n return { id: \"experiment\", op: \"and\", rules: [...experimentBucketRules(salt, from, to), targeting] };\n}\n\n/** Problems with a variant list; empty when it can run. */\nexport function variantProblems(variants: ReadonlyArray<GuideExperimentVariant>): string[] {\n const problems: string[] = [];\n if (variants.length < 2) problems.push(\"An A/B test needs at least two variants.\");\n if (variants.length > 5) problems.push(\"An A/B test can have at most five variants.\");\n const guides = variants.filter((v) => v.guideId);\n if (guides.length === 0) problems.push(\"At least one variant must show a guide.\");\n if (variants.filter((v) => !v.guideId).length > 1) problems.push(\"Only one variant can be the control group (no guide).\");\n if (new Set(guides.map((v) => v.guideId)).size !== guides.length) problems.push(\"Each variant needs its own guide.\");\n if (new Set(variants.map((v) => v.id)).size !== variants.length) problems.push(\"Variant ids must be unique.\");\n if (variants.some((v) => !Number.isInteger(v.weight) || v.weight < 1)) problems.push(\"Every variant needs a whole-number share of at least 1%.\");\n const total = variants.reduce((s, v) => s + v.weight, 0);\n if (total !== 100) problems.push(`Traffic shares must add up to 100% (now ${total}%).`);\n return problems;\n}\n\n/** Splits 100% as evenly as possible across `n` variants (first ones get the remainder). */\nexport function evenWeights(n: number): number[] {\n if (n <= 0) return [];\n const base = Math.floor(100 / n);\n return Array.from({ length: n }, (_, i) => base + (i < 100 - base * n ? 1 : 0));\n}\n","/**\n * Custom CSS for guides and themes (zod-free; the server sanitizes on save, the web runtime\n * sanitizes again and scopes before injecting).\n *\n * Guides render inside the SDK's Shadow DOM, so page styles and guide styles never mix. Within the\n * shadow root, every rule is additionally prefixed with the guide's own container selector, so one\n * guide's CSS can't restyle another guide, the resource center or the messenger. Sanitizing removes\n * what could reach outside the container or load anything: `@import`, `:host` / `::slotted` rules,\n * `url()`s other than https images and `data:image/…`, legacy script hooks (`expression()`,\n * `behavior`, `-moz-binding`, `javascript:`) and any markup.\n */\n\nexport const MAX_CUSTOM_CSS = 20000;\n\nconst BLOCKED_AT_RULES = /^@(import|charset|namespace|document|-moz-document)\\b/i;\nconst ALLOWED_AT_RULES = /^@(media|supports|container|layer|keyframes|-webkit-keyframes|font-face)\\b/i;\n\ninterface Block {\n /** Selector or at-rule prelude; \"\" for a bare declaration list. */\n prelude: string;\n /** Declarations (for rules) or nested CSS (for grouping at-rules). */\n body: string;\n}\n\n/** Splits CSS into top-level `prelude { body }` blocks, respecting strings and nesting. Statements without a block are dropped. */\nfunction splitBlocks(css: string): Block[] {\n const out: Block[] = [];\n let i = 0;\n const n = css.length;\n while (i < n) {\n let prelude = \"\";\n let quote: string | null = null;\n while (i < n) {\n const ch = css[i]!;\n if (quote) {\n prelude += ch;\n if (ch === \"\\\\\") prelude += css[++i] ?? \"\";\n else if (ch === quote) quote = null;\n } else if (ch === '\"' || ch === \"'\") {\n quote = ch;\n prelude += ch;\n } else if (ch === \"{\") break;\n else if (ch === \";\") {\n prelude = \"\"; // a statement (e.g. @import) – dropped\n } else if (ch === \"}\") {\n prelude = \"\"; // stray brace\n } else prelude += ch;\n i++;\n }\n if (i >= n) break;\n // css[i] === \"{\"\n i++;\n let depth = 1;\n let body = \"\";\n quote = null;\n while (i < n && depth > 0) {\n const ch = css[i]!;\n if (quote) {\n body += ch;\n if (ch === \"\\\\\") body += css[++i] ?? \"\";\n else if (ch === quote) quote = null;\n } else if (ch === '\"' || ch === \"'\") {\n quote = ch;\n body += ch;\n } else if (ch === \"{\") {\n depth++;\n body += ch;\n } else if (ch === \"}\") {\n depth--;\n if (depth > 0) body += ch;\n } else body += ch;\n i++;\n }\n out.push({ prelude: prelude.trim(), body });\n }\n return out;\n}\n\n/** Splits a selector list on top-level commas. */\nfunction splitSelectors(list: string): string[] {\n const out: string[] = [];\n let depth = 0;\n let cur = \"\";\n for (const ch of list) {\n if (ch === \"(\" || ch === \"[\") depth++;\n else if (ch === \")\" || ch === \"]\") depth = Math.max(0, depth - 1);\n if (ch === \",\" && depth === 0) {\n out.push(cur.trim());\n cur = \"\";\n } else cur += ch;\n }\n if (cur.trim()) out.push(cur.trim());\n return out;\n}\n\nfunction safeUrl(raw: string): boolean {\n const u = raw.trim().replace(/^['\"]|['\"]$/g, \"\").trim();\n return /^https:\\/\\//i.test(u) || /^data:image\\/(png|jpe?g|gif|webp|svg\\+xml)[;,]/i.test(u);\n}\n\n/** Cleans one declaration list. */\nfunction cleanDeclarations(body: string): string {\n return body\n .replace(/url\\(([^)]*)\\)/gi, (m, inner: string) => (safeUrl(inner) ? m : \"none\"))\n .replace(/expression\\s*\\(/gi, \"(\")\n .replace(/javascript\\s*:/gi, \"\")\n .replace(/(^|[;{\\s])(-moz-binding|behavior)\\s*:[^;]*;?/gi, \"$1\")\n .replace(/[{}]/g, \"\")\n .trim();\n}\n\n/** Removes everything unsafe; keeps the rule structure. */\nexport function sanitizeCustomCss(input: string | null | undefined): string {\n if (!input) return \"\";\n let css = String(input).slice(0, MAX_CUSTOM_CSS);\n css = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\").replace(/<(script|style)\\b[^>]*>[\\s\\S]*?<\\/\\1\\s*>/gi, \"\").replace(/<\\/?[a-z!][^>]*>/gi, \"\").replace(/</g, \"\");\n return render(splitBlocks(css), 0);\n}\n\nfunction render(blocks: Block[], depth: number): string {\n const parts: string[] = [];\n for (const b of blocks) {\n if (!b.prelude) continue;\n if (b.prelude.startsWith(\"@\")) {\n if (BLOCKED_AT_RULES.test(b.prelude) || !ALLOWED_AT_RULES.test(b.prelude)) continue;\n if (/^@(-webkit-)?keyframes|^@font-face/i.test(b.prelude)) {\n // Keyframe selectors (from/to/50%) and font-face descriptors are declarations-like.\n const inner = /^@font-face/i.test(b.prelude) ? cleanDeclarations(b.body) : splitBlocks(b.body).map((k) => `${k.prelude}{${cleanDeclarations(k.body)}}`).join(\"\");\n parts.push(`${b.prelude}{${inner}}`);\n } else if (depth < 3) parts.push(`${b.prelude}{${render(splitBlocks(b.body), depth + 1)}}`);\n continue;\n }\n const selectors = splitSelectors(b.prelude).filter((s) => !/:host|::slotted|::part/i.test(s));\n if (!selectors.length) continue;\n parts.push(`${selectors.join(\",\")}{${cleanDeclarations(b.body)}}`);\n }\n return parts.join(\"\\n\");\n}\n\n/**\n * Prefixes every selector with `scope` (e.g. `.g-scope[data-guide=\"abc\"]`). `:root`, `html`,\n * `body`, `:scope` and `&` at the start of a selector refer to the container itself.\n */\nexport function scopeCustomCss(css: string, scope: string): string {\n return scopeBlocks(splitBlocks(sanitizeCustomCss(css)), scope, 0);\n}\n\nfunction scopeBlocks(blocks: Block[], scope: string, depth: number): string {\n const parts: string[] = [];\n for (const b of blocks) {\n if (b.prelude.startsWith(\"@\")) {\n if (/^@(-webkit-)?keyframes|^@font-face/i.test(b.prelude)) parts.push(`${b.prelude}{${b.body}}`);\n else if (depth < 3) parts.push(`${b.prelude}{${scopeBlocks(splitBlocks(b.body), scope, depth + 1)}}`);\n continue;\n }\n const sels = splitSelectors(b.prelude).map((s) => {\n const self = s.match(/^(:root|html|body|:scope|&)(?![\\w-])(.*)$/i);\n if (self) return `${scope}${self[2] ?? \"\"}`;\n return `${scope} ${s}`;\n });\n parts.push(`${sels.join(\",\")}{${b.body}}`);\n }\n return parts.join(\"\\n\");\n}\n","/**\n * WCAG 2.1 colour contrast (zod-free). The editor warns when a guide's colours fall below AA:\n * 4.5:1 for body text, 3:1 for large text and UI components (button outlines, the close icon).\n */\n\nexport const WCAG_AA_TEXT = 4.5;\nexport const WCAG_AA_LARGE = 3;\n\nfunction channel(c: number): number {\n const s = c / 255;\n return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;\n}\n\n/** `#rgb` / `#rrggbb` → [r, g, b]; null when not a hex colour. */\nexport function parseHexColor(hex: string | null | undefined): [number, number, number] | null {\n if (!hex) return null;\n const m = hex.trim().match(/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i);\n if (!m) return null;\n const h = m[1]!.length === 3 ? m[1]!.split(\"\").map((c) => c + c).join(\"\") : m[1]!;\n return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];\n}\n\nexport function relativeLuminance(hex: string): number | null {\n const rgb = parseHexColor(hex);\n if (!rgb) return null;\n return 0.2126 * channel(rgb[0]) + 0.7152 * channel(rgb[1]) + 0.0722 * channel(rgb[2]);\n}\n\n/** Contrast ratio 1–21 between two hex colours, or null when either is not a hex colour. */\nexport function contrastRatio(a: string, b: string): number | null {\n const la = relativeLuminance(a);\n const lb = relativeLuminance(b);\n if (la === null || lb === null) return null;\n const [hi, lo] = la > lb ? [la, lb] : [lb, la];\n return Math.round(((hi + 0.05) / (lo + 0.05)) * 100) / 100;\n}\n\n/** Text colour (black or white) with the better contrast on `background`. */\nexport function readableTextOn(background: string): \"#ffffff\" | \"#111827\" {\n const white = contrastRatio(background, \"#ffffff\") ?? 0;\n const dark = contrastRatio(background, \"#111827\") ?? 0;\n return white >= dark ? \"#ffffff\" : \"#111827\";\n}\n\nexport interface ContrastIssue {\n /** What is hard to read. */\n pair: \"text\" | \"button\" | \"link\";\n ratio: number;\n required: number;\n message: string;\n}\n\n/**\n * Contrast problems of a guide's effective colours (guide appearance over the project theme).\n * Buttons use white or dark text, whichever reads better, so only a mid-tone primary colour fails.\n */\nexport function contrastIssues(colors: { primaryColor?: string; backgroundColor?: string; textColor?: string }): ContrastIssue[] {\n const issues: ContrastIssue[] = [];\n const { primaryColor, backgroundColor, textColor } = colors;\n if (textColor && backgroundColor) {\n const r = contrastRatio(textColor, backgroundColor);\n if (r !== null && r < WCAG_AA_TEXT) issues.push({ pair: \"text\", ratio: r, required: WCAG_AA_TEXT, message: `Text on the background has a contrast of ${r}:1; WCAG AA needs ${WCAG_AA_TEXT}:1.` });\n }\n if (primaryColor) {\n const label = contrastRatio(primaryColor, readableTextOn(primaryColor));\n if (label !== null && label < WCAG_AA_TEXT) issues.push({ pair: \"button\", ratio: label, required: WCAG_AA_TEXT, message: `Button labels on the primary colour have a contrast of ${label}:1; WCAG AA needs ${WCAG_AA_TEXT}:1.` });\n if (backgroundColor) {\n const link = contrastRatio(primaryColor, backgroundColor);\n if (link !== null && link < WCAG_AA_LARGE) issues.push({ pair: \"link\", ratio: link, required: WCAG_AA_LARGE, message: `The primary colour on the background (links, outlined buttons) has a contrast of ${link}:1; WCAG AA needs ${WCAG_AA_LARGE}:1.` });\n }\n }\n return issues;\n}\n","/**\n * The `detail` of an `exception` event (docs/error-monitoring/sdks.md): everything about an error\n * beyond the indexed properties (breadcrumbs, contexts, tags, extra, the exception chain, threads,\n * debug images…), in the Sentry event shape so the issue page renders Guidely and Sentry SDK events\n * alike. Zod-free: SDKs use these helpers at runtime, the server schema lives in `events.ts`.\n */\n\n/** Largest `detail` kept per occurrence (JSON characters); SDKs and the server trim to it. */\nexport const MAX_EXCEPTION_DETAIL_BYTES = 64 * 1024;\n/** A `detail` larger than this is dropped whole instead of trimmed (the event is still stored). */\nexport const MAX_EXCEPTION_DETAIL_RAW_BYTES = 1024 * 1024;\nexport const MAX_BREADCRUMBS = 100;\nexport const MAX_EXCEPTION_CHAIN = 20;\nexport const MAX_DETAIL_FRAMES = 250;\nexport const MAX_DETAIL_THREADS = 100;\nexport const MAX_DEBUG_IMAGES = 500;\nexport const MAX_ERROR_TAGS = 50;\n\nexport type ErrorLevelName = \"fatal\" | \"error\" | \"warning\" | \"info\" | \"debug\";\n\n/** A Sentry-shaped frame (oldest call first in a stack, the crashing frame last). */\nexport interface DetailFrame {\n function?: string;\n module?: string;\n package?: string;\n filename?: string;\n abs_path?: string;\n lineno?: number;\n colno?: number;\n in_app?: boolean;\n instruction_addr?: string;\n image_addr?: string;\n symbol_addr?: string;\n platform?: string;\n context_line?: string;\n pre_context?: string[];\n post_context?: string[];\n vars?: Record<string, unknown>;\n [k: string]: unknown;\n}\n\nexport interface DetailMechanism {\n type?: string;\n handled?: boolean;\n synthetic?: boolean;\n source?: string;\n exception_id?: number;\n parent_id?: number;\n data?: Record<string, unknown>;\n meta?: Record<string, unknown>;\n [k: string]: unknown;\n}\n\nexport interface DetailException {\n type?: string;\n value?: string;\n module?: string;\n thread_id?: number | string;\n mechanism?: DetailMechanism;\n stacktrace?: { frames?: DetailFrame[]; registers?: Record<string, string> };\n}\n\nexport interface Breadcrumb {\n /** Unix seconds (fractional). */\n timestamp?: number;\n type?: string;\n category?: string;\n message?: string;\n level?: ErrorLevelName | string;\n data?: Record<string, unknown>;\n}\n\nexport interface ExceptionDetail {\n level?: ErrorLevelName;\n exception?: { values: DetailException[] };\n threads?: { values: Array<{ id?: number | string; name?: string; crashed?: boolean; current?: boolean; main?: boolean; stacktrace?: { frames?: DetailFrame[] } }> };\n breadcrumbs?: { values: Breadcrumb[] };\n contexts?: Record<string, Record<string, unknown>>;\n tags?: Record<string, string>;\n extra?: Record<string, unknown>;\n user?: { id?: string; email?: string; username?: string; ip_address?: string; [k: string]: unknown };\n fingerprint?: string[];\n debug_meta?: { images: Array<Record<string, unknown>> };\n request?: { url?: string; method?: string; headers?: Record<string, string>; query_string?: string; data?: unknown; [k: string]: unknown };\n transaction?: string;\n server_name?: string;\n logger?: string;\n dist?: string;\n environment?: string;\n platform?: string;\n [k: string]: unknown;\n}\n\nconst size = (v: unknown) => {\n try {\n return JSON.stringify(v)?.length ?? 0;\n } catch {\n return Infinity;\n }\n};\n\n/** Tags as Sentry keeps them: at most 50, keys ≤ 32 and values ≤ 200 characters, values stringified. */\nexport function normalizeTags(tags: Record<string, unknown> | null | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(tags ?? {})) {\n if (Object.keys(out).length >= MAX_ERROR_TAGS) break;\n if (!k || v === undefined || v === null) continue;\n out[k.slice(0, 32)] = String(v).slice(0, 200);\n }\n return out;\n}\n\n/**\n * Trims a detail to `max` JSON characters, in the order the contract fixes: oldest breadcrumbs, then\n * frame variables and source context, then threads other than the crashed one, then extra, then\n * frames from the middle of long stacks. Mutates and returns `detail`.\n */\nexport function trimExceptionDetail<T extends ExceptionDetail>(detail: T, max = MAX_EXCEPTION_DETAIL_BYTES): T {\n const d = detail;\n if (d.breadcrumbs?.values && d.breadcrumbs.values.length > MAX_BREADCRUMBS) d.breadcrumbs.values = d.breadcrumbs.values.slice(-MAX_BREADCRUMBS);\n if (d.exception?.values && d.exception.values.length > MAX_EXCEPTION_CHAIN) d.exception.values = d.exception.values.slice(-MAX_EXCEPTION_CHAIN);\n if (d.threads?.values && d.threads.values.length > MAX_DETAIL_THREADS) d.threads.values = d.threads.values.slice(0, MAX_DETAIL_THREADS);\n if (d.debug_meta?.images && d.debug_meta.images.length > MAX_DEBUG_IMAGES) d.debug_meta.images = d.debug_meta.images.slice(0, MAX_DEBUG_IMAGES);\n const stacks = () => [...(d.exception?.values ?? []), ...(d.threads?.values ?? [])].map((x) => x.stacktrace).filter((s): s is { frames?: DetailFrame[] } => !!s);\n for (const s of stacks()) if (s.frames && s.frames.length > MAX_DETAIL_FRAMES) s.frames = s.frames.slice(-MAX_DETAIL_FRAMES);\n if (size(d) <= max) return d;\n while (d.breadcrumbs?.values.length && size(d) > max) d.breadcrumbs.values = d.breadcrumbs.values.slice(Math.ceil(d.breadcrumbs.values.length / 2));\n if (size(d) <= max) return d;\n for (const s of stacks())\n for (const f of s.frames ?? []) {\n delete f.vars;\n delete f.pre_context;\n delete f.post_context;\n }\n if (size(d) <= max) return d;\n if (d.threads?.values) d.threads.values = d.threads.values.filter((t) => t.crashed || t.current);\n if (size(d) <= max) return d;\n if (d.extra) d.extra = { _trimmed: true };\n if (d.request) delete d.request.data;\n // Long stacks lose middle frames first: the crash site and the entry point stay readable.\n for (const s of stacks()) while (s.frames && s.frames.length > 20 && size(d) > max) s.frames.splice(Math.floor(s.frames.length / 2) - 5, 10);\n if (d.debug_meta?.images && size(d) > max) d.debug_meta.images = d.debug_meta.images.slice(0, 50);\n return d;\n}\n\n/** An `ignoreErrors` / `denyUrls` / `allowUrls` entry: a substring, or a pattern. */\nexport type ErrorFilterPattern = string | RegExp;\n\nconst matches = (patterns: readonly ErrorFilterPattern[], value: string) => patterns.some((p) => (typeof p === \"string\" ? p !== \"\" && value.includes(p) : safeTest(p, value)));\n\nfunction safeTest(re: RegExp, value: string): boolean {\n re.lastIndex = 0;\n return re.test(value);\n}\n\n/**\n * True when the SDK's filters drop an error: `ignoreErrors` matches `\"<type>: <message>\"` or the\n * message; `denyUrls` matches the innermost frame file; a non-empty `allowUrls` that doesn't match\n * it drops the error too. Errors without a frame file pass the URL filters. Shared by every SDK\n * (conformance vectors `errorFilters`).\n */\nexport function errorFilterDrops(e: { type?: string; message?: string; file?: string | null }, opts: { ignoreErrors?: readonly ErrorFilterPattern[]; denyUrls?: readonly ErrorFilterPattern[]; allowUrls?: readonly ErrorFilterPattern[] }): boolean {\n const message = e.message ?? \"\";\n if (opts.ignoreErrors?.length && (matches(opts.ignoreErrors, `${e.type || \"Error\"}: ${message}`) || matches(opts.ignoreErrors, message))) return true;\n if (!e.file) return false;\n if (opts.denyUrls?.length && matches(opts.denyUrls, e.file)) return true;\n if (opts.allowUrls?.length && !matches(opts.allowUrls, e.file)) return true;\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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